﻿var views ={DEFAULT:'1',FLEXIBLE:'2',ONEWAYLEGS:'3',FLEXIBLELEGS:'4',MAP:'5'};
var viewMgr = new viewManager();
var hasOnewayLegs = false;
var mapFlightsPerAirport = 2;
var flexUrl = LANG_ROOT_PATH + 'AJAX/FlexibleFlights2.aspx';
var imgPlus = IMG_ROOT + 'i/plus.gif';
var imgMinus = IMG_ROOT + 'i/minus.gif';

var hideElement = function(elem){ elem.style.display = 'none'; };
var getElement = function(id){ return (document.all ? document.all[id] : document.getElementById(id)); };

// add templates
templates.addTemplate("flightTemplate");
templates.addTemplate("detailsTemplate");
if(getElement("emailTemplate")){ templates.addTemplate("emailTemplate"); }

var generateSearchFrame = function(qs){
	var url = LANG_ROOT_PATH + "AJAX/SearchJS.aspx";
	if(qs.length > 0 && qs[0] != '?'){ qs = '?' + qs; }
	url += qs;
	setTimeout(function(){
		$(document.body).append('<iframe name="searchframe" src="' + url + '" style="width:0px;height:0px" frameborder="0"></iframe>');
	}, 250);
};

var stopPage = function(){
	try{
		if(window.stop){ window.stop(); }
		else{ document.execCommand('Stop'); }
	}
	catch (e){ }
};

var showResultsPanel = function(){
	var resultsPanel = getElement('divResultsBody');
    if(resultsPanel && resultsPanel.style.display != ''){ resultsPanel.style.display = ''; }
};

/* Event callbacks */
var onOnewayLegsAdded = function(view){
	hasOnewayLegs = view.hasFlights();
	if(hasOnewayLegs){
		var cheapestItem = view.getCheapestItem();
		var tablabel = $('#legsFromPrice');
		if(cheapestItem && tablabel.get(0) != document){
			tablabel.html('(' + TXT_FROM_PRICE + ' ' + cheapestItem.price + ')');
		}
		if(view.outboundMgr && view.outboundMgr.render){
			var cheapestOutbound = view.outboundMgr.render.renderPriceLink(view.outboundMgr.cheapestItem);
			var ouboundlabel = $('#cheapOutbound');
			if(cheapestOutbound && ouboundlabel.get(0) != document){ ouboundlabel.html(cheapestOutbound); }
		}
		if(view.inboundMgr && view.inboundMgr.render){
			var cheapestInbound = view.inboundMgr.render.renderPriceLink(view.inboundMgr.cheapestItem);
			var inboundlabel = $('#cheapInbound');
			if(cheapestInbound && inboundlabel.get(0) != document){ inboundlabel.html(cheapestInbound); }
		}
		view = viewMgr.activeView;
		if(view && (view.id == views.DEFAULT || view.id == views.ONEWAYLEGS)){ toggleFlightsFilter((view.id == views.ONEWAYLEGS)); }
	}
};

var onDefaultResultsAdded = function(view){
    if(view.outboundMgr && view.outboundMgr.render){
        var cheapestItem = view.outboundMgr.render.renderPriceLink(view.outboundMgr.cheapestItem);
        var label = $('#cheapReturn');
        if(cheapestItem && label.get(0) != document){ label.html(cheapestItem); }
    }
};

var toggleFlightsFilter = function(isOneWay){
	var flightsFilter = $('#flightsFilter');
	if(flightsFilter.get(0) != document){ flightsFilter.css('display',(hasOnewayLegs ? '' : 'none')); }
	var chkSelected = $((isOneWay ? '#chkLegs' : '#chkReturns'));
	if(chkSelected.get(0) != document){ chkSelected.attr("checked","checked"); }
	var showReturns = $('#showReturns');
	if(showReturns.get(0) != document){ showReturns.css("fontWeight",(isOneWay ? "normal" : "bold")); }
	var showLegs = $('#showLegs');
	if(showLegs.get(0) != document){ showLegs.css("fontWeight",(isOneWay ? "bold" : "normal")); }
};

var onShowDefault = function(view){
	toggleFlightsFilter(false);
};

var onShowOneway = function(view){
	toggleFlightsFilter(true);
	if(view.firstView){
		if(view.outboundMgr != null && view.outboundMgr.filteredResults.length == 0){
			view.outboundMgr.filter.dates.setAll(true);
			view.outboundMgr.filterResults(true, false);
		}
		if(view.inboundMgr != null && view.inboundMgr.filteredResults.length == 0){
			view.inboundMgr.filter.dates.setAll(true);
			view.inboundMgr.filterResults(true, false);
		}
	}
};

var onShowFlexible = function(view){
	var flightsFilter = $('#flightsFilter');
	if(flightsFilter.get(0) != document){ flightsFilter.css('display','none'); }
	var isFlexOneway = (view.id == views.FLEXIBLELEGS);
	var showFlex = $('#flexResultsLink');
	if(showFlex.get(0) != document){ showFlex.css("fontWeight",(isFlexOneway ? "normal" : "bold")); }
	var showLegs = $('#flexLegsLink');
	if(showLegs.get(0) != document){ showLegs.css("fontWeight",(isFlexOneway ? "bold" : "normal")); }
};

