﻿var dateInput = null;
var dateDisplay = null;
var currentMonth = null;
var currentYear = null;
var calendarContainer = null;
var calendarTable = null;
var iframe = null;
var monthRow = null;
var monthCell = null;
var prevMonthCell = null;
var nextMonthCell = null;
var rowWeeks = new Array(6);
var isIE = null;
var myDate = null;
var startDate = null;
var endDate = null;
var slCB = null;
var divFooterLegend = null;

function createCalendarFramework(highlightOtherDate)
{	
	var table = document.createElement("TABLE");
	var thead = document.createElement("THEAD");
	var tbody = document.createElement("TBODY");
	var row = document.createElement("TR");
	var cell, nav;
	
	cell = document.createElement("TD");	
	cell.appendChild(createHeaderNavigation(highlightOtherDate));
	row.appendChild(cell);
			
	thead.appendChild(row);
	table.appendChild(thead);	
	
	row = document.createElement("TR");
	cell = document.createElement("TD");	
	cell.appendChild(createBody());
	row.appendChild(cell);
	tbody.appendChild(row);
	
	row = document.createElement("TR");
	cell = document.createElement("TD");	
	cell.appendChild(createFooter(highlightOtherDate));
	row.appendChild(cell);
	tbody.appendChild(row);
	
	table.appendChild(tbody);
	table.className = "calendar";
	table.cellPadding = 0;
	table.cellSpacing = 0;
	var container = document.createElement("DIV");
	container.appendChild(table);
	container.style.zIndex=1000;
	
	return container;
}

function createHeaderNavigation(highlightOtherDate)
{
	var table = document.createElement("TABLE");	
	var tbody = document.createElement("TBODY");
	var row = document.createElement("TR");
	var cell;
	var nav;
	
	cell = document.createElement("TD");	
	nav = document.createElement("A");	
	nav.href = "javascript:PrevYear("+highlightOtherDate+");";
	nav.appendChild(document.createTextNode("<<"));
	cell.appendChild(nav);
	row.appendChild(cell);
	
	
	cell = document.createElement("TD");	
	nav = document.createElement("A");	
	nav.href = "javascript:PrevMonth("+highlightOtherDate+");";
	nav.appendChild(document.createTextNode("<"));
	cell.appendChild(nav);	
	cell.colspan = 2;
	cell.align = "right";
	row.appendChild(cell);	
	
	cell = document.createElement("TD");
	cell.colspan = 3;	
	cell.width = "100%";	
	cell.align = "center";
	row.appendChild(cell);
	
	cell = document.createElement("TD");	
	nav = document.createElement("A");	
	nav.href = "javascript:NextMonth("+highlightOtherDate+");";
	nav.appendChild(document.createTextNode(">"));
	cell.appendChild(nav);	
	row.appendChild(cell);
	
	cell = document.createElement("TD");	
	nav = document.createElement("A");	
	nav.href = "javascript:NextYear("+highlightOtherDate+");";
	nav.appendChild(document.createTextNode(">>"));
	cell.appendChild(nav);
	row.appendChild(cell);
		
	tbody.appendChild(row);
	table.appendChild(tbody);	
	table.className = "calendarNavigation";
	
	return table;
}

function createBody()
{
	var table = document.createElement("TABLE");	
	var tbody = document.createElement("TBODY");
	var row = document.createElement("TR");
	var cell;
					
	for(var i = 0; i < 7; i++)
	{
		row = document.createElement("TR");
		
		for(var j = 0; j < 7; j++)
		{
			cell = document.createElement("TD");
			
			if(i == 0)
			{
				cell.className = "wkHd";
				cell.appendChild(document.createTextNode(days[j].substr(0, 1)));
			}
			else
			{
				if(j == 0 || j == 6)
				{
					cell.className = "wknd";
				}
				else
				{
					cell.className = "wkdy";
				}
			}
			
			row.appendChild(cell);
		}
		
		tbody.appendChild(row);
	}
	
	table.appendChild(tbody);
	table.className = "calendarBody";
	table.width = "100%";
	
	return table;
}

function createFooterLegend(tbody)
{
    var row = document.createElement("TR");
    var cell = document.createElement("TD");   
    var div = document.createElement("Div");
    div.setAttribute("id", "divLegend");  
    divFooterLegend = div;
    divFooterLegend.className = "footerLegend";
    divFooterLegend.innerHTML = "<table border='0' cellspacing='2' cellpadding='2'>"
                                +"<tr><td valign='middle'><img src='images/cal_1.gif' width='18px' height='18px'  border='0' /></td><td valign='middle'>- " + calText[1] + "</td></tr>"
                                +"<tr><td valign='middle'><img src='images/cal_4.gif' width='18px' height='18px'  border='0' /></td><td valign='middle'>- " + calText[2] + "</td></tr>"
                                +"<tr><td valign='middle'><img src='images/cal_2.gif' width='18px' height='18px'  border='0' /></td><td valign='middle'>- " + calText[3] + "</td></tr>"
                                +"<tr><td valign='middle'><img src='images/cal_3.gif' width='18px' height='18px'  border='0' /></td><td valign='middle'>- " + calText[4] + "</td></tr>"
                                +"</table>";
    cell.appendChild(div);
    row.appendChild(cell);
    tbody.appendChild(row);  
}

