//window.onload = loadIndex;

//globals
//var msg = 'Enter city name...';
var msg = '';
var tempIDArrayFrom = new Array();
var tempIDArrayTo = new Array();

function loadIndex() {
	// most current browsers support document.implementation
//	if (document.implementation && document.implementation.createDocument) {
//		xmlDoc = document.implementation.createDocument("", "", null);
//		//alert('F '+xmlDoc);
//	}
	// MSIE uses ActiveX
//	else if (window.ActiveXObject) {
//		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
//		//alert('ie '+xmlDoc);
//	}
	//download xml file
	//xmlDoc.async = "false";
	//load xml
	//xmlDoc.load("./html_forms/airports.xml");
	//xmlDoc.load("./App_Data/airports.xml");
}

//trim text [rTrim & lTrim]
function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function searchXML( xDiv , control , mainFormOrNot ) {
/*	if (!xmlDoc) {
		loadIndex();
	}*/
	
	//disable loading icon if it's present
	var mm = control + "_nearby";
	if( $(mm).className == 'show' ) sLoading( mm , 2 );
	
	//get usr entered value
	var inputVal = document.getElementById(control).value;
	//all input letters r upper cased
	//document.getElementById(control).value.toUpperCase();
	//trim and upperCase it
	var inputValToUpper = trim(inputVal.toUpperCase());
	//alert(inputValToUpper);
	//the div
	var div_ = document.getElementById(xDiv);
	//load all airport nodes from the xml
	var allitems = xmlDoc.getElementsByTagName("airport");
	
	//hide the nearby
	document.getElementById( control + '_nearby' ).className = 'hide';
		
	//reset variables and counters
	var counter = 0;
	var colorID = 0;
	var results = 0;
	
	//empty the div b4 load any new data inside it
	div_.innerHTML = '';
	//show the results div if it's hidden
	div_.style.display = 'block';
	
	//if usr enters a value, make search
	if( inputVal != '' ){
		//alert(allitems.length);
		//v.1, search all airport codes <airport code="XXX">	
		//v.2, search all airport city names <city>XXX</city>
		for (i=0;i<allitems.length;i++) {
			
			//get code attribute for each airport in the xml
			//attributes now r not searched, instead, we use it to display the airport attributes in the div
			var attr = allitems[i].getAttribute('code');
			//[new feature] get city name to search with
			var cityName = xmlDoc.getElementsByTagName("city")[i].childNodes[0].nodeValue;
			//trim and upperCase it
			attrTrimmedAndToUpper = trim(attr.toUpperCase());
			cityNameTrimmedAndToUpper = trim(cityName.toUpperCase());
			
			//only 10 results displayed
			if( results == 10 ) break;
			
			//search values started with the entered value
			if( ( cityNameTrimmedAndToUpper.indexOf( inputValToUpper , 0 ) != -1 )
				&& 
			    ( cityNameTrimmedAndToUpper.indexOf( inputValToUpper , 0 ) == 0 ) )
			{
			
				//color select [experimental]
				color = '';
				/*if( colorID == 0 ){
					color = '#DDFEE4';
					colorID++;
				}else{
					color = '#DDFEE4';
					colorID--;
				}*/
				
				//change class to green
				div_.className = 'ac';
			
				//airport code
				code = attrTrimmedAndToUpper;
				//airport desc
				content_ = xmlDoc.getElementsByTagName("city")[i].childNodes[0].nodeValue;
				//IE6 fix, hide select menu
				selectList('none');
				//write new airport entry
				writeDivContent( xDiv , i , color , control , code , content_ );
    
				//this is to know if there's any results found
				counter++;
				//just 10 results counter
				results++;
				
			}
        
		}	
			
			//handleKeyword( event.keyCode , xDiv , control );
			//alert(event.keyCode);
		
		//if no results, display this msg
		if( counter == 0 ){
		
			//change class to red
			div_.className = 'ae';
			div_.innerHTML = 'No airports...';
			
		}else{
		
            //commit advanced search only if suggest is built on the main form
            if(! mainFormOrNot ){
                document.getElementById( xDiv ).innerHTML += '<img src="./html_forms/images/1x1.gif" width="100%" height="1" />';
                document.getElementById( xDiv ).innerHTML += '<div id="srch_" style="padding:5px 0; cursor:pointer;" onmouseover="over(this.id);" onmouseout="out(this.id);" onclick="openAdvancedSearch(this.parentNode.id);">&nbsp;<img src="./html_forms/images/search.gif" width="17" height="12" />&nbsp;Extended Search</div>';
                
            }
            
		}
		
	}else{
		//change class to green
		div_.className = 'ac';
		//if nothing is entered in the textbox, display this msg
		//div_.innerHTML = msg;
	}
}