var onShowMap = function(view){
	var flightsFilter = $('#flightsFilter');
	if(flightsFilter.get(0) != document){ flightsFilter.css('display','none'); }
	if(view.map){
		var defaultGroups ={
			defaultId: (view.isDeparture ? 'dep' : 'dest'),
			groups: [
				{ id: 'dep', lat: searchSettings.dep.lat, lon: searchSettings.dep.lon },
				{ id: 'dest', lat: searchSettings.dest.lat, lon: searchSettings.dest.lon }
			]
		};
		var lat = (view.isDeparture ? searchSettings.dep.lat : searchSettings.dest.lat);
		var lon = (view.isDeparture ? searchSettings.dep.lon : searchSettings.dest.lon);
		view.map.createMap(lat, lon, defaultGroups);
		view.updateMarkers();
	}
};

var onMapEndpointChanged = function(view, move){
	var depElem = $('#mapDeps');
	if(depElem.get(0) != document){ depElem.css("fontWeight",(view.isDeparture ? "bold" : "normal")); }
	var destElem = $('#mapDests');
	if(destElem.get(0) != document){ destElem.css("fontWeight",(view.isDeparture ? "normal" : "bold")); }
	if(view.map){
		var group = (view.isDeparture ? 'dep' : 'dest');
		var lat = (view.isDeparture ? searchSettings.dep.lat : searchSettings.dest.lat);
		var lon = (view.isDeparture ? searchSettings.dep.lon : searchSettings.dest.lon);
		view.map.extendBoundsGroup(group,{lat:lat, lon:lon});
		if(move){ view.map.moveTo(lat, lon); }
	}
};

/* Map view render function */
var renderMapResults = function(){
	var dests ={};
	var mapIata = mapView.iata;
	var isDep = mapView.isDeparture;
	var elem = $(this.resultsElement);
	var rendered = 0;
	var numResults = 0;
	var filteredArray = this.getFilteredResults();
	if(!filteredArray || filteredArray.length == 0){
		var msg = (this.flights.length == 0 ? TXT_NO_RESULTS_MSG : TXT_NO_RESULTS);
		elem.html(this.getErrorHtml(msg));
	}
	else{
		var resultsHtml = '';
		var flightTemplate = templates.getTemplate("flightTemplate");
		for(var i = 0, len = filteredArray.length; i < len; i++){
			var result = filteredArray[i];
			var item = (this.isGrouped ? result.filtered[0] : result);
			var iata = (isDep ? item.dep : item.dest);
			var retIata = (item.inbound ? (isDep ? item.inbound.dest : item.inbound.dep) : null);
			if(retIata && iata != retIata){ continue; }
			if(mapIata == null || iata == mapIata){
				if(!dests[iata]){
					dests[iata] = [];
					dests[iata].push(result);
				}
				else if(iata == mapIata || dests[iata].length < mapFlightsPerAirport){
					dests[iata].push(result);
				}
			}
		}
		var arr, len, headerItem, dataItem, itemSize;
		if(mapIata != null && dests[mapIata]){
			numResults = dests[mapIata].length;
			arr = this.selectPageResults(dests[mapIata]);
			len = (arr ? arr.length : 0);
			if(len > 0){
				headerItem = (this.isGrouped ? arr[0].filtered[0] : arr[0]);
				resultsHtml += this.render.renderMapHeader(this, headerItem, isDep);
				for(var i = 0; i < len; i++){
					dataItem = (this.isGrouped ? arr[i].filtered[0] : arr[i]);
					itemSize = (this.isGrouped ? arr[i].filtered.length : 1);
					resultsHtml += flightTemplate.apply({ item: dataItem, mgr: this, render: this.render, view: this.view, size: itemSize });
					rendered++;
				}
			}
		}
		else{
			for(var apt in dests){
				arr = dests[apt];
				len = (arr ? arr.length : 0);
				if(len > 0){
					headerItem = (this.isGrouped ? arr[0].filtered[0] : arr[0]);
					resultsHtml += this.render.renderMapHeader(this, headerItem, isDep);
					for(var i = 0; i < len; i++){
						dataItem = (this.isGrouped ? arr[i].filtered[0] : arr[i]);
						itemSize = (this.isGrouped ? arr[i].filtered.length : 1);
						resultsHtml += flightTemplate.apply({ item: dataItem, mgr: this, render: this.render, size: itemSize });
						rendered++;
					}
				}
			}
		}
		if(resultsHtml.length == 0){
			var msg = (this.flights.length == 0 ? TXT_NO_RESULTS_MSG : TXT_NO_RESULTS);
			resultsHtml = this.getErrorHtml(msg);
		}
		elem.html(resultsHtml);
	}
	if(mapIata != null){
		if(this.render){
			this.setResultsCount(this.render.getResultCounts(numResults, this.getTotalCount(), this.operatorCount));
			this.render.renderPaging(this, numResults);
		}
	}
	else{
		if(this.render){
			this.setResultsCount(this.render.getResultCounts(this.getFilteredCount(), this.getTotalCount(), this.operatorCount));
		}
		var pageElem = $(this.pagingElement);
		if(pageElem.get(0) != document){ pageElem.html('<span class="ChangePageSelected"><b>1</b></span>'); }
	}
	return rendered;
};

var getDisplayPrice = function(price){
	if(searchSettings.decimalSeparator != null && searchSettings.decimalSeparator.length > 0){
		var i = price.indexOf(searchSettings.decimalSeparator);
		if(i > -1){ price = '<span class="priceBig">' + price.substring(0, i) + '</span>' + price.substr(i, price.length); }
		return price;
	}
	else{ return item.price; }
};

var pad2 = function(num){ return (num < 10 ? '0' : '') + num.toString(); };

var renderSliderTime = function(val){
	return pad2(val) + ':00';
};

