/*
$Id: AutoComplete.js 7011 2007-08-31 10:44:53Z abagai $
*/
 
/* Initialization */


var field="";
function checkField(fieldnum){

if(fieldnum=="1"){
field="1";

}
else if(fieldnum=="2"){
field="2";

}
else if(fieldnum=="3"){
field="3";


}
else{

}

}



var deparray="";
var retarray="";
var datedep="";
var dateret="";
//alert("before cookie");
//alert("document" + document);
var visitordata = new Cookie(document, "visitordata", 72);
//alert("after cookie");
var departureIsClicked=false;
var destinationIsClicked=false;
var ajaxDropDownIsOpen=false;


/* Interactive Flight Search Map: */
var populationFlag = '';

function airportName(set) {
	/*
		0 = input string
		1 = code
		2 = airport name (can be empty)
		3 = state (can be empty)
		4 = city
		5 = country
	     	6 = latitude
		7 = longitude
	*/
  if (set[2]==set[4]) set[4]=""; // remove city name if same as airport name
  //an = set[2]+" ["+set[1]+"]"+((!set[4] && !set[3])?", ":" ")+((set[4])?set[4]+", ":"")+((set[3])?set[3]+", ":"")+set[5];
  an = set[4]+" ["+set[1]+"]"+", "+set[5];
  //an = set[2]+" ["+set[1]+"]"+((!set[4] && !set[3])?", ":" ")+((set[4])?set[4]+", ":"")+((set[3])?set[3]+", ":"")+set[5];
  return an;


} // airportName








/* AutopComplete Form: */
var oAutoCompleteFrom = oAutoCompleteTo = null;
var resultsExists = false;
var fsSubmitFlag = 0;
nogoCharsExp = /[.*+?|(){}[\]\\]/g;

window.onload = init;

if(document.addEventListener) {
	document.addEventListener("DOMContentLoaded", init, null);
}

// cache array
var aDB = [];
var aSelected = [];

// Initiate objects
function init() {
		
	//pick_image();
	//attachMenuHandlers();
	if(arguments.callee.done) return;

	arguments.callee.done = true;
	
	oAutoCompleteFrom = new AutoComplete("From", new ErrorDisplay("errorFrom"));
	oAutoCompleteTo = new AutoComplete("To", new ErrorDisplay("errorTo"));

	/* Start : Codes added for DarkSite IE6 */
		
	/*if(document.`.From.style.visibility == ''){
		return;
	}*/
	
	/* End : Codes added for DarkSite IE6 */	

	/*if( !(document.searchForm == null)){
		document.searchForm.From.focus();
	}*/
	//attachMenuHandlers();
}

function pick_image(){

	document.getElementById("random-image").src = random_images[rand(6)-1];
}

function rand ( n )
{
  return ( Math.floor ( Math.random ( ) * n + 1 ) );
}

/* 
  * before submitting fligh search, 
  * make sure it has not been submitted in the last 3 seconds
  */
function submitFlightSearch(){
var datedep=document.getElementById('depdate').value;
deparray=datedep.split("/");
var dateret=document.getElementById('retdate').value;
retarray=dateret.split("/");
document.getElementById('departureYear').value=deparray[2];

document.getElementById('departureMonth').value=deparray[1];
var depday=deparray[0].replace(/^\s+|\s+$/g,"");
document.getElementById('departureDay').value=depday;

document.getElementById('returnYear').value=retarray[2];
document.getElementById('returnMonth').value=retarray[1];
var retday=retarray[0].replace(/^\s+|\s+$/g,"");
document.getElementById('returnDay').value=retday;



	if ((ChosenDate()) && (validateForm('searchForm'))){
		if (fsSubmitFlag==0) {
		  fsSubmitFlag = 1;     
		  startTimerForSubmitButton();
		 document.searchForm.submit();
		}
	}


}
function startTimerForSubmitButton() { 
  setTimeout("enableSubmitButton()",1000);
}
function enableSubmitButton() {
  fsSubmitFlag = 0;
}


/* 
  * Auto Complete functionality: 
  */
function AutoComplete(sTextboxId, oError) {
//alert("inside autocomplete");
  this.name=sTextboxId;
//alert("check this- " + document.getElementById(sTextboxId));
	this.textbox = document.getElementById(sTextboxId);
	this.dropdownNode = null;
	this.menuPos = 0;
	this.menuShown = false;
	this.errorHandler = oError;
	
	this.init();
}

AutoComplete.prototype.trim = function(string) { return string.replace(/^\s+|\s+$/, ''); };

// Initiates text field with events and calls the dropdown creation method
AutoComplete.prototype.init = function() {

	if(this.textbox == null) return;
	this.textbox.setAttribute("autocomplete", "off");
	var oThis = this;

	this.textbox.onkeyup = 
	this.textbox.onclick = 
	this.textbox.onkeydown = 
	this.textbox.onblur = function(oEvent)
	{	
		if(!oEvent) var oEvent = window.event;
		switch(oEvent.type)	{			
			case "keyup":
				oThis.handleKeyup(oEvent);
				break;
			case "keydown":
				oThis.handleKeyDown(oEvent);
				break;
			case "blur":
				//alert("Blur");			
				//oThis.selectOnBlur();
				oThis.hideDropdown();
				break;
		}
	}

	this.createDropdown();
	//this.textbox.focus();
	
	// Re-position dropdown if window is resized
	window.onresize = function() {
		if(oThis.menuShown) oThis.positionDropdown();
	}
}

