/* ExtJS config begin */

Ext.Ajax.timeout = 600000; /* 10 min */
Ext.BLANK_IMAGE_URL = staticContentRoot + "img/misc/x.gif"

/* ExtJS config end */


/* constants and paterns */

Date.patterns = {
	MonthYear:"n-Y",
    DayMonthYear:"j-n-Y"
/*
Format  Description                                                             Example returned values
------  ----------------------------------------------------------------------  -----------------------
  n     Numeric representation of a month, without leading zeros                1 to 12
  Y     A full numeric representation of a year, 4 digits                       Examples: 1999 or 2003
*/
};

var onloadGlobalHandler = {
	extraDataLoaded: true,
	actions: {},

	addAction: function(name, handler) {
		this.actions[name] = handler;
	}
	,

	execute: function(){
		if(!this.extraDataLoaded){
			setTimeout(function(){onloadGlobalHandler.execute()},100);
			return;
		}
		for( var i in this.actions ){
			this.actions[i]();
		}
	}
};

var onunloadGlobalHandler = {
	extraDataLoaded: true,
	actions: {},

	addAction: function(name, handler) {
		this.actions[name] = handler;
	}
	,

	execute: function(){
		if(false){ // old value !this.extraDataLoaded
			setTimeout(function(){onunloadGlobalHandler.execute()},100);
			return;
		}
		for( var i in this.actions ){
			this.actions[i]();
		}
	}
};

// Ext.onReady( function(){onloadGlobalHandler.execute()} );
Ext.EventManager.on(window, "load", function(){onloadGlobalHandler.execute()})
Ext.EventManager.on(window, "unload", function(){onunloadGlobalHandler.execute()})

