var CurrentView = 0; // 0=Default, 1=Flexible
var FlightsPerPage = 25;
var UpdateFrequency = 2000;
var SearchFinished = false;
var AirportsList = new Object();
var CountryList = new Object();
var DefaultInfo = GetDefaultInfo('DefaultInfo');
var FlexibleInfo = GetFlexibleInfo('FlexibleInfo');
var MyMap = null;
var MapBounds = null;
var MapVisible = false;
var MapAirport = null;
var MapIsDep = false;
var MapFlights = 2;
var WaitingOn = true;
var priceBubble1 = 'price_bubble1.gif';
var priceBubble2 = 'price_bubble2.gif';
var altBubble = false;

var MonthNames = new Array(TXT_JANUARY,TXT_FEBRUARY,TXT_MARCH,TXT_APRIL,TXT_MAY,TXT_JUNE,TXT_JULY,TXT_AUGUST,TXT_SEPTEMBER,TXT_OCTOBER,TXT_NOVEMBER,TXT_DECEMBER);
var MonthAbbr = new Array(TXT_JAN,TXT_FEB,TXT_MAR,TXT_APR,TXT_MAY_SHORT,TXT_JUN,TXT_JUL,TXT_AUG,TXT_SEP,TXT_OCT,TXT_NOV,TXT_DEC);

function trim(str){ return str.replace(/^\s+/, "").replace(/\s+$/, ""); };

function FocusItem(elem){
	elem.focus();
	elem.select();
}

function ContinentListChanged(elem, targetId, val){
	if(val == ''){ elem.selectedIndex -= 1; }
	if(elem){ FetchCountries(targetId, elem.value); }
}

// FORM VALIDATION
function validateByPriceForm(){
	var depField = GetItemById('tbAptDep');
	var depIATAField = GetItemById('tbDepIata');
	var errAptDep = GetItemById('errAptDep');
	var continentField = GetItemById('ddContinents');
	var countryField = GetItemById('ddCountries');
	var blnOneWay = GetItemById('optOneWay').checked;
	var chkDateRange = GetItemById('chkDateRange');
	var maxPrice = GetItemById('tbMaxPrice');
	var currency = GetItemById('ddCurrency');
	var minStay = GetItemById('tbMinStay');
	var maxStay = GetItemById('tbMaxStay');

	if(trim(depField.value) == ''){
		if(errAptDep){ errAptDep.innerHTML = '<font color=red>X</font>'; }
		FocusItem(depField);
		alert(TXT_NO_DEP_ERROR);
		return false;
	}

	var URL = BYPRICE_FOLDER;
	var depCity = depField.value.replace(TXT_ALL_AIRPORTS,'');
	depCity = trim(depCity.replace(',',' ').replace('  ',' '));
	var regex = /\s+/g;
	var fileName = TXT_BYPRICE_NAME;
	fileName = fileName.replace('{0}', depCity);
	fileName = fileName.replace(regex, '-');

	if(depIATAField.value.length == 3){ URL += depIATAField.value + "/"; }
	else{ URL += encodeURIComponent(depField.value) + "/"; }

	URL += continentField.value + (countryField.value != '' ? '-' + countryField.value : '') + "/";
	if(blnOneWay){ URL += TXT_ONEWAY.replace(regex, '-') + "/"; }

	if(maxPrice && maxPrice.value.length > 0){
		URL += maxPrice.value + "/";
	}

	var minStayVal = (minStay ? trim(minStay.value) : '');
	if(minStayVal.length > 0){
		URL += TXT_MIN_STAY_URL + '_' + minStayVal + "/";
	}

	var maxStayVal = (maxStay ? trim(maxStay.value) : '');
	if(maxStayVal.length > 0){
		URL += TXT_MAX_STAY_URL + '_' + maxStayVal + "/";
	}

	if(chkDateRange && chkDateRange.checked){
		URL += GetItemById('dtMinDate').value + "/";
		URL += GetItemById('dtMaxDate').value + "/";
	}

	URL += fileName + '.htm';

	if(currency && currency.value.length > 0){
		document.cookie = 'Currency=' + currency.value + '; path=/;';
	}

	abortFetchCountries();
	window.location.href = URL;

	return false;
}

function HideWaiting(){
	var waitFrame, waitElem;
	if(WaitingOn){
		if(WAITING_ELEM && WAITING_ELEM.length > 0){ waitElem = GetItemById(WAITING_ELEM); }
		if(waitElem){
			waitElem.style.display = 'none';
			waitElem.parentNode.removeChild(waitElem);
		}
		if(WAITING_FRAME && WAITING_FRAME.length > 0){ waitFrame = GetItemById(WAITING_FRAME); }
		if(waitFrame){
			waitFrame.style.display = 'none';
			waitFrame.parentNode.removeChild(waitFrame);
		}
	}
	WaitingOn = false;
}

Array.prototype.insert = function(position, newValue){
	if(position > -1)
		this.splice(position, 0, newValue);
	else
		this.push(newValue);
};

function AddFlight(ResultType, DepIata, DestIata, DepDate, Airline, RetDate,
					Operator, OPID, FLID, Price, OldPrice, Currency, DisplayCurrency, Img, BookURL, OutDepTime, OutArrTime,
					InDepTime, InArrTime, OutStops, InStops, OutDuration, InDuration, ETicket, TotalPrice, OldTotalPrice,
					InclTax, Way, IsAlternative, CPC, Adults, Children, Infants, CacheAge)
{
	var flight = new FlightResultClass (ResultType, DepIata, DestIata, DepDate, Airline, RetDate,
		Operator, OPID, FLID, Price, OldPrice, Currency, DisplayCurrency, Img, BookURL, OutDepTime, OutArrTime,
		InDepTime, InArrTime, OutStops, InStops, OutDuration, InDuration, ETicket, TotalPrice, OldTotalPrice,
		InclTax, Way, IsAlternative, CPC, Adults, Children, Infants, CacheAge);

	flight.WriteTable();
	AddCommand(flight);
}

function UpdateFlight(ResultType, DepIata, DestIata, DepDate, Airline, RetDate,
					Operator, OPID, FLID, Price, OldPrice, Currency, DisplayCurrency, Img, BookURL, OutDepTime, OutArrTime,
					InDepTime, InArrTime, OutStops, InStops, OutDuration, InDuration, ETicket, TotalPrice, OldTotalPrice,
					InclTax, Way, IsAlternative, CPC, Adults, Children, Infants, CacheAge)
{
	var flight = new FlightResultClass (ResultType, DepIata, DestIata, DepDate, Airline, RetDate,
		Operator, OPID, FLID, Price, OldPrice, Currency, DisplayCurrency, Img, BookURL, OutDepTime, OutArrTime,
		InDepTime, InArrTime, OutStops, InStops, OutDuration, InDuration, ETicket, TotalPrice, OldTotalPrice,
		InclTax, Way, IsAlternative, CPC, Adults, Children, Infants, CacheAge);

	flight.UpdateFlight();
}

