var updateUrl = LANG_ROOT_PATH + 'AJAX/UpdateFlights.aspx';
var updateObj = GetXmlRequestObject();
var updateQueue = new Array();
var currentUpdate = null;

// gets a reference to the xml request object
function GetXmlRequestObject(){
	var obj = null;
	if(window.XMLHttpRequest){
		obj = new XMLHttpRequest();
	}
	else if(window.ActiveXObject){
		try{ obj = new ActiveXObject('Msxml2.XMLHTTP'); }
		catch(e){
			try{ obj = new ActiveXObject('Microsoft.XMLHTTP'); }
			catch(oc){ obj = null; }
		}
	}
	return obj;
}


// make a request to the server
function UpdateFlightAjax(owner, updateElement){
	if(owner && owner.flight){
		var flight = owner.flight;
		if(!currentUpdate){ DoFlightUpdate(flight); }
		else{ QueueUpdate(flight); }
		if(updateElement){ updateElement(flight); }
	}
}

function QueueUpdate(flight){
	flight.IsQueued = true;
	updateQueue.push(flight);
}

// make a request to the server
function DoFlightUpdate(flight){
	if(flight.IsUpdated){
		if(updateQueue.length > 0){ DoFlightUpdate(updateQueue.shift()); }
		else{ currentUpdate = null; }
		return;
	}

	flight.IsQueued = false;
	flight.IsUpdating = true;
	currentUpdate = flight;
	if(updateObj && updateObj.readyState != 0)
		updateObj.abort();

	if(updateObj){
		var pg = updateUrl;
		pg += '?opid=' + flight.OPID;
		pg += '&depIATA=' + flight.DepIata;
		pg += '&destIATA=' + flight.DestIata;
		pg += '&depart=' + encodeURIComponent(flight.DepDateObj.ToString('yyyy-m-y'));
		pg += '&return=' + encodeURIComponent(flight.RetDateObj.ToString('yyyy-m-y'));
		pg += '&oneway=' + (flight.Way == 2 ? 'false' : 'true');
		pg += '&type=' + flight.ResultType;
		pg += '&hashCode=' + encodeURIComponent(HASH_CODE);
		
		updateObj.open('GET', pg, true);
		updateObj.onreadystatechange = function(){
			if(updateObj.readyState == 4){
				try{
					if(updateObj.responseText){ eval(updateObj.responseText); }
				}
				catch(ex){}
				if(currentUpdate){ currentUpdate.UpdateFailed = !currentUpdate.IsUpdated; currentUpdate.IsUpdating = false; currentUpdate.IsQueued = false; }
				if(updateQueue.length > 0){ DoFlightUpdate(updateQueue.shift()); }
				else{ currentUpdate = null; }
				UpdateFilter();
			}
		};
		updateObj.send(null);
	}
}

function GetItemById(id){
	return (document.all ? document.all[id] : document.getElementById(id));
}