AutoComplete.prototype.selectOnBlur = function()
{
	if(!(this.dropdownNode == null) && !(this.dropdownNode.childNodes[this.menuPos] == null))
	{
		this.highlightLocation();
		//this.textbox.value = this.trim(this.dropdownNode.childNodes[this.menuPos].firstChild.nodeValue);
				
		aSelected.push(this.textbox.value);
	    this.hideDropdown();
	}
	//var cSuggestionNodes = this.dropdownNode.childNodes;
	//alert(cSuggestionNodes[0].nodeValue);
	//if(this.menuPos == 0) this.menuPos = cSuggestionNodes.length;
	//if(cSuggestionNodes.length > 0){
	//	var oNode = cSuggestionNodes[this.menuPos];
		//populate(cSuggestionNodes[this.menuPos]);
	//	this.highlightSuggestion(oNode);
	//	this.textbox.value = oNode.firstChild.nodeValue;
	//}

}
// Creates the autocomplete dropdown
AutoComplete.prototype.createDropdown = function()
{


	var oThis = this;

	this.dropdownNode = document.createElement("div");
    	this.dropdownNode.setAttribute("id", "ajaxDropdown")
	this.dropdownNode.className = "suggest";
	
	this.dropdownNode.onmouseover =
	this.dropdownNode.onmousedown = function(oEvent) {
		if(!oEvent) oEvent = window.event;
		var oTarget = oEvent.srcElement || oEvent.target;
		
		if(oEvent.type == "mouseover") oThis.highlightSuggestion(oTarget);
		else {
			oThis.highlightLocation();
      //alert("mouse");
      oThis.textbox.value = oThis.trim(oTarget.firstChild.nodeValue);
			aSelected.push(oThis.textbox.value);
		}
	}

	document.body.appendChild(this.dropdownNode);
}

// Keyup event handler
AutoComplete.prototype.handleKeyup = function(oEvent)
{
	var iKeyCode = oEvent.keyCode;
	
	// Hide dropdown if less than 3 charachters
	if(this.textbox.value.length < 2) {
		this.hideDropdown();
		if(iKeyCode != 9) this.errorHandler.hideError();
	}
	else
	{
		if(iKeyCode < 8 || iKeyCode >= 9 && iKeyCode < 32 || (iKeyCode >= 33 && iKeyCode <= 46) || (iKeyCode >= 112 && iKeyCode <= 123)) return;
		this.search();
	}
}


// Keydown event handler
AutoComplete.prototype.handleKeyDown = function(oEvent)
{		//alert(this);
	if(!this.menuShown) return;
	var iKeyCode = oEvent.keyCode;
		
	switch(iKeyCode) {
		// Tab
		case 9:
      this.highlightLocation();
      //alert("tab");
      this.textbox.value = this.trim(this.dropdownNode.childNodes[this.menuPos].firstChild.nodeValue);
			
			aSelected.push(this.textbox.value);
      this.hideDropdown();
			break;

		// Return key
		case 13:
      this.highlightLocation();
      //alert("return");
      this.textbox.value = this.trim(this.dropdownNode.childNodes[this.menuPos].firstChild.nodeValue);
			aSelected.push(this.textbox.value);

			var oFormElements = this.textbox.form.elements;

	    // Focus next (if any) element
      var currentTabIndex = this.textbox.tabIndex
      for(var i=0, iLength=oFormElements.length;i<iLength;i++)
			{
				if(oFormElements[i].tabIndex==currentTabIndex+1){
					//oFormElements[i].focus();
					break;
				}
			}
			this.hideDropdown();
			break;
			
		// Up arrow
		case 38:
			// Prevent caret to be moved to the left
			if(oEvent.preventDefault) oEvent.preventDefault();
			this.previousSuggestion();
			break;

		// Down arrow
		case 40:
			this.nextSuggestion();
	}
}

// Highlights next element when pressing down arrow
AutoComplete.prototype.nextSuggestion = function()
{
	var cSuggestionNodes = this.dropdownNode.childNodes;
	
	// XXX remove -1 if only > and not >=??
	if(this.menuPos >= cSuggestionNodes.length-1)
	{
		this.menuPos = -1;
	}
	
	if(cSuggestionNodes.length > 0 && this.menuPos < cSuggestionNodes.length-1)
	{
		var oNode = cSuggestionNodes[++this.menuPos];
	
		this.highlightSuggestion(oNode);
		this.textbox.value = oNode.firstChild.nodeValue;
	}
}

// Highlights previous element when pressing up arrow
AutoComplete.prototype.previousSuggestion = function()
{
	var cSuggestionNodes = this.dropdownNode.childNodes;

	if(this.menuPos == 0) this.menuPos = cSuggestionNodes.length;

	// XXX make this a return in the beginning??
	if(cSuggestionNodes.length > 0)
	{
		var oNode = cSuggestionNodes[--this.menuPos];

		this.highlightSuggestion(oNode);
		this.textbox.value = oNode.firstChild.nodeValue;
	}
}


// Search
AutoComplete.prototype.search = function() {
	var oThis = this;
  	inputStr = this.textbox.value.replace(nogoCharsExp, "");
	var sIndex = encodeURIComponent(inputStr.slice(0,10).toLowerCase());
	var aSuggestions = [];
  
	var regExp = new RegExp("^" + inputStr, "i");
	var bSelected = false;
	// If cached result exists
	if(!aDB[sIndex]) {

		var sLanguage = (location.search)? "&language=en":"";
    	    aDB[sIndex] = -1; // check this out!
	
		HttpClient.get(ajaxURL +  sIndex + sLanguage, function(oRequest) {
			eval(oRequest);
			oThis.search();
		});
  } else if (aDB[sIndex]!= -1) {
		for(var i=0, iLength=aDB[sIndex].length; i<iLength; i++) {
			if(aDB[sIndex][i][0].search(regExp) != -1) {
				aSuggestions.push(aDB[sIndex][i]);
			}
		}

		for(var i=0, iLength=aSelected.length;i<iLength;i++) {
			if(this.textbox.value.indexOf(aSelected[i])>-1) {
				bSelected = true;
			}
		}
		
		// If any hits
		if(aSuggestions.length)	{
			this.errorHandler.hideError();
			this.showDropdown(this.removeDuplicates(aSuggestions));
		}	else if(!bSelected)	{
			this.displayError();
		}
	}
} // search