function FlightResultClass(ResultType, DepIata, DestIata, DepDate, Airline, RetDate,
							Operator, OPID, FLID, Price, OldPrice, Currency, DisplayCurrency, Img, BookURL, OutDepTime, OutArrTime,
							InDepTime, InArrTime, OutStops, InStops, OutDuration, InDuration, ETicket, TotalPrice, OldTotalPrice,
							InclTax, Way, IsAlternative, CPC, Adults, Children, Infants, CacheAge)
{
	this.Table = '';
	this.ResultType = ResultType;
	this.DepIata = DepIata;
	this.DepAirport = GetAirport(this.DepIata);
	this.DestIata = DestIata;
	this.DestAirport = GetAirport(this.DestIata);
	this.DepDate = DepDate;
	this.Airline = Airline;
	this.RetDate = RetDate;
	this.Operator = Operator;
	this.OPID = OPID;
	this.FLID = FLID;
	this.Price = Price;
	this.OldPrice = OldPrice;
	this.Currency = Currency;
	this.DisplayCurrency = DisplayCurrency;
	this.Img = Img;
	this.BookURL = BookURL;
	this.OutDepTime = OutDepTime;
	this.OutArrTime = OutArrTime;
	this.InDepTime = InDepTime;
	this.InArrTime = InArrTime;
	this.OutStops = OutStops;
	this.InStops = InStops;
	this.OutDuration = OutDuration;
	this.InDuration = InDuration;
	this.ETicket = ETicket;
	this.TotalPrice = TotalPrice;
	this.OldTotalPrice = OldTotalPrice;
	this.InclTax = InclTax;
	this.Way = Way;
	this.IsAlternative = IsAlternative;
	this.CPC = CPC;
	this.IsConverted = false;
	this.Adults = Adults;
	this.Children = Children;
	this.Infants = Infants;
	this.CacheAge = CacheAge;
	this.FlexibleFlight = false;
	this.IsCached = true;
	this.TableRef = null;
	this.UpdateCell = null;
	this.IsQueued = false;
	this.IsUpdating = false;
	this.IsUpdated = false;
	this.UpdateFailed = false;

	this.DepDateObj = new DateObject(this.DepDate, 'dd/MM/yyyy');
	this.RetDateObj = new DateObject(this.RetDate, 'dd/MM/yyyy');
	this.DepDay = this.DepDateObj.GetDay();
	this.DepMonth = this.DepDateObj.GetMonth();
	this.DepYear = this.DepDateObj.GetYear();

	this.ShortPrice = new String(this.Price);
	this.ShortPrice = this.ShortPrice.replace(this.DisplayCurrency, '');

	if(this.ResultType == 1){
		this.FlexibleFlight = true;
		SetGraphItem(this);
	}

	if(this.Way == null){ this.Way = 2; }
	if(this.IsAlternative == null){ this.IsAlternative = false; }
	if(this.CPC == null){ this.CPC = 0; }
	if(this.Currency != this.DisplayCurrency){ this.IsConverted = true; }

	this.GetRedirectLink = function(){
		var strLink = LANG_ROOT_PATH + 'redirect.aspx';
		strLink += '?opid=' + OPID;
		strLink += '&url=';
		strLink += '&DepartAirport=' + DepIata;
		strLink += '&DestinationAirport=' + DestIata;
		strLink += '&Adults=' + Adults;
		strLink += '&Children=' + Children;
		strLink += '&Infants=' + Infants;
		strLink += '&DepartureDate=' + DepDate;
		strLink += '&ReturnDate=' + RetDate;
		return strLink;
	}

	this.GetShallowRedirectLink = function(){
		var strLink = LANG_ROOT_PATH + 'redirect.aspx';
		strLink += '?opid=' + OPID;
		strLink += '&url=';
		return strLink;
	}

	this.GetFlexibleLink = function(){
		var regex = /\s+/g;
		var fileName = TXT_RESULTS_NAME.replace('{0}', this.DepAirport.City).replace('{1}', this.DestAirport.City);
		fileName = fileName.replace(regex, '-');
		
		var strLink = FLIGHTS_FOLDER;
		if(this.Way == 1){ strLink += TXT_ONEWAY.replace(regex, '-') + '/'; }
		strLink += DEP_IATA + '/' + DestIata + '/';
		strLink += fileName + '.htm';
		return strLink;
	}

	this.GetInclTaxes = function(){
		var strTaxIncl = '';
		var strCss = 'txtOrange';
		if(!this.InclTax){ strTaxIncl = TXT_TAX_EXCLUDED; }
		else if(this.InclTax == '0'){ strTaxIncl = TXT_TAX_EXCLUDED; }
		else if(this.InclTax == '2'){ strTaxIncl = TXT_EXCLUDING_TICKET_EMISSION; }
		else if(this.InclTax == '3'){ strTaxIncl = TXT_APPROX_PRICE; }
		else{ strTaxIncl = TXT_TAX_INCLUDED; strCss = 'txtGreen' }

		if(strTaxIncl != ''){ strTaxIncl = '<br><span class="' + strCss + '">' + strTaxIncl + '</span>'; }
		return strTaxIncl;
	}
	
	this.GetCacheInfo = function(){
		var html = '';
		if(this.CacheAge != null && this.CacheAge != '0'){
			var timeSpan = this.CacheAge.split(':');
			var cachAgeText = TXT_LAST_UPDATED + ': ';
			var days = (timeSpan.length > 0 ? parseInt(timeSpan[0]) : 0);
			var hours = (timeSpan.length > 1 ? parseInt(timeSpan[1]) : 0);
			var mins = (timeSpan.length > 2 ? parseInt(timeSpan[2]) : 0);
			var cacheImg = '<img src=' + IMG_ROOT + 'i/clock3.gif width=11 height=11 border=0 align=absmiddle>';
			this.IsCached = true;

			if(days > 0)
				cachAgeText += TXT_DAYS_AGO.replace('%1',days);
			else if(hours > 0)
				cachAgeText += TXT_HOURS_AGO.replace('%1',hours);
			else if(mins > 0)
				cachAgeText += TXT_MINS_AGO.replace('%1',mins);
			else{
				cacheImg = '<img src=' + IMG_ROOT + 'i/tick-green.gif width=14 height=15 border=0 align=absmiddle>';
				cachAgeText = TXT_VERIFIED_AVAILABILITY;
				this.IsCached = false;
			}

			html = cacheImg + ' ' + cachAgeText;
		}
		else{
			html = '<img src=' + IMG_ROOT + 'i/tick-green.gif width=14 height=15 border=0 align=absmiddle> ' + TXT_VERIFIED_AVAILABILITY;
			this.IsCached = false;
		}

		return html;
	}

	this.GetItemHtml = function(){
		var opDetail = '<img src="' + this.Img + '" border=0>';
		var redirectUrl = this.GetRedirectLink();
		var apts = this.DepIata	+ ' >> ' + this.DestIata;
		html = '<table width="100%" align=center cellpadding=0 border=0>'
		html += '<tr><td width="50%" valign="middle">';
		html += '<span class="ResultPrice">' + this.Price + '</span>' + this.GetInclTaxes() + '</td>';
		html += '<td width="50%" align="center"><a href="' + redirectUrl + '" target="_blank">' + opDetail + '</a></td></tr>';
		html += '<tr><td>' + apts + '</td>';
		html += '<td align="center"><a href="' + redirectUrl + '" target="_blank">' + this.Operator + '</a></td></tr>';
		html += '<tr><td>' + this.DepDate + '</td>';
		html += '<td align="center">' + this.OutDepTime + ' >> ' + this.OutArrTime + '</td></tr>';
		if(this.Way == 2){
			html += '<tr><td>' + this.RetDate + '</td>';
			html += '<td align="center">' + this.InDepTime + ' >> ' + this.InArrTime + '</td></tr>';
		}
		html += '</table>';
		html += '<div style="padding-top:4px;">' + this.GetCacheInfo() + '</div>';
		return html;
	}

	this.GetConvertedFromText = function(oldPrice, oldCurrency){
		var html = '<img src="' + IMG_ROOT + 'i/asterix.gif" width=12 height=11> ' + TXT_CONVERTED_FROM;
		html = html.replace('%1',oldCurrency);
		html = html.replace('%2','<b>' + oldPrice + ' ' + oldCurrency + '</b>');
		if(TXT_CONVERTED_INFO && TXT_CONVERTED_INFO.length > 0){
		    html += '&nbsp;&nbsp;<img src="' + IMG_ROOT + 'i/info4.gif" width=11 height=11 onclick="showInfoBalloon(this, event, \'<b>' + oldCurrency + '</b>\')">';
		}
		return html;
	}
	
	if(this.DepAirport &&
		(!this.DepAirport.CheapestFlight ||
		this.TotalPrice < this.DepAirport.CheapestFlight.TotalPrice)){
		this.DepAirport.SetCheapest(this);
	}

	if(this.DestAirport &&
		(!this.DestAirport.CheapestFlight ||
		this.TotalPrice < this.DestAirport.CheapestFlight.TotalPrice)){
		this.DestAirport.SetCheapest(this);
	}

	this.BuildResult = function(parent){
		var content = createTable({css:'tbl', cellPadding:2, cellSpacing:0, border:0});
		content.style.tableLayout = 'fixed';
		content.flight = this;
		this.TableRef = content;
		parent.appendChild(content);

		try{
			var row1, row2, row3, row4, row5;
			var depAptHtml, destAptHtml;

			row1 = appendTableRow(content);
			if(this.Way == 2){ row2 = appendTableRow(content); }

			var depText = this.DepIata;
			depAptHtml = '<span title="' + (this.DepAirport ? this.DepAirport.GetFullName() : this.DepIata) + '">';
			depAptHtml += depText + '</span>';

			var destText = this.DestIata;
			destAptHtml = '<span title="' + (this.DestAirport ? this.DestAirport.GetFullName() : this.DestIata) + '">';
			destAptHtml += destText + '</span>';

			var redirectUrl = this.GetRedirectLink();

			row3 = appendTableRow(content);

			var tdR1C1 = appendTableCell(row1, {vAlign:'top', width:'95px', html:'&nbsp;', rowSpan:(this.Way == 2 ? 3 : 2)});
			var tdR1C2 = appendTableCell(row1, {vAlign:'top', width:'120px', html:'&nbsp;'});
			var tdR1C3 = appendTableCell(row1, {vAlign:'top', align:'center', html:'&nbsp;', css:'hideOverflow'});
			var tdR1C4 = appendTableCell(row1, {vAlign:'top', width:'106px', html:'&nbsp;'});
			var tdR1C5 = appendTableCell(row1, {vAlign:'top', align:'center', width:'55px', html:'&nbsp;'});
			var tdR1C6 = appendTableCell(row1, {vAlign:'middle', align:'center', width:'90px', html:'&nbsp;', rowSpan:(this.Way == 2 ? 2 : 1)});

			if(this.Way == 2 && row2 != null){
				//2nd Row
				var tdR2C2 = appendTableCell(row2, {vAlign:'top', html:'<div class="hideOverflow">' + destAptHtml + ' >> ' + depAptHtml + '</div>'});
				var tdR2C3 = appendTableCell(row2, {html:'&nbsp;'});
				var tdR2C4 = appendTableCell(row2, {vAlign:'top',  html:this.InDepTime + ' >> ' + this.InArrTime});
				var tdR2C5 = appendTableCell(row2, {vAlign:'top', align:'center', html:this.InStops});
			}

			var tdR3C1 = appendTableCell(row3, {vAlign:'top', html:'&nbsp;', colSpan:2});
			var tdR3C2 = appendTableCell(row3, {vAlign:'top', html:'&nbsp;'});
			var tdR3C3 = appendTableCell(row3, {vAlign:'top', align:'center', html:'&nbsp;'});
			var tdR3C4 = appendTableCell(row3, {vAlign:'top', align:'center', html:'&nbsp;'});

			var cssPriceTop = (altBubble ? 'PriceTop2' : 'PriceTop1');
			var cssPriceBtm = (altBubble ? 'PriceBtm2 UpdateLink' : 'PriceBtm1');
			var priceTopDiv = createDiv({css:cssPriceTop});
			var priceBtmDiv = createDiv({css:cssPriceBtm});
			priceTopDiv.appendChild(createAnchor({href:redirectUrl, css:'ResultPrice', target:'_blank', html:this.Price}));
			priceTopDiv.innerHTML += this.GetInclTaxes();
			if(this.IsCached && (!this.IsUpdated && !this.IsUpdating && !this.IsQueued && !this.UpdateFailed)){
				var updateJS = 'UpdateFlightAjax(this,UpdateRender);HideUpdate(this);';
				var updateSpan = createElem('SPAN', {css:'UpdateLink PriceUpdate'});
				var updateLink = createAnchor({html:TXT_UPDATE}, updateJS);
				updateLink.flight = this;
				updateSpan.innerHTML = '<img src=' + IMG_ROOT + 'i/update.gif width=11 height=11 border=0 align=absmiddle>&nbsp;';
				updateSpan.appendChild(updateLink);
				priceBtmDiv.appendChild(updateSpan);
			}
			else{
				priceBtmDiv.innerHTML = '<img src=' + IMG_ROOT + 'i/t.gif width=1 height=11 border=0>';
			}

			altBubble = !altBubble;
			tdR1C1.innerHTML = '';
			tdR1C1.appendChild(priceTopDiv);
			tdR1C1.appendChild(priceBtmDiv);

			tdR1C2.innerHTML = '<div class="hideOverflow">' + depAptHtml + ' >> ' + destAptHtml + '</div>';
			tdR1C3.innerHTML = this.Airline;
			tdR1C3.title = this.Airline;
			tdR1C4.innerHTML = this.OutDepTime + ' >> ' + this.OutArrTime;
			tdR1C5.innerHTML = this.OutStops;

			var tailFin = '<img src="' + this.Img + '" alt="' + this.Operator + '" border=0/>';
			var finLink = createAnchor({href:redirectUrl, target:'_blank', html:tailFin})
			tdR1C6.innerHTML = '';
			tdR1C6.appendChild(finLink);

			tdR3C1.innerHTML = this.GetCacheInfo();
			this.UpdateCell = tdR3C1;

			if(this.UpdateFailed){
				this.UpdateCell.innerHTML += '<BR><img src=' + IMG_ROOT + 'i/warning.gif width=11 height=10 border=0 align=absmiddle> ';
				this.UpdateCell.innerHTML += '<SPAN class="UpdateLink">' + TXT_UPDATE_FAILED + '</SPAN>';
			}
			else if(this.IsQueued){
				this.UpdateCell.innerHTML = '<img src="' + IMG_ROOT + 'i/snake_update2.gif" width=12 height=12 border=0 align=absmiddle> ';
				this.UpdateCell.innerHTML += '<SPAN class="UpdateLink">' + TXT_WAIT + '</SPAN>';
			}
			else if(this.IsUpdating){
				this.UpdateCell.innerHTML = '<img src="' + IMG_ROOT + 'i/snake_update2.gif" width=12 height=12 border=0 align=absmiddle> ';
				this.UpdateCell.innerHTML += '<SPAN class="UpdateLink">' + TXT_UPDATING + '</SPAN>';
			}

			var dep = new DateObject(this.DepDate, 'dd/MM/yyyy');
			var altText = '<b>' + dep.ToString('d MMM');

			if(this.Way == 2){
				var ret = new DateObject(this.RetDate, 'dd/MM/yyyy');
				altText += ' - ' + ret.ToString('d MMM');
			}

			altText += '</b>';
			tdR3C2.innerHTML = '<span class=txtDate>' + altText + '</span>';

			var bookItLink = createAnchor({href:redirectUrl, css:'BookIt', target:'_blank', html:TXT_BOOK_IT})
			tdR3C3.innerHTML = '';
			tdR3C3.appendChild(bookItLink);

			var opLink = createAnchor({href:redirectUrl, css:'GreenLink', target:'_blank', html:this.Operator})
			tdR3C4.innerHTML = '';
			tdR3C4.appendChild(opLink);

			if(this.IsConverted){
				row4 = appendTableRow(content);
				var tdR4C1 = appendTableCell(row4, {vAlign:'top', html:'<span class=txtConverted>' + this.GetConvertedFromText(OldPrice,Currency) + '</span>', colSpan:5});
			}
		}
		catch(e){}

		return content;
	}

	this.WriteTable = function(){
		try{
			var info = GetSettingsInfo(this.ResultType);
			this.Table = info.Table;

			var pos = this.FindPosition(info.Results);
			if(pos >= 0){ info.Results.insert(pos, this); }
			else{ info.Results[info.Results.length] = this; }

			if(!blnUpdating){
				blnUpdating = true;
				setTimeout('UpdateWhenFree()', UpdateFrequency);
			}
		}
		catch(e){}
	}

	this.UpdateFlight = function(){
		try{
			var info = GetSettingsInfo(this.ResultType);
			this.Table = info.Table;
			var isUpdated = false;
			for(var i = 0; i < info.Results.length; i++){
				var item = info.Results[i];
				var isMatch = (this.OPID == item.OPID && this.DepIata == item.DepIata && this.DestIata == item.DestIata && 
								this.DepDate == item.DepDate && this.RetDate == item.RetDate && this.OutDepTime == item.OutDepTime && 
								this.OutArrTime == item.OutArrTime && this.InDepTime == item.InDepTime && this.InArrTime == item.InArrTime)
				if(isMatch){
					for(var prop in item){
						item[prop] = this[prop];
					} 
					item.IsUpdated = true
					isUpdated = true;
				}
			}
			if(!isUpdated){
				this.WriteTable();
				AddCommand(this);
			}
		}
		catch(e){}
	}

	this.FindPosition = function(SearchArray){
		if(SearchArray.length==0)
			return -1;

		var intStart = 0;
		var intBeginning = 0;
		var intEnd = SearchArray.length;
		var blnFound = false;
		if(SearchArray.length >= 10){
			while(!blnFound){
				var intHalfWay = parseInt((intEnd-intBeginning)/2) + intBeginning;
				if(this.TotalPrice > SearchArray[intHalfWay].TotalPrice){
					intBeginning = intHalfWay;
				}
				else{
					intEnd = intHalfWay;
				}

				if(intEnd - intBeginning <= 3)
					blnFound = true;
			}
		}
		for(var i = intBeginning; i < SearchArray.length; i++){
			if(this.TotalPrice < SearchArray[i].TotalPrice){
				return i;
			}
		}
	}
}// End FlightResultClass

