// <![CDATA[

// autocomplete code for carsearch.php

carAirportAuto = {};

carAirportAuto.$txt = null;
carAirportAuto.$txt2 = null;
carAirportAuto.$airports = null;
carAirportAuto.$airports2 = null;
carAirportAuto.curIdx = 0;
carAirportAuto.maxr = 10;
carAirportAuto.minQueryLength = 3;
carAirportAuto.f = null;
carAirportAuto.aItems = null;

/*
// $airports2 can be null in this version of the autocomplete, since it's created only if the user checks off
// different drop off point checkbox
var $txt, $txt2, $airports=null, $airports2=null;
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
carAirportAuto.goUp = function () {
	if(carAirportAuto.curIdx > 0)
		carAirportAuto.highlight(--carAirportAuto.curIdx);
}
// move selection down in list
carAirportAuto.goDown = function () {
	if(carAirportAuto.curIdx < carAirportAuto.maxr)
		carAirportAuto.highlight(++carAirportAuto.curIdx);
}

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

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

// clear suggestion list DOM elements
carAirportAuto.clearBoxes = function () {

    carAirportAuto.noshim();

	carAirportAuto.$airports.html("");

    if (carAirportAuto.$airports2)
	    carAirportAuto.$airports2.html("");
}

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

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

carAirportAuto.shimit = function (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);
}

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

    var shimobj = document.getElementById('myif2');
    if (shimobj)    
        shimobj.style.display = 'none';
}

// Setup our suggestion list given the array of aItems
carAirportAuto.populateSuggestionList = function (aItems) {

	carAirportAuto.clearBoxes();

	var expr = carAirportAuto.f ? carAirportAuto.$txt.val() : carAirportAuto.$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:carAirportAuto.selectAirport(" + i + ")' onmouseover='carAirportAuto.highlight(" + i + ",true)'>" + t + "</a>";

			h += "<tr><td nowrap='nowrap'>" + lk + "</td></tr>";
		}



		
		if(carAirportAuto.f) {
            var x = getScreenX(document.searchForm.pickup, document.getElementById("airports").offsetParent)+'px';
            var y = getScreenY(document.searchForm.pickup, document.getElementById("airports").offsetParent)+document.getElementById("pickup").offsetHeight+'px';

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

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

			carAirportAuto.$airports.html(h);

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

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

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

			carAirportAuto.$airports2.html(h);

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

		carAirportAuto.highlight(0);
		
	}
	
};

// request matches from the server, if matches are found
// setup aItems and process our suggestionList
carAirportAuto.startSearch = function (query){
	if(query.length >= carAirportAuto.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((carAirportAuto.f && carAirportAuto.$txt.val() != queriedVal) ||
				 (!carAirportAuto.f && carAirportAuto.$txt2.val() != queriedVal)
				){
				return;
			}

			// now map all our "a" elements to JS objects
			if(data.documentElement.childNodes.length > 0){
				carAirportAuto.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')
					};
					carAirportAuto.aItems.push(thisItem);
				}
				carAirportAuto.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 < carAirportAuto.aItems.length){
						if(previousItem != null && previousItem.c == carAirportAuto.aItems[i].c){
							carAirportAuto.aItems.splice(i, 1);	
						} else {
							previousItem = carAirportAuto.aItems[i];
							i++;
						}
					}
				if(carAirportAuto.aItems.length > carAirportAuto.maxr){
					carAirportAuto.aItems = carAirportAuto.aItems.slice(0, carAirportAuto.maxr);
				}
				carAirportAuto.populateSuggestionList(carAirportAuto.aItems);
				
				fromSet = carAirportAuto.f ? true : fromSet;
				toSet = !carAirportAuto.f ? true : toSet;
			} else {
				fromSet = carAirportAuto.f ? false : fromSet;
				toSet = !carAirportAuto.f ? false : toSet;
				carAirportAuto.clearBoxes();
			}
		});
	} else {
		carAirportAuto.resetSuggestions();
	}
}

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

carAirportAuto.setupTxt1 = function () {
	carAirportAuto.$txt = jQuery("#pickup");
	carAirportAuto.$airports = jQuery("#airports");

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

	carAirportAuto.$txt.keyup(function(e) {
        if (!document.searchForm.airport.checked)
            return;

		carAirportAuto.f = true;

		var k = e.keyCode;

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

			case 38:
				carAirportAuto.goUp();
				break;

			case 13:
				carAirportAuto.selectAirport(carAirportAuto.curIdx);
				break;

			default:
				fromCode = carAirportAuto.$txt.val();
				carAirportAuto.curIdx = null;
				carAirportAuto.startSearch(carAirportAuto.$txt.val());
		}
		e.stopPropagation();
	});
	
	carAirportAuto.$txt.focus(function(e) {
		carAirportAuto.f = true;
        if (carAirportAuto.$airports2)
		    carAirportAuto.$airports2.html("");
	});
	
	carAirportAuto.$txt.blur(function(e) {
		carAirportAuto.selectAirport(carAirportAuto.curIdx);
	});
}

carAirportAuto.setupTxt2 = function () {
	carAirportAuto.$txt2 = jQuery("#dropoff");
	carAirportAuto.$airports2 = jQuery("#airports2");

	carAirportAuto.$txt2.val("");
	carAirportAuto.$txt2.get(0).disabled = false;

	carAirportAuto.$txt2.keyup(function(e) {
        if (!document.searchForm.airport.checked)
            return;

		carAirportAuto.f = false;

		var k = e.keyCode;

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

			case 38:
				carAirportAuto.goUp();
				break;

			case 13:
				carAirportAuto.selectAirport(carAirportAuto.curIdx);
				break;

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




// ]]>