var renderSliderDuration = function(val){
	var pattern = searchSettings.durationFormat;
	var hours = Math.floor(val/60.0);
	var mins = val - (hours*60);
	return pattern.replace('%1', hours).replace('%2', pad2(mins));
};

/* Create Views */
var defaultView = new pageView({
	id:views.DEFAULT,
	tab:'#tabReturn',
	panels:['#timeRetFilter','#resultsHeader','#resultsTitlebar','#dateFilterRow','#flightsFilter','#progressiveResults','#airlineRow','#durationRetFilter'],
	onflightsadded:onDefaultResultsAdded,
	onshow:onShowDefault,
	onafterrender:showResultsPanel,
	isGrouped:searchSettings.useGrouping,
	sorters:{outbound:{value:'href1Sort0',airline:'href1Sort1',depart:'href1Sort3',arrive:'href1Sort4',stops:'href1Sort5',operator:'href1Sort2',duration:'href1Sort6',img:'sort1Img'}},
	outboundMgr:{
		resultsElement:'#progressiveResults',
		resultsCount:'#resultsCounts',
		pagingElement:'#spanPages',
		transportRow:'#transportRow',
		filterRow:'#rowOutbound',
		pageSizeSelect:'PageCountSize',
		premiumOp:searchSettings.premiumOp,
		showAirlineLogos:searchSettings.showAirlineLogos,
		filters:{depAirports:'airportsDep',destAirports:'airportsDest',operators:'operatorsFilter',dates:'dateFilter',transportTypes:'transportFilter',airlines:'airlinesFilter'},
		sliders:{
			depTime:{id:'#deptime',min:'mindeptime',max:'maxdeptime',minlabel:'#depStartTime',maxlabel:'#depEndTime'},
			retTime:{id:'#rettime',min:'minrettime',max:'maxrettime',minlabel:'#retStartTime',maxlabel:'#retEndTime'},
			outDuration:{id:'#outDuration',min:'outDurationMin',max:'outDurationMax',minlabel:'#outDurationMinLabel',maxlabel:'#outDurationMaxLabel',renderValue:renderSliderDuration,stepSize:5},
			retDuration:{id:'#retDuration',min:'retDurationMin',max:'retDurationMax',minlabel:'#retDurationMinLabel',maxlabel:'#retDurationMaxLabel',renderValue:renderSliderDuration,stepSize:5}
		}
	}
});
viewMgr.addView(defaultView, true);

var flexibleView = new flexiblePageView({
	id:views.FLEXIBLE,
	tab:'#tabFlexible',
	panels:['#timeRetFilter','#flexibleHeader','#flexibleResultsHeader','#flexWayNav','#flexibleTitlebar','#flexibleResults','#airlineRow','#flexiblePanel','#durationRetFilter'],
	onshow:onShowFlexible,
	onafterrender: showResultsPanel,
	sorters:{ outbound:{ value: 'href2Sort0', airline: 'href2Sort1', depart: 'href2Sort3', arrive: 'href2Sort4', stops: 'href2Sort5', operator: 'href2Sort2', duration: 'href2Sort6', img: 'sort2Img'} },
	outboundMgr:{
		resultsElement:'#flexibleResults',
		resultsCount:'#resultsCounts',
		pagingElement:'#spanPages',
		transportRow:'#transportRow',
		filterRow:'#rowOutbound',
		pageSizeSelect:'PageCountSize',
		xmlRequest:new ajaxRequester(),
		ajaxUrl:flexUrl,
		chart:new BarChart('flexibleView.outboundMgr','flexChart1','graphMonthLabel'),
		way:searchSettings.way,
		showAirlineLogos:searchSettings.showAirlineLogos,
		filters:{depAirports:'airportsDep',destAirports:'airportsDest',operators:'operatorsFilter',airlines:'airlinesFilter'},
		sliders:{
			depTime:{id:'#deptime',min:'mindeptime',max:'maxdeptime',minlabel:'#depStartTime',maxlabel:'#depEndTime'},
			retTime:{id:'#rettime',min:'minrettime',max:'maxrettime',minlabel:'#retStartTime',maxlabel:'#retEndTime'},
			outDuration:{id:'#outDuration',min:'outDurationMin',max:'outDurationMax',minlabel:'#outDurationMinLabel',maxlabel:'#outDurationMaxLabel',renderValue:renderSliderDuration,stepSize:5},
			retDuration:{id:'#retDuration',min:'retDurationMin',max:'retDurationMax',minlabel:'#retDurationMinLabel',maxlabel:'#retDurationMaxLabel',renderValue:renderSliderDuration,stepSize:5}
		}
	}
});
viewMgr.addView(flexibleView);