// Remove duplicates before showing them
AutoComplete.prototype.removeDuplicates = function(aSuggestions) {
	for(var i=0;i<aSuggestions.length;i++) {
		var sCode = aSuggestions[i][1];
		for(var j=i;j<aSuggestions.length;j++) {
			if(i != j) {
				if(sCode == aSuggestions[j][1]) {
					aSuggestions.splice(j,1);
					j--;
			  }
			}
		}	
	}
return aSuggestions;
} // removeDublicates



// Visually show that no hit has been found
AutoComplete.prototype.displayError = function() {
	this.hideDropdown();
	this.errorHandler.showError(aErrorMessage["noHit"]);
}

// Shows the suggestion dropdown
AutoComplete.prototype.showDropdown = function(aSuggestions) {
	var oSuggestionNode, sSuggestion;

	this.menuShown = true;
	
	this.dropdownNode.innerHTML = "";
	this.positionDropdown();

	var iLength = (aSuggestions.length < 10)? aSuggestions.length:10;
	
	// Show 10 results at the time
	for(var i=0; i<iLength; i++) {
		oSuggestionNode = document.createElement("div");
		sSuggestion = document.createTextNode(this.createTextNode(aSuggestions[i]));
		oSuggestionNode.appendChild(sSuggestion);

    var latitude = document.createAttribute("latitude");
    latitude.nodeValue = aSuggestions[i][6];
    oSuggestionNode.setAttributeNode(latitude);

    var longitude = document.createAttribute("longitude");
    longitude.nodeValue = aSuggestions[i][7];
    oSuggestionNode.setAttributeNode(longitude);

    var airportCode = document.createAttribute("airportCode");
    airportCode.nodeValue = aSuggestions[i][1];
    oSuggestionNode.setAttributeNode(airportCode);

    oSuggestionNode.appendChild(sSuggestion);
		this.dropdownNode.appendChild(oSuggestionNode);
	}

	this.textbox.focus();
	this.highlightSuggestion(this.dropdownNode.firstChild);
	this.dropdownNode.style.display = "block";
	if(this.textbox.offsetWidth >225){
	this.dropdownNode.style.width = (this.textbox.offsetWidth - (parseInt(this.getStyle(this.textbox, "border-left-width")) + parseInt(this.getStyle(this.textbox, "border-right-width")))) + "px";
	this.dropdownNode.style.left = this.getOffsetX()+ "px";
	this.dropdownNode.style.top = (this.getOffsetY()+ this.textbox.offsetHeight - parseInt(this.getStyle(this.textbox, "border-bottom-width"))) + "px";
	}else{
	this.dropdownNode.style.width = (this.textbox.offsetWidth+parseInt(10) - (parseInt(this.getStyle(this.textbox, "border-left-width")) + parseInt(this.getStyle(this.textbox, "border-right-width")))) + "px";
	this.dropdownNode.style.left = this.getOffsetX()-parseInt(4) + "px";
	this.dropdownNode.style.top = (this.getOffsetY()+parseInt(2) + this.textbox.offsetHeight - parseInt(this.getStyle(this.textbox, "border-bottom-width"))) + "px";
	}
	ajaxDropDownIsOpen=true;
  
} // showDropdown

// Hides and clears the dropdown
AutoComplete.prototype.hideDropdown = function() {
	this.menuShown = false;
	this.menuPos = 0;
	this.dropdownNode.style.display = "none";
} // hideDropdown

AutoComplete.prototype.positionDropdown = function() {
	this.dropdownNode.style.width = (this.textbox.offsetWidth - (parseInt(this.getStyle(this.textbox, "border-left-width")) + parseInt(this.getStyle(this.textbox, "border-right-width")))) + "px";
	this.dropdownNode.style.left = this.getOffsetX() + "px";
	this.dropdownNode.style.top = (this.getOffsetY() + this.textbox.offsetHeight - parseInt(this.getStyle(this.textbox, "border-bottom-width"))) + "px";
} //positionDropdown

// text node builder for suggestion
AutoComplete.prototype.createTextNode = function(aSuggestion) {
	var sSuggestion;
	sSuggestion = airportName(aSuggestion);
	return sSuggestion;
} // createTextNode

// Highligts the current suggestion
AutoComplete.prototype.highlightSuggestion = function(oSuggestionNode) {
	var cSuggestionNodes = this.dropdownNode.childNodes;
	
	for (var i=0; i < cSuggestionNodes.length; i++) {
		var oNode = cSuggestionNodes[i];

		if(oNode == oSuggestionNode) {
			// Update position so up/down arrow keys get the correct suggestion if used
			this.menuPos = i;
			oNode.className = "highlight";
		}
		else oNode.className = "";
	}
} // highlightSuggestion

// returns the left position of any element
AutoComplete.prototype.getOffsetX = function() {
	var iOffsetLeft = 0;
	var oNode = this.textbox;

	while(oNode.offsetParent) {
		iOffsetLeft += oNode.offsetLeft;
		oNode = oNode.offsetParent;
	}

	iOffsetLeft += document.body.offsetLeft;

	return iOffsetLeft;
} //getOffsetX

// returns the top position of any element
AutoComplete.prototype.getOffsetY = function() {
	var iOffsetTop = 0;
	var oNode = this.textbox;

	while(oNode.offsetParent) {
		iOffsetTop += oNode.offsetTop;
		oNode = oNode.offsetParent;
	}

	iOffsetTop += document.body.offsetTop;
	
	return iOffsetTop;
} // getOffsetY

// Returns computed style value
AutoComplete.prototype.getStyle = function(oNode, sStyle) {
	if(document.defaultView) 	{
		return document.defaultView.getComputedStyle(oNode, null).getPropertyValue(sStyle);
	}
	else if(oNode.currentStyle) {
		var sStyle = sStyle.replace(/-\D/gi, function(sMatch) {
			return sMatch.charAt(sMatch.length - 1).toUpperCase();
		});

		return oNode.currentStyle[sStyle];
	}	else return null;
} // getStyle


