/* Path to images definition and progress indicator image preloading */
var pathToImages = '';
var prelImg = new Image();
prelImg.src = pathToImages + 'progress.gif';

/* Other global vars, used in functions */
var elementToLoad = null;
var fromAP = null;
var firstLoad = true;	
var where = (navigator.appName == "Microsoft Internet Explorer") ? -1 : null;

/* Form field id's: */
var fromCountryFieldId = 'fromCountry';
var fromAirportFieldId = 'fromAirport';
var toCountryFieldId = 'toCountry';
var toAirportFieldId = 'toAirport';

var countryChoice = -1;
var airportChoice = -1;
var triggerElem = '';

var phaseNo = 0;
var functionsToCall = Array();
var globalPhaseCount = 0;

var initialElemId = null;

function functionDispatcher() {
	if (phaseNo <= globalPhaseCount)
		eval(functionsToCall[phaseNo]);
	else
		document.getElementById('progress').style.display = 'none';
}

function fromCountryPhases(phaseCount) {
	document.getElementById('progress').style.display = 'block';
	globalPhaseCount = phaseCount;
	phaseNo = 0;
	functionsToCall[0] = 'loadAirports(document.getElementById(fromCountryFieldId), fromAirportFieldId, 1, null);'; 
	functionsToCall[1] = 'getFieldSelections(true);';
	functionsToCall[2] = 'loadAvailableCountries(document.getElementById(fromAirportFieldId), toCountryFieldId);'; 
	functionsToCall[3] = 'restoreDestCountry();';
	functionsToCall[4] = 'loadAirports(document.getElementById(toCountryFieldId), toAirportFieldId, 0, document.getElementById(fromCountryFieldId));'; 
	functionsToCall[5] = 'restoreDestAirport();';
	functionsToCall[6] = "showResults('resultArea', 'fetchResult', fromCountryFieldId, fromAirportFieldId, toCountryFieldId, toAirportFieldId, 0);"; 
	functionDispatcher();	
}

function fromAirportPhases(phaseCount) {
	document.getElementById('progress').style.display = 'block';
	globalPhaseCount = phaseCount;
	phaseNo = 0;
	functionsToCall[0] = 'getFieldSelections(true);';
	functionsToCall[1] = 'loadAvailableCountries(document.getElementById(fromAirportFieldId), toCountryFieldId);'; 
	functionsToCall[2] = 'restoreDestCountry();';
	functionsToCall[3] = 'loadAirports(document.getElementById(toCountryFieldId), toAirportFieldId, 0, document.getElementById(fromCountryFieldId));'; 
	functionsToCall[4] = 'restoreDestAirport();';
	functionsToCall[5] = "showResults('resultArea', 'fetchResult', fromCountryFieldId, fromAirportFieldId, toCountryFieldId, toAirportFieldId, 0);"; 
	functionDispatcher();	
}

function toCountryPhases(phaseCount) {
	document.getElementById('progress').style.display = 'block';
	globalPhaseCount = phaseCount;
	phaseNo = 0;
	functionsToCall[0] = 'loadAirports(document.getElementById(toCountryFieldId), toAirportFieldId, 0, document.getElementById(fromCountryFieldId));'; 
	functionsToCall[1] = "showResults('resultArea', 'fetchResult', fromCountryFieldId, fromAirportFieldId, toCountryFieldId, toAirportFieldId, 0);"; 
	functionDispatcher();	
}

function toAirportPhases(phaseCount) {
	document.getElementById('progress').style.display = 'block';
	globalPhaseCount = phaseCount;
	phaseNo = 0;
	functionsToCall[0] = "showResults('resultArea', 'fetchResult', fromCountryFieldId, fromAirportFieldId, toCountryFieldId, toAirportFieldId, 0);"; 
	functionDispatcher();	
}