var onewayLegsView = new pageView({
	id:views.ONEWAYLEGS,
	tab:'#tabOneWay',
	panels:['#resultsHeader','#outboundTitlebar','#inboundTitlebar','#lnkOutbound','#dateFilterRow','#flightsFilter','#tbOneWayLegsOut','#dateFilterInRow','#InboundTable','#divInboundResults','#tblInboundFoot','#airlineRow','#airlineInboundRow'],
	onflightsadded:onOnewayLegsAdded,
	isGrouped:searchSettings.useGrouping,
	onshow:onShowOneway,
	onafterrender: showResultsPanel,
	sorters:{
		outbound:{value:'href1Sort0',airline:'href1Sort1',depart:'href1Sort3',arrive:'href1Sort4',stops:'href1Sort5',operator:'href1Sort2',duration:'href1Sort6',img:'sort1Img'},
		inbound:{value:'href3Sort0',airline:'href3Sort1',depart:'href3Sort3',arrive:'href3Sort4',stops:'href3Sort5',operator:'href3Sort2',duration:'href3Sort6',img:'sort3Img'}
	},
	outboundMgr:{
		resultsElement:'#tbOneWayLegsOut',
		resultsCount:'#resultsCounts',
		pagingElement:'#spanPages',
		transportRow:'#transportRow',
		filterRow:'#rowOutbound',
		pagesize:10,
		pageSizeSelect:'PageCountSize',
		showAirlineLogos:searchSettings.showAirlineLogos,
		filters:{depAirports:'airportsDep',destAirports:'airportsDest',operators:'operatorsFilter',dates:'dateFilter',transportTypes:'transportFilter',airlines:'airlinesFilter'},
		sliders:{
			depTime:{id:'#deptime',min:'mindeptime',max:'maxdeptime',minlabel:'#depStartTime',maxlabel:'#depEndTime'},
			outDuration:{id:'#outDuration',min:'outDurationMin',max:'outDurationMax',minlabel:'#outDurationMinLabel',maxlabel:'#outDurationMaxLabel',renderValue:renderSliderDuration,stepSize:5}
		}
	},
	inboundMgr:{
		resultsElement:'#tbOneWayLegsIn',
		resultsCount:'#resultsCountsIn',
		pagingElement:'#spanInboundPages',
		transportRow:'#transportInboundRow',
		filterRow:'#tblInbound',
		pagesize:10,
		pageSizeSelect:'InboundPageCountSize',
		showAirlineLogos:searchSettings.showAirlineLogos,
		filters:{depAirports:'airportsDepIn',destAirports:'airportsDestIn',operators:'operatorsInboundFilter',dates:'dateFilterIn',transportTypes:'transportInboundFilter',airlines:'airlinesInboundFilter'},
		sliders:{
			depTime:{id:'#deptimein',min:'mindeptimein',max:'maxdeptimein',minlabel:'#indepStartTime',maxlabel:'#indepEndTime'},
			outDuration:{id:'#inDuration',min:'inDurationMin',max:'inDurationMax',minlabel:'#inDurationMinLabel',maxlabel:'#inDurationMaxLabel',renderValue:renderSliderDuration,stepSize:5}
		}
	}
});
viewMgr.addView(onewayLegsView);

var flexibleLegsView = new flexiblePageView({
	id:views.FLEXIBLELEGS,
	tab:'#tabFlexible',
	panels:['#flexibleHeader','#flexibleResultsHeader','#flexWayNav','#flexibleOutTitlebar','#flexibleInTitlebar','#lnkOutbound','#tbOneWayLegsOut','#flexiblePanel','#flexiblePanel2','#InboundTable','#divInboundResults','#tblInboundFoot','#airlineRow','#airlineInboundRow'],
	onshow:onShowFlexible,
	onafterrender: showResultsPanel,
	sorters:{
		outbound:{value:'href2Sort0',airline:'href2Sort1',depart:'href2Sort3',arrive:'href2Sort4',stops:'href2Sort5',operator:'href2Sort2',duration:'href2Sort6',img:'sort2Img'},
		inbound:{value:'href3Sort0',airline:'href3Sort1',depart:'href3Sort3',arrive:'href3Sort4',stops:'href3Sort5',operator:'href3Sort2',duration:'href3Sort6',img:'sort3Img'}
	},
	outboundMgr:{
		resultsElement:'#tbOneWayLegsOut',
		resultsCount:'#resultsCounts',
		pagingElement:'#spanPages',
		transportRow:'#transportRow',
		filterRow:'#rowOutbound',
		pagesize:10,
		pageSizeSelect:'PageCountSize',
		xmlRequest:new ajaxRequester(),
		ajaxUrl:flexUrl,
		way:1,
		showAirlineLogos:searchSettings.showAirlineLogos,
		chart:new BarChart('flexibleLegsView.outboundMgr','flexChart1','graphMonthLabel'),
		filters:{depAirports:'airportsDep',destAirports:'airportsDest',operators:'operatorsFilter',airlines:'airlinesFilter'},
		sliders:{
			depTime:{id:'#deptime',min:'mindeptime',max:'maxdeptime',minlabel:'#depStartTime',maxlabel:'#depEndTime'},
			outDuration:{id:'#outDuration',min:'outDurationMin',max:'outDurationMax',minlabel:'#outDurationMinLabel',maxlabel:'#outDurationMaxLabel',renderValue:renderSliderDuration,stepSize:5}
		},
		sorter:new sortManager('sort2Img')
	},
	inboundMgr:{
		resultsElement:'#tbOneWayLegsIn',
		resultsCount:'#resultsCountsIn',
		pagingElement:'#spanInboundPages',
		transportRow:'#transportInboundRow',
		filterRow:'#tblInbound',
		pagesize:10,
		pageSizeSelect:'InboundPageCountSize',
		xmlRequest:new ajaxRequester(),
		ajaxUrl:flexUrl,
		way:1,
		showAirlineLogos:searchSettings.showAirlineLogos,
		chart:new BarChart('flexibleLegsView.inboundMgr','flexChart2','graphMonthLabel2'),
		filters:{depAirports:'airportsDepIn',destAirports:'airportsDestIn',operators:'operatorsInboundFilter',airlines:'airlinesInboundFilter'},
		sliders:{
			depTime:{id:'#deptimein',min:'mindeptimein',max:'maxdeptimein',minlabel:'#indepStartTime',maxlabel:'#indepEndTime'},
			outDuration:{id:'#inDuration',min:'inDurationMin',max:'inDurationMax',minlabel:'#inDurationMinLabel',maxlabel:'#inDurationMaxLabel',renderValue:renderSliderDuration,stepSize:5}
		}
	}
});
viewMgr.addView(flexibleLegsView);