// ========================================================
// START IMAGE SPOTS HIGHLIGHT
// Highligts the selection on the map
// ========================================================
AutoComplete.prototype.highlightLocation = function(){
	if(!(this.dropdownNode.childNodes[this.menuPos] == null))
	{
	  var latitude=this.dropdownNode.childNodes[this.menuPos].getAttribute("latitude");
	  var longitude=this.dropdownNode.childNodes[this.menuPos].getAttribute("longitude");
		//alert("highlightLocation ");
	  placeSpot(this.textbox.name, this.dropdownNode.childNodes[this.menuPos].getAttribute("airportCode"), latitude, longitude, 1);
	}
} // highlightLocation


function placeSpot(field, apc, latitude, longitude, spoteffect) {

  // Write airport code of selected airport to hidden form field
  if(field=="From"){
    document.searchForm.fromAirportCode.value=apc;
   // document.searchForm.fromLat.value=latitude;    
   //document.searchForm.fromLon.value=longitude;    
  } else {
    document.searchForm.toAirportCode.value=apc;
   // document.searchForm.toLat.value=latitude;    
   // document.searchForm.toLon.value=longitude;    
  }
  var offsetX=208;
  var offsetY=50;
  var xPos=(offsetX+longitude*1.441)+"px";
  var yPos=(offsetY-latitude*1.458)+"px";

  //If location is outside map boundaries do not display anything
  if (latitude>66.5||latitude<-45||longitude>180||longitude<-178.5){
    latitude="undefined";
    longitude="undefined";
  }

// spotpositioning starts here
  if (field=="From"){
    if(!(document.getElementById("spotContainer1") == null)){
    	document.getElementById("spotContainer1").className="spotHide";
	    cityMarker=document.getElementById("spotContainer1").style;
	    cityMarker.top=yPos;
	    cityMarker.left=xPos;
	    if(latitude!="undefined"){
	      if (spoteffect) setTimeout('document.getElementById("spotImage1").src=zoomSpot1.src; document.getElementById("spotContainer1").className="";',50);
	      setTimeout('document.getElementById("spotImage1").src=Spot1.src; document.getElementById("spotContainer1").className="spotAdj"; ',50+(750*spoteffect));
	    }
	 }   
  } else {
  	if(!(document.getElementById("spotContainer2") == null)){
	    document.getElementById("spotContainer2").className="spotHide";
	    cityMarker=document.getElementById("spotContainer2").style; 
	    cityMarker.top=yPos;
	    cityMarker.left=xPos;
	    if(latitude!="undefined"){
	      if (spoteffect) setTimeout('document.getElementById("spotImage2").src=zoomSpot2.src; document.getElementById("spotContainer2").className="";',50);
	      setTimeout('document.getElementById("spotImage2").src=Spot2.src; document.getElementById("spotContainer2").className="spotAdj";',50+(750*spoteffect));
	    }
	}
  }
} // placeSpot


// If selected month is in the past, increase the year with one
function validateMonth(flightType){
	
  Today = new Date();
  currentYear=Today.getYear();

  // Some browsers start counting the year from 1900. 2006 is then represented by 106.
  if (Today.getYear()<1900){currentYear+=1900;}

  if (flightType=="departure"){
    monthSelector=myForm.departureMonth;
    yearSelector=myForm.departureYear;
  }else{
    monthSelector=myForm.returnMonth;
    yearSelector=myForm.returnYear;
  }
  
  selectedMonth=getSelection(monthSelector)
  selectedYear=getSelection(yearSelector)

  if (selectedMonth<Today.getMonth()+1){
    if (selectedYear==currentYear){
      for (var i=0; i < yearSelector.length; i++) {
        if (yearSelector.options[i].value==currentYear){
          try{
            yearSelector.options[i+1].selected=true;
          }catch(e){}
        }
      }
    }
  }
}

function getSelection(theSelector){
  for (var i=0; i < theSelector.length; i++) {
    if(theSelector.options[i].selected==true){
      return theSelector.options[i].value;
    }
  }
}

function setSelector(theSelector,value){
  for (var i=0; i < theSelector.length; i++) {
    if(theSelector.options[i].value==value){
      theSelector.options[i].selected=true;
    }
  }
}

function validateForm(searchForm) {

  if (ajaxDropDownIsOpen==true){
    ajaxDropDownIsOpen=false;
	  //alert ("DROPDOWN OPEN!");
  }
    
  if(!document.getElementById('From').value){
		oAutoCompleteFrom.errorHandler.showError(aErrorMessage["noOrigin"]);		
		//alert ("Error NoOrgin");
		return false;
	}
	
	if(!document.getElementById('To').value){
		oAutoCompleteTo.errorHandler.showError(aErrorMessage["noDestination"]);
		//alert ("Error noDestination");
		return false;
	}
	
	if(oAutoCompleteFrom.errorHandler.error || oAutoCompleteTo.errorHandler.error) {
		//alert ("ERORS LEFT !");
		return false;
	}
	else{
	  //alert ("INSIDE SAVE FORM !");
   	
	 saveForm();
    return true;
  }
} // validateForm