function initialPhases(phaseCount) {
	document.getElementById('progress').style.display = 'block';
	globalPhaseCount = phaseCount;
	phaseNo = 0;
	functionsToCall[0] = "loadAvailableCountries(null, fromCountryFieldId);";
	functionsToCall[1] = "setInitialSelection(fromCountryFieldId, 1);";
	functionsToCall[2] = 'loadAirports(document.getElementById(fromCountryFieldId), fromAirportFieldId, 1, null);'; 
	functionsToCall[3] = "setInitialSelection(fromAirportFieldId, 2);";
	functionsToCall[4] = 'loadAvailableCountries(document.getElementById(fromAirportFieldId), toCountryFieldId);'; 
	functionsToCall[5] = "setInitialSelection(toCountryFieldId, 3);";
	functionsToCall[6] = 'loadAirports(document.getElementById(toCountryFieldId), toAirportFieldId, 0, document.getElementById(fromCountryFieldId));'; 
	functionsToCall[7] = "setInitialSelection(toAirportFieldId, 4);";
	functionsToCall[8] = "setInitialSelection('fetchResult', 5);";
	functionsToCall[9] = 'getFieldSelections(true);';
	functionsToCall[10] = "showResults('resultArea', 'fetchResult', fromCountryFieldId, fromAirportFieldId, toCountryFieldId, toAirportFieldId, 0);"; 
	functionDispatcher();	
}

function restoreDestCountry() {
	if (countryChoice != -1) {
		for (var i = 0; i < document.getElementById(toCountryFieldId).options.length; i++) {
			if (document.getElementById(toCountryFieldId).options[i].value == countryChoice) {
				document.getElementById(toCountryFieldId).selectedIndex = i;
				break;
			}
		}
	}
	phaseNo++;
	functionDispatcher();
}

function restoreDestAirport() {
	if (airportChoice != -1) {
		for (var i = 0; i < document.getElementById(toAirportFieldId).options.length; i++) {
			if (document.getElementById(toAirportFieldId).options[i].value == airportChoice) { 
				document.getElementById(toAirportFieldId).selectedIndex = i;
				break;
			}
		}
	}
	phaseNo++;
	functionDispatcher();
}

/* Loads Country field with values */
function loadCountries() {
  if (req.readyState == 4 && req.status == 200 ) {
    var countryList = eval(req.responseText);

	  if (elementToLoad != null) {
		  while (elementToLoad.options.length) {
		      elementToLoad.remove(0);
		  }
		}
    var newElem;
		if (elementToLoad == null) elementToLoad = document.getElementById(fromCountryFieldId);
		for (var i = 0; i < countryList.length; i++) {
	    newElem = document.createElement('option');
	    newElem.text = countryList[i].name;
	    newElem.value = countryList[i].code;
	    elementToLoad.add(newElem, where);
		}

		phaseNo++;
		functionDispatcher();
	}
}

/* 
 * Receives Airport field loading request along with required parameters 
 * elem - country of airport (pointer to select object)
 * elemToLoad - id of the elemento to load values to
 * setFromApNull - whether to clear cached 'fromAirport' value
 * fromCountryElem - from country (pointer to select object)
 */
function loadAirports(elem, elemToLoad, setFromApNull, fromCountryElem) {
	if (setFromApNull == 1) fromAP = null;
	elementToLoad = document.getElementById(elemToLoad);
	if (fromCountryElem != null) fromCountry = fromCountryElem.options[fromCountryElem.selectedIndex].value 

	/* Invoking data request */
	getData('getairport.php?country=' + elem.options[elem.selectedIndex].value + '&' + ((fromAP != null)?'airport=' + fromAP + '&':'') + ((fromCountryElem != null)?'fromcountry=' + fromCountry + '&':''), 2);
}

/*
 * Receives country field loading request along with required parameters
 * elem - from airport (pointer to select object)
 * elemToLoad - id of the element to load values to
 */