var mapView = new mapPageView({
	id:views.MAP,
	tab:'#tabMap',
	panels:['#timeRetFilter','#flexibleHeader','#flexibleResultsHeader','#mapTitlebar','#dateFilterRow','#progressiveResults','#pnlMap','#mapNav','#airlineRow','#durationRetFilter'],
	sorters:{outbound:{value:'href2Sort0',airline:'href2Sort1',depart:'href2Sort3',arrive:'href2Sort4',stops:'href2Sort5',operator:'href2Sort2',duration:'href2Sort6',img:'sort2Img'}},
	onshow:onShowMap,
	onafterrender: showResultsPanel,
	isGrouped: searchSettings.useGrouping,
	useView:defaultView,
	map:new mapManager({id:'mapDiv',useLoader:true}),
	accessor:'mapView',
	renderOverride:renderMapResults,
	onEndpointChanged:onMapEndpointChanged
});
viewMgr.addView(mapView);

var makeRangeSlider = function(id, minlabel, maxlabel, type, renderValue){
	$(id).slider({
		range:true,
		slide:function(e,ui){ 
			var elem = $(this);
			var minval = parseInt(elem.slider('value',0),10);
			var maxval = parseInt(elem.slider('value',1),10);
			$(minlabel).html(renderValue(minval));
			$(maxlabel).html(renderValue(maxval));
		},
		change:function(e,ui){ 
			var hnd = ui.handle["0"];
			viewMgr.changeSlider(type, this.id, hnd.id, ui.value);
		}
	});
};

$(window).bind("load",function(){
	makeRangeSlider('#deptime','#depStartTime','#depEndTime','time',renderSliderTime);
	makeRangeSlider('#rettime','#retStartTime','#retEndTime','time',renderSliderTime);
	makeRangeSlider('#deptimein','#indepStartTime','#indepEndTime','time',renderSliderTime);
	if(searchSettings.enableDurationsFilter){
		makeRangeSlider('#outDuration','#outDurationMinLabel','#outDurationMaxLabel','duration',renderSliderDuration);
		makeRangeSlider('#retDuration','#retDurationMinLabel','#retDurationMaxLabel','duration',renderSliderDuration);
		makeRangeSlider('#inDuration','#inDurationMinLabel','#inDurationMaxLabel','duration',renderSliderDuration);
	}
	viewMgr.refreshSliders();
});