// Save form into cookie with 3 days expiration
function saveForm(){
	
	

  visitordata.departureYear   = getSelection(myForm.departureYear);

  visitordata.departureMonth  = getSelection(myForm.departureMonth);
  visitordata.departureDay    = getSelection(myForm.departureDay);
  visitordata.returnYear      = getSelection(myForm.returnYear);
  visitordata.returnMonth     = getSelection(myForm.returnMonth);
  visitordata.returnDay       = getSelection(myForm.returnDay);
  visitordata.departure       = document.searchForm.From.value;
  visitordata.destination     = document.searchForm.To.value;
  visitordata.fromAirportCode = document.searchForm.fromAirportCode.value;
  visitordata.toAirportCode   = document.searchForm.toAirportCode.value;
  visitordata.fromLon         = document.searchForm.fromLon.value;
  visitordata.fromLat         = document.searchForm.fromLat.value;
  visitordata.toLon           = document.searchForm.toLon.value;
  visitordata.toLat           = document.searchForm.toLat.value;
  var fromairport=document.getElementById('From').value;
  var start=fromairport.indexOf('[');
  var end=fromairport.indexOf(']');
  document.searchForm.fromAirportCode.value=fromairport.substring(start+1,end);

  var toairport=document.getElementById('To').value;
  start=toairport.indexOf('[');
  end=toairport.indexOf(']');
  document.searchForm.toAirportCode.value=toairport.substring(start+1,end);
  //visitordata.store();
} // saveForm


function readFormCookie(){
	
  var query=this.location.search.substring(1);
  if (query!="") { 
    refineSearch();
    return;
  }
  
  return;
  
  visitordata.load()
 setSelector(myForm.departureYear,visitordata.departureYear);
  setSelector(myForm.departureMonth,visitordata.departureMonth);
  setSelector(myForm.departureDay,visitordata.departureDay);
  setSelector(myForm.returnYear,visitordata.returnYear);
  setSelector(myForm.returnMonth,visitordata.returnMonth);
  setSelector(myForm.returnDay,visitordata.returnDay);
  
  document.searchForm.toAirportCode.value=visitordata.toAirportCode;
  document.searchForm.fromAirportCode.value=visitordata.fromAirportCode;
  
  if (visitordata.departure && visitordata.departure!=""){
  	
    placeSpot("From", visitordata.fromAirportCode, visitordata.fromLat, visitordata.fromLon, 0);
    document.searchForm.From.value = visitordata.departure;
    document.searchForm.From.style.color = "#000";
    departureIsClicked=true;
  }
  if (visitordata.destination && visitordata.destination!=""){
    placeSpot("To", visitordata.toAirportCode, visitordata.toLat, visitordata.toLon, 0);
    document.searchForm.To.value = visitordata.destination;
    document.searchForm.To.style.color = "#000";
    destinationIsClicked=true;
  }
} // readFormCookie


function refineSearch() {
  
 var lsRegExp = /\+/g;
  var query=(unescape(String(this.location.search.substring(1)))).replace(lsRegExp, " ");

  var refVal = new Array();
  if (query.length > 0){
    var params=query.split("&");
    for (var i=0 ; i<params.length ; i++){
      var pos = params[i].indexOf("=");
      var name = params[i].substring(0, pos);
      var value = params[i].substring(pos + 1);
      refVal[name] = value;
    }
  }

  if (refVal["sevenDayLookUp"]) myForm.sevenDayLookUp.checked = "true";
  if (refVal["returnTrip"]) myForm.returnTrip.checked = "true";

  if (refVal["From"] && refVal["fromAirportCode"]) {
	
    myForm.From.value = refVal["From"];
//alert("In -- " + myForm.From.value);
    myForm.fromAirportCode.value = refVal["fromAirportCode"];
    
    if (refVal["fromLat"] && refVal["fromLon"]) {
      placeSpot("From", refVal["fromAirportCode"], refVal["fromLat"], refVal["fromLon"], 0);
    }
  }
  if (refVal["To"] && refVal["toAirportCode"]) {
    myForm.To.value = refVal["To"];
    myForm.toAirportCode.value = refVal["toAirportCode"];
    
    if (refVal["toLat"] && refVal["toLon"]) {
      placeSpot("To", refVal["toAirportCode"], refVal["toLat"], refVal["toLon"], 0);
    }
  }
 
} // refineSearch

function populateFields(que) {

  var lsRegExp = /\+/g;
  //alert("string in js1 :"+que);
  var query=(unescape(String(que))).replace(lsRegExp, " ");
  //alert("string in js2 :"+query);
  var refVal = new Array();
  if (query.length > 0){
    var params=query.split("&");
    for (var i=0 ; i<params.length ; i++){
      var pos = params[i].indexOf("=");
      var name = params[i].substring(0, pos);
      var value = params[i].substring(pos + 1);
      refVal[name] = value;
    }
  }

   
  if (refVal["sevenDayLookUp"]) myForm.sevenDayLookUp.checked = "true";
  if (refVal["returnTrip"]) myForm.returnTrip.checked = "true";

  if (refVal["From"] && refVal["fromAirportCode"]) {

    myForm.From.value = refVal["From"];
    //alert("In Populate " + myForm.From.value);
    myForm.fromAirportCode.value = refVal["fromAirportCode"];
    
    if (refVal["fromLat"] && refVal["fromLon"]) {
      placeSpot("From", refVal["fromAirportCode"], refVal["fromLat"], refVal["fromLon"], 0);
    }
  }
  if (refVal["To"] && refVal["toAirportCode"]) {
    myForm.To.value = refVal["To"];
    myForm.toAirportCode.value = refVal["toAirportCode"];
    
    if (refVal["toLat"] && refVal["toLon"]) {
      placeSpot("To", refVal["toAirportCode"], refVal["toLat"], refVal["toLon"], 0);
    }
  }
 
} // refineSearch

function setDateDropdowns(){
 var Departure = new Date();
  var Return    = new Date();
	var depday="";
	var depmonth="";
	var retday="";
	var retmonth="";
  // Default dates is departure today plus 3 days. Return today plus 7 days.
  Departure.setDate(Departure.getDate() + 1);
  Return.setDate(Return.getDate() + 7);
  var myDepartureYear = Departure.getYear();
  var myReturnYear = Return.getYear();
 if (myDepartureYear<1900){myDepartureYear+=1900;}
   if (myReturnYear<1900){myReturnYear+=1900;}
	if(Departure.getDate()< 10){
	depday="0"+Departure.getDate();
	}
	else{
	depday=Departure.getDate();
	}
	if(Return.getDate()<10){
	retday="0"+Return.getDate();
	}
	else{
	retday=Return.getDate();
	}

	depmonth=(parseInt(Departure.getMonth())+1);
	retmonth=(parseInt(Return.getMonth())+1);

	if(depmonth<=9)
	{
		depmonth="0"+(parseInt(Departure.getMonth())+1);
	}

	if(retmonth<=9){
		retmonth="0"+(parseInt(Return.getMonth())+1);
	}

	document.getElementById('depdate').value=depday+"/"+depmonth+"/"+myDepartureYear;
    	document.getElementById('retdate').value=retday+"/"+retmonth+"/"+myReturnYear;

 
} // setDateDropdowns

