// <![CDATA[

// autocomplete code for flightsearch.php

var $txt, $txt2, $airports, $airports2;
var to;

// Index of our currently selected/active autocomplete entry
var curIdx = 0;
// 	Max number of rows of suggestions
var maxr = 10;
var minQueryLength = 3;
//var rs;
// 	Select "From" airport active, false implies airport 2
var f = null;
//	The suggestions array we will be showing
//	Should be setup in our ajax callback, and sorted
// 	then will be used by populateSuggestionList
var aItems;

// Our final output variables
// should be set upon a sucessful selection of 
// a suggestion, or if a suggestion is not selected to whatever
// is in the input box upon loss of focus
var fromCode = "";
var toCode = "";

// tracks if our codes have been set using autocomplete since the last
// autocomplete request for that field -- if this is false when the 
// respective input is deselected we need to use the input value
// as the code
var fromSet = false;
var toSet = false;

// move selection up in list
function goUp() {
	var s = f ? "" : "2";

	if(curIdx > 0)
		highlight(--curIdx);
}
// move selection down in list
function goDown() {
	var s = f ? "" : "2";

	if(curIdx < maxr)
		highlight(++curIdx);
}

// update DOM to change visible selection, update curIdx to point to the
// correct entry in aItems
function highlight(idx) {
	var s = f ? "" : "2";

	$lk = jQuery("#airports" + s + " a:eq(" + idx + ")");
	jQuery("#airports" + s + " a").removeClass("hlk");
	$lk.addClass("hlk");
	curIdx = $lk.get(0).id;
}

// clear suggestion list DOM elements
function clearBoxes() {

    noshim();

	$airports.html("");
	$airports2.html("");
}

// select an airport from our suggestion list at index
function selectAirport(index){

	if( (aItems != null && aItems.length > 0) ){
		var code = aItems[index].c;
		if(f){
			$txt.val(aItems[index].n + " - " + aItems[index].an + " (" + aItems[index].c + ")");
			fromCode = code;
			fromSet = true;
		} else {
			$txt2.val(aItems[index].n + " - " + aItems[index].an + " (" + aItems[index].c + ")");
			toCode = code;
			toSet = true;
		}
		resetSuggestions();
	} else {
	/*
		if(f){
			if(!fromSet) fromCode = $txt.val();
		} else {
			if(!toSet) toCode = $txt2.val();
		}
	*/
		resetSuggestions();
	}
}
// reset suggestion script state
function resetSuggestions(){
	clearBoxes();
	//f = null;
	aItems = null;
	curIdx = null;
}

function shimit(obj,table,theIf) {

var shimobj=theIf.style;
shimobj.height=table.offsetHeight+'px';
shimobj.width=table.offsetWidth+'px';
shimobj.left=obj.offsetLeft+'px';
shimobj.top=obj.offsetTop+'px';
shimobj.zIndex='1';
shimobj.display='block';
//alert(shimobj.height + ' ' + shimobj.width + ' ' + shimobj.left + ' ' + shimobj.top);
}

function noshim() {
    var shimobj = document.getElementById('myif').style;
    shimobj.display = 'none';
    var shimobj = document.getElementById('myif2').style;
    shimobj.display = 'none';
}

// Setup our suggestion list given the array of aItems
function populateSuggestionList(aItems) {
	clearBoxes();

	var expr = f ? $txt.val() : $txt2.val();
	h = "" ;
	
	if(aItems.length) {
		for(var i=0; i< aItems.length; i++) {
			var item = aItems[i];
			
			var c = item.c;
			var n = item.n;
			var an = item.an;
			
		  var matchStr = new RegExp("^(" + expr + ")", "i");		
		  
			var hc = c.replace(matchStr, "<span class='hc'>$1</span>");
			var hn = n.replace(matchStr, "<span class='hn'>$1</span>");
			var han = an.replace(matchStr, "<span class='hn'>$1</span>");;

			t = hn + " - " + han + " (" + hc + ")";

			lk = "<a class='lk' id='" + i + "' href='javascript:void(0)' onclick='javascript:selectAirport(" + i + ")' onmouseover='highlight(" + i + ",true)'>" + t + "</a>";

			h += "<tr><td nowrap='nowrap'>" + lk + "</td></tr>";
		}
		
		if(f) {
            var x = getScreenX(document.searchForm.from, document.getElementById("airports").offsetParent)+'px';
            var y = getScreenY(document.searchForm.from, document.getElementById("airports").offsetParent)+document.getElementById("from").offsetHeight+'px';

            document.getElementById('airports').style.left = x;
            document.getElementById('airports').style.top = y;

		    h = "<table id='airportsTable'>" + h + "</table>";

			$airports.html(h);

            shimit(document.getElementById('airports'), 
                   document.getElementById('airportsTable'),
                   document.getElementById('myif'));
        }
		else {
            var x = getScreenX(document.searchForm.to, document.getElementById("airports2").offsetParent)+'px';
            var y = getScreenY(document.searchForm.to, document.getElementById("airports2").offsetParent)+document.getElementById("to").offsetHeight+'px';

            document.getElementById('airports2').style.left = x;
            document.getElementById('airports2').style.top = y;

		    h = "<table id='airports2Table'>" + h + "</table>";

			$airports2.html(h);

            shimit(document.getElementById('airports2'), 
                   document.getElementById('airports2Table'),
                   document.getElementById('myif2'));
		}

		highlight(0);
		
	}
	
};