function createFooter(highlightOtherDate)
{
	var table = document.createElement("TABLE");	
	var tbody = document.createElement("TBODY");
	
	if(highlightOtherDate)
	{
	    createFooterLegend(tbody);
	}
	
	var row = document.createElement("TR");
	var cell = document.createElement("TD");
	var nav = document.createElement("A");
	
	cell.align = "center";	
	nav.appendChild(document.createTextNode((typeof(calText) != "undefined")?calText[0]:close));
	nav.href = "javascript:closeCalendar();";					
	cell.appendChild(nav);
	row.appendChild(cell);
	tbody.appendChild(row);
	
	table.appendChild(tbody);
	table.className = "calendarFooter";
	table.width = "100%";
	
	return table;
}

function GetMonthText(month)
{	
	return months[month];
}

function PrevMonth(highlightOtherDate)
{
	currentMonth--;
	
	if(currentMonth < 0)
	{
		currentMonth = 11;
		currentYear--;
	}
	
	configureForDate(highlightOtherDate);
}

function NextMonth(highlightOtherDate)
{
	currentMonth++;
	
	if(currentMonth > 11)
	{
		currentMonth = 0;
		currentYear++;
	}	
	configureForDate(highlightOtherDate);
}

function PrevYear(highlightOtherDate)
{
    currentYear --;
    configureForDate(highlightOtherDate);
}

function NextYear(highlightOtherDate)
{
    currentYear ++;
    configureForDate(highlightOtherDate);
}

function getTopPosition(relTo)
{
	var top	= relTo.offsetTop + relTo.offsetHeight;
	while((relTo = relTo.offsetParent) != null)
		top += relTo.offsetTop;
	return top;  
}

function getLeftPosition(relTo)
{
	var left = relTo.offsetLeft;
	while((relTo = relTo.offsetParent) != null)
		left += relTo.offsetLeft;
	return left;
}

function showCalendar(btn, sDate, sStart, sEnd, callback, highlightOtherDate)
{	
    if(highlightOtherDate)
	{
	   highlightOtherDate = (calDates && calDates.length > 0);//(guaranteedDate.length > 0) || (discountAvailableDate.length > 0);
	}	
	if(isIE == null)
	{
		if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) 
			isIE = true;
		else
			isIE = false;
	}
	
	if(sStart != null && sStart != "")
		startDate = new Date(sStart);
	else
		startDate = null;
		
	if(sEnd != null && sEnd != "")	
		endDate = new Date(sEnd);			
	else
		endDate = null;
		
	
	var button = document.getElementById(btn);
	myDate = new Date(sDate);	
	slCB = callback;
	
	currentMonth = myDate.getMonth();
	currentYear = myDate.getFullYear();
	
	if(calendarContainer == null)
	{
		calendarContainer = createCalendarFramework(highlightOtherDate);
		document.body.appendChild(calendarContainer);		
		calendarTable = calendarContainer.childNodes[0];	
		calendarContainer.style.position = "absolute";	
		calendarContainer.style.backgroundColor = "#ffffff";
	}
	
	if(isIE && iframe == null)
	{
		iframe = document.createElement("IFRAME");
		iframe.style.position = "absolute";
		iframe.border= "0px";
		iframe.style.border = "0px";				
		document.body.appendChild(iframe);		
	}
	
	if(calendarContainer.style.display == "block")
	{
		closeCalendar();
		return;
	}
	
	calendarContainer.style.left = getLeftPosition(button) + "px";	
	calendarContainer.style.top = getTopPosition(button) + "px";
	
	if(iframe)
	{
		iframe.style.left = calendarContainer.style.left;
		iframe.style.top = calendarContainer.style.top;
		iframe.style.display = "block";
	}
	
	
	calendarContainer.style.display = "block";	
	configureForDate(highlightOtherDate);
	if(highlightOtherDate)
	{
	    divFooterLegend.style.display = "block";	    
	}
	else if(divFooterLegend)
	{
	    divFooterLegend.style.display = "none";	    
	}
}

function resizeFrame()
{
	iframe.style.height = calendarContainer.offsetHeight + "px";
	iframe.style.width = calendarContainer.offsetWidth + "px";
}

function configureForDate(highlightOtherDate)
{	
	configureMonth();
	configureDays(highlightOtherDate);
	
	if(iframe)
		resizeFrame();
}