/*
   Calendar 
 */
function makeArray()    {
    this[0] = makeArray.arguments.length;
    for (i = 0; i<makeArray.arguments.length; i++)
        this[i+1] = makeArray.arguments[i];
}

var daysofmonth   = new makeArray( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var daysofmonthLY = new makeArray( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var monthsofyear  = new makeArray( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);

function LeapYear(year) {
    if ((year/4)   != Math.floor(year/4))   return false;
    if ((year/100) != Math.floor(year/100)) return true;
    if ((year/400) != Math.floor(year/400)) return false;
    return true;
}

function ValidDate(day, month, year) {
  if ( (LeapYear(year) && (day > daysofmonthLY[month])) ||
       (!LeapYear(year) && (day > daysofmonth[month])) ) {
    return false;
  } else {
    return true;
  }
}

function ChosenDate() {

    year =document.getElementById('departureYear').value;
    month =document.getElementById('departureMonth').value ;
    day =document.getElementById('departureDay').value;
    retYear =document.getElementById('returnYear').value;
    retMonth =document.getElementById('returnMonth').value ;
    retDay =document.getElementById('returnDay').value;
    var flag = 1;	
    if (!ValidDate(day-0,month-0,year-0))	{
      flag = 0;
      oDateError.showError(aErrorMessage["invDepDate"]);
      return false;
    } else if (!ValidDate(retDay-0,retMonth-0,retYear-0)) {
      flag = 0;
      oDateError.showError(aErrorMessage["invRetDate"]);
      return false;
    }
    oDateError.hideError();
    return(true);
}

function calender() {
  var myDate=new Date();
  myDate.setFullYear(myDate.getFullYear());
  return myDate.getFullYear();
}


var minYear = parseInt(currentDate.getFullYear());
var fullDate="";
var preventPreviousDate ="";
var preventFutureDate = "";
function displayDatePickerCal(dateFieldName, dateDD, monthDD, yearDD) {
	preventPreviousDate =false;
    preventFutureDate = false;
	//alert("Hello");
	fullDate="1";
	dateDropDown =document.getElementById(dateDD);
  monthDropDown =document.getElementById(monthDD);
  yearDropDown =document.getElementById(yearDD);


	var minDt,maxDt;
	var targetDateField = document.getElementById(dateFieldName);
	if(targetDateField.stDate != "") {
		minDt = targetDateField.stDate
	}
	if(targetDateField.enDate != "") {
		maxDt = targetDateField.enDate
	}
	if(minDt)	{
		var arrMinDt= splitDateString(minDt);
		minDate = arrMinDt[0];
		minMonth= parseInt(arrMinDt[1] - 1);
		minYear = arrMinDt[2];		
		preventPreviousDate = false;
	}
	
	if(maxDt)	{		
		var arrMaxDt =splitDateString(maxDt);
		maxDate = arrMaxDt[0];
		maxMonth= parseInt(arrMaxDt[1] - 1);
		maxYear = arrMaxDt[2];
		preventFutureDate = false;
	}
  


	currentfield = dateFieldName;
	
  var parent = monthDropDown;
  var x = parent.offsetLeft;
	
  var y = parent.offsetTop + parent.offsetHeight;

	
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop;
 }
	
  drawDatePicker(targetDateField, x, y);
}

/********************* STATIC HTML TO BE WRITTEN ********************************/
function displayDatePicker(dateFieldName, dateDD, monthDD, yearDD) {	

preventPreviousDate =true;
    preventFutureDate = true;
  dateDropDown =document.getElementById(dateDD);
  monthDropDown =document.getElementById(monthDD);
  yearDropDown =document.getElementById(yearDD);


	var minDt,maxDt;
	var targetDateField = document.getElementById(dateFieldName);
	if(targetDateField.stDate != "") {
		minDt = targetDateField.stDate
	}
	if(targetDateField.enDate != "") {
		maxDt = targetDateField.enDate
	}
	if(minDt)	{
		var arrMinDt= splitDateString(minDt);
		minDate = arrMinDt[0];
		minMonth= parseInt(arrMinDt[1] - 1);
		minYear = arrMinDt[2];		
		preventPreviousDate = true;
	}
	
	if(maxDt)	{		
		var arrMaxDt =splitDateString(maxDt);
		maxDate = arrMaxDt[0];
		maxMonth= parseInt(arrMaxDt[1] - 1);
		maxYear = arrMaxDt[2];
		preventFutureDate = true;
	}
  


	currentfield = dateFieldName;
	
  var parent = monthDropDown;
  var x = parent.offsetLeft;
	
  var y = parent.offsetTop + parent.offsetHeight;

	
  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop;
 }
	
  drawDatePicker(targetDateField, x, y);
} // displayDatePicker



