// airportPop object
// --------------------------------------------------------------------------------
// contains variables and functions for airports and carriers popup
//
var airportPop = {};  
airportPop.curPos = {}; 
airportPop.tripType = "RT";
airportPop.countryList = function(){
	var txt;
	txt = airportPop.curPos.innerHTML;
	txt = txt.substring(0, txt.indexOf(" "));
 	airportsInPlace(txt);
}
airportPop.positionPopup = function(idName){
	x = findPosX(id(idName));
	y = findPosY(id(idName));
	id("dapopup").style.top = y+"px";
	id("dapopup").style.left = x+"px";
	id("dapopup").style.visibility="visible";  
	id("dapopup").style.display="block";  
}
airportPop.drawOnMap = 1;

// airportCompleter()
// --------------------------------------------------------------------------------
// calls startAirports function that displays airport list
//
function airportCompleter(inputControl, evt) {

	evt = evt ? evt : (event ? event : null);
	if (evt) {
		// Ignore keys that dont factor in to the text entry
		var key = evt.charCode ? evt.charCode : evt.keyCode;
		 
		if ( (key!=8 && key < 32) || (key >= 33 && key <= 46) || (key >= 112 && key <= 123))
		  return;
		// Store away the current input
		currentFlight = inputControl.id;
		if(inputControl.value.length>2){
			// MK: we need to see if this is departure box, then add country code to show more relevant airports first
			var srch= inputControl.value;
			if(inputControl.name == 'deptPlace1' && airportPop.drawOnMap  ){
				srch = srch+'&originCountryCode='+document.getElementById('originCountryCode').value;
			}
			startAirports(srch, inputControl.id);
		}
	}  
	
}

// airportCompleter()
// --------------------------------------------------------------------------------
// calls startAirlines function that displays airlines list
//
function airlineCompleter(inputControl, evt) {
	
	evt = evt ? evt : (event ? event : null);
	
	if(id("pCarrier").value==""){
		id("pCarrierhidden").value="";
	}
	
	if (evt) {
	// Ignore keys that dont factor in to the text entry
	var key = evt.charCode ? evt.charCode : evt.keyCode;
	
	if (key < 32 || (key >= 33 && key <= 46) ||
	 (key >= 112 && key <= 123))
	  return;
	
	var acceptableValues = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ';
	
	var clearRequest = false;
	
	for (i = 0; i < inputControl.value.length; i++ )
	{	
		if (acceptableValues.indexOf(inputControl.value.charAt(i)) == -1)
		{
			clearRequest = true;
		}
	}
	
	if(clearRequest){
		inputControl.value = inputControl.value.replace(inputControl.value,'');	
	}
	
	// Store away the current input
	currentFlight = inputControl.id;
	if(inputControl.value.length>1) 
		startAirlines(inputControl.value, inputControl.id);
	}   
}

// cityChosen()
// --------------------------------------------------------------------------------
// closes the popup list of items, which is airline or airport list
//
function cityChosen(div){    
 	var airportStr = id(div).innerHTML;
	var airportCodeStr = div;
	id(currentFlight).value=airportStr;
	id(currentFlight+"hidden").value=airportCodeStr;
	listOff();
	if(airportPop.drawOnMap === 1){
		if(Number(siteId)<11){
			drawSearchOnMap(); 
		}
	}
	 
} 
 
// airportsInPlace()
// --------------------------------------------------------------------------------
// ajax call to the list of airports in a country, or, on an island
// 
function airportsInPlace(areaName)
{   
	if(id(areaName).style.display=="block"){
		id(areaName).style.display = "none"; 
	}
	else{
		LoadAjaxContent(areaName, '/modules/findAFlight/airportsForCountryList.jsp', 'countryName=' + areaName);
		id(areaName).style.display = "block";
	}
}

// startAirports()
// --------------------------------------------------------------------------------
// ajax call to the list of airports, airport name is the argument
// 
function startAirports(query, idName) {   
	currentFlight = idName;
	args = "search="+query;   
	LoadAjaxCallFunction('/modules/findAFlight/airportCompletorList.jsp', args, listResult);
	airportPop.positionPopup(idName);
}

// startAirlines()
// --------------------------------------------------------------------------------
// ajax call to the list of airports, airline name is the argument
// 
function startAirlines(query, idName) {   
	currentFlight = idName;
	args = "search="+query;   
	LoadAjaxCallFunction('/modules/findAFlight/airlineCompletorList.jsp', args, listResult);
	airportPop.positionPopup(idName); 
	
}