function configureMonth()
{
	var cell = calendarTable.getElementsByTagName("TABLE").item(0).rows.item(0).cells.item(2);
	if(cell.childNodes.length > 0)
		cell.removeChild(cell.childNodes.item(0));
	cell.appendChild(document.createTextNode(GetMonthText(currentMonth) + " " + currentYear));
}

function configureDays(highlightOtherDate)
{
	var daysTable = calendarTable.getElementsByTagName("TABLE").item(1);
	var currentDate = new Date();	
	var firstOfMonth;
	var row, cell, link;
	
	currentDate.setFullYear(currentYear, currentMonth, 1);
	currentDate.setHours(0, 0, 0, 0);
	firstOfMonth = currentDate.getDay();	
	
	for(var i = 0; i < daysTable.rows.length-1; i++)
	{
		row = daysTable.rows.item(i+1);
		
		for(var j = 0; j < 7; j++)
		{
			cell = row.cells.item(j);
			
			if(cell.childNodes.length > 0)
				cell.removeChild(cell.childNodes.item(0));
			
			if(i == 0)
			{
				if(firstOfMonth > j)
				{
					cell.onmouseover = null;
					cell.onmouseout = null;
					cell.className = "";
					cell.appendChild(document.createTextNode(""));
				}
				else
				{									
					appendDay(currentDate, cell, highlightOtherDate);					
					currentDate.setDate(currentDate.getDate() + 1);	
				}
			}						
			else
			{
				if(currentDate.getMonth() == currentMonth)
				{
					appendDay(currentDate, cell, highlightOtherDate);
					currentDate.setDate(currentDate.getDate() + 1);
				}
				else
				{
					cell.onmouseover = null;
					cell.onmouseout = null;
					cell.className = "";
					cell.appendChild(document.createTextNode(""));		
				}
			}						
		}		
	}
}

function dOn()
 {
     
     if(this.className=="")
     {
         this.className = "on";
     }
     else
     {
        this.className += " on";
     }
     /**********************
     if(this.className == "today")
         this.className = "ton";
     if(this.className == "guaranteedDate")
         this.className = "guaranteedDateMouseOver";
     if(this.className == "discountDate")
         this.className = "discountDateMouseOver" 
         ********************/
 }
function dOff()
 {
     if(this.className=="on")
     {
         this.className = "";
     }
     else
     {
        this.className = this.className.substring(0, this.className.lastIndexOf(" on"));
     }
     /*******************
     if(this.className == "ton")
         this.className = "today";
     if(this.className == "guaranteedDateMouseOver")
         this.className = "guaranteedDate";
     if(this.className == "discountDateMouseOver")
         this.className = "discountDate" 
     ***********************/
 }

function appendDay(currentDate, cell, highlightOtherDate)
{
    
    HighlightAvailableDates(currentDate, cell, highlightOtherDate);
    if((startDate == null || startDate <= currentDate) && (endDate == null || endDate >= currentDate))
	{
		var link = document.createElement("A");
		link.href = "javascript:selectDate('" + (currentDate.getMonth()+1) + "/" + currentDate.getDate() + "/" + currentDate.getFullYear() + "');";
		link.appendChild(document.createTextNode(currentDate.getDate()));
		cell.appendChild(link);
		
		cell.onmouseover = dOn;
		cell.onmouseout = dOff;
		
	}
	else
	{
		cell.onmouseover = null;
		cell.onmouseout = null;
		cell.appendChild(document.createTextNode(currentDate.getDate()));
	}
	
}


/**
possible css className  3!
todayDate, todayguaranteedDate,  todayguaranteeddiscountDate, guaranteedDate,  guaranteeddiscountDate, discountDate
**/
function HighlightAvailableDates(currentDate, cell, highlightOtherDate)
{
    var className = "";
    
    if((currentDate - myDate) == 0)
	{
		className += "selectedDate ";		
	}
	if(highlightOtherDate)   
	{	    
	    /**if(HasCurrentDate(guaranteedDate, currentDate))
	    {	       
	        className += "guaranteed";	
	    }
	    if(HasCurrentDate(discountAvailableDate, currentDate))
	    {
	        className += "discount";   
	    }**/
	    for(var i = 0; i < calDates.length; i++) {
			if((calDates[i][0] - currentDate) == 0)
			{
				if(calDates[i][1]==true) className += "guaranteed";
				else className += "offer";
				if(calDates[i][2] > 0) className += "discount";
				break;
			}
	    }
	}
	if(className != "")
	{
	    className += "Date";
	}
	cell.className = className;
}

function HasCurrentDate(dateArray, date)
{
    var retVal = false;
    for(i = 0; i < dateArray.length; i++)
    {
        if((dateArray[i] - date) == 0)
        {
            retVal = true;
            break;
        }
    }
    return retVal;
}