var pageManager = {
	unfinishedElem: 'resultsWaiting',
	searchingElem: 'SearchingTbl',
	filterElem: 'RefineSearch',
	otherAirlinesElem: 'otherAirlines',
	otherAgentsElem: 'otherOperators',
	operators: {},
	inprogress: [],
	finished: {},
	searchFinished: false,
	waitingVisible: true,
	hasFlexibleReturns: false,
	hasFlexibleOneways: false,
	altRoutesDisplayed: false,
	addOperators: function (ops) {
		for (var i = ops.length; i--; ) {
			var op = ops[i];
			if (!this.operators[op.opid]) {
				op.hasFlights = false;
				op.isFinished = false;
				this.operators[op.opid] = op;
				this.inprogress.push(op.opid);
			}
		}
		this.renderSearching();
	},
	endOperator: function (opid) {
		this.hideWaiting();
		for (var i = this.inprogress.length; i--; ) {
			if (this.inprogress[i] == opid) {
				this.inprogress.splice(i, 1);
				this.setOperatorFinished(this.operators[opid]);
				this.renderSearching();
				return;
			}
		}
		this.renderSearching();
	},
	setOperatorHasFlights: function (opid) {
		if (this.operators[opid]) {
			this.operators[opid].hasFlights = true;
		}
	},
	setOperatorFinished: function (op) {
		op.isFinished = true;
		if (!this.finished[op.opid]) {
			this.finished[op.opid] = op;
			this.appendOtherOperator(op);
			this.updateInProgress();
		}
	},
	appendOtherOperator: function (op) {
		if (!op || op.hasFlights || !this.isAirline(op.type)) { return; }
		var el = getElement(this.otherAirlinesElem);
		if (el) {
			var html = '<div class="OtherOperator"><a href="' + op.link + '" target="_blank">' +
				'<img src="' + IMG_ROOT + 'i/operator/' + op.logo + '" alt="' + op.name + '" onError="hideElement(this)" border=0></a><br>' +
				'<a class="GreenLink" href="' + op.link + '" target="_blank">' + op.name + '</a></div>';
			el.innerHTML += html;
			var tblOtherOps = getElement('tblOtherAirlines');
			if (tblOtherOps) { tblOtherOps.style.display = ''; }
		}
	},
	addOnlineAgent: function (op) {
		var el = getElement(this.otherAgentsElem);
		if (el) {
			var html = '<div class="OtherOperator"><a href="' + op.link + '" target="_blank">' +
				'<img src="' + IMG_ROOT + 'i/operator/btn/' + op.logo + '" alt="' + op.name + '" onError="hideElement(this)" border=0></a><br>' +
				'<a class="GreenLink" href="' + op.link + '" target="_blank">' + op.name + '</a></div>';
			if (op.tracker) { html += '<div style="display:none">' + op.tracker + '</div>'; }
			el.innerHTML += html;
			var tblOtherOps = getElement('tblOtherOperators');
			if (tblOtherOps) { tblOtherOps.style.display = ''; }
		}
	},
	renderSearching: function () {
		var html = '';
		for (var prop in this.operators) {
			var op = this.operators[prop];
			if (!op) { continue; }
			if (op.isFinished) {
				if (op.hasFlights) {
					html += '<div class=SearchedOperator>' + op.name + '</div>';
				}
			}
			else {
				html += '<div class=SearchingOperator>' + op.name + '</div>';
			}
		}
		var el = getElement('SearchedOps');
		if (el) { el.innerHTML = html; }
	},
	updateInProgress: function () {
		var count = this.inprogress.length;
		var elUnfinished = getElement(this.unfinishedElem);
		if (count > 0 && elUnfinished) {
			elUnfinished.innerHTML = TXT_MORE_RESULTS.replace('%1', '<b>' + count + '</b>');
		}
		else if (elUnfinished) { elUnfinished.style.display = 'none'; }
	},
	endSearching: function () {
		var elSearching = getElement(this.searchingElem);
		var elFilter = getElement(this.filterElem);
		this.updateInProgress();
		if (elSearching) { elSearching.style.display = 'none'; }
		if (elFilter) { elFilter.style.display = ''; }
		this.hideWaiting();
		viewMgr.refreshSliders();
	},
	endSearch: function () {
		this.searchFinished = true;
		searchSettings.searchFinished = true;
		this.endSearching();
		var elUnfinished = getElement(this.unfinishedElem);
		var elMapTab = getElement('tabMap');
		if (elUnfinished) { elUnfinished.style.display = 'none'; }
		if (elMapTab) { elMapTab.style.display = ''; }
		showResultsPanel();
		LogSearch(viewMgr.getResultsCount(views.DEFAULT));
		this.hideWaiting();
		viewMgr.refresh();
		this.showAlternativeRoute();
	},
	hideWaiting: function () {
		var waitFrame, waitElem;
		if (this.waitingVisible) {
			if (WAITING_ELEM && WAITING_ELEM.length > 0) { waitElem = getElement(WAITING_ELEM); }
			if (waitElem) {
				waitElem.style.display = 'none';
				waitElem.parentNode.removeChild(waitElem);
			}
			if (WAITING_FRAME && WAITING_FRAME.length > 0) { waitFrame = getElement(WAITING_FRAME); }
			if (waitFrame) {
				waitFrame.style.display = 'none';
				waitFrame.parentNode.removeChild(waitFrame);
			}
		}
		this.waitingVisible = false;
	},
	showLoadingScreen: function (visible) {
		visible = visible && this.searchFinished;
		this.setLoadingScreenVisibility(visible);
	},
	setLoadingScreenVisibility: function (visible) {
		var loadingScreen = getElement("updating");
		if (loadingScreen) { loadingScreen.style.display = (visible ? "" : "none"); }
	},
	isAirline: function (type) {
		switch (type) {
			case optype.ONLINE_TRAVEL_AGENT:
				return false;
			case optype.TRAINS:
				return false;
			case optype.BUSES:
				return false;
			case optype.FERRIES:
				return false;
			case optype.OTHER:
				return false;
			default:
				return true;
		}
	},
	setFlexible: function (hasReturn, hasOneway) {
		this.hasFlexibleReturns = hasReturn;
		this.hasFlexibleOneways = hasOneway;
		if (getElement('tabFlexible')) {
			getElement('tabFlexible').style.display = (this.hasFlexibleReturns ? '' : 'none');
			if (getElement('flexLegsLink')) {
				getElement('flexLegsLink').style.display = (this.hasFlexibleOneways ? '' : 'none');
			}
		}
	},
	stopSearch: function () {
		stopPage();
		this.endSearch();
	},
	toggleFilter: function (inbound, img) {
		var visible = viewMgr.toggleFilter(inbound);
		var targetImg = getElement(img);
		if (targetImg && visible != null) { targetImg.src = (visible ? imgMinus : imgPlus); }
	},
	showAlternativeRoute: function () {
		var altDeps = searchSettings.altDeps;
		var altDests = searchSettings.altDests;
		var showAlt = (viewMgr.getResultsCount(views.DEFAULT) == 0 && altDeps && altDests && (altDeps.length > 0 || altDests.length > 0));
		if (this.altRoutesDisplayed || !showAlt) { return; }
		var len, apt;
		var content = '<table width="90%" align="center" border="0" cellpadding="0">';
		content += '<tr><td colspan="2"><p>' + TXT_ALT_AIRPORTS_NO_RESULTS1 + '</p><p>' + TXT_ALT_AIRPORTS_NO_RESULTS2 + '</p></td></tr>';
		content += '<tr><td><h3>' + TXT_DEPARTURES + '</h3></td>';
		content += '<td><input type="checkbox" id="altDepNearby" checked/><label for="altDepNearby">' + TXT_INCLUDE_NEARBY + '</label></td></tr>';
		len = altDeps.length;
		if (len > 0) {
			for (var i = 0; i < len; i++) {
				apt = altDeps[i];
				content += '<tr><td colspan="2">' + this.getAltRadioButton(apt.city, apt.country, apt.name, apt.iata, true, (i == 0), apt.dist) + '<br/></td></tr>';
			}
			apt = searchSettings.dep;
			content += '<tr><td colspan="2">' + this.getAltRadioButton(apt.name, apt.country, null, apt.iata, true, false) + '<br/></td></tr>';
		}
		else {
			apt = searchSettings.dep;
			content += '<tr><td colspan="2">' + this.getAltRadioButton(apt.name, apt.country, null, apt.iata, true, true) + '<br/></td></tr>';
		}
		content += '<tr><td><h3>' + TXT_DESTINATIONS + '</h3></td>';
		content += '<td><input type="checkbox" id="altDestNearby" checked/><label for="altDestNearby">' + TXT_INCLUDE_NEARBY + '</label></td></tr>';
		len = altDests.length;
		if (len > 0) {
			for (var i = 0; i < len; i++) {
				apt = altDests[i];
				content += '<tr><td colspan="2">' + this.getAltRadioButton(apt.city, apt.country, apt.name, apt.iata, false, (i == 0), apt.dist) + '<br/></td></tr>';
			}
			apt = searchSettings.dest;
			content += '<tr><td colspan="2">' + this.getAltRadioButton(apt.name, apt.country, null, apt.iata, false, false) + '<br/></td></tr>';
		}
		else {
			apt = searchSettings.dest;
			content += '<tr><td colspan="2">' + this.getAltRadioButton(apt.name, apt.country, null, apt.iata, false, true) + '<br/></td></tr>';
		}
		content += '<tr><td align="center" colspan="2"><p>' +
			'<div class="smallbutton" onclick="lbox.hideLightBox();pageManager.generateAlternativeUrl();"><span class="text">' + TXT_YES + '</span></div> ' +
			'<div class="smallbutton" onclick="lbox.hideLightBox();"><span class="text">' + TXT_NO + '</span></div>' +
			'</p></td></tr></table>';
		lbox.showLightBox(content, 580, true);
		this.altRoutesDisplayed = true;
	},
	getAltRadioButton: function (city, country, txt, iata, isDep, checked, distance) {
		var html, id, data;
		var groupId = (isDep ? 'altDeps' : 'altDests');
		id = groupId + iata.toUpperCase();
		data = (isDep ? 'depcity' : 'destcity') + '=' + encodeURIComponent(city) + '&' + (isDep ? 'depIATA' : 'destIATA') + '=' + iata;
		html = '<input type="radio" name="' + groupId + '" id="' + id + '" value="' + data + '" ' + (checked ? 'checked' : '') + '/>';
		html += ' <label for="' + id + '">' + city + (txt ? ' ' + txt : '') + ', ' +
			country + (distance > 0 ? ' (' + distance + ' KM)' : '') + '</label>';
		return html;
	},
	generateAlternativeUrl: function () {
		var i, len, depVal, destVal;
		var altDeps = document.getElementsByName("altDeps");
		len = altDeps.length;
		for (i = 0; i < len; i++) {
			if (altDeps[i].checked) { depVal = altDeps[i].value; break; }
		}
		var altDests = document.getElementsByName("altDests");
		len = altDests.length;
		for (i = 0; i < len; i++) {
			if (altDests[i].checked) { destVal = altDests[i].value; break; }
		}
		if (depVal && destVal) {
			var depNearby = getElement("altDepNearby");
			var destNearby = getElement("altDestNearby");
			var url = FLIGHTS_FOLDER + "flysearch.aspx";
			url += '?' + depVal + '&' + destVal + (depNearby && !depNearby.checked ? '' : '&depAll=1');
			url += (destNearby && !destNearby.checked ? '' : '&destAll=1') + '&' + searchSettings.altQueryString;
			window.location.href = url;
		}
	}
};