/*
config structure:
	id: String
	requestURL: String
	opacity: Boolean. Default: false
	templateName: String
	position: String.  (relative/fixed/centered)
	offsets:{el:Object/String, t:Number, l:Number},
	closeOnBlur:false [TBD]
	beforeCloseAction:null [TBD]
	afterCloseAction:null [TBD]

*/
var popupFramework = {
	templates: {
		shim: '<div id="popupShimOuter" style="display:none"><iframe src="javascript:false" frameBorder="0" scroll="none"></iframe></div>',
		popupSmall:'<div id="{[values.config.id]}Dialog" class="glbPopupSm popupDiv"><div class="glbPopupPanel"><p class="popupClose"><a href="#" onclick="popupFramework.hide({id:\'{[values.config.id]}\'});return false">Close window</a></p><h2>{[values.contentData.title]}</h2><div id="{[values.config.id]}Content" class="popupContent">{[values.contentData.content]}</div></div>',
		popupLarge:'<div id="{[values.config.id]}Dialog" class="glbPopupLg popupDiv"><div class="glbPopupPanel"><p class="popupClose"><a href="#" onclick="popupFramework.hide({id:\'{[values.config.id]}\'});return false">Close window</a></p><h2>{[values.contentData.title]}</h2><div id="{[values.config.id]}Content" class="popupContent">{[values.contentData.content]}</div></div>',
		calendar:'<div id="{[values.config.id]}Dialog" class="glbCalPopupWrapper popupDiv"><div class="glbCalPopup"><div class="calMonthNav"><p class="calMonthNavBack"><a href="#" onclick="calendar.prevMonth();return false">Previous month</a></p><p class="calMonthNavClose"><a href="#" onclick="calendar.hide({id:\'{[values.config.id]}\'});return false"><img src="img/buttons/btn-cal-close.gif" alt="Close popup" title="Close popup" width="15" height="15" /></a></p><p class="calMonthNavNext"><a href="#" onclick="calendar.nextMonth();return false">Next month</a></p></div><div id="{[values.config.id]}MonthBlock1" class="calMonthBlock"></div><div id="{[values.config.id]}MonthBlock2" class="calMonthBlock"></div></div></div>',
		popupCityOrAirport:'<div id="{[values.config.id]}Dialog" class="glbLookupPopup popupDiv"><div class="hLookupTitle"><h3>Airport selection</h3><p class="calMonthNavClose"><a href="#" onclick="popupFramework.hide({id:\'{[values.config.id]}\'});return false"><img src="img/buttons/btn-cal-close.gif" alt="Close popup" title="Close popup" width="15" height="15" /></a></p></div><div class="glbLookupContent"><form action="#"><fieldset><label>Country</label><select id="{[values.config.id]}country-select" name="{[values.config.id]}country-select" class="lookupCountryDDL"><option value="0">Loading...</option></select></fieldset><fieldset><label>City or airport</label><div class="glbLookupCity"><div class="glbLookupCityLinks" id="{[values.config.id]}CityLinks"><tpl for="contentData.alphabet"><a href="#" onclick="popupLookup.onClickQuickLink({#});return false">{.}</a> </tpl></div><div class="glbLookupCityListOuter"><div id="{[values.config.id]}CityList" class="glbLookupCityList"></div></div></div></fieldset></form></div></div>'
	}
	,
	popups: {
		didOnlineHelp: {
			contentData: {title:'popup title1',content:'text text1'}
		}
	}
	,
	lazyContentsPool: {
		didOnlineHelp: {
			isPending: true,
			strContentData: "{title:'popup title1',content:'text text'}",
			config: {}
		}
	}
	,
	show: function(config) {
		if(!Ext.get(config.id+"Outer")) {
			var	cbStack = [];
				cbStack[cbStack.length] = {handler:popupFramework.doShow,scope:popupFramework,params:[config,cbStack]}
			this.create(config,cbStack);
		}
		else {
			this.doShow(config);
		}
	}
	,
	doShow: function(config) {
		if(!Ext.get(config.id+"Outer").isDisplayed()){
			var shim = Ext.get("popupShimOuter");
			if(!shim) {
				shim = Ext.getBody().insertHtml("afterBegin", this.templates.shim, true);
				// a = Ext.getBody().dom.style.backgroundAttachment="fixed";
			}

			shim.removeClass('popupShimOuterOpacity');
			shim.addClass((config.opacity)?'popupShimOuterOpacity':'');

			var top=0;
			var left=0;
			if(config.offsets) {
				if(config.offsets.el && config.position!="centered"){
					var el = Ext.get(config.offsets.el);
					var xy = el.getXY();
					top = xy[1];
					left = xy[0];
				}
				top += (config.offsets.t)?config.offsets.t:0;
				left += (config.offsets.l)?config.offsets.l:0;
				var outerXY = Ext.get('all').getXY();
				top -= outerXY[1];
				left -= outerXY[0];
			}

			Ext.get(config.id+"Dialog").applyStyles('margin:'+top+'px 0 0 '+left+'px;');

			Ext.get("popupShimOuter").setDisplayed(true);
			Ext.get(config.id+"Outer").setDisplayed(true);

			if(this.lazyContentsPool[config.id] && this.lazyContentsPool[config.id].isPending){
				this.lazyContentsPool[config.id].isPending = false;
				this.populationLazyContent(this.lazyContentsPool[config.id].config, this.lazyContentsPool[config.id].strContentData)
			}

		}

	}
	,
	hide: function(config) {
		Ext.get(config.id+"Outer").setDisplayed(false);
		Ext.get("popupShimOuter").setDisplayed(false);
	}
	,
	create: function(config,cbStack) {
		if(!this.popups[config.id]) {
				cbStack = (cbStack)? cbStack : [];
				cbStack[cbStack.length] = {handler:popupFramework.doCreate,scope:popupFramework,params:[config,cbStack]}
			this.load(config,cbStack);
		}
		else {
			this.doCreate(config,cbStack);
		}
	}
	,
	doCreate: function(config,cbStack) {
		if(!Ext.get(config.id+"Outer")){
			switch(config.position){
				case "relative":
					config.positionClass = "popupOuterDivRelative";
					break;
				case "fixed":
					config.positionClass = "popupOuterDivFixed";
					break;
				case "centered":
					config.positionClass = "popupOuterDivCentered";
					break;
				default:
					config.positionClass = "popupOuterDivCentered";
			}

			var tpl = new Ext.XTemplate('<div id="{[values.config.id]}Outer" class="popupOuterDiv {[values.config.positionClass]}" style="display:none"><table class="popupOuterTable"><tr><td class="popupOuterTD">'+((this.templates[config.templateName])?this.templates[config.templateName]:'{html}')+'</td></tr></table></div>');
			tpl.insertFirst(Ext.getBody(),{config:config,contentData:this.popups[config.id].contentData})
		}
		if(cbStack){
			var handler = cbStack[cbStack.length-1].handler;
			var scope = cbStack[cbStack.length-1].scope;
			var params = cbStack[cbStack.length-1].params;
			cbStack.length--;
			handler.apply(scope,params);

		}
	}
	,
	load: function(config,cbStack) {
		Ext.Ajax.request({
			url: config.requestURL,
			params: { needTemplate:(this.templates[config.templateName])?false:true },
			options: { config:config,cbStack:cbStack },
			success: this.loadCallBack,
			scope: this
		});
	}
	,
	loadCallBack: function(response,options) {
		var config = options.options.config;
		var cbStack = options.options.cbStack;
		if(!this.popups[config.id]){
			try {
				eval('this.popups.' + config.id + ' = ' + response.responseText);
			}
			catch (e) {
				return false;
			}
			if(this.popups[config.id].template){
				this.templates[config.templateName] = this.popups[config.id].template;
			}
		}
		if(cbStack){
			var handler = cbStack[cbStack.length-1].handler;
			var scope = cbStack[cbStack.length-1].scope;
			var params = cbStack[cbStack.length-1].params;
			cbStack.length--;
			handler.apply(scope,params);
		}
	}
	,
	populationLazyContent: function(config, response){
 		// {id:'idOfPopup', populationHandler:{handler:customFunction,scope:thisOfcustomFunction}}, response.responseText

  		this.lazyContentsPool[config.id] = {
   			isPending: (Ext.get(config.id+"Outer"))? false : true,
   			strContentData: response,
   			config: config
  		}

  		if(Ext.get(config.id+"Outer")){
   			if(config.populationHandler){
    			var extHandler = config.populationHandler;
    			extHandler.handler.apply(extHandler.scope,[config, response]);
   			}
   			else {
    			/* default population according to simple data format */
    			eval("var tContentData =" + response);
    			Ext.get(config.id+"Content").dom.innerHTML = tContentData.content;
   			}
  		}
 	}
}