function HideUpdate(elem){
	if(elem && elem.parentNode){
		elem.parentNode.innerHTML = '';
	}
}

function UpdateRender(flight){
	if(flight){
		if(flight.UpdateCell){
			var msg = null;
			if(flight.IsQueued){ msg = TXT_WAIT; }
			else if(flight.IsUpdating){ msg = TXT_UPDATING; }
			if(msg){
				var html = '<img src="' + IMG_ROOT + 'i/snake_update2.gif" width=12 height=12 border=0 align=absmiddle> ';
				html += '<SPAN class="UpdateLink">' + msg + '</SPAN>';
				flight.UpdateCell.innerHTML = html;
			}
		}
		if(flight.TableRef){
			var currNode = flight.TableRef;
			if(currNode.parentNode && currNode.parentNode.nodeName == 'TD'){
				currNode.parentNode.className = 'ResultCellUpdate';
			}
		}
	}
}

function createDiv(props, onclick){
	var div = document.createElement('DIV');
	if(props.id != null){ div.id = props.id; }
	if(props.css != null){ div.className = props.css; }
	if(props.html != null){ div.innerHTML = props.html; }
	if(onclick != null){ div.onclick = (typeof(onclick) == 'function' ? onclick : new Function(onclick)); }
	return div;
}

function createAnchor(props, onclick){
	var anchor = document.createElement('A');
	if(props.href != null){ anchor.href = props.href; }
	if(props.id != null){ anchor.id = props.id; }
	if(props.css != null){ anchor.className = props.css; }
	if(props.target != null){ anchor.target = props.target; }
	if(props.html != null){ anchor.innerHTML = props.html; }
	if(onclick != null){ anchor.onclick = (typeof(onclick) == 'function' ? onclick : new Function(onclick)); }
	return anchor;
}

function createElem(tag, props, onclick){
	var elem = document.createElement(tag);
	if(props.id != null){ elem.id = props.id; }
	if(props.css != null){ elem.className = props.css; }
	if(props.html != null){ elem.innerHTML = props.html; }
	if(onclick != null){ elem.onclick = (typeof(onclick) == 'function' ? onclick : new Function(onclick)); }
	return elem;
}

