/*
$Id: AutoCompleteAirport.js 6567 2007-03-28 14:35:11Z mtakag $
*/
var oAutoCompleteFromAirport = oAutoCompleteToAirport = null;
var resultsExists = false;
var fsSubmitFlag = 0;
nogoCharsExp = /[.*+?|(){}[\]\\]/g;

//window.onload = init1;

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

// cache array
var aDB = [];
var aSelected = [];
var airports = new Array();

// AutoComplete constructor

// Initiate objects
function init1() {
if(arguments.callee.done) return;
	arguments.callee.done = true;
	
	//attachMenuHandlers();
 	//if (window.attachEvent) window.attachEvent('onload', sfHover);
	if (window.attachEvent) window.attachEvent();
}


function AutoComplete(sTextboxId, oError) {
  this.name=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() {
	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":
				oThis.hideDropdown();
        break;
		}
	}
	this.createDropdown();
	
	// Re-position dropdown if window is resized
	window.onresize = function()
	{
		if(oThis.menuShown) oThis.positionDropdown();
	}
}

// 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 {
      //alert("mouse");
			oThis.textbox.value = oThis.trim(oTarget.firstChild.nodeValue);      
      document.airportForm.airportCode.value = oTarget.getAttribute("airportCode");
			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 2 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)
{
	if(!this.menuShown) return;

	var iKeyCode = oEvent.keyCode;

	switch(iKeyCode) {
		// Tab
		case 9:
			this.textbox.value = this.dropdownNode.childNodes[this.menuPos].firstChild.nodeValue;
      document.airportForm.airportCode.value=this.dropdownNode.childNodes[this.menuPos].getAttribute("airportCode");
			aSelected.push(this.textbox.value);
      this.hideDropdown();
			break;

		// Return key
		case 13:
			this.textbox.value = this.dropdownNode.childNodes[this.menuPos].firstChild.nodeValue;
			document.airportForm.airportCode.value=this.dropdownNode.childNodes[this.menuPos].getAttribute("airportCode");
			aSelected.push(this.textbox.value);
		
			var oFormElements = this.textbox.form.elements;
		
		if (validateFormA(document.airportForm)==true){
		}document.airportForm.submit()
			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, 3).toLowerCase());
	var aSuggestions = [];

	var regExp = new RegExp("^" + inputStr, "i");
	var bSelected = false;
	
	// If cached restult exists
	if(aDB[sIndex])
	{
		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]))
			{
				bSelected = true;
			}
		}
		
		// If any hits
		if(aSuggestions.length)
		{
			this.errorHandler.hideError();
			this.showDropdown(this.removeDuplicates(aSuggestions));
	//		this.showDropdown(aSuggestions);
		}
		else if(!bSelected)
		{
			this.displayError();
		}
	}
	else
	{
		var curlang = document.getElementById("currentLanguage").value;
		var sLanguage = (location.search)? "&language=en":"";
		aDB[sIndex] = -1;
		//var ajaxURL ="/dynamicSearchWizard.do?language=" + curlang + "&page=destinations&inputString=";
		HttpClient.get(ajaxURLAirport +  sIndex + sLanguage, function(oRequest)
		{
			eval(oRequest);
			oThis.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;
}

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

// 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);
	}

	// not sure if this is the way to go
	this.highlightSuggestion(this.dropdownNode.firstChild);
	this.dropdownNode.style.display = "block";
  ajaxDropDownIsOpen=true;
}

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

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";
}

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

	//sSuggestion = aSuggestion[4] + ((!aSuggestion[2] && !aSuggestion[3])? ", ":" ") + ((aSuggestion[2])? aSuggestion[2] + ", ":"") + ((aSuggestion[3])? aSuggestion[3] + ", ":"") + aSuggestion[5];
	sSuggestion = aSuggestion[4]+" ["+aSuggestion[1]+"]"+", "+aSuggestion[5];
	return sSuggestion;
}

// 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 = "";
	}
}

// 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;
}

// 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;
}

// 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;
}

function validateFormAirport(formName){
	//alert("I am in validate form!!!");
	
		var fromairport=document.airportForm.FromAirport.value;
  var start=fromairport.indexOf('[');
  var end=fromairport.indexOf(']');
  var airCode=fromairport.substring(start+1,end);
  //alert(airCode);
  document.airportForm.airportCode.value=airCode;
  //alert("This is the airportCodevalue"+document.getElementById('airportCode').value);
	
  if(!document.airportForm.FromAirport.value){
		//alert("i am in Error form");
		oAutoCompleteFromAirport.errorHandler.showError(aErrorMessageAirport["noOrigin"]);
		return false;
	}
	if(oAutoCompleteFromAirport.errorHandler.error || oAutoCompleteFromAirport.errorHandler.error){
		//alert("wrong code");
		return false;
	}
	else{
		//alert("True");
		submitAirportInformation();
		document.airportForm.submit();
  
    }
}

function loadAirportSelector(){
	var currLang = document.getElementById("currentLanguage").value;
	//alert(currLang);
 	var airportSelector = document.getElementById("airport")
 	var countrySelector = document.getElementById("country")
	var waitText = "<option>"+loadingAirlinesText+"</option>";
  	var selectedCountry = getSelected(countrySelector);
	if (selectedCountry=="null"){return;}
 		 airportSelector.innerHTML=waitText;
		//alert("Fine");
		 airportSelectorURL="/destination_overview1.do?language=" + currLang + "&method=fetchAirports";
		//alert(airportSelectorURL);
	
		 HttpClient.get(airportSelectorURL + "&country=" + getSelected(countrySelector), function(oRequest){
		//alert("fine2");
		 eval(oRequest);
    		 populateSelector(airportSelector);
		
  	});
}

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

function populateSelector(sel){
  // Clear the selector before populating it
  for (var i=0;i<sel.options.length ;i++){
    sel.options[i]=null;
  }
    //sel.options[0]=(new Option(chooseAirportText,"null"));
  for (var i=0;i<airports.length ;i++){
    sel.options[i+1]=(new Option(airports[i][1],airports[i][0]));
	
  }
}