// request matches from the server, if matches are found
// setup aItems and process our suggestionList
function startSearch(query){
	if(query.length >= minQueryLength){
		query = query.replace(/ /, "%20");
		var queryStr = "auto/gz.php?q="+query;
		jQuery.get("auto/gz.php?q="+query, function(data){
			// first verify that the result we're processing still
			// applies to what has been input

			queriedVal = data.documentElement.getAttribute('q');
			if((f && $txt.val() != queriedVal) ||
				 (!f && $txt2.val() != queriedVal)
				){
				return;
			}

			// now map all our "a" elements to JS objects
			if(data.documentElement.childNodes.length > 0){
				aItems = new Array();
				var z = 0;
				for(i=0; i<data.documentElement.childNodes.length; i++){
					var a = data.documentElement.childNodes.item(i);
					z++;
					var thisItem = {
						'c' :  a.getAttribute('c'),
						'n' :  a.getAttribute('n'),
						'an' : a.getAttribute('an'),
						'p' :  a.getAttribute('p')
					};
					aItems.push(thisItem);
				}
				aItems.sort(function (a, b) {
						var pLess = b.p - a.p;
						var anLess = a.an < b.an;
						if(pLess != 0){
							return pLess;
						} else {
							return (anLess) ?  -1 : 1;
						}
					});
					var previousItem = null;
					var i=0;
					while(i < aItems.length){
						if(previousItem != null && previousItem.c == aItems[i].c){
							aItems.splice(i, 1);	
						} else {
							previousItem = aItems[i];
							i++;
						}
					}
				if(aItems.length > maxr){
					aItems = aItems.slice(0, maxr);
				}
				populateSuggestionList(aItems);
				
				fromSet = f ? true : fromSet;
				toSet = !f ? true : toSet;
			} else {
				fromSet = f ? false : fromSet;
				toSet = !f ? false : toSet;
				clearBoxes();
			}
		});
	} else {
		resetSuggestions();
	}
}

function showMessage(isfrom) {
	var s, nm, pos;
	if(isfrom) {
		s = "origin";
		nm = $txt.val();
		pos = 1;
		$ap = $airports;
	}
	else {
		s = "destination";
		nm = $txt2.val();
		pos = 0;
		$ap = $airports2;
	}
	nm = " '" + nm + "'";
	var msg = "Unrecognized " + s + " airport. Please check and reenter.";
	$ap.html("<table><tr><td class='error'>" + msg + "</td></tr></table>");
}

// setup event handlers
jQuery(document).ready(function() {

	$txt = jQuery("#from");
	$txt2 = jQuery("#to");
	$airports = jQuery("#airports");
	$airports2 = jQuery("#airports2");

	$airports.html("");
	$txt.val("");
	$txt2.val("");
	$txt.get(0).disabled = false;
	$txt2.get(0).disabled = false;

	$txt.keyup(function(e) {
		f = true;

		var k = e.keyCode;

		switch(k) {
			case 40:
				goDown();
				break;

			case 38:
				goUp();
				break;

			case 13:
				selectAirport(curIdx);
				break;

			default:
				fromCode = $txt.val();
				curIdx = null;
				startSearch($txt.val());
		}
		e.stopPropagation();
	});
	$txt2.keyup(function(e) {
		f = false;

		var k = e.keyCode;

		switch(k) {
			case 40:
				goDown();
				break;

			case 38:
				goUp();
				break;

			case 13:
				selectAirport(curIdx);
				break;

			default:
				toCode = $txt2.val();
				curIdx = null;
				startSearch($txt2.val());
		}
		e.stopPropagation();
	});
	
	$txt.focus(function(e) {
		f = true;
		$airports2.html("");
	});
	
	$txt2.focus(function(e) {
		f = false;
		$airports.html("");
	});
	
	$txt.blur(function(e) {
		selectAirport(curIdx);
	});
	$txt2.blur(function(e) {
		selectAirport(curIdx);
	});

});






// ]]>