// startAirlines()
// --------------------------------------------------------------------------------
// ajax response function, lists the airlines or airports, and adds key up, or key down functionality to this list.
// 
function listResult(args){ 
	id("dapopup").innerHTML = args;
	
	// Get all the user li elements
	var li = id("dapopup").getElementsByTagName("li"); 
	id(currentFlight).onkeydown = function(e){  
		var keycode = (window.event) ? window.event.keyCode : e.keyCode;  
	
		var txt;
		
		if ( keycode == 9 || keycode == 13 ) { // if [TAB] or [Enter] keys are pressed Add the user to the text entry field 
			txt = airportPop.curPos.innerHTML;
			if(txt){
				txt = txt.substring(txt.indexOf("(")+2, txt.indexOf(")")-1); 
				if(txt.length==3 || txt.length==2) cityChosen(txt);   //if airport or airline chosen close popup and  update input values
				else{
					airportPop.countryList();
				}
			} else {
					var popup =  id("dapopup"),
					liList = popup.getElementsByTagName("li"),
					length = liList.length,
					txt = "", 
					cityCode = "", 
					cityName = "";
				
				if( popup.style.display === "block" ) {
					
					if( length>0 ) {
						txt = liList[0].innerHTML;  
						/cityChosen\(\'(.*)\'\)/.test(txt)
						cityCode = RegExp.$1;
						cityChosen(cityCode); 
					} else {
						id(currentFlight).value = "";
						id(currentFlight+"hidden").value = "";
						id("dapopup").style.display="none";
					}
						
				}
			}
		} 		
		else if ( keycode == 38 ){	// if up key pressed, select the previous list item, or the last one (if we're at the beginning)
			//alert(airportPop.curPos.previousObject().className);
			//var test = prevOne(airportPop.curPos);
			//alert(test.className);
			if(window.event){return updatePos( airportPop.curPos.previousSibling || li[ li.length - 1 ] );}
			else {return updatePos( prevOne(airportPop.curPos) || li[ li.length - 1 ] );}
		}
		else if ( keycode == 40 ){	// If the down key is pressed select the next item, or the first one (if we're at the end)
			if(window.event){return updatePos(airportPop.curPos.nextSibling || li[0] );}
			else{return updatePos( nextOne(airportPop.curPos) || li[0] );} 
		}
		else if(keycode == 39 && currentFlight != "pCarrier") {  //If right key pressed, switch functionality to countries  
			airportPop.countryList();
		}
		
	};
	if (!window.XMLHttpRequest) {setUniversalPopupCover("dapopup");}
}

// updatePos()
// --------------------------------------------------------------------------------
// helper function for the up and down keys
// 
function updatePos( elem ) {  
	// Update the position to the currently selected element
	airportPop.curPos = elem; 
	airportPop.curPos.scrollIntoView(false);
	// Get all the user li elements
	var li = id("dapopup").getElementsByTagName("li");  
	// Remove the 'current' class from the currently selected one
	for ( var i = 0; i < li.length; i++ )
		removeClass( li[i], "current" );
	
	// And add the hilite to the current user item
	addClass( airportPop.curPos, "current" );
	
	return false;
}

// addClass()
// --------------------------------------------------------------------------------
// adds a class to an element
// 
function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

// removeClass()
// --------------------------------------------------------------------------------
// removes a class from an element
// 
function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}
function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));

}

 // nextOne()
// --------------------------------------------------------------------------------
// adding functionality for proper nextSibling function, firefox fix
//

function nextOne(obj){
	var n = obj;
	do n = n.nextSibling;
	while (n && n.nodeType != 1);
	
	if(typeof(n!="undefined"))	return n;
	else return false;
}

// prevOne()
// --------------------------------------------------------------------------------
// adding functionality for proper previousSibling function, firefox fix
//
 
function prevOne(obj){
	var p = obj;
	do p = p.previousSibling;
	while (p && p.nodeType != 1);
	return p;
}



// listOff()
// --------------------------------------------------------------------------------
// close airport, or airline list popup 
//
function listOff(){ 
	id('dapopup').style.display="none";  
	if(navigator.appName == "Microsoft Internet Explorer"){
		id('dapopupCover').style.display="none";
	}
}

// delayedListOff()
// --------------------------------------------------------------------------------
// delay the popup closing, utilizing closure method
//
function delayedListOff() {
	var time = 600;
	// Initialize an enclosed callback
	setTimeout(function(){
		// Which utilizes the time variable and flag variable two passed in from the enclosing function
		listOff();
	}, time );
}