//function refreshDatePicker(dateFieldName, year, month, day)
function refreshDatePicker(dateFieldName,cDate, cMonth,cYear) {
  var thisDay = new Date();

  if ((cMonth >= 0) && (cYear > 0)) {
    thisDay = new Date(cYear, cMonth, 1);
	  var day = parseInt(cDate);
  } 
 
  // start generating the code for the calendar table
  var html = TABLE;

  html += TR_title;

  if((preventPreviousDate == true) && (thisDay.getMonth() == minMonth) && (thisDay.getFullYear() == minYear)) {
  	html += TD_buttons + "" + xTD;
  } else {
  	html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "/assets/images/cal-prev.gif") + xTD;
  } 
  html += TD_title + monthArrayLong[thisDay.getMonth()] + " " + thisDay.getFullYear()  + xTD;

  if((preventFutureDate == true) && (thisDay.getMonth() == maxMonth) && (thisDay.getFullYear() == maxYear)) {
  	html += TD_buttons + xTD;
  } else {
    // ----------- Modified -------------------
  	html += TD_closecal + getButtonCode(dateFieldName, thisDay, 1,  "/assets/images/cal-next.gif") + xTD;
    // --------------------------------------------------  
  }
  html += xTR;


  // this is the row that indicates which day of the week we're on
  html += TR_days;

  for(i = 0; i < dayArrayShort.length; i++)
  html += TD_days + dayArrayShort[i] + xTD;

  html += xTR;

  // now we'll start populating the table with days of the month
  html += TR;

  // first, the leading blanks
  for (i = 0; i < thisDay.getDay(); i++)
    html += TD_notavail + "" + xTD; 	

	var daySeq;
  // now, the days of the month

  do {
		dayNum = thisDay.getDate();
		dayNum = parseInt(dayNum);
		cMonth = parseInt(cMonth);
		cYear = parseInt(cYear);	
		
		
		daySeq = thisDay.getDay();
		
		checkPastDate(dayNum,cMonth,cYear);		
		checkToday(dayNum,cMonth,cYear);
		checkFutureDate(dayNum,cMonth,cYear)
		
		TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";

		
    if((preventPreviousDate == true) && (preventFutureDate == true)) {
			if((scPastDate == true) && (scToday == true)) {	
				if(daySeq == 0 || daySeq == 6) {			
					html += TD_holiday + dayNum + xTD;
				} else {
				  html += TD_DisToday + dayNum + xTD;
				}
			} else if((scPastDate == true) && (scToday == false))	{	
				if(daySeq == 0 || daySeq == 6) {			
					html += TD_holiday + dayNum + xTD;
				}	else{
				  html += TD_notavail + dayNum + xTD;
				}
			} else if((scPastDate == false) && (scToday == true))	{				
				 if(daySeq == 0 || daySeq == 6) {
					if(allowWeekend)
						html += TD_EnHoliday_today + TD_onclick + dayNum + xTD;
					else
						html += TD_holiday + dayNum + xTD;
				 } else
					html += TD_Today + TD_onclick + dayNum + xTD;
			}	else if((scFutureDate == true) && (scToday == true)) {			
				// html += TD_DisToday + dayNum + xTD;
				if(daySeq == 0 || daySeq == 6) {			
					html += TD_holiday + dayNum + xTD;
				} else {
				  html += TD_DisToday + dayNum + xTD;
				}
			} else if((scFutureDate == true) && (scToday == false))	{			
				//html += TD_notavail + dayNum + xTD;
				if(daySeq == 0 || daySeq == 6) {			
					html += TD_holiday + dayNum + xTD;
				}	else {
				  html += TD_notavail + dayNum + xTD;
				}
			}	else if((scFutureDate == false) && (scToday == true))	{		 
				//html += TD_Today + TD_onclick + dayNum + xTD;
				if(daySeq == 0 || daySeq == 6) {
					if(allowWeekend)
						html += TD_EnHoliday + TD_onclick + dayNum + xTD;
					else
						html += TD_holiday + dayNum + xTD;
				 } else
					html += TD_Today + TD_onclick + dayNum + xTD;
			}	else {
				if(daySeq == 0 || daySeq == 6) {
					if(allowWeekend)
						html += TD_EnHoliday + TD_onclick + dayNum + xTD;
					else
						html += TD_holiday + dayNum + xTD;
				}	else
					html += TD + TD_onclick + dayNum + xTD;
			}	
		} else if((preventPreviousDate == true) && (preventFutureDate == false)) {	
			
			if((scPastDate == true) && (scToday == true))	{	
				if(daySeq == 0 || daySeq == 6) {			
          html += TD_holiday + dayNum + xTD;
        }	else {
          html += TD_DisToday + dayNum + xTD;
        }
      }	else if((scPastDate == true) && (scToday == false))	{	
        if(daySeq == 0 || daySeq == 6) {			
          html += TD_holiday + dayNum + xTD;
        }	else {
          html += TD_notavail + dayNum + xTD;
        }
      } else if((scPastDate == false) && (scToday == true))	{				
         if(daySeq == 0 || daySeq == 6) {
          if(allowWeekend)
            html += TD_EnHoliday + TD_onclick + dayNum + xTD;
          else
            html += TD_holiday + dayNum + xTD;
         } else
          html += TD_Today + TD_onclick + dayNum + xTD;
      }	else {
        if(daySeq == 0 || daySeq == 6) {
          if(allowWeekend)
            html += TD_EnHoliday + TD_onclick + dayNum + xTD;
          else
            html += TD_holiday + dayNum + xTD;
         }
         else
          html += TD + TD_onclick + dayNum + xTD;
      } 	
		} else if((preventPreviousDate == false) && (preventFutureDate == true)) {	
			
			if((scFutureDate == true) && (scToday == true))	{			
				// html += TD_DisToday + dayNum + xTD;
				if(daySeq == 0 || daySeq == 6) {			
					html += TD_holiday + dayNum + xTD;
				}	else{
					html += TD_DisToday + dayNum + xTD;
				}
			} else if((scFutureDate == true) && (scToday == false))	{			
				//html += TD_notavail + dayNum + xTD;
				if(daySeq == 0 || daySeq == 6) {			
					html += TD_holiday + dayNum + xTD;
				}	else {
					html += TD_notavail + dayNum + xTD;
				}
			}	else if((scFutureDate == false) && (scToday == true))	{		 
				//html += TD_Today + TD_onclick + dayNum + xTD;
				if(daySeq == 0 || daySeq == 6) {
					if(allowWeekend)
					  html += TD_EnHoliday + TD_onclick + dayNum + xTD;
					else
					  html += TD_holiday + dayNum + xTD;
				} else
					html += TD_Today + TD_onclick + dayNum + xTD;
			} else {
				if(daySeq == 0 || daySeq == 6) {
					if(allowWeekend)
						html += TD_EnHoliday + TD_onclick + dayNum + xTD;
					else
						html += TD_holiday + dayNum + xTD;
					} else
					  html += TD + TD_onclick + dayNum + xTD;
			}	
		}	else	{	
			if(scToday == true)	{
					html += TD_Today + TD_onclick + dayNum + xTD;
			}	else {
					html += TD + TD_onclick + dayNum + xTD;
			}
		}
		
		// if this is a Saturday, start a new row
		if (thisDay.getDay() == 6)
		  html += xTR + TR;
    
		// increment the day
		thisDay.setDate(thisDay.getDate() + 1);
	
  } while (thisDay.getDate() > 1)

  // fill in any trailing blanks
  if (thisDay.getDay() > 0) {
    for (i = 6; i > thisDay.getDay(); i--)
      html += TD_notavail + "" + xTD;	 
  }
  html += xTR;
 
  // and finally, close the table
  html += xTABLE;

  document.getElementById(datePickerDivID).innerHTML = html;
 } // refreshDatePicker