function selectDate(sDate)
{
	closeCalendar();	
	if(slCB) {
		if(typeof(calDates) != "undefined") {
			var d = new Date(sDate);
			for(var i = 0; i < calDates.length; i++) {
				if((calDates[i][0] - d) == 0) {
					var args = { g:calDates[i][1], d:calDates[i][2] };
					slCB(sDate, args);
					return;
				}
			}
		}
		slCB(sDate);
	}
}

function closeCalendar()
{	
	calendarContainer.style.display = "none";
	if(iframe) iframe.style.display = "none";	
	if(divFooterLegend) divFooterLegend.style.display = "none";
}

function formatDateString(tb)
{	
	var d = new Date(tb.value);
	var str = days[d.getDay()] + ", " + months[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear();
	tb.value = str;
}

function getDateString(date)
{	
	var str = days[date.getDay()] + ", " + months[date.getMonth()] + " " + date.getDate() + ", " + date.getFullYear();
	return str;
}

function getUrlDate(dateString)
{
	var d = new Date(dateString);
	return (d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear();
}

function isValidTc(code) {
	
	var re = /^[a-zA-Z]([\w'.]{1,}-){1,}[0-9]+[\s]*$/;
	return re.test(code); 	
}


function checkForTc(value) {
	if(isValidTc(value)) {
		return asyncReqSearchUrl(value);		
	}
	else return false;
}

function validateTextInput(ss)
{
	
	var searchString = document.getElementById(ss);	
	if(searchString.value == null || searchString.value.length < minStringLength) {
		alert(moreText);
		return false;
	}
	else if(checkForTc(searchString.value)) {
		return false;
	}
	else {
		return true;
	}
}

function validateInput(ss, sd, ed)
{	
	var searchString = document.getElementById(ss);
	var startDate = document.getElementById(sd);
	var endDate = document.getElementById(ed);
	var start, end;
	
	start = new Date(startDate.value);	
	end = new Date(endDate.value);	
	
	if(searchString.value == null || searchString.value.length < minStringLength) {
		alert(moreText);		
		return false;
	}
	else if(checkForTc(searchString.value)) {
		return false;
	}
	else if(start.setDate(start.getDate()+1) < new Date()) {
		alert(pastDate);
		return false;
	}
	else if(start > end) {
		alert(startPastEnd);
		return false;
	}
	else
	{
	    return true;
	}
}

function asyncReqSearchUrl(txtVal) {
	var xmlReq = null;
	if(xmlReq != null)
	{
		 alert("Busy processing previous request");
		 return;
	}
	xmlReq = createXmlRequest();				
	if(xmlReq == null) {
		 alert("This browser does not support XML Http Requests");
		 return;
    }	
    
	xmlReq.open("GET", applicationUrl+"ajax/CrossDomainCall.aspx?domain=CRMWebServiceUrl&path=TourCenter/GetTCSearchUrl.aspx" +"&returnType=json&tourCenterCode="+txtVal+"&dummy="+Math.random(), false);		 
	xmlReq.send(null);
	if(xmlReq.status==200)
	{	
		 return redirectToSearchUrl(xmlReq.responseText);
	}
	else
	{
		if(xmlReq.statue==409)
			alert(xmlReq.responseText);
		else
			alert(xmlReq.status + "sa : " + xmlReq.statusText);
	}

	xmlReq = null;
	return false;			
}

function redirectToSearchUrl(jsonText)
{   
	var json = eval('(' + jsonText + ')');
	if(json.GetTCSearchUrl.Error)
	{				
		var arr = getErrorMessages(json.GetTCSearchUrl.Error.Exception);
		var msg = "";			
		for(var j=0; j<arr.length; j++)
		{
			msg += arr[j] + "\r\n";
		}
		alert(msg);
	}
	else if(json.GetTCSearchUrl.ValidRequest)
	{		
		var isValidtc__ = json.GetTCSearchUrl.ValidRequest.SearchResult.Result.validtc["#text"]; 
		if(isValidtc__=="True")
		{	
			var site = json.GetTCSearchUrl.ValidRequest.SearchResult.Result.Site["#text"];
			location.href = site;
			return true;
		}		
	} 	
	return false;
}
	
function search(tb)
{    
	var textBox = document.getElementById(tb);
	var exploricaUrl = salesSiteUrl;
	var collectionsUrl = "SearchResults";
	
	if(textBox.value == null || textBox.value.length < 3)
	{		
		var x = exploricaUrl + "Search";
		
		if(channelId != null && channelId != "")
			x += "&channelId=" + channelId;
			
		window.location.href = x;
	}
	else
	{
		var url = exploricaUrl + collectionsUrl + "?type=all&ss=" + textBox.value.replace(/&/, '%26');
			
		window.location.href = url;  
	}
}