function countryCompleter(inputControl, evt) {

	evt = evt ? evt : (event ? event : null);
	if (evt) {
		// Ignore keys that dont factor in to the text entry
		var key = evt.charCode ? evt.charCode : evt.keyCode;
		if (key < 32 || (key >= 33 && key <= 46) ||
		 (key >= 112 && key <= 123))
		  return;
		// Store away the current input
		currentFlight = inputControl.id;
		if(inputControl.value.length>1){
			// MK: we need to see if this is defarture box, then add country code to show more relevant airports first
			var srch= inputControl.value;
			if(inputControl.name == 'deptPlace1'){
				srch = srch+'&originCountryCode='+document.getElementById('originCountryCode').value;
			}
			startCountries(srch, inputControl.id);
		}
	}  
	
}

// startCountries()
// --------------------------------------------------------------------------------
// ajax call to the list of countries
// 
function startCountries(query, idName) { 

	currentFlight = idName;
	args = "search="+query;   
	LoadAjaxCallFunction('/modules/findAFlight/countryCompletor.jsp', args, listResultCountries);
	airportPop.positionPopup(idName);
}

function countryChosen(div){ 
 	
 	div = trim(div);
 	var divArray = div.split('***');
 	
	id(currentFlight).value=divArray[0];
	id(currentFlight+"hidden").value=divArray[1];
	
	listOff();
	
	//drawSearchOnMap(); 
}

function listResultCountries(args){ 
	
	id("dapopup").innerHTML = args;
	 
	// Get all the user li elements
	var li = id("dapopup").getElementsByTagName("li"); 
	
	id(currentFlight).onkeydown = function(e){  
		
		var ev = (window.event) ? window.event : e; 
		var keycode = ev.keyCode;
	
		var txt;
		
		if ( keycode == 9 || keycode == 13 ) { // if [TAB] or [Enter] keys are pressed Add the user to the text entry field 
			
			txt = airportPop.curPos.innerHTML;
			
			if(txt){
				txt = txt.substring(txt.indexOf("(")+2, txt.indexOf(")")-1); 
				countryChosen(txt);
			}
			else{
				id(currentFlight).value="";
			}
		
		}else{ 		
		
			if ( keycode == 38 ){	// if up key pressed, select the previous list item, or the last one (if we're at the beginning)

				if(window.event){
					return updatePosCountries( airportPop.curPos.previousSibling || li[ li.length - 1 ] );
				}else {
					return updatePosCountries( prevOne(airportPop.curPos) || li[ li.length - 1 ] );
				}
			}
			else if ( keycode == 40 ){	// If the down key is pressed select the next item, or the first one (if we're at the end)
				if(window.event){
					return updatePosCountries(airportPop.curPos.nextSibling || li[0] );
				}else{
					return updatePosCountries( nextOne(airportPop.curPos) || li[0] );
				} 
			}
	
		}
		
	};
	
	if (!window.XMLHttpRequest) {setUniversalPopupCover("dapopup");}
}

function updatePosCountries( elem ) {  
	// Update the position to the currently selected element
	airportPop.curPos = elem; 
	//airportPop.curPos.scrollIntoView(false);
	// Get all the user li elements
	var li = id("dapopup").getElementsByTagName("li");  
	// Remove the 'current' class from the currently selected one
	for ( var i = 0; i < li.length; i++ )
		removeClass( li[i], "current" );
	
	// And add the hilite to the current user item

	addClass( airportPop.curPos, "current" );
	
	return false;
}
function checkIfPartial(e){ 
	var evt = (window.event) ? window.event : e,
	    target = (typeof evt.target !== 'undefined') ? evt.target : evt.srcElement, 
		hiddenEl = document.getElementById(target.id+"hidden"),
		val = target.value;
	
	if ( !( /\([A-Z]{3}\)/.test(val)) ) { 	  
		if ( val.length>2 ) { 
	 
			var txt = document.getElementById("dapopup").getElementsByTagName("li")[0].innerHTML;
				cityName =  txt.match(/>(.*)</)[1]; 
	 
			if(txt){
				cityCode = txt.substring(txt.indexOf("(")+2, txt.indexOf(")")-1); 
				target.value = cityName;
				hiddenEl.value = cityCode;
			} else {
            	target.value = "";
				hiddenEl.value = "";
            }
			
		}  else {
			target.value = "";
			hiddenEl.value = "";
		}
	}
}