function createInput(props, onclick){
	var elem = document.createElement('INPUT');
	if(props.type != null){ elem.type = props.type; }
	if(props.id != null){ elem.id = props.id; }
	if(props.css != null){ elem.className = props.css; }
	if(props.value != null){ elem.value = props.value; }
	if(onclick != null){ elem.onclick = (typeof(onclick) == 'function' ? onclick : new Function(onclick)); }
	return elem;
}

function createTable(props){
	var table = document.createElement('TABLE');
	if(props.id != null){ table.id = props.id; }
	if(props.css != null){ table.className = props.css; }
	if(props.cellPadding != null){ table.cellPadding = props.cellPadding; }
	if(props.cellSpacing != null){ table.cellSpacing = props.cellSpacing; }
	if(props.border != null){ table.border = props.border; }
	return table;
}

function appendTableRow(table){
	return table.insertRow(table.rows.length);
}

function appendTableCell(row, props){
	var cell = row.insertCell(row.cells.length);
	if(props.css != null){ cell.className = props.css; }
	if(props.align != null){ cell.align = props.align; }
	if(props.vAlign != null){ cell.vAlign = props.vAlign; }
	if(props.width != null){ cell.width = props.width; }
	if(props.html != null){ cell.innerHTML = props.html; }
	if(props.colSpan != null){ cell.colSpan = props.colSpan; }
	if(props.rowSpan != null){ cell.rowSpan = props.rowSpan; }
	if(props.title != null){ cell.title = props.title; }
	return cell;
}

function SearchOperator(name, id, fintail, website){
	this.Name = name;
	this.OPID = id;
	this.Fintail = fintail;
	this.Website = website;
	this.HasFlights = false;
}

var blnUpdating = false;

function UpdateWhenFree(){
	UpdateFilter();
	blnUpdating = false;
}

function UpdatePageCounts(info){
	var intPages = parseInt(info.FilteredResults.length/FlightsPerPage);
	if(info.FilteredResults.length%FlightsPerPage)
		intPages += 1;

	var intStartFlight = (info.CurrentPage*FlightsPerPage) - (FlightsPerPage-1);
	var intEndFlight = (info.CurrentPage*FlightsPerPage > info.FilteredResults.length) ? info.FilteredResults.length : info.CurrentPage*FlightsPerPage;

	DisplayPages(info);
}

function DisplayPages(info){
	var strPageLinks = '';
	var clickFunc = '';
	var AllowedPageSpan = 5;
	var blnShowGoToFirst = false;
	var blnShowGoToLast = false;
	var intPages = parseInt(info.FilteredResults.length/FlightsPerPage);

	if(info.FilteredResults.length%FlightsPerPage > 0)
		intPages++;

	if(info.CurrentPage > intPages)
		info.CurrentPage = (intPages == 0 ? 1 : intPages);

	for(i = 1; i <= intPages; i++){
		var minOffSet = (info.CurrentPage + AllowedPageSpan > intPages) ? ((intPages - (info.CurrentPage+AllowedPageSpan))*-1) : 0;
		var maxOffSet = (info.CurrentPage - AllowedPageSpan < 0) ? ((info.CurrentPage - AllowedPageSpan)*-1) : 0;

		if((i > (info.CurrentPage - AllowedPageSpan) - minOffSet) && 
			(i < (info.CurrentPage + AllowedPageSpan) + maxOffSet)){
			if(info.CurrentPage == i){
				strPageLinks += '<span class="ChangePageSelected"><b>' + i + ' </b></span> ';
			}
			else{
				clickFunc = 'GoToPage(' + i + ',' + info.ResultType + ')';
				strPageLinks += '<a class="ChangePage" onclick="' + clickFunc + '">' + i + '</a> ';
			}
		}

		if(info.CurrentPage - AllowedPageSpan >= 1)
			blnShowGoToFirst = true;

		if(info.CurrentPage + AllowedPageSpan <= intPages)
			blnShowGoToLast = true;
	}

	clickFunc = 'GoToPage(1,' + info.ResultType + ')';
	var strStart = blnShowGoToFirst ? '<a class="ChangePage" onclick="' + clickFunc + '"> ' + TXT_FIRST + '</a> ' : '';

	clickFunc = 'GoToPage(' + intPages + ',' + info.ResultType + ')';
	var strEnd = blnShowGoToLast ? '<a class="ChangePage" onclick="' + clickFunc + '">' + TXT_LAST + '</a>' : '';

	GetItemById(info.PagesID).innerHTML = strStart + strPageLinks + strEnd ;
	GetItemById(info.FooterID).style.display = '';
}

function GoToPage(page, type){
	showLoadingScreen(true);
	window.scrollTo(0,0);

	var info = GetSettingsInfo(type);
	info.CurrentPage = page;
	setTimeout('UpdateFilter()', 80);
}

function ChangePageSize(){
	showLoadingScreen(true);
	FlightsPerPage = GetItemById('PageCountSize').value;
	ResetCurrentPage();
	setTimeout('UpdateFilter()', 80);
}

function InsertNoResultsRow(tblID){
	var table = GetItemById(tblID);
	var mainrow = appendTableRow(table);
	var cell = appendTableCell(mainrow, {css:'ResultCell', html:'<div class="ErrorMessage">' + TXT_NO_RESULTS + '</div>'});
}

function InsertFilteredRow(flight){
	var table = GetItemById(flight.Table);
	var mainrow = appendTableRow(table);
	var cell = appendTableCell(mainrow, {css:(flight.IsUpdating || flight.IsQueued ? 'ResultCellUpdate' : 'ResultCell')});
	flight.BuildResult(cell);
}

function InsertFlightHeader(flight, i){
	var apt = flight.DestAirport;
	var city = apt.GetFullName();
	var table = GetItemById(flight.Table);
	var spacerow = appendTableRow(table);
	var mainrow = appendTableRow(table);
	var cell = appendTableCell(mainrow, {css:'mapHeader'});
	var aShowMap = createAnchor({css:'greyLink', html:TXT_SHOW_ON_THE_MAP}, (apt.MapPin ? function(){ apt.MapPin.showInfoWindow(true); } : null));
	var divMap = createDiv({css:'mapHeadRight'});
	divMap.appendChild(aShowMap);
	cell.appendChild(divMap);

	var leftContent = '<span class="txtIndex">' + (i + 1) + '.</span> ';
	leftContent += '<img src="' + IMG_ROOT + 'i/map/sml/' + GetSmallPinImage(flight.TotalPrice) + '" width=12 height=18 hspace=4 align=absmiddle> ';
	leftContent += apt.GetFullName() + ', ' + apt.Country + ' (' + apt.IATA + ')';
	leftContent += '&nbsp;&nbsp;&nbsp;<a href="' + flight.GetFlexibleLink() + '" class="flexLink">' + TXT_MORE_FLIGHTS_TO.replace('%1', apt.City) + '</a>';
	cell.appendChild(createDiv({css:'mapHeadLeft', html:leftContent}));
}

function DisplayPage(info){
	ClearTableById(info.Table);
	UpdatePageCounts(info);

	if(info.FilteredResults.length == 0){
		InsertNoResultsRow(info.Table);
		return;
	}

	for(var i = 0; i < FlightsPerPage; i++){
		var PageOffSet = (info.CurrentPage - 1) * FlightsPerPage ;
		if(i + PageOffSet > info.FilteredResults.length - 1)
			break;

		var item = info.FilteredResults[i + PageOffSet];
		InsertFlightHeader(item, i + PageOffSet);
		InsertFilteredRow(item);
	}
}

function ClearTables(){
	ClearTableById(DefaultInfo.Table);
	ClearTableById(FlexibleInfo.Table);
}

// Filtered (Not Shown) Arrays
var arrAirportsDepNotShown = new Array();
var arrAirportsDestNotShown = new Array();
var arrOperatorsFinished = new Array();

var DateDepStart;
var DateDepEnd;
var DateRetStart;
var DateRetEnd;
var PriceStart;
var PriceEnd;

function loadVars(info){
	if(info.DateDepStart)
		DateDepStart = parseInt(GetItemById(info.DateDepStart).value);

	if(info.DateDepEnd)
		DateDepEnd = parseInt(GetItemById(info.DateDepEnd).value);

	if(info.DateRetStart)
		DateRetStart = parseInt(GetItemById(info.DateRetStart).value);

	if(info.DateRetEnd)
		DateRetEnd = parseInt(GetItemById(info.DateRetEnd).value);

	if(info.PriceStart)
		PriceStart = parseInt(GetItemById(info.PriceStart).value);

	if(info.PriceEnd)
		PriceEnd = parseInt(GetItemById(info.PriceEnd).value);

	if(info.DepArray)
		arrAirportsDepNotShown = getAptsNotShown(info.DepID);

	if(info.DestArray)
		arrAirportsDestNotShown = getDestAptsNotShown(info.DestID);
}

function getOpsNotShown(id){
	var filterTable = GetItemById(id);
	var arr = new Array();

	if(filterTable == null || filterTable.rows.length == 0)
		return arr;

	for(var i = 0; i < filterTable.rows.length; i++){
		var node = filterTable.rows[i].cells[0].childNodes[0];
		if(node.tagName == 'INPUT' && node.type == 'checkbox' && !node.checked){
			arr.push(node.value);
		}
	}

	return arr;
}