function writeDivContent( oDiv , i , color , control , code , content ){

	var div_ = document.getElementById( oDiv );
	//change class to green
	div_.className = 'ac';
	
	//set overflow
	//div_.style.overflow = 'visible';
	
	//write new entry in the results div
	div_.innerHTML += "<div id='x"+oDiv+i+"' onmouseover='over(this.id);' onmouseout='out(this.id);' style='background-color: " + color + "; width: 100%; cursor: pointer; height: 20px;' onclick=setValue("+i+",'"+oDiv+"','"+control+"')>" + content.slice(0,15) + " - [<span id='sx"+oDiv+i+"'>" + code + "</span>] " + "</div>";
	//alert(i);
//window.onkeydown = function(event){

//alert(event.keyCode);
//handleKeyword( event.keyCode , oDiv , control , i );
//}

//alert('---x'+oDiv+i);	

}
//////////////////////////////////////////////////////////////////////////////////////////////////
//used in homepage
var f1 , f2 , f3 , f4 , f5 , f6;
var t1 , t2 , t3 , t4 , t5 , t6;
function setValue( id , oDiv , control , as , lat , lon ){//alert(lat);alert(lon);

	selectedValue = document.getElementById( "sx" + oDiv + id ).innerHTML;
	document.getElementById( control ).value = selectedValue;
	document.getElementById(oDiv).style.display = 'none';
	
	if(! as ){//put this if we r not in advanced search
	
	    //IE6 fix, show select menu
	    //selectList_('inline');
	    //write the nearby
	    var nearby = document.getElementById( control + '_nearby' );
	    nearby.className = 'show';
	    //reset to 0, we r not in adv. search
	    document.getElementById( control + '_as' ).value = 0;
	    
	    //save lon,lat and other data in temp arrays
	    saveToTempArray( id , oDiv );
	    
	    //set textbox flags to 1
	    //alert(document.getElementById( control + '_suggest' ).value);
	    document.getElementById( control + '_suggest' ).value = 1;
	    //alert(document.getElementById( control + '_suggest' ).value);
	    
	    //oneLeg_roundTrip.push( lat , lon );
	    
	    //get lon/lat for every selected value to draw the map for one-leg && round-trip
	    if( oDiv.indexOf('from_one_leg') != -1 ){//from one leg
	        f1 = lat;
	        t1 = lon;
	    }else if( oDiv.indexOf('to_one_leg') != -1 ){//to one leg
	        f2 = lat;
	        t2 = lon;
	    }else if( oDiv.indexOf('from_round_trip') != -1 ){//from round trip
	        f3 = lat;
	        t3 = lon;
	    }else if( oDiv.indexOf('to_round_trip') != -1 ){//to round trip
	        f4 = lat;
	        t4 = lon;
	    }else if( oDiv.indexOf('from1') != -1 ){//from multi leg
	        f5 = lat;
	        t5 = lon;
	    }else if( oDiv.indexOf('to1') != -1 ){//to multi leg
	        f6 = lat;
	        t6 = lon;
	    }
	    
	    //write contents to tooltip
	    temp_ = new Array();
	    temp_[0] = response.airports[id].airport.code;
        temp_[1] = response.airports[id].airport.city;
        temp_[2] = response.airports[id].airport.country;
        //alert(control);
        if( control.indexOf('from_one_leg') > -1)
	        $("fixedtipdiv1").innerHTML = temp_[0] + ', ' + temp_[1] + '<br />' + temp_[2];
	    else if( control.indexOf('to_one_leg') > -1)
	        $("fixedtipdiv2").innerHTML = temp_[0] + ', ' + temp_[1] + '<br />' + temp_[2];
	    else if( control.indexOf('from_round_trip') > -1)
	        $("fixedtipdiv3").innerHTML = temp_[0] + ', ' + temp_[1] + '<br />' + temp_[2];
	    else if( control.indexOf('to_round_trip') > -1)
	        $("fixedtipdiv4").innerHTML = temp_[0] + ', ' + temp_[1] + '<br />' + temp_[2];
	    else if( control.indexOf('from1') > -1)
	        $("fixedtipdiv5").innerHTML = temp_[0] + ', ' + temp_[1] + '<br />' + temp_[2];
	    else if( control.indexOf('to1') > -1)
	        $("fixedtipdiv6").innerHTML = temp_[0] + ', ' + temp_[1] + '<br />' + temp_[2];
	    
	}else{//we r n advanced search
	
	    //enable btn
        //document.getElementById( 'asrch' ).disabled = false;
        
        //save the id of the selected value from the suggest [hidden field {index.html}]
        //TRUNCATED :: COZ WE JUST USE THE DATA FROM THE TEMP ARRAY
	    //var assi = document.getElementById( 'asearch_selected_id' );
	    //assi.value = id;
	    //alert(assi.value);
        
	}
	
}
//////////////////////////////////////////////////////////////////////////////////////////////////
function saveToTempArray( id , div ){//alert(id);alert(div);
    //save the JSON ids to call them l8r by this id to get lon , lat...
    //take only last 2
    //alert(div.indexOf('from'));
    //alert(div.indexOf('CalcCode2'));
    if(div.indexOf('from')==0 || div.indexOf('CalcCode1')>0 ){//home,aircraft,airport catalog
        //alert('From');
        //alert(response.airports[id].airport.code);
        //tempIDArrayFrom[0] = new Array( response.airports[id].airport.code , response.airports[id].airport.lon , response.airports[id].airport.lat , response.airports[id].airport.city , response.airports[id].airport.country , response.airports[id].airport.desc );
        tempIDArrayFrom[0] = response.airports[id].airport.code;
        tempIDArrayFrom[1] = response.airports[id].airport.lon;
        tempIDArrayFrom[2] = response.airports[id].airport.lat;
        tempIDArrayFrom[3] = response.airports[id].airport.city;
        tempIDArrayFrom[4] = response.airports[id].airport.country;
        tempIDArrayFrom[5] = response.airports[id].airport.desc;
//alert(tempIDArrayFrom[2]);
        //ff = response.airports[id].airport.code+'|'+response.airports[id].airport.lon+'|'+response.airports[id].airport.lat+'|'+response.airports[id].airport.city+'|'+response.airports[id].airport.country+'|'+response.airports[id].airport.desc;
    }else if(div.indexOf('to')==0 || div.indexOf('CalcCode2')>0){
        //alert('To');
        //tempIDArrayTo[0] = new Array( response.airports[id].airport.code , response.airports[id].airport.lon , response.airports[id].airport.lat , response.airports[id].airport.city , response.airports[id].airport.country , response.airports[id].airport.desc );
        tempIDArrayTo[0] = response.airports[id].airport.code;
        tempIDArrayTo[1] = response.airports[id].airport.lon;
        tempIDArrayTo[2] = response.airports[id].airport.lat;
        tempIDArrayTo[3] = response.airports[id].airport.city;
        tempIDArrayTo[4] = response.airports[id].airport.country;
        tempIDArrayTo[5] = response.airports[id].airport.desc;
        //alert(tempIDArrayTo[2]);
    }
    
    //alert(tempIDArrayFrom[0]);
    //alert(tempIDArrayFrom[0][1]);
    //alert(tempIDArrayTo.length);
}

function over( id ){
	document.getElementById(id).style.background = '#76A8DB';
	document.getElementById(id).style.color = '#FFFFFF';
}
function out( id ){
	document.getElementById(id).style.background = '';
	document.getElementById(id).style.color = '';
}
/*function Blur( control , div ){
	if( document.getElementById(control).blur ){
		document.getElementById(div).style.display = 'none';
	}	
}*/
document.onclick = function () {
	var divs = document.getElementsByTagName('div');//alert(divs.length);
	for (var i=0 ; i < divs.length ; i++ ) {
		if (divs[i].className == 'ac') divs[i].style.display = 'none'; //divs[i].innerHTML = msg;
		if (divs[i].className == 'ae') { divs[i].className = 'ac'; /*divs[i].innerHTML = msg;*/ }
	}
	//IE6 fix, show select menu
	//conditional coz it makes an error in IE when set to inline only
	//the menu still appearing after the transparent layer appears 
	if( document.getElementById('container').style.display == 'block' ) selectListShowHide('none');
	else selectListShowHide('inline');
}