var URI = function(url){
	this.Url = "";
	this.TLD = "";
	this.DomainName = "";
	this.SubDomain = null;
	try{
		if(url.match(new RegExp(/^http\:\/\/|^https\:\/\/|^ftp\:\/[\/]/i))){
			url = url.replace(new RegExp(/^http\:\/\/|^https\:\/\/|^ftp\:\/[\/]/i), "");
		}
		url = url.replace(new RegExp(/\/(.*)/),""); 
		this.Url = trim(url);

		if(url.match(new RegExp(/\.[a-z]{2,3}\.[a-z]{2}$/i))){
			this.TLD = url.match(new RegExp(/\.[a-z]{2,3}\.[a-z]{2}$/i))[0];
			url = url.replace(this.TLD, ""); 
		}
		else if(url.match(new RegExp(/\.[a-z]{2,4}$/i))){
			this.TLD = url.match(new RegExp(/\.[a-z]{2,4}$/i))[0];
			url = url.replace(this.TLD, ""); 
		}

		if(url.indexOf(".") != -1){
			var ixDot = url.indexOf(".");
			this.DomainName = url.substr(ixDot+1);
			this.SubDomain = url.substr(0,ixDot);
		}
		else{ this.DomainName = url; }
	}
	catch(e){}
};

var cookieManager = {
	writeCookie: function (aptdep, aptdest, outdate, retdate, adults, childs, infants, fly, tra, fer, bus) {
		if (aptdep == '' || aptdest == '' || aptdep == aptdest || outdate == '') { return; }
		try {
			var cookieVal, data;
			data = 'DEP=' + aptdep + '&DEST=' + aptdest + '&OUT=' + outdate +
				(adults != 1 ? '&ADU=' + adults : '') +
				(childs != 0 ? '&CHI=' + childs : '') +
				(infants != 0 ? '&INF=' + infants : '') +
				(fly != 1 ? '&FLI=' + fly : '') +
				(tra != 0 ? '&TRA=' + tra : '') +
				(fer != 0 ? '&FER=' + fer : '') +
				(bus != 0 ? '&BUS=' + bus : '');
			if (retdate) { data += '&RET=' + retdate; }
			if (searchSettings.dep.all) { data += '&DEPALL=1'; }
			if (searchSettings.dest.all) { data += '&DESTALL=1'; }

			var cheapestItem = defaultView.getCheapestItem();
			cookieVal = data +
				'&VAL=' + (cheapestItem ? (cheapestItem.opvalue ? cheapestItem.opvalue : cheapestItem.value) : '') +
				'&CURR=' + (cheapestItem ? (cheapestItem.opvalue ? cheapestItem.opcurrency : cheapestItem.currency) : '');

			var arr = [];
			arr.push(cookieVal);

			var maxCookies = 4;
			// Read Previous Search cookies
			for (var i = 1; i <= maxCookies; i++) {
				var ps = this.getCookie('PS' + (i));
				if (ps) {
					var end = ps.indexOf('&VAL');
					var itemData = ps.substring(0, end);
					if (itemData != data) { arr.push(ps); }
				}
			}
			var len = (arr.length <= maxCookies ? arr.length : maxCookies);
			var docUri = new URI(document.domain);
			var host = null;
			if (docUri.DomainName.length > 0 && docUri.TLD.length > 0) { host = docUri.DomainName + docUri.TLD; }

			// Write Previous Search cookies
			for (var i = 0; i < len; i++) {
				var datestr = this.getValue(arr[i], 'OUT');
				var dt = Date.parseDate(datestr, 'yyyy/MM/dd');
				dt.setDate(dt.getDate() + 1);
				this.setCookie('PS' + (i + 1), arr[i], dt, '/', host);
			}
		}
		catch (e) { }
	},
	setCookie: function (name, value, expires, path, domain, secure) {
		try {
			document.cookie = name + '=' + value +
				(expires ? '; expires=' + expires.toGMTString() : '') +
				(path ? '; path=' + path : '') +
				(domain ? '; domain=' + domain : '') +
				(secure ? '; secure' : '');
		} catch (e) { }
	},
	getCookie: function (name) {
		var arg = name + '[\=]([^\;]*)?';
		var re = new RegExp(arg);
		var m = re.exec(document.cookie);
		if (m == null) { return m; }
		else { return m[1]; }
	},
	getValue: function (text, name) {
		var arg = name + '[\=]([^\;|^\&]*)?';
		var re = new RegExp(arg);
		var m = re.exec(text);
		if (m == null) { return m; }
		else { return m[1]; }
	}
};