function getAptsNotShown(id){
	var filterTable = GetItemById(id);
	var arr = new Array();

	if(filterTable == null || filterTable.rows.length == 0)
		return arr;

	for(var i = 0; i < filterTable.rows.length; i++){
		var node = filterTable.rows[i].cells[0].childNodes[0];
		if(node.tagName == 'INPUT' && node.type == 'checkbox' && !node.checked){
			arr.push(node.value);
		}
	}

	return arr;
}

function getDestAptsNotShown(id){
	var filterTable = GetItemById(id);
	var arr = new Array();

	if(filterTable == null || filterTable.rows.length == 0)
		return arr;

	for(var i = 0; i < filterTable.rows.length; i++){
		var aptTable = filterTable.rows[i].cells[1].childNodes[1];
		for(var j = 0; j < aptTable.rows.length; j++){
			var node = aptTable.rows[j].cells[0].childNodes[0];
			if(node.tagName == 'INPUT' && node.type == 'checkbox' && !node.checked){
				arr.push(node.value);
			}
		}
	}

	return arr;
}

function selectAll(id, checked){
	var filterTable = GetItemById(id);

	if(filterTable == null || filterTable.rows.length == 0)
		return;

	for(var i = 0; i < filterTable.rows.length; i++){
		var node = filterTable.rows[i].cells[0].childNodes[0];
		if(node.tagName == 'INPUT' && node.type == 'checkbox'){
			node.checked = checked;
		}
	}

	filter();
}

function selectAllDests(id, checked){
	var delayFunc = function(){ selectAllDestsDelayed(id, checked); }
	showLoadingScreen(true);
	setTimeout(delayFunc, 80);
}

function selectAllDestsDelayed(id, checked){
	var filterTable = GetItemById(id);

	if(filterTable == null || filterTable.rows.length == 0){
		showLoadingScreen(false);
		return;
	}

	for(var i = 0; i < filterTable.rows.length; i++){
		var node = filterTable.rows[i].cells[0].childNodes[0];
		if(node.tagName == 'INPUT' && node.type == 'checkbox'){
			node.checked = checked;
			if(node.resultType != null){
				SetCountryCheck(node.value, checked, false, node.resultType);
			}
		}
	}

	if(CurrentView == 0){ RedrawFilters(0); }
	else if(CurrentView == 1){ RedrawFilters(1); }
	filter();
}

function filter(){

	showLoadingScreen(true);
	ResetCurrentPage();
	setTimeout('UpdateFilter()', 80);
}

function UpdateFilter(){
	showLoadingScreen(true);
	try{
		ClearTables();
		var info;
		if(CurrentView == 0){	// Default Results
			info = GetSettingsInfo(0);
		}
		if(CurrentView == 1){	// Flexible Results
			info = GetSettingsInfo(1);
		}
		if(info){
			DoFilter(info);
		}
	}
	catch(e){}
	showLoadingScreen(false);
}

function DoFilter(info){
	if(!info.Results)
		return;

	FilterResults(info);
	SetFlightCounts(info);

	DisplayPage(info);
}

function SetFlightCounts(info){
	if(info && info.CountsTextID){
		try{
			var countsDIV = GetItemById(info.CountsTextID);
			var showingNum = '<b>' + info.FilteredResults.length + '</b>';
			var totalNum = '<b>' + info.Results.length + '</b>';
			var operatorNum = '<b>' + info.OperatorsArray.length + '</b>';

			var countsHtml = TXT_RESULTS;
			countsHtml = countsHtml.replace('%1', showingNum);
			countsHtml = countsHtml.replace('%2', totalNum);
			countsHtml = countsHtml.replace('%3', operatorNum);
			countsDIV.innerHTML = '<div class=FilterCounts>' + countsHtml + '</div>';
		}
		catch(e){}
	}
}

function FilterResults(info){
	loadVars(info);

	info.FilteredResults = new Array();
	var ResultView = info.Results;

	for(var i = 0; i < ResultView.length; i++){
		var item = ResultView[i];

		var blnAirport1Ok	= false;
		var blnAirport2Ok	= false;
		var blnDate1Ok		= false;
		var blnDate2Ok		= false;
		var blnPriceOk		= false;
		var blnAllOk		= false;

		if(!findStringInArray(arrAirportsDepNotShown, item.DepIata))
			blnAirport1Ok = true;

		if(!findStringInArray(arrAirportsDestNotShown, item.DestIata))
			blnAirport2Ok = true;

		if((dateToDays(item.DepDateObj.GetDate()) >= DateDepStart) &&
			(dateToDays(item.DepDateObj.GetDate()) <= DateDepEnd))
			blnDate1Ok = true;

		if(item.Way == 1 || ((dateToDays(item.RetDateObj.GetDate()) >= DateRetStart) &&
			(dateToDays(item.RetDateObj.GetDate()) <= DateRetEnd)))
			blnDate2Ok = true;

		if((item.TotalPrice >= PriceStart) &&
			(item.TotalPrice <= PriceEnd))
			blnPriceOk = true;

		blnAllOk = blnAirport1Ok && blnAirport2Ok && blnDate1Ok && blnDate2Ok && blnPriceOk;

		if(item.DestIata && MyMap){
			if(blnAllOk){ MyMap.showMarker(item.DestIata); }
			else{ MyMap.hideMarker(item.DestIata); }
		}

		if(blnAllOk){ info.FilteredResults[info.FilteredResults.length] = item; }
		else{ item.TableRef = null; item.UpdateCell = null; }
	}
}

function AirportObject(city, fullname, iata){
	this.City = city;
	this.Full = fullname;
	this.IATA = iata;
}

function OperatorObject(opid, operator, url, price, val){
	this.OPID = opid;
	this.Operator = operator;
	this.Url = url;
	this.Price = price;
	this.Value = val;
}

function DateFilterObject(out_date, in_date, alt, price, url, val){
	this.OutDate = out_date;
	this.InDate = in_date;
	this.IsChecked = !alt;
	this.IsAlternative = alt;
	this.Price = price;
	this.Value = val;
	this.Url = url;

	this.toString = function(){
		return this.OutDate.toString() + this.InDate.toString();
	}

	function displayText(){
		var out = '';
		var ret = '';
		var outputString = '';
		out = new DateObject(this.OutDate, 'dd/MM/yyyy');
		outputString = out.ToString('d MMM');

		if(this.InDate != null && this.InDate != ''){
			ret = new DateObject(this.InDate, 'dd/MM/yyyy');
			outputString += ' - ' + ret.ToString('d MMM');
		}

		return outputString;
	}
	this.displayText = displayText;
}

function SettingsInfo(){
	this.ID = '';
	this.View = 0;
	this.ResultType = 0;
	this.CurrentPage = 1;
	this.Table = 'progressiveResults';
	this.Results = new Array();
	this.FilteredResults = new Array();
	this.AltResults = new Array();
	this.DepArray = new Array();
	this.DepID = 'airportsDep';
	this.DestArray = new Array();
	this.DestCountry = new Object();
	this.DestID = 'airportsDest';
	this.DatesID = 'dateFilter';
	this.OperatorsArray = new Array();
	this.OperatorsID = 'operatorsFilter';
	this.GetAirport = GetAirport;
	this.NonStopID = 'chkNonStop';
	this.OneStopID = 'chk1Stop';
	this.TwoStopID = 'chk2Stop';
	this.DateDepStart = 'depstart';
	this.DateDepEnd = 'depend';
	this.DateRetStart = 'retstart';
	this.DateRetEnd = 'retend';
	this.PriceStart = 'pricestart';
	this.PriceEnd = 'priceend';
	this.CountsTextID = 'resultsCounts';
	this.FooterID = 'tblResFoot';
	this.PagesID = 'spanPages';
	this.TabName = 'tabCheapest';
	this.FlexRequest = null;
	this.GraphData = null;
	this.Chart = null;
	this.Way = SEARCH_WAY;
	this.DepIATA = SEARCH_DEP;
	this.DestIATA = SEARCH_DEST;
	this.GraphMonth = SEARCH_MONTH;
	this.GraphYear = SEARCH_YEAR;

	this.GetTooltipHtml = function(index){
		var html = '', opDetail = '', apts = '';
		if(this.GraphData && this.GraphData.length > index && this.GraphData[index]){
			var item = this.GraphData[index];
			var html = item.GetItemHtml();
		}
		return html;
	}
	
	this.AddDestAirport = function(airport){
		if(!this.DestCountry[airport.Country]){
			this.DestCountry[airport.Country] = new Object();
		}
		if(!this.DestCountry[airport.Country][airport.IATA]){
			this.DestCountry[airport.Country][airport.IATA] = airport;
		}
	}

	this.GetCountries = function(){
		var countryArray = new Array();
		if(this.DestCountry){
			for(var prop in this.DestCountry){
				countryArray.push(prop);
			} 
		}
		countryArray.sort(CompareString);
		return countryArray;
	}

	this.GetCountryAirports = function(countryName){
		var country = this.DestCountry[countryName];
		return country;
	}

	this.GetCountryAirportsArray = function(countryName){
		var country = this.DestCountry[countryName];
		var airportsArray = new Array();
		if(country){
			for(var prop in country){
				airportsArray.push(country[prop]);
			} 
		}
		airportsArray.sort(CompareAirports);
		return airportsArray;
	}
}