function checkPastDate(chDate,chMonth,chYear) {	
	minDate = parseInt(minDate);
	minMonth = parseInt(minMonth);
	minYear = parseInt(minYear);

	scPastDate = false;
	var pdate = -2;
	var pmonth = -2;
	var pyear = -2;

	if(chDate < minDate)
		pdate = -1;
	else if(chDate == minDate)
		pdate = 0;
	else
		pdate = 1;

	if(chMonth < minMonth)
		pmonth = -1;
	else if(chMonth == minMonth)
		pmonth = 0;
	else
		pmonth = 1;

	if(chYear < minYear)
		pyear = -1;
	else if(chYear == minYear)
		pyear = 0;
	else
		pyear = 1;

	var cmpString = pdate.toString() + pmonth.toString() + pyear.toString();		
	switch (cmpString) {
		case "-1-1-1":
  		scPastDate = true;
  		break
		case "-1-10":
  		scPastDate = true;
  		break
		case "-10-1":
  		scPastDate = true;
  		break
		case "-100":
  		scPastDate = true;
  		break
		case "-11-1":
  		scPastDate = true;
  		break
		case "0-1-1":
  		scPastDate = true;
  		break
		case "0-10":
  		scPastDate = true;
  		break
		case "00-1":
  		scPastDate = true;
  		break
		case "01-1":
  		scPastDate = true;
  		break
		case "1-1-1":
  		scPastDate = true;
  		break
		case "1-10":
  		scPastDate = true;
  		break
		case "10-1":
  		scPastDate = true;
  		break
		case "11-1":
  		scPastDate = true;
  		break
		default:
  		scPastDate = false;
	}	
	return scPastDate;
} 

function convertToMonth(date){

if(date =="01"){
	monthNumber="Jan";
}
if(date =="02"){
	monthNumber="Feb";
}
if(date =="03"){
	monthNumber="Mar";
}
if(date =="04"){
	monthNumber="Apr";
}
if(date =="05"){
	monthNumber="May";
}
if(date =="06"){
	monthNumber="Jun";
}
if(date =="07"){
	monthNumber="Jul";
}
if(date =="08"){
	monthNumber="Aug";
}
if(date =="09"){
	monthNumber="Sep";
}
if(date =="10"){
	monthNumber="Oct";
}
if(date =="11"){
	monthNumber="Nov";
}
if(date =="12"){
	monthNumber="Dec";
}
return monthNumber;

}
function updateDateField(dateFieldName, dateString) {

  DateArray = new Array();
 
  var targetDateField = document.getElementById(dateFieldName);
  if (dateString)
    targetDateField.value = dateString;

  DateArray = dateString.split("/")
  DateOpt = new Option();
  MonthOpt = new Option();
  YearOpt = new Option();
	
  DateOpt.text = DateArray[0];
  MonthOpt.text = DateArray[1];
  YearOpt.text = DateArray[2];
	if(DateArray[0] < 10){

	DateArray[0]="0"+DateArray[0]; // This is for showing the date in two digits
	}
	if(DateArray[1] < 10){
	DateArray[1]="0"+DateArray[1]; // This is for showing the Month in two digits
	}
  if(field=="1"){

  document.searchForm.depdate.value=DateArray[0]+"/"+DateArray[1]+"/"+DateArray[2];  //new line
  }
  if(field=="2"){
  document.searchForm.retdate.value=DateArray[0]+"/"+DateArray[1]+"/"+DateArray[2];  //new line
  }
  if(field=="3"){
    document.flifoQueryAction.departuredate.value=DateArray[0]+"-"+convertToMonth(DateArray[1])+"-"+DateArray[2];  //new line
  }


  DateOpt.selected = true;
  MonthOpt.selected = true;
  YearOpt.selected = true;

  dateDropDown.selectedIndex = (DateArray[0]-1);
  monthDropDown.selectedIndex = (DateArray[1]-1);
  yearDropDown.selectedIndex = (DateArray[2]-calender());

  document.getElementById(datePickerDivID).style.visibility = "hidden";
  if ((dateString) && (typeof(datePickerClosed) == "function"))
    datePickerClosed(targetDateField);


  try{
		doDateDependentChanges();
	}	catch (err){
		//return false;
	}
} // updateDateField

function changeEnable(){
	document.getElementById('retdate').disabled=false;
	document.getElementById('retlabel').style.color="black"; 
}
function changeDisable(){
	document.getElementById('retdate').disabled=true;
	document.getElementById('retlabel').style.color="gray"; 
}