var popupLookup = {
	idLookup: "popupLookup",
	params: null,
	oCountrySelect: null,
	oCityLinks: null,
	oCityList: null,
	countries: null,
	cities: {},
	quickLinksMapping: {},
	alphabet: [],
	isInit: false,

	init: function(params) {
		switch(params.flowType){
			case "flight":
				this.requestParams = {
					templateName:'popupCityOrAirport',
					baseUrl:'AirportLookUpPopupForward.do',
					countryUrl:'CountriesSearchForward.do',
					cityUrl:'AirportLocationsSearchByCountry.do'
				}
				break;
			case "hotel":
				this.requestParams = {
					templateName:'popupCity',
					baseUrl:'CityLookUpPopupForward.do',
					countryUrl:'CountriesSearchForward.do',
					cityUrl:'HotelLocationsSearchByCountry.do'
				}
				break;
		}
		var cbStack = [];
		cbStack[cbStack.length] = {handler:popupLookup.doInit,scope:popupLookup,params:[params,cbStack]};
		popupFramework.create({id:this.idLookup,requestURL:this.requestParams.baseUrl,opacity:true,templateName:this.requestParams.templateName,position:'centered'},cbStack);
	}
	,
	doInit: function(params,cbStack) {
		this.alphabet = popupFramework.popups[this.idLookup].contentData.alphabet;
		this.oCountrySelect = Ext.get(this.idLookup+"country-select");
		this.oCityLinks = Ext.get(this.idLookup+"CityLinks");
		this.oCityList = Ext.get(this.idLookup+"CityList");

		this.oCountrySelect.on('change', this.changeCountry, this)
		this.oCountrySelect.dom.disabled = true;
		this.isInit = true;

		Ext.Ajax.request({
			url: this.requestParams.countryUrl,
			params: { test:1 },
			options: {},
			success: this.fillCountries,
			scope: this
		});

		this.show(params);
	}
	,
	fillCountries: function(response,options) {
		/* please check response here beg */
		if(!isValidAjaxResponse(response.responseText))
		{
			response.responseText = '[[\'\',\'\']]';
		}
		else
		{
			if(isAjaxSessionExpired(response.responseText)){
				forwardSessionExpired();
			}
		}
		/* please check response here end */
		eval('this.countries = ' + response.responseText);

		var defCountry = (this.params.defCountry) ? this.params.defCountry : "0";

		this.oCountrySelect.dom.length = 0;
		for(var i=0; i<this.countries.length; i++){
			this.oCountrySelect.dom.options.length++;
			this.oCountrySelect.dom.options[i] = new Option (this.countries[i][0], this.countries[i][1], false,(this.countries[i][1]==defCountry)?true:false);
		}

		this.oCountrySelect.dom.disabled = false;
		this.changeCountry(null,this.oCountrySelect.dom);
	}
	,
	changeCountry: function(e,o){
		var val = o.value;
		var countryRef = val + this.params.locality;
		if(val == "0"){
			this.oCityLinks.addClass("glbLookupCityLinksDisabled");
			this.oCityList.dom.innerHTML = "";
		}
		else {
			if(!this.cities[countryRef]){
				this.oCountrySelect.dom.disabled = true;
				this.oCityLinks.addClass("glbLookupCityLinksDisabled");
				this.oCityLinks.addClass("glbLookupCityLinksDisabled");
				this.oCityList.dom.innerHTML = "";
				Ext.Ajax.request({
					url:  this.requestParams.cityUrl,
					params: { 	countryCode: val,
								locality: this.params.locality,
								/* special param for App begin */
								isDepartureLocationLookup: (this.params.locality=='departure')?true:false
								/* special param for App end */
					 },
					options: {},
					success: this.callBackChangeCountry,
					scope: this
				});
			}
			else{
				this.doChangeCountry(val);
			}
		}
	}
	,
	callBackChangeCountry: function(response,options){
		/* please check response here beg */
		if(!isValidAjaxResponse(response.responseText))
		{
			response.responseText = '[]';
		}
		else
		{
			if(isAjaxSessionExpired(response.responseText)){
				forwardSessionExpired();
			}
		}
		/* please check response here end */
		var countryCode = options.params.countryCode;
		var countryRef = countryCode + this.params.locality;
		eval('this.cities["'+countryRef+'"] = ' + response.responseText);
		this.quickLinksMapping[countryRef] = [];
		for(var i=0; i<this.alphabet.length; i++){
			this.quickLinksMapping[countryRef][i] = false;
		}

		for(var i=0; i<this.cities[countryRef].length; i++){
			if(i && (this.cities[countryRef][i][0].charAt(0).toUpperCase() == this.cities[countryRef][i-1][0].charAt(0).toUpperCase())){
				continue;
			}
			for(var k=0; k<this.alphabet.length; k++){
				if(this.cities[countryRef][i][0].charAt(0).toUpperCase() == this.alphabet[k].toUpperCase()){
					this.quickLinksMapping[countryRef][k] = true;
					break;
				}
			}
		}
		this.doChangeCountry(countryCode);
	}
	,
	doChangeCountry: function(value){
		var countryRef = value + this.params.locality;
		var str="";
		for(var i=0; i<this.cities[countryRef].length; i++){
			str+='<a href="#" class="'+((i%2)?'evenItem':'oddItem')+'" onclick="popupLookup.selectCity(\''+value+'\',\''+i+'\');return false">'+this.cities[countryRef][i][0]+'</a>';
		}

		this.oCityList.dom.innerHTML = str;
		this.oCountrySelect.dom.disabled = false;
		var itemsCityLinks = this.oCityLinks.dom.getElementsByTagName("A");
		for(var i=0; i<this.quickLinksMapping[countryRef].length; i++){
			if(this.quickLinksMapping[countryRef][i]){
				Ext.get(itemsCityLinks[i]).removeClass("letterDisabled");
			}
			else {
				Ext.get(itemsCityLinks[i]).addClass("letterDisabled");
			}
		}
		this.oCityLinks.removeClass("glbLookupCityLinksDisabled");
	}
	,
	selectCity: function(countryCode,cityNumber){
		var oCity = this.cities[countryCode+this.params.locality][cityNumber];
		Ext.get(this.params.sources.idTextField).dom.value = oCity[0];
		Ext.get(this.params.sources.idValueField).dom.value = oCity[1];
		
		var origin = "" + this.params.sources.idTextField;
		
		if ((origin.lastIndexOf('RT') != -1) || (origin.lastIndexOf('OW') != -1) || (origin.lastIndexOf('MC') != -1))
		{
			origin = origin.substring(0, origin.length - 2);
		}
		selectedLocations[origin] = oCity[0];
		
		if (this.params.onCitySelect) {
			this.params.onCitySelect();
		}
		this.hide();
	}
	,
	onClickQuickLink: function(n){
		var countryCode = this.oCountrySelect.dom.value;
		if (!countryCode || countryCode == "0")
		{
			return;
		}
		var countryRef = countryCode + this.params.locality
		if(this.quickLinksMapping[countryRef][n-1]){
			for(var i=0; i<this.cities[countryRef].length; i++){
				if(this.cities[countryRef][i][0].charAt(0).toUpperCase() == this.alphabet[n-1].toUpperCase()){
					break;
				}
			}
			aa= this.oCityList.dom.getElementsByTagName("A");
			he = aa[i].offsetTop - aa[0].offsetTop

			this.oCityList.dom.scrollTop = he;

		}
	}
	,
	show: function(params) {
		params.locality = (params.locality)?params.locality:"";

		if(!this.isInit){
			this.init(params)
			return false;
		}

		this.params = params;

		this.oCityLinks.addClass("glbLookupCityLinksDisabled");
		this.oCityList.dom.innerHTML = "";

		var defCountry = (this.params.defCountry) ? this.params.defCountry : "0";
		for(var i=0; i<this.oCountrySelect.dom.length; i++){
			if(this.oCountrySelect.dom.options[i].value == defCountry){
				this.oCountrySelect.dom.selectedIndex = i;
				break;
			}
		}
		this.changeCountry(null,this.oCountrySelect.dom);

		popupFramework.show({id:this.idLookup,opacity:true,templateName:this.requestParams.templateName,position:'centered'});
		return true;
	}
	,
	hide: function() {
		popupFramework.hide({id:this.idLookup});
	}


}