function GetDefaultInfo(id){
	var obj = new SettingsInfo();
	obj.ID = id;
	obj.View = 1;
	obj.ResultType = 0;
	obj.DatesID = null;
	obj.GetAirport = GetAirport;
	obj.TabName = 'tabCheapest';
	obj.GetAirport = GetAirport;

	obj.GetTooltipHtml = function(val){
		var html = '', opDetail = '', apts = '';
		if(this.GraphData && this.GraphData[val]){
			var item = this.GraphData[val];
			var html = item.GetItemHtml();
		}
		return html;
	}

	return obj;
}

function GetFlexibleInfo(id){
	var obj = new SettingsInfo();
	obj.ID = id;
	obj.View = 1;
	obj.ResultType = 1;
	obj.DatesID = null;
	obj.GetAirport = GetAirport;
	obj.TabName = 'tabMonth';
	return obj;
}

function GetSettingsInfo(type){
	switch(type){
		case 0:
			return DefaultInfo;
		case 1:
			return FlexibleInfo;
	}
	return null;
}

function ResetCurrentPage(){
	GetSettingsInfo(0).CurrentPage = 1;
	GetSettingsInfo(1).CurrentPage = 1
}

function AddCommand(item){
	var info = GetSettingsInfo(item.ResultType);
	if(info){
		if(info.DepArray && !FindAirportInArray(info.DepArray, item.DepIata)){
			var depapt = info.GetAirport(item.DepIata);
			if(depapt){
				info.DepArray.push(depapt);
				if(CurrentView == info.View)
					drawAirports(info.DepArray, info.DepID, info);
			}
		}

		if(info.DestArray && !FindAirportInArray(info.DestArray, item.DestIata)){
			var destapt = info.GetAirport(item.DestIata);
			if(destapt){
				info.AddDestAirport(destapt);
				if(CurrentView == info.View)
					drawDestAirports(info.DestID, info);
			}
		}

		if(info.OperatorsArray && !findOperatorInArray(info.OperatorsArray, item)){
			var redirectUrl = item.GetRedirectLink();
			var operator = new OperatorObject(item.OPID, item.Operator, redirectUrl, item.ShortPrice, item.TotalPrice)
			info.OperatorsArray.push(operator);
		}
	}
}

function RedrawFilters(type){
	var info = GetSettingsInfo(type);

	if(info.DepArray)
		drawAirports(info.DepArray, info.DepID, info);

	if(info.DestArray)
		drawDestAirports(info.DestID, info);
}

function SetOperatorFinished(opid){
	for(var i = 0; i < arrOperatorsFinished.length; i++){
		if(opid == arrOperatorsFinished[i])
			return;
	}

	arrOperatorsFinished.push(opid);
}

function OpIsFinished(opid){
	for(var i = 0; i < arrOperatorsFinished.length; i++){
		if(opid == arrOperatorsFinished[i])
			return true;
	}

	return false;
}

function ClearTableById(id){
	var mTable = GetItemById(id);

	if(mTable == null)
		return;

	while(mTable.rows[0])
		mTable.deleteRow(0);
}

function CompareString(a,b){
	return ((a > b) ? 1 : ((a < b) ? -1 : 0));
}

function CompareName(a,b){
	return ((a.Name > b.Name) ? 1 : ((a.Name < b.Name) ? -1 : 0));
}

function CompareAirports(a,b){
	return ((a.GetFullName() > b.GetFullName()) ? 1 : ((a.GetFullName() < b.GetFullName()) ? -1 : 0));
}

function CompareOperatorArray(a,b){
	var x = null;
	var y = null;
	x = b.Operator.toLowerCase();
	y = a.Operator.toLowerCase();

	return ((x < y) ? 1 : ((x > y) ? -1 : 0));
}

function CompareDatesArray(a,b){
	var x1 = new DateObject(a.OutDate, 'dd/MM/yyyy');
	var x2 = new DateObject(a.InDate, 'dd/MM/yyyy');
	var y1 = new DateObject(b.OutDate, 'dd/MM/yyyy');
	var y2 = new DateObject(b.InDate, 'dd/MM/yyyy');

	if(x1.DateItem < y1.DateItem)
		return -1;
	else if(x1.DateItem > y1.DateItem)
		return 1;
	else if(x2.DateItem < y2.DateItem)
		return -1;
	else if(x2.DateItem > y2.DateItem)
		return 1;
	else
		return 0;
}

function drawAirports(arr, id, info){
	var airports = GetItemById(id);

	if(airports == null)
		return;

	while(airports.rows[0])
		airports.deleteRow(0);

	arr.sort(CompareDistance);

	for(var i = 0; i < arr.length; i++){
		var oprow, opcell1, opcell2;
		var aptFull = arr[i].GetFullName();
		var checked = (arr[i].Checked ? ' checked' : '');

		var chk = '<INPUT Type=checkbox onClick="SetAirportCheck(this.value,this.checked,true)"' + checked + ' id=chk' + i + ' value="' + arr[i].IATA + '">';
		var apt = arr[i].City + ' (' + arr[i].IATA + ')' + (arr[i].Distance < 0 ? '' : '<br>' + arr[i].Distance + ' KM');
		oprow = appendTableRow(airports);
		opcell1 = appendTableCell(oprow, {vAlign:'top', width:'14px', html:chk, title:aptFull});
		opcell2 = appendTableCell(oprow, {css:'AptCheckText', html:apt, title:aptFull});
	}
}

function drawDestAirports(id, info){
	var destTable = GetItemById(id);

	if(destTable == null)
		return;

	while(destTable.rows[0])
		destTable.deleteRow(0);
	
	var imgPlus = IMG_ROOT + 'i/plus.gif';
	var imgMinus = IMG_ROOT + 'i/minus.gif';
	var arrCountry = info.GetCountries();
	for(var i = 0; i < arrCountry.length; i++){
		var arr = info.GetCountryAirportsArray(arrCountry[i]);
		if(arr == null && arr.length == 0) continue;

		var ct = GetCountry(arr[0].CountryCode);
		var ctVisible = (ct ? ct.Visible : false);

		var ctrow, ctcell1, ctcell2;
		var ctHtml = '<img src="' + (ctVisible ? imgMinus : imgPlus) + '" id="img' + ct.Code + '" border=0 align=absmiddle>&nbsp;&nbsp;' + ct.Name;
		var linkCt = createDiv({css:'countryLink', html:ctHtml}, 'ToggleCountry("' + ct.Code + '","tbl' + ct.Code + '","img' + ct.Code + '","' + imgPlus + '","' + imgMinus + '")');
		var chkCt = createInput({type:'checkbox', id:'chk' + ct.Code, value:ct.Code}, 'SetCountryCheck("' + ct.Code + '",this.checked,true,' + info.ResultType + ')');
		chkCt.defaultChecked = ct.Checked;
		chkCt.resultType = info.ResultType;

		ctrow = appendTableRow(destTable);
		ctcell1 = appendTableCell(ctrow, {vAlign:'top', width:'14px', title:ct.Name});
		ctcell1.appendChild(chkCt);
		ctcell2 = appendTableCell(ctrow, {css:'AptCheckText', title:ct.Name});
		ctcell2.appendChild(linkCt);

		var aptTable = createTable({id:'tbl' + ct.Code, width:'100%', cellPadding:0, cellSpacing:1, border:0});
		if(!ctVisible){ aptTable.style.display = 'none'; }
		ctcell2.appendChild(aptTable);

		for(var j = 0; j < arr.length; j++){
			var oprow, opcell1, opcell2;
			var aptFull = arr[j].GetFullName();
			var checked = (arr[j].Checked ? ' checked' : '');
			var chk = '<INPUT Type=checkbox onClick="SetAirportCheck(this.value,this.checked,true)"' + checked + ' id=chk' + arr[j].IATA + ' value="' + arr[j].IATA + '">';
			var apt = arr[j].City + ' (' + arr[j].IATA + ')';
			oprow = appendTableRow(aptTable);
			opcell1 = appendTableCell(oprow, {vAlign:'top', width:'14px', html:chk, title:aptFull});
			opcell2 = appendTableCell(oprow, {css:'AptCheckText', html:apt, title:aptFull});
		}
	}
}

function showLoadingScreen(blnVal){
	GetItemById('updating').style.display = (blnVal && SearchFinished ? '' : 'none');
	if(blnVal){ LoadingScreen.show(); }
	else{ LoadingScreen.hide(); }
}

function isDateCheckedInArray(arr, item){
	var dateToFind = item.DepDate + item.RetDate;
	for(var i = 0; i < arr.length; i++){
		if(arr[i].toString() == dateToFind){
			return arr[i].IsChecked;
		}
	}
	return false;
}

function getDateFromArray(arr, dateToFind){
	for(var i = 0; i < arr.length; i++){
		if(arr[i].toString() == dateToFind)
			return arr[i];
	}
}

function findDateInArray(arr, item){
	var dateToFind = item.DepDate + item.RetDate;
	for(var i = 0; i < arr.length; i++){
		if(arr[i].toString() == dateToFind){
			if(item.TotalPrice < arr[i].Value){
				arr[i].Url = item.GetRedirectLink();
				arr[i].Price = item.ShortPrice;
				arr[i].Value = item.TotalPrice;
			}
			return true;
		}
	}
	return false;
}