function loadAvailableCountries(elem, elemToLoad) {
	var country = null;
	elementToLoad = document.getElementById(elemToLoad);
	if (elem == null) {
		fromAP = -1;
	} else {
		fromAP = elem.options[elem.selectedIndex].value;
		if (elem.options[elem.selectedIndex].value == '0') country = document.getElementById(fromCountryFieldId).options[document.getElementById(fromCountryFieldId).selectedIndex].value
	}
	
	/* Invoking data request */
	getData('getcountry.php?' + ((fromAP != -1)?'airport=' + fromAP + '&':'') + ((country != null)?'country=' + country + '&':''), 1);
}

/* Loads airport field with values */
function loadAirports2() {
  if (req.readyState == 4 && req.status == 200 ) {
    var apList = eval(req.responseText);

	  while (elementToLoad.options.length) {
	      elementToLoad.remove(0);
	  }
    var newElem;
    newElem = document.createElement('option');
    newElem.text = 'Qualsiasi Aeroporto';
    newElem.value = '0';
    elementToLoad.add(newElem, where);
		for (var i = 0; i < apList.length; i++) {
	    newElem = document.createElement('option');
	    newElem.text = apList[i].name + ' (' + apList[i].code + ')';
	    newElem.value = apList[i].code;
	    elementToLoad.add(newElem, where);
		}
		
		phaseNo++;
		functionDispatcher();
  }
}

/* 
 * Loads requested url 
 * url - url to load
 * mode - # of function to use for processing loaded data
 */
function loadUrl(url, mode) {
  if(window.XMLHttpRequest) {
    try { req = new XMLHttpRequest();
    } catch(e) { req = false; }
  } else if(window.ActiveXObject) {
    try { req = new ActiveXObject('Msxml2.XMLHTTP');
    } catch(e) {
    try { req = new ActiveXObject('Microsoft.XMLHTTP');
    } catch(e) { req = false; }
  } }
  if(req) {
    switch (mode) {
    	case 1:
    		req.onreadystatechange = loadCountries; break;
    	case 2:
    		req.onreadystatechange = loadAirports2; break;
    	case 3:
    		req.onreadystatechange = loadSearchResults; break;
    	case 4:
    		req.onreadystatechange = sessValLoaded; break;
  	}
    req.open('GET', url, true);
    req.send('');
  }
}

/*
 * Prepares correct url and requests loading of it
 * scriptname - name of the PHP script to load (along with parameters as GET request vars)
 * mode - # of function to use for processing loaded data
 */
function getData(scriptname, mode) {
	var url = window.location.toString();
	/*
	* Important place. Here you have to replace 'demo.html' with your real page file name
	* If it is site root (e.g. no specific html name), then simply add 'scriptname + ...' to the url: url += scriptname + ...
	*/
	//url = url.replace( /demo.html/, scriptname + 't=' + ((new Date()).valueOf()));
	url += (scriptname + 't=' + ((new Date()).valueOf()));
	loadUrl(url, mode);
}

/* 
 * Shows results, according to user choices 
 * elemId - id of the result container div
 * checkElemId - id of checkbox, stating whether to fetch results without pressing Search button
 * fromCountryId - id of field fromCountry
 * fromApId - id of field fromAirport
 * toCountryId - id of field toCountry
 * toApId - id of field toAirport
 * force - whether to force loading event if checkbox (checkElemId) is not checked. This is necessary when Search button is pressed
 */