function printPage ()
{
	if (window.print)
	{
		try{window.print();}
		catch(e){}
	}
}


// Cookie

function getCookie(name) {
	var a,start,end;
	a=' '+document.cookie+';';
	start=a.indexOf(' '+name+'=');
	if (start==-1) return null;
	start+=name.length+2;
	end=a.indexOf(';',start);
	return unescape(a.substring(start,end));
}

function getCookieItem(name,cookie) {
	var a,start,end;
	a=cookie+'~';
	start=a.indexOf(name+'=');
	if (start==-1) return null;
	start+=name.length+1;
	end=a.indexOf('~',start);
	return a.substring(start,end);
}

function prepareCookieItem(name, value) {
	return staEscape(name + '=' + value) + '~'; 
}

function setCookie(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" + value + ((expires) ? "; expires=" + expires.toGMTString() : "") + ((path) ? "; path=" + path : "") + ((domain) ? "; domain=" + domain : "") + ((secure) ? "; secure" : "");
}

function deleteCookie(name,path,domain) {
  if (getCookie(name)) {
  	setCookie(name,0,new Date("Thu, 01-Jan-70 00:00:01 GMT"),path,domain,null)
  }
}

function staEscape(string)
{
	var result = "";

	if (null == string || "" == string){
		return result;
	}

	result = string.replace(/[' ']/g, '&nbsp');
	result = result.replace(/[',']/g, '&comma');
	result = result.replace(/[';']/g, '&semicolon');
	result = result.replace(/['~']/g, '&tilde');

	return result;
}

function staUnescape(string)
{
	var result = "";

	if (null == string || "" == string){
		return result;
	}

	result = string.replace(/&nbsp/g," ");
	result = result.replace(/&comma/g,",");
	result = result.replace(/&semicolon/g,";");
	result = result.replace(/&tilde/g,"~");

	return result;
}