var pageResultsAdded = function(result){
	if(result && result.flights && result.flights.length > 0){
		pageManager.setOperatorHasFlights(result.operator.opid);
	}
};
viewMgr.attachEvents({ onResultsAdded: pageResultsAdded });

var updateRadioButtonList = function(radioBtn, uniqueId, firstInput, secondInput, inbound, isOutLeg){
	var priceElement = getElement('price' + uniqueId);
	var vals = (radioBtn && radioBtn.value ? radioBtn.value.split('|', 3) : []);
	var price = null;
	var priceText = null;
	if(priceElement){
		var firstVal = getElement(firstInput + uniqueId);
		var secondVal = getElement(secondInput + uniqueId);
		if(firstVal){
			firstVal.value = (vals.length > 0 ? vals[0] : '');
			price = parseFloat(firstVal.value);
		}
		if(secondVal){ price += parseFloat(secondVal.value); }
		if(price){
			priceText = formatCurrencyFromSettings(price);
			if(priceText){ priceElement.innerHTML = getDisplayPrice(priceText); }
		}
	}
	var row, tbl;
	var elem = radioBtn.parentNode;
	while (elem && elem.tagName != "TABLE" && elem.tagName != "BODY"){
		if(elem.tagName == "TR"){ row = elem; }
		elem = elem.parentNode;
		if(elem.tagName == "TABLE"){ tbl = elem; }
	}
	if(tbl){
		for(var i = 1, len = tbl.rows.length; i < len; i++){
			tbl.rows[i].className = null;
		}
	}
	if(row){ row.className = 'optionSelected'; }
	if(vals.length >= 3){ viewMgr.setSelectedOption(uniqueId,{ dep: vals[1], arr: vals[2], value: price, price: priceText }, inbound, isOutLeg); }
};

var emailOffer = function(id){
	var url = LANG_ROOT_PATH + 'AJAX/Statistics.asmx/EmailOffer';
	if(typeof jxRequest != 'undefined'){
		var fromEmail = getElement('fromEmail' + id);
		var fromName = getElement('fromName' + id);
		var toEmail = getElement('toEmail' + id);
		var toName = getElement('toName' + id);
		var msg = getElement('message' + id);
		var body = getElement('body' + id);
		var offerUrl = getElement('url' + id);
		var lang = LANG_CODE;
		if(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(toEmail.value)){
			var content = 'fromEmail=' + encodeURIComponent(fromEmail.value) +
				'&fromName=' + encodeURIComponent(fromName.value) +
				'&toEmail=' + encodeURIComponent(toEmail.value) +
				'&toName=' + encodeURIComponent(toName.value) +
				'&lang=' + encodeURIComponent(lang) +
				'&url=' + encodeURIComponent(offerUrl.value) +
				'&msg=' + encodeURIComponent(msg.value) +
				'&body=' + encodeURIComponent(sterilizeHtml(body.innerHTML));
			jxRequest.Request(url, null, 'POST', content);
			lbox.hideLightBox();
		}
	}
};

var sterilizeHtml = function(html){
	return html.replace(/\</g, "[").replace(/\>/g, "]")
};