function showResults(elemId, checkElemId, fromCountryId, fromApId, toCountryId, toApId, force) {
	var elem = document.getElementById(elemId);
	var checkElem = document.getElementById(checkElemId);
	var fromCountry = document.getElementById(fromCountryId);
	var fromAirport = document.getElementById(fromApId);
	var toCountry = document.getElementById(toCountryId);
	var toAirport = document.getElementById(toApId);
	var canFetchResult = 0;
	
	document.getElementById('progress').style.display = 'none';
	if (checkElem.checked || force ) {
		if ((fromAirport.options.length > 0) && (toAirport.options.length > 0) && (fromCountry.options.length > 0) && (toCountry.options.length > 0)) {
			if ((fromAirport.options[fromAirport.selectedIndex].value != 0) || (toAirport.options[toAirport.selectedIndex].value != 0)) {
				var resText = 'Stai cercando voli da <strong>' + fromCountry.options[fromCountry.selectedIndex].value + ' ' +
					((fromAirport.options[fromAirport.selectedIndex].value != '0')?fromAirport.options[fromAirport.selectedIndex].text:'Qualsiasi Aeroporto') + 
					'</strong> a <strong>' + toCountry.options[toCountry.selectedIndex].value + ' ' +
					((toAirport.options[toAirport.selectedIndex].value != '0')?toAirport.options[toAirport.selectedIndex].text:'Qualsiasi Aeroporto') + '</strong> aeroporto<br /><br />';
				resText += '<strong>Risultati della ricerca:</strong><br /><br />';
				elementToLoad = elem;
				canFetchResult = 1;
			} else {
				resText = 'Restringi la ricerca...';
			}
		} else {
			resText = 'Restringi la ricerca...';
		}
		
		elem.innerHTML = resText;
		if (canFetchResult) getData('getresults.php?fromc=' + fromCountry.options[fromCountry.selectedIndex].value + '&fromap=' + fromAirport.options[fromAirport.selectedIndex].value + 
			'&toc=' + toCountry.options[toCountry.selectedIndex].value + '&toap=' + toAirport.options[toAirport.selectedIndex].value + '&checked=' + checkElem.checked + '&', 3);

	}
}

/* Requests SQL query and fills result container div with retrieved data */
function loadSearchResults() {
  if (req.readyState == 4 && req.status == 200 ) {
    var resList = eval(req.responseText);
		var resText = '<table width="97%" border="0" cellspacing="3" id="SearchResult"><tr><th>Id Rotta</th><th>Compagnia</th><th>Partenza</th><th>Arrivo</th><th>Commenta</th></tr>';

		for (var i = 0; i < resList.length; i++) {
	    resText += '<tr><td>' + resList[i].routeId + '</td><td><a href="http://www.easylowcost.net/compagnieaeree/europa/go.php?ID=' + resList[i].airlineId + '" target="_blank">' + resList[i].airlineName + '(' + resList[i].airlineId + ')</td><td>' + 
	    	resList[i].fromAp + '(<a href="http://www.easylowcost.net/destinations/europa/index.php?code=' + resList[i].fromApId + '&city=' + 
	    	resList[i].fromAp + '">' + resList[i].fromApId + '</a>)' + '</td><td>' + resList[i].toAp + '(<a href="http://www.easylowcost.net/destinations/europa/index.php?code=' + resList[i].toApId + '&city=' + resList[i].toAp + '">' + resList[i].toApId + '</a>)' + '</td><td><a href="http://www.easylowcost.net/eu/' + resList[i].airlineName + '/' + resList[i].airlineName + '.html">Commenta</a></td></tr>';
		}
		resText += '</table>';;
		
		var tmp = elementToLoad.innerHTML;
		elementToLoad.innerHTML = tmp + resText; 
		
	}
}

function getFieldSelections(dispatch) {
	countryChoice = document.getElementById(toCountryFieldId).value;
	airportChoice = document.getElementById(toAirportFieldId).value;
	if (dispatch) {
		phaseNo++;
		functionDispatcher();
	}
}

function setInitialSelection(elemId, mode) {
	initialElemId = elemId;
	getData('getsessval.php?mode=' + mode + '&', 4);
}

function sessValLoaded() {
  if (req.readyState == 4 && req.status == 200 ) {
    var selectedItem = eval(req.responseText);
    
    if (selectedItem[0].value != '-1') {
    	if (initialElemId == 'fetchResult') {
				document.getElementById('fetchResult').checked = (selectedItem[0].value == 'true');
    	} else {
	    	for (var i = 0; i < document.getElementById(initialElemId).options.length; i++) {
	    		if (document.getElementById(initialElemId).options[i].value == selectedItem[0].value) {
	    			document.getElementById(initialElemId).selectedIndex = i;
	    			break;
	    		}
	    	}
    	}
    }

		phaseNo++;
		functionDispatcher();
  }
}