function findOperatorInArray(arr, item){
	for(var i = 0; i < arr.length; i++){
		if(arr[i].OPID == item.OPID){
			if(item.TotalPrice < arr[i].Value){
				arr[i].Url = item.GetRedirectLink();
				arr[i].Price = item.ShortPrice;
				arr[i].Value = item.TotalPrice;
			}
			return true;
		}
	}
	return false;
}

function findStringInArray(arrString,strToFind){
	for(var i=0;i<arrString.length;i++){
		if(arrString[i]==strToFind){
			return true;
		}
	}
	return false;
}

function Sort(sortAlg){
	showLoadingScreen(true);
	setTimeout('DoSort(' + sortAlg + ')');
	filter();
}

var blnSortByPriceInv = false;
var blnSortByAirlineInv = true;
var blnSortByOperatorInv = true;
var blnSortByDepartTime = true;
var blnSortByArriveTime = true;

function DoSort(sortAlg){
	switch(sortAlg){
		case 0:
			blnSortByPriceInv=!blnSortByPriceInv;
			GetSettingsInfo(0).Results.sort(ComparePrice);
			if(GetSettingsInfo(1).Results){ GetSettingsInfo(1).Results.sort(ComparePrice); }
			break;
		case 1:
			blnSortByAirlineInv=!blnSortByAirlineInv;
			GetSettingsInfo(0).Results.sort(CompareAirline);
			if(GetSettingsInfo(1).Results){ GetSettingsInfo(1).Results.sort(CompareAirline); }
			break;
		case 2:
			blnSortByOperatorInv=!blnSortByOperatorInv;
			GetSettingsInfo(0).Results.sort(CompareOperator);
			if(GetSettingsInfo(1).Results){ GetSettingsInfo(1).Results.sort(CompareOperator); }
			break;
		case 3:
			blnSortByDepartTime=!blnSortByDepartTime;
			GetSettingsInfo(0).Results.sort(CompareDepartTime);
			if(GetSettingsInfo(1).Results){ GetSettingsInfo(1).Results.sort(CompareDepartTime); }
			break;
		case 4:
			blnSortByArriveTime=!blnSortByArriveTime;
			GetSettingsInfo(0).Results.sort(CompareArriveTime);
			if(GetSettingsInfo(1).Results){ GetSettingsInfo(1).Results.sort(CompareArriveTime); }
			break;
	}
}

function ComparePrice(a,b){
	var x = null;
	var y = null;
	if(!blnSortByPriceInv){
		x = a.TotalPrice;
		y = b.TotalPrice;
	}
	else{
		x = b.TotalPrice;
		y = a.TotalPrice;
	}
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function CompareAirline(a,b){
	var x = null;
	var y = null;
	if(!blnSortByAirlineInv){
		x = a.Airline.toLowerCase();
		y = b.Airline.toLowerCase();
	}
	else{
		x = b.Airline.toLowerCase();
		y = a.Airline.toLowerCase();
	}
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function CompareOperator(a,b){
	var x = null;
	var y = null;
	if(!blnSortByOperatorInv){
		x = a.Operator.toLowerCase();
		y = b.Operator.toLowerCase();
	}
	else{
		x = b.Operator.toLowerCase();
		y = a.Operator.toLowerCase();
	}
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function CompareDepartTime(a,b){
	var x = null;
	var y = null;
	if(!blnSortByDepartTime){
		x = a.OutDepTime.replace(':','');
		y = b.OutDepTime.replace(':','');
	}
	else{
		x = b.OutDepTime.replace(':','');
		y = a.OutDepTime.replace(':','');
	}
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

function CompareArriveTime(a,b){
	var x = null;
	var y = null;
	if(!blnSortByArriveTime){
		x = a.OutArrTime.replace(':','');
		y = b.OutArrTime.replace(':','');
	}
	else{
		x = b.OutArrTime.replace(':','');
		y = a.OutArrTime.replace(':','');
	}
	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
function UpdateFlexible(){
	if(CurrentView == 1){
		RedrawFilters(1);
	}

	setTimeout('UpdateFilter()', 80);
}

function FetchFlexibleDayFlights(day, type, way){
	showLoadingScreen(true);
	var info = GetSettingsInfo(type);
	info.DepArray = new Array();
	info.DestArray = new Array();
	info.OperatorsArray = new Array();
	info.Results = new Array();
	ClearAirportCheapest();
	info.FlexRequest.FetchResults('day', info.ResultType, info.DepIATA,
		info.DestIATA, day, info.GraphMonth, info.GraphYear, SEARCH_ADULTS,
		SEARCH_CHILDREN, SEARCH_INFANTS, way, CURRENCY_REGION);
}

function GetNextMonthFlexibleFlights(graphNum){
	var info = null;
	if(graphNum == 1 && CurrentView == 1)
		info = GetSettingsInfo(1);

	if(info == null)
		return;

	info.GraphMonth++;
	if(info.GraphMonth > 12){
		info.GraphMonth = 1;
		info.GraphYear++;
	}

	info.GraphData = GetEmptyGraphArray(info);
	FetchFlexibleMonthFlights(info);
}

function GetPrevMonthFlexibleFlights(graphNum){
	var info = null;
	if(graphNum == 1 && CurrentView == 1)
		info = GetSettingsInfo(1);

	if(info == null)
		return;

	var now = new Date();
	var nowMonth = now.getMonth() + 1;
	var nowYear = now.getFullYear();
	if(info.GraphMonth == nowMonth && info.GraphYear == nowYear)
		return;

	info.GraphMonth--;
	if(info.GraphMonth < 1){
		info.GraphMonth = 12;
		info.GraphYear--;
	}

	info.GraphData = GetEmptyGraphArray(info);
	FetchFlexibleMonthFlights(info);
}

function FetchFlexibleMonthFlights(info){
	showLoadingScreen(true);
	info.DepArray = new Array();
	info.DestArray = new Array();
	info.OperatorsArray = new Array();
	info.Results = new Array();
	ClearAirportCheapest();
	info.FlexRequest.FetchResults('month', info.ResultType, info.DepIATA,
		info.DestIATA, 1, info.GraphMonth, info.GraphYear, SEARCH_ADULTS,
		SEARCH_CHILDREN, SEARCH_INFANTS, info.Way, CURRENCY_REGION);
}

function GetEmptyGraphArray(info){
	var arr = new Array();
	var dtMonth = new Date(info.GraphYear, (info.GraphMonth-1), 1);
	while(dtMonth.getMonth() == (info.GraphMonth-1)){
		arr.push(null);
		dtMonth.setDate(dtMonth.getDate() + 1);
	}
	return arr;
}

function SetGraphItem(item){
	var index = item.DepDay - 1;
	var info = GetSettingsInfo(item.ResultType)
	if(info.GraphData && (info.GraphData[index] == null || 
		item.TotalPrice < info.GraphData[index].TotalPrice)){
		info.GraphData[index] = item;
	}
}

function EndSearch(){
	SearchFinished = true;
	AddAirportsToMap();
	if(CurrentView == 0){
		RedrawFilters(0);
	}
	else if(CurrentView == 1){
		RedrawFilters(1);
	}
	UpdateFilter();
}

function SetAirportCheck(iata, checked, update){
	var apt = GetAirport(iata);
	if(apt){
		apt.Checked = checked;
		if(MyMap){
			if(checked){ MyMap.showMarker(apt.IATA); }
			else{ MyMap.hideMarker(apt.IATA); }
		}
		var country = GetCountry(apt.CountryCode);
		if(country && checked){ country.Checked = checked; }
		if(CurrentView == 0){ RedrawFilters(0); }
		else if(CurrentView == 1){ RedrawFilters(1); }
		if(update){ filter(); }
	}
}

function SetCountryCheck(cc, checked, update, type){
	var info = GetSettingsInfo(type);
	var country = GetCountry(cc);
	if(country){
		country.Checked = checked;
		var airports = info.GetCountryAirports(country.Name);
		if(airports){
			for(var prop in airports){
				apt = airports[prop];
				apt.Checked = checked;
				if(MyMap){
					if(checked){ MyMap.showMarker(apt.IATA); }
					else{ MyMap.hideMarker(apt.IATA); }
				}
			}
		}
		if(update){
			if(CurrentView == 0){ RedrawFilters(0); }
			else if(CurrentView == 1){ RedrawFilters(1); }
			filter();
		}
	}
}

/* MANAGE DATES */
function DateObject(date_string, format){
	this.DateItem = new Date();
	this.DateString = date_string;
	this.Format = format;

	this.GetDay = function(){ return this.DateItem.getDate(); }
	this.GetMonth = function(){ return this.DateItem.getMonth()+1; }
	this.GetYear = function(){ return this.DateItem.getFullYear(); }
	this.GetDate = function(){ return this.DateItem; }

	this.GetMonthName = function(month){ return MonthNames[month-1]; }
	this.GetMonthAbbr = function(month){ return MonthAbbr[month-1]; }

	this.ToString = function(fmt){
		var d = this.DateItem.getDate();
		var m = this.DateItem.getMonth()+1;
		var y = this.DateItem.getFullYear();
		var outString = '';

		switch(fmt){
			case 'd MMM':
				outString = d + ' ' + this.GetMonthAbbr(m);
				break;
			case 'd MMMM':
				outString = d + ' ' + this.GetMonthName(m);
				break;
			case 'yyyy-m-y':
				outString = y + '-' + m + '-' + d;
				break;
			default:
				outString = this.DateItem.toLocaleDateString();
				break;
		}

		return outString;
	}

	this.ParseDate = function(){
		if(!this.DateString || !this.Format)
			return new Date();

		var d, m, y;
		var dateParts = this.DateString.split('/');
		var fmtParts = this.Format.split('/');

		for(var i = 0; i < fmtParts.length; i++){
			switch(fmtParts[i]){
				case 'd':
				case 'dd':
					if(i < dateParts.length){ d = parseInt(dateParts[i], 10); }
					break;
				case 'M':
				case 'MM':
					if(i < dateParts.length){ m = parseInt(dateParts[i], 10) - 1; }
					break;
				case 'yyyy':
					if(i < dateParts.length){ y = parseInt(dateParts[i], 10); }
					break;
			}
		}
		return new Date(y, m, d);
	}

	this.DateItem = this.ParseDate();
}

function GetAirport(iata){
	return AirportsList[iata];
}

function GetCountry(countrycode){
	return CountryList[countrycode];
}

function AddAirport(iata, city, name, country, countrycode, dist, lat, lon, isDep){
	new AirportDetails(AirportsList, iata, city, name, country, countrycode, dist, lat, lon, isDep);
	new CountryDetails(CountryList, country, countrycode);
}

function ClearAirportCheapest(){
	for(var iata in AirportsList){
		AirportsList[iata].SetCheapest(null);
	}
}

function CountryDetails(obj, name, countrycode){
	this.Name = name;
	this.Code = countrycode;
	this.Visible = false;
	this.Checked = true;

	if(obj[countrycode] == null)
		obj[countrycode] = this;
}

function AirportDetails(obj, iata, city, name, country, countrycode, dist, lat, lon, isDep){
	this.IATA = iata;
	this.City = city;
	this.Name = name;
	this.Country = country;
	this.CountryCode = countrycode;
	this.Distance = dist;
	this.Latitude = lat;
	this.Longitude = lon;
	this.IsDep = isDep;
	this.CheapestFlight = null;
	this.MapPin = null;
	this.Checked = true;

	this.GetFullName = function(){
		var fullname = this.City;
		fullname += (this.Name.length > 0 ? ' ' + this.Name : '');
		return fullname;
	}

	this.SetCheapest = function(flight){
		this.CheapestFlight = flight;
	}
	
	if(obj[iata] != null)
		return;

	obj[iata] = this;
}

function CompareDistance(a, b){
	var x = a.Distance;
	var y = b.Distance;
	return ((x < y && x >= 0) ? -1 : ((y < x && y >= 0) ? 1 : 0));
}

function FindAirportInArray(arr, iata){
	for(var i = 0; i < arr.length; i++){
		if(arr[i].IATA == iata)
			return arr[i];
	}

	return null;
}

function StopSearch(){
	try{
		if(window.stop){ window.stop(); }
		else{ document.execCommand('Stop'); }
	}
	catch(e){}
	EndSearch();
}

function CreateMap(){
	var map = new mapManager({id:'mapDiv',resize:true});
	map.createMap(DEP_LATITUDE, DEP_LONGITUDE)
	return map;
}

function ShowMap(visible){
	MapVisible = visible;
	MapAirport = null;

	GetItemById('pnlMap').style.display = (MapVisible ? '' : 'none');

	if(MapVisible){
		if(!MyMap){
			MyMap = CreateMap()
		}
	}
}

function CreateMarker(point, apt) {
	var flight = apt.CheapestFlight;
	if(!flight || !MyMap) return;
	var aptName = apt.GetFullName();
	var obj = {id:apt.IATA, img:null, width:0, height:0, lat:point.lat, lon:point.lon, html:null, title:aptName, visible:true};
	obj.img = IMG_ROOT + 'i/map/' + GetPinImage(flight.TotalPrice);
	obj.width = 20;
	obj.height = 34;

	var html = '<div class="mapResult">';
	if(flight){
		obj.title = aptName + ' - ' + flight.Price;
		var txt = TXT_FROM_TO;
		txt = txt.replace('%1', (flight.DepAirport ? flight.DepAirport.GetFullName() :  flight.DepIata));
		txt = txt.replace('%2', (flight.DestAirport ? flight.DestAirport.GetFullName() :  flight.DestIata));
		html += '<div class="mapText">' + txt + '</div>';
		html += apt.CheapestFlight.GetItemHtml();
		html += '<div style="padding-top:4px;">';
		html += '<a class="blueText" href="' + flight.GetRedirectLink() + '" target="_blank">';
		html += TXT_VERIFY_AVAILABILITY;
		html += '</a></div>';
		html += '<div style="padding-top:4px;">';
		html += '<a class="GreenLink" href="' + flight.GetFlexibleLink() + '">';
		html += TXT_MORE_FLIGHTS_TO.replace('%1', apt.City);
		html += '</a></div>';
	}
	else{
		html += '<div class="mapText">' + aptName + '</div>';
	}
	html += '</div>';

	obj.html = html;

	return MyMap.updateMarkers(obj);
}

function CreateDepMarker(point, name) {
	if(MyMap){
		var obj = {img:null, width:0, height:0, left:0, top:0, lat:point.lat, lon:point.lon, html:null, title:name};
		obj.img = IMG_ROOT + 'i/map/man.png';
		obj.width = 33;
		obj.height = 39;
		obj.left = 27;
		obj.top = 37;
		obj.html = '<div class="mapText">' + TXT_LEAVING_FROM + '</div>'
		return MyMap.addMarker(obj);
	}
	return null;
}

var DepMarker = null
function AddAirportsToMap(){
	if(!MyMap){ MyMap = CreateMap(); }
	if(MyMap){
		if(!DepMarker){ DepMarker = CreateDepMarker({lat:DEP_LATITUDE, lon:DEP_LONGITUDE}, DEP_CITY); }
		for(var iata in AirportsList){
			var apt = AirportsList[iata];
			if(apt && !apt.IsDep){
				var point = {lat:apt.Latitude, lon:apt.Longitude};
				apt.MapPin = CreateMarker(point, apt);
			}
		}
		MyMap.renderMapBounds();
	}
}

function ShowMapFlightsByAirport(iata, isDep){
	MapAirport = iata;
	MapIsDep = isDep;
	SetAirportCheck(iata,true,false);
	filter();
}

function GetPinImage(price){
	if(price < LOW_RANGE){
		return 'price-low.png';
	}
	else if(price < HIGH_RANGE){
		return 'price-mid.png';
	}
	else{
		return 'price-high.png';
	}
}

function GetSmallPinImage(price){
	if(price < LOW_RANGE){
		return 'price-low-sml.gif';
	}
	else if(price < HIGH_RANGE){
		return 'price-mid-sml.gif';
	}
	else{
		return 'price-high-sml.gif';
	}
}

function ToggleMap(id, txtId, imgId, onImg, offImg) {
	var panel, image, text;
	
	try{
		panel = GetItemById(id);
		image = GetItemById(imgId);
		text = GetItemById(txtId);

		if(panel.style.display == 'none'){
			panel.style.display = '';
			image.src = offImg;
			if(text){ text.innerHTML = TXT_HIDE_MAP; }
			if(!MyMap){ MyMap = CreateMap(); }
			if(MyMap){ MyMap.checkResize(); }
			return true;
		}
		else{
			panel.style.display = 'none';
			image.src = onImg;
			if(text){ text.innerHTML = TXT_SHOW_MAP; }
			return false;
		}
	}
	catch(e){}
}

function ToggleCountry(countrycode, id, imgId, onImg, offImg) {
	var visible = ToggleElem(id, imgId, onImg, offImg);
	var country = GetCountry(countrycode);
	if(country){ country.Visible = visible; }
}

function ToggleElem(id, imgId, onImg, offImg) {
	var panel, image;
	
	try{
		panel = GetItemById(id);
		image = GetItemById(imgId);

		if(panel.style.display == 'none'){
			panel.style.display = '';
			image.src = offImg;
			return true;
		}
		else{
			panel.style.display = 'none';
			image.src = onImg;
			return false;
		}
	}
	catch(e){}
}

function HideElement(elem){
	elem.style.display = 'none';
}

function SetElemVisibility(ids, visible) {
	for(var i = 0; i < ids.length; i++){
		var elem = GetItemById(ids[i]);
		if(elem){ elem.style.display = (visible ? '' : 'none'); }
	}
}

function ValidateNumeric(evt, tbMaxPrice){
	if(!evt && window.event){ evt = window.event; }
	var keyCode = evt.keyCode;
	
	var MAX_LENGTH = 999999999;

	//navigation keys
	switch(keyCode){
		case 8: //backspace
		case 9: //tab
		case 35://end		
		case 36://home		
		case 37://left arrow
		case 39://right arrow
		case 46://delete
		case 144://num lock
			return true;
	}

	if((keyCode >= 45 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105))
	{		
		if (parseInt(tbMaxPrice.value + "" + String.fromCharCode(keyCode), 10) > MAX_LENGTH) {alert(TXT_AMOUNT_LARGE); evt.returnValue = false; return false;} return true;
	}
	
	evt.returnValue = false;
	return false;
}

function GetItemById(id){
	return (document.all ? document.all[id] : document.getElementById(id));
}
