/*  Prototype JavaScript framework, version 1.4.0
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

//note: stripped down version of prototype, to be used with moo.fx by mad4milk (http://moofx.mad4milk.net).

var Class = {
	create: function() {
		return function() {
			this.initialize.apply(this, arguments);
		}
	}
};

Object.extend = function(destination, source) {
	for (var property in source) destination[property] = source[property];
	return destination;
};

Function.prototype.bind = function(object) {
	var __method = this;
	return function() {
		return __method.apply(object, arguments);
	}
};

if (!Array.prototype.forEach){
	Array.prototype.forEach = function(fn, bind){
		for(var i = 0; i < this.length ; i++) fn.call(bind, this[i], i);
	};
}

Array.prototype.each = Array.prototype.forEach;

String.prototype.camelize = function(){
	return this.replace(/-\D/gi, function(match){
		return match.charAt(match.length - 1).toUpperCase();
	});
};

var $A = function(iterable) {
	var nArray = [];
	for (var i = 0; i < iterable.length; i++) nArray.push(iterable[i]);
	return nArray;
};

function $() {
	if (arguments.length == 1) return get$(arguments[0]);
	var elements = [];
	$c(arguments).each(function(el){
		elements.push(get$(el));
	});
	return elements;

	function get$(el){
		if (typeof el == 'string') el = document.getElementById(el);
		return el;
	}
};

if (!window.Element) var Element = {};

Object.extend(Element, {

	remove: function(element) {
		element = $(element);
		element.parentNode.removeChild(element);
	},

	hasClassName: function(element, className) {
		element = $(element);
		return !!element.className.match(new RegExp("\\b"+className+"\\b"));
	},

	addClassName: function(element, className) {
		element = $(element);
		if (!Element.hasClassName(element, className)) element.className = (element.className+' '+className);
	},

	removeClassName: function(element, className) {
		element = $(element);
		if (Element.hasClassName(element, className)) element.className = element.className.replace(className, '');
	}

});

document.getElementsByClassName = function(className){
	var elements = [];
	var all = document.getElementsByTagName('*');
	$A(all).each(function(el){
		if (Element.hasClassName(el, className)) elements.push(el);
	});
	return elements;
};

Function.prototype.bindAsEventListener = function(object) {
  var __method = this, args = $A(arguments), object = args.shift();
  return function(event) {
    return __method.apply(object, [event || window.event].concat(args));
  }
}
var monthName = new Array(
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
);

var tripTypeName = new Array();
tripTypeName["O"] = "Oneway";
tripTypeName["R"] = "Return";
tripTypeName["M"] = "Multi";
tripTypeName["RT"] = "Round Trip";

var  searchOptionTypeName = new Array();
searchOptionTypeName["T"] =  "Flexible";
searchOptionTypeName["F"] =  "Must";



var travelClass=new Array();
travelClass["ECO"]="Economy";
travelClass["PRM"]="Premium";
travelClass["BUS"]="Business";
travelClass["BUSGLOBAL"]="Business/First";
travelClass["FIR"]="First";


var valueSplitConstant = ":";
var cookieStrSplitConstant="|"
var regionCodeConstant = 'REGION';
var tripTypeConstant = 'TRIPTYPE';
var fromCodeConstant = 'FROM';
var toConstant = 'TO';
var depDayConstant = 'DEPDAY';
var depMonthConstant = 'DEPMONTH';
var depYearConstant = 'DEPYEAR';
var retDayConstant = 'RETDAY';
var retMonthConstant = 'RETMONTH';
var retYearConstant = 'RETYEAR';
var flexibleConstant = 'FLEXIBLE';
var adultConstant = 'ADULTS';
var childConstant = 'CHILDREN';
var infantConstant = 'INFANTS';
var travelClassConstant = 'TRAVELCLASS';


var PastSearchClass = Class.create();
PastSearchClass.prototype={
  initialize:function() {
	  //dummy
	},
	setRegionCode:function(varRegionCode)
	{
	  if(varRegionCode.value!=null)
	  {
		this.regionCodeValue=varRegionCode.value;
	  }	
	  else if(varRegionCode!=null)
	  {
		this.regionCodeValue=varRegionCode;
	  }
	},
    setIntTripType:function(varIntTripType)
	{
	  if(varIntTripType.value!=null)
	  {
		this.intTripTypeValue=varIntTripType.value;
	  }	
	  else if(varIntTripType!=null)
	  {
		this.intTripTypeValue=varIntTripType;
	  }
	},
	setIntFrom:function(varIntFrom)
	{
	  if(varIntFrom.value!=null)
	  {
		this.intFromValue=varIntFrom.value;
	  }	
	  else if(varIntFrom!=null)
	  {
		this.intFromValue=varIntFrom;
	  }
	},
	setIntTo:function(varIntTo)
	{
	  if(varIntTo.value!=null)
	  {
		this.intToValue=varIntTo.value;
	  }	
	  else if(varIntTo!=null)
	  {
		this.intToValue=varToFrom;
	  }
	},
	setIntDepDay:function(varIntDepDay)
	{
	  if(varIntDepDay.value!=null)
	  {
		this.intDepDayValue=varIntDepDay.value;
	  }	
	  else if(varIntDepDay!=null)
	  {
		this.intDepDayValue=varIntDepDay;
	  }
	},
	setIntDepMonth:function(varIntDepMonth)
	{
	  if(varIntDepMonth.value!=null)
	  {
		this.intDepMonthValue=varIntDepMonth.value;
	  }	
	  else if(varIntDepMonth!=null)
	  {
		this.intDepMonthValue=varIntDepMonth;
	  }
	},
	setIntDepYear:function(varIntDepYear)
	{
	  if(varIntDepYear.value!=null)
	  {
		this.intDepYearValue=varIntDepYear.value;
	  }	
	  else if(varIntYearDay!=null)
	  {
		this.intDepYearValue=varIntDepYear;
	  }
	},
	setIntRetDay:function(varIntRetDay)
	{
	  if(varIntRetDay.value!=null)
	  {
		this.intRetDayValue=varIntRetDay.value;
	  }	
	  else if(varIntRetDay!=null)
	  {
		this.intRetDayValue=varIntRetDay;
	  }
	},
	setIntRetMonth:function(varIntRetMonth)
	{
	  if(varIntRetMonth.value!=null)
	  {
		this.intRetMonthValue=varIntRetMonth.value;
	  }	
	  else if(varIntRetDay!=null)
	  {
		this.intRetMonthValue=varIntRetDay;
	  }
	},
	setIntRetYear:function(varIntRetYear)
	{
	  if(varIntRetYear.value!=null)
	  {
		this.intRetYearValue=varIntRetYear.value;
	  }	
	  else if(varIntRetYear!=null)
	  {
		this.intRetYearValue=varIntRetYear;
	  }
	},
	
	setIntFlexiDates:function(varIntFlexiDates)
	{
	  if(varIntFlexiDates.value!=null)
	  {
		this.intFlexiDatesValue=varIntFlexiDates.value;
	  }	
	  else if(varIntFlexiDates!=null)
	  {
		this.intFlexiDatesValue=varIntFlexiDates;
	  }
	},
	setIntAdults:function(varIntAdults)
	{
	  if(varIntAdults.value!=null)
	  {
		this.intAdultsValue=varIntAdults.value;
	  }	
	  else if(varIntAdults!=null)
	  {
		this.intAdultsValue=varIntAdults;
	  }
	},
    setIntChildren:function(varIntChildren)
	{
	  if(varIntChildren.value!=null)
	  {
		this.intChildrenValue=varIntChildren.value;
	  }	
	  else if(varIntChildren!=null)
	  {
		this.intChildrenValue=varIntChildren;
	  }
	},
    setIntInfants:function(varIntInfants)
	{
	  if(varIntInfants.value!=null)
	  {
		this.intInfantsValue=varIntInfants.value;
	  }	
	  else if(varIntInfants!=null)
	  {
		this.intInfantsValue=varIntInfants;
	  }
	},
	setIntTravelClass:function(varIntTravelClass)
	{
	  if(varIntTravelClass.value!=null)
	  {
		this.intTravelClassValue=varIntTravelClass.value;
	  }	
	  else if(varIntTravelClass!=null)
	  {
		this.intTravelClassValue=varIntTravelClass;
	  }
	},
	
	getRegionCode:function()
	{
		return this.regionCodeValue;
	},
    getIntTripType:function()
	{
		return this.intTripTypeValue;
	},
	getIntFrom:function()
	{
		return this.intFromValue;
	},
	getIntTo:function()
	{
		return this.intToValue;
	},
	getIntDepDay:function()
	{
		return this.intDepDayValue;
	},
    getIntDepMonth:function()
	{
		return this.intDepMonthValue;
	},
    getIntDepYear:function()
	{
		return this.intDepYearValue;
	},
    getIntRetDay:function()
	{
		return this.intRetDayValue;
	},
    getIntRetMonth:function()
	{
		return this.intRetMonthValue;
	},
    getIntRetYear:function()
	{
		return this.intRetYearValue;
	},
   
    getIntFlexiDates:function()
	{
		return this.intFlexiDatesValue;
	},
    getIntAdults:function()
	{
		return this.intAdultsValue;
	}, 
    getIntChildren:function()
	{
		return this.intChildrenValue;
	},
	getIntInfants:function()
	{
		return this.intInfantsValue;
	},
    getIntTravelClass:function()
	{
		return this.intTravelClassValue;
	},
	serialize:function()
	{
		var returnStr='';
		returnStr=returnStr+ regionCodeConstant + valueSplitConstant+ this.regionCodeValue+valueSplitConstant;
		returnStr=returnStr+ tripTypeConstant + valueSplitConstant+ this.intTripTypeValue+valueSplitConstant;
		returnStr=returnStr+ fromCodeConstant + valueSplitConstant+ this.intFromValue+valueSplitConstant;
		returnStr=returnStr+ toConstant + valueSplitConstant+ this.intToValue+valueSplitConstant;
		returnStr=returnStr+ depDayConstant + valueSplitConstant+ this.intDepDayValue+valueSplitConstant;
		returnStr=returnStr+ depMonthConstant + valueSplitConstant+ this.intDepMonthValue+valueSplitConstant;
		returnStr=returnStr+ depYearConstant + valueSplitConstant+ this.intDepYearValue+valueSplitConstant;
		returnStr=returnStr+ retDayConstant + valueSplitConstant+ this.intRetDayValue+valueSplitConstant;
		returnStr=returnStr+ retMonthConstant + valueSplitConstant+ this.intRetMonthValue+valueSplitConstant;
		returnStr=returnStr+ retYearConstant + valueSplitConstant+ this.intRetYearValue+valueSplitConstant;
		returnStr=returnStr+ flexibleConstant + valueSplitConstant+ this.intFlexiDatesValue+valueSplitConstant;
		returnStr=returnStr+ adultConstant + valueSplitConstant+ this.intAdultsValue+valueSplitConstant;
		returnStr=returnStr+ childConstant + valueSplitConstant+ this.intChildrenValue+valueSplitConstant;
		returnStr=returnStr+ infantConstant + valueSplitConstant+ this.intInfantsValue+valueSplitConstant;
		returnStr=returnStr+ travelClassConstant + valueSplitConstant+ this.intTravelClassValue;

		returnStr=returnStr+cookieStrSplitConstant;
		//alert(' return String ' + returnStr);
		return returnStr;
	},
	deSerialize:function(pastSearchCookieStr)
	{
		//alert(' pastSearchCookieStr ' +pastSearchCookieStr);
		var cookieArray=pastSearchCookieStr.split(valueSplitConstant);

		//alert(' cookieArray ' + cookieArray);
		
		for(var j=0;j<cookieArray.length;j=j+2)
		{
			//alert( ' cookieArray[ '  + j + ' ] ' + cookieArray[j]);
			if(cookieArray[j]==regionCodeConstant)
			{
				this.regionCodeValue=cookieArray[j+1];
			}
			else if(cookieArray[j]==tripTypeConstant)
			{
				this.intTripTypeValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==fromCodeConstant)
			{
				this.intFromValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==toConstant)
			{
				this.intToValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==depDayConstant)
			{
				this.intDepDayValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==depMonthConstant)
			{
				this.intDepMonthValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==depYearConstant)
			{
				this.intDepYearValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==retDayConstant)
			{
				this.intRetDayValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==retMonthConstant)
			{
				this.intRetMonthValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==retYearConstant)
			{
				this.intRetYearValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==flexibleConstant)
			{
				this.intFlexiDatesValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==adultConstant)
			{
				this.intAdultsValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==childConstant)
			{
				this.intChildrenValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==infantConstant)
			{
				this.intInfantsValue=cookieArray[j+1];	
			}
			else if(cookieArray[j]==travelClassConstant)
			{
				this.intTravelClassValue=cookieArray[j+1];	
			}
		}
	},
	compare:function(obj)
	{
		//alert("this.regionCodeValue:" + this.getRegionCode() + ": obj.regionCodeValue : " + obj.getRegionCode());
		if(this.regionCodeValue!=obj.regionCodeValue ||
		   this.intTripTypeValue!=obj.intTripTypeValue ||
		   this.intFromValue!=obj.intFromValue ||
		   this.intToValue!=obj.intToValue ||
		   this.intDepDayValue!=obj.intDepDayValue ||
		   this.intDepMonthValue!=obj.intDepMonthValue ||
		   this.intDepYearValue!=obj.intDepYearValue ||
		   this.intRetDayValue!=obj.intRetDayValue ||
		   this.intRetMonthValue!=obj.intRetMonthValue ||
		   this.intRetYearValue!=obj.intRetYearValue ||
		   this.intRetYearValue!=obj.intRetYearValue ||
		   this.intFlexiDatesValue!=obj.intFlexiDatesValue ||
		   this.intAdultsValue!=obj.intAdultsValue ||
           this.intChildrenValue!=obj.intChildrenValue ||
		   this.intInfantsValue!=obj.intInfantsValue ||
		   this.intTravelClassValue!=obj.intTravelClassValue
		)
		{
			//alert(" Objects are not same");
			return false;
		}
		return true;
	},
	display:function()
	{
		var seatForKeys;
		var seatForVals;
		var itineraryForVals;
		var tripTypeReturn;
		var searchType;
		
		var totalPsgrsForVals=parseInt(this.intAdultsValue)+parseInt(this.intChildrenValue);
		
		if(parseInt(totalPsgrsForVals)>1){
			seatForVals=totalPsgrsForVals+" seats";
		}
		else{
			seatForVals=totalPsgrsForVals+" seat";
		}
		
		if(this.intTripTypeValue == 'R' && (this.regionCodeValue == "AM" || this.regionCodeValue == "am"))
		{
			tripTypeReturn = tripTypeName["RT"];
		}
		else
		{
			tripTypeReturn = tripTypeName[this.intTripTypeValue];	
		}

		if(this.intFlexiDatesValue)
		{
			searchType = 'T';
		}
		else
		{
			searchType = 'F';
		}

		//alert( ' this.intDepDayValue ' + this.intDepMonthValue);
		//alert( ' monthName[this.intDepMonthValue] ' + monthName[this.intDepMonthValue]);

		itineraryForKeys =this.serialize();

		var index= itineraryForKeys.indexOf(cookieStrSplitConstant);
		itineraryForKeys =itineraryForKeys.substring(0,index);

		itineraryForVals =this.intFromValue +
						  ' to '    		+
			              this.intToValue   +
			              ' '               +
			              this.intDepDayValue +
			              ' '               +
			              monthName[this.intDepMonthValue-1] +
			              ' '               +
			              seatForVals       +
			              ' - '             +
			              tripTypeReturn;

		var itinerary= new Array();
		itinerary [0] =itineraryForKeys;
		itinerary [1] =itineraryForVals;
		return itinerary;
	
	}
}
 var regionAustralia='au';
 var regionAsia='as';
 var regionAfrica='af';
 var regionAmerica='am';
 var regionEurope='eu';
 var regionSouthPacific='sp';
 var cookieLimitPerRegion = 10;
 var existingCount =0;

 var regionCounterArray = new Array();
	
 regionCounterArray[regionAustralia] = 1;
 regionCounterArray[regionAsia] = 1;
 regionCounterArray[regionAfrica] = 1;
 regionCounterArray[regionAmerica] = 1;
 regionCounterArray[regionEurope] = 1;
 regionCounterArray[regionSouthPacific] = 1;

 function addPastSearch()
 {
	var tripType;
	//alert(' Inside AddPastSearch ');
	var formObject = document.getElementById('intForm');

	var regionCode = formObject.regionCode;

	//alert(' isReturn(formObject.intTripType.value) ' + isReturn(formObject.intTripType));
	if(isReturn(formObject.intTripType))
	{
		tripType = 'R'
	}
	else
	{
		tripType = 'O';
	}

	//alert(' tripType  ' + tripType);
	var intFrom = formObject.intFrom;
	var intTo = formObject.intTo;
	var intDepDay = formObject.intDepDay;
	var intDepMonth = formObject.intDepMonth;
	var intDepYear = formObject.intDepYear;
	
	var intRetDay = formObject.intRetDay;
	var intRetMonth = formObject.intRetMonth;
	var intRetYear = formObject.intRetYear;
	
	var intFlexiDates = formObject.intFlexiDates;
	
	var intAdults = formObject.intAdults;
	var intChildren = formObject.intChildren;
	var intInfants = formObject.intInfants;
	var intTravelClass = formObject.intTravelClass;

	/*var regionCode = document.getElementById('regionCode');
	alert(' regionCode ' +regionCode);
	var tripType = document.getElementById('intTripType');
	var intFrom = document.getElementById('intFrom');
	var intTo = document.getElementById('intTo');

	var intDepDay = document.getElementById('intDepDay');
	var intDepMonth = document.getElementById('intDepMonth');
	var intDepYear = document.getElementById('intDepYear');
	
	var intRetDay = document.getElementById('intRetDay');
	var intRetMonth = document.getElementById('intRetMonth');
	var intRetYear = document.getElementById('intRetYear');
	
	var intFlexiDates = document.getElementById('intFlexiDates');
	
	var intAdults = document.getElementById('intAdults');
	var intChildren = document.getElementById('intChildren');
	var intInfants = document.getElementById('intInfants');
	var intTravelClass = document.getElementById('intTravelClass');
    */

	var currentPastSearchObject = new PastSearchClass();
	
	currentPastSearchObject.setRegionCode(regionCode);
	currentPastSearchObject.setIntTripType(tripType);
	currentPastSearchObject.setIntFrom(intFrom);
	currentPastSearchObject.setIntTo(intTo);
	currentPastSearchObject.setIntDepDay(intDepDay);
	currentPastSearchObject.setIntDepMonth(intDepMonth);
	currentPastSearchObject.setIntDepYear(intDepYear);
	currentPastSearchObject.setIntRetDay(intRetDay);
	currentPastSearchObject.setIntRetMonth(intRetMonth);
	currentPastSearchObject.setIntRetYear(intRetYear);
	currentPastSearchObject.setIntFlexiDates(intFlexiDates);
	currentPastSearchObject.setIntAdults(intAdults);
	currentPastSearchObject.setIntChildren(intChildren);
	currentPastSearchObject.setIntInfants(intInfants);
	currentPastSearchObject.setIntTravelClass(intTravelClass);

	writePastSearchCookie(currentPastSearchObject);	
 }
 
 function writePastSearchCookie(currentPastSearchObject)
 {
	//alert("past SEarch cookie get " + getCookieValue("pastSearchCookie"));
	//alert("inside write Past Search Cookie");
	var pastSearchCookieArray;
	var newPastSearchCookieString;

	var currentCookie= getCookieValue("pastSearchCookie");
	if(currentCookie==null)
	{
		//alert(" Current Cookie is null");
		currentCookie='';
		newPastSearchCookieString=currentCookie + currentPastSearchObject.serialize();
	}
	else
	{
		//alert(" Current Cookie is not null");
		newPastSearchCookieString = parseAndComparePastSearchCookie(currentCookie,currentPastSearchObject)
	}

	var pastSearchCookie = "pastSearchCookie="+newPastSearchCookieString;	
	//document.write(pastSearchCookie);
	//alert("past SEarch cookie SET " + pastSearchCookie);
	document.cookie=pastSearchCookie+";path=/"; 
	
 }

 function parseAndComparePastSearchCookie(currentCookie,currentPastSearchObject)
 {	
		

		//alert(" inside parseAndComparePastSearchCookie ");
		var pastSearchArrayObject = new Array();
		var newPastSearchCookie ='';
		var pastSearchStrArray = currentCookie.split("|");

		//alert ( ' pastSearchStrArray size ' + pastSearchStrArray.length);

		for(var i=0;i< pastSearchStrArray.length-1;i++)
		{
			//alert(' For Loop one ');
			pastSearchArrayObject[i] = new PastSearchClass();
			pastSearchArrayObject[i].deSerialize(pastSearchStrArray[i]);
			if(pastSearchArrayObject[i].compare(currentPastSearchObject))
			{
				//alert("Match Found ");
				pastSearchStrArray.splice(i,1);
				//alert(' after deletion ');
				 break;
			}
		}
		newPastSearchCookie = currentPastSearchObject.serialize();
		//alert ( ' pastSearchStrArray size after iteration ' + pastSearchStrArray.length);
		for(var k=0;k<pastSearchStrArray.length-1;k++)
		{
			//alert(' For Loop two ');
			pastSearchArrayObject[k] = new PastSearchClass();
			//alert(' pastSearchStrArray[' + k + ']' + pastSearchStrArray[k]);
 			pastSearchArrayObject[k].deSerialize(pastSearchStrArray[k]);
			
			var regionFromCookieObject = pastSearchArrayObject[k].getRegionCode();
			//alert(' regionFromCookieObject ' + regionFromCookieObject);
			newPastSearchCookie = addPastSearchCookieByRegion(pastSearchArrayObject[k],regionFromCookieObject,newPastSearchCookie);
		}
		return newPastSearchCookie;
 }

 function addPastSearchCookieByRegion(arrayObject,region,newPastSearchCookie)
 {
	 
	 //alert(' inside addPastSearchCookieByRegion ' );
	 //alert('regionCounterArray[ ' + region + ' ] ' + regionCounterArray[region]);
	 existingCount = regionCounterArray[region];
	 //alert( ' eligible to add ' + existingCount < cookieLimitPerRegion);
	 if(existingCount <= cookieLimitPerRegion)
	 {
		
		//alert(' eligible to add for the region ' + region);
		newPastSearchCookie = newPastSearchCookie + arrayObject.serialize();

		existingCount = existingCount+1;
		regionCounterArray[region] = existingCount;
		
	 }
	// else
	// {
		 //alert(' exceed the limit');
	// }
	 //alert(' regionArray[ ' + region + ']' + regionCounterArray[region]);
	 return newPastSearchCookie;	
 }

 function populatePastSearch(mySelect)
 {
    var cookieStrArray;
	var uc = new UserContextInfo();
	var ucRegion = uc.getLastRegion();
    mySelect.options[0] = new Option("Your past flight searches",  0);
    var cookieArray = new Array();
	 
	var cookieVal= getCookieValue("pastSearchCookie");	
	if(!cookieVal)
	{
		cookieStrArray=new Array();
	}
	else
	{
		cookieStrArray = cookieVal.split('|');
	}
	
	var c=1;
	var count=0;
	for(var b=0;b < cookieStrArray.length-1;b++)
	{
		cookieArray[b] = new PastSearchClass();
		cookieArray[b].deSerialize(cookieStrArray[b]);
		var optionArray = cookieArray[b].display();
		//alert(" ucRegion :  " + ucRegion + " : cookieRegion : " +cookieArray[b].getRegionCode());  
		if(ucRegion.toLowerCase() == cookieArray[b].getRegionCode() && count < 10 ){
			
			var optionKey = optionArray[0];
			//alert(' optionKey ' + optionKey);
			var optionVal = optionArray[1];
			//alert(' optionVal ' + optionVal);
			mySelect.options[c] = new Option(optionVal,optionKey);
			c++;
			count++;
		}

	}
 }

 function isReturn(tripTypeObj){
	for(var i=0;i<tripTypeObj.length;++i){
		if((tripTypeObj[i].value=='R'||tripTypeObj[i].value=='return')&&tripTypeObj[i].checked){
			return true;
		}
	}
	return false;
}
//restorePastSearch(this,intDepartCalendar,intReturnCalendar,intTravelClass,fromToHandler,<render:encodeName name="intShowHideReturn"/>);
function restorePastSearch(selectIndex,departCalendar,returnCalendar,intTravelClass,fromToHandler,intShowHideReturn)
{
	var selectedValue="";
	var populateObject = new PastSearchClass();
	var departDate = new Date();
	var returnDate = new Date();
	var travelClassId = intTravelClass;
	this.intShowHideReturn = intShowHideReturn;

	if (0 == parseInt(selectIndex.value)) {                               
		return;                                                            
	 } else {
		selectedValue=selectIndex.value;
	 }
	 //alert(' selectedValue ' + selectedValue);
	 populateObject.deSerialize(selectedValue);
	 
	 //alert(' fromToHandler ' + fromToHandler);
	 fromToHandler.setInitialValues(populateObject.getIntFrom(),populateObject.getIntTo());
	 
	 departDate.setDate(populateObject.getIntDepDay());
	 departDate.setMonth(populateObject.getIntDepMonth()-1);
	 departDate.setYear(populateObject.getIntDepYear());
	 
	 returnDate.setDate(populateObject.getIntRetDay());
	 returnDate.setMonth(populateObject.getIntRetMonth()-1);
	 returnDate.setYear(populateObject.getIntRetYear());

	 departCalendar.update(departDate);
	 returnCalendar.update(returnDate);	
	
	setCommonFields(populateObject.getIntTripType(),
					populateObject.getIntFlexiDates(),
					populateObject.getIntAdults(),
					populateObject.getIntChildren(),
					populateObject.getIntInfants());
	
	this.intShowHideReturn();

	//alert(' travelClass ' + populateObject.getIntTravelClass());
	if(populateObject.getIntTravelClass()){	
	 document.getElementById(travelClassId).value =populateObject.getIntTravelClass();
	}
}

function setCommonFields(tripType,searchBy,adults,children,infants)
{
	if (tripType) {
		if (tripType == 'R') {
			document.getElementById('intTripTypeReturn').checked=true;
			document.getElementById('intTripTypeOneWay').checked=false;
			
		} else {

			document.getElementById('intTripTypeReturn').checked=false;
			document.getElementById('intTripTypeOneWay').checked=true;

		}
	}

	if (searchBy){
		if (searchBy=="true") {
			document.getElementById('intFlexiDatesCheckBox').checked=true;
		} 
		else
		{
			document.getElementById('intFlexiDatesCheckBox').checked=false;
		}
	}
	else
	{
		document.getElementById('intFlexiDatesCheckBox').checked=false;
	}

	document.getElementById('intAdults').value =adults;
	document.getElementById('intChildren').value =children;
	document.getElementById('intInfants').value =infants;
}

function DateRange(from,to){
	this.from=from;
	this.to=to;
}
DateRange.prototype.withinRange=function(value){
	return(this.from.getTime()<=value.getTime()&&value.getTime()<=this.to.getTime());
}
DateRange.prototype.intersectsRange=function(dateRange){
	return(
		(dateRange.from.getTime()<=this.to.getTime()&&this.to.getTime()<=dateRange.to.getTime()) ||
		(dateRange.from.getTime()<=this.from.getTime()&&this.from.getTime()<=dateRange.to.getTime()) );
}
DateRange.prototype.intersectsRanges=function(dateRangeArray){
	for(var i=0;i<dateRangeArray.length;++i){
		if(this.intersectsRange(dateRangeArray[i])){
			return true;
		}
	}
}

	

Date.prototype.padded=function(value){return (value<10?('0'+value):value.toString());}
Date.prototype.getFullMonth=function(){return Date.Months[this.getMonth()];}
Date.prototype.getShortMonth=function(){return Date.ShortMonths[this.getMonth()];}
Date.prototype.getFullDay=function(){return Date.Days[this.getDay()];}
Date.prototype.getShortDay=function(){return Date.ShortDays[this.getDay()];}
Date.prototype.getShortDayIndex=function(index){return Date.ShortDays[index];}
Date.prototype.format=function(formatString){
	var s=new String(formatString);	
	s=s.replace('HH',this.padded(this.getHours()));
	s=s.replace('H',this.getHours().toString());
	s=s.replace('MM',this.padded(this.getMinutes()));
	s=s.replace('M',this.getMinutes().toString());
	s=s.replace('SS',this.padded(this.getSeconds()));
	s=s.replace('S',this.getSeconds().toString());
	s=s.replace('YYYY',this.getFullYear().toString());
	s=s.replace('YY',this.getFullYear().toString().substring(2,4));
	s=s.replace('DDDD',this.getFullDay());
	s=s.replace('DDD',this.getShortDay());
	s=s.replace('DD',this.padded(this.getDate()));
	//s=s.replace('D',this.getDate().toString());  // Not a Java standard
	s=s.replace('mmmm',this.getFullMonth());
	s=s.replace('mmm',this.getShortMonth());
	s=s.replace('mm',this.padded(this.getMonth()+1));
//	s=s.replace('m',(this.getMonth()+1).toString()); // Fails on ...ember months.
	return s;
}


Date.prototype.withinRange=function(dateRange){
	return(dateRange.from.getTime()<=this.getTime()&&this.getTime()<=dateRange.to.getTime());
}
Date.prototype.withinRanges=function(dateRangeArray){
	for(var i=0;i<dateRangeArray.length;++i){
		if(this.withinRange(dateRangeArray[i])){
			return true;
		}
	}
	return false;
}


Date.prototype.dateWithinRange=function(dateRange){
	var from=new Date(dateRange.from.getTime());
	var to=new Date(dateRange.to.getTime());
	from.setHours(0,0,0,0);
	to.setHours(23,59,59,999);
	return(from.getTime()<=this.getTime()&&this.getTime()<=to.getTime());
}
Date.prototype.dateWithinRanges=function(dateRangeArray){
	for(var i=0;i<dateRangeArray.length;++i){
		if(this.dateWithinRange(dateRangeArray[i])){
			return true;
		}
	}
	return false;
}
Date.prototype.monthWithinRange=function(dateRange){
	var from=new Date(dateRange.from.getTime());
	var to=new Date(dateRange.to.getTime());
	from.setDate(1);
	from.setHours(0,0,0,0);
	to.setMonth(dateRange.to.getMonth()+1,1);
	to.setHours(0,0,0,0);
	to.setTime(to.getTime()-1);
	return(from.getTime()<=this.getTime()&&this.getTime()<=to.getTime());
}
Date.prototype.monthWithinRanges=function(dateRangeArray){
	for(var i=0;i<dateRangeArray.length;++i){
		if(this.monthWithinRange(dateRangeArray[i])){
			return true;
		}
	}
	return false;
}
/* This files assumes the date.js file has also been included into the page. */

Calendar.prototype.updateDaySelectOptions=function(){
	var options=this.dayField.options;
	var optionsLength=0;
	var selectedIndex=0;
	var m=this.displayDate.getMonth();
	var d=this.displayDate.getDate();
	var temp=new Date(this.displayDate);
	for(var i=1;i<=31;++i){
		temp.setDate(i);
		if(m==temp.getMonth()){
			if(temp.dateWithinRanges(this.dateRanges)){
				if(i==d){
					selectedIndex=optionsLength;
				}
				options[optionsLength]=new Option(temp.format(daySelectFormat),i);
				++optionsLength;
			}
		}
	}
	options.length=optionsLength;
	this.dayField.selectedIndex=selectedIndex;
}
Calendar.prototype.updateMonthYearSelectOptions=function(){
	var options=this.monthYearField.options;
	var optionsLength=0;
	var selectedIndex=0;
	var ddm=this.displayDate.getMonth();
	var ddy=this.displayDate.getFullYear();
	var endM=this.endDate.getMonth();
	var endY=this.endDate.getFullYear();
	var temp=new Date(this.startDate);
	temp.setDate(1);
	var m=temp.getMonth();
	var y=temp.getFullYear();
	while(y<endY||(m<=endM&&y<=endY)){
		if(temp.monthWithinRanges(this.dateRanges)){
			if(m==ddm&&y==ddy){
				selectedIndex=optionsLength;
			}
			var label=buildMonthYearSelectLabel(temp.getShortMonth(),y);
			var value=(m+1)+','+y;
			options[optionsLength]=new Option(label,value);
			++optionsLength;
		}
		temp.setMonth(m+1);
		m=temp.getMonth();
		y=temp.getFullYear();
	}
	options.length=optionsLength;
	this.monthYearField.selectedIndex=selectedIndex;
}
Calendar.prototype.updateHourSelectOptions=function(){

	var options=this.hourField.options;
	var fieldVal=this.hourField.value;

	options.length=0;
	var range=new DateRange(new Date(this.displayDate),new Date(this.displayDate));
	range.from.setHours(0,0,0);
	range.to.setHours(11,59,59);
	var selected=false;
	var selectedIndex=null;
	if (this.isAnytime) {
		if (this.isAnytimeSelected||!this.hasUserSetHour){ selectedIndex=options.length;}
		options[options.length]=new Option(Date.time[0],'Anytime',false,false);
	}
	if(range.intersectsRanges(this.dateRanges)){
		if(this.hourRangeSelected&&range.withinRange(this.displayDate)&& selectedIndex == null){selectedIndex=options.length;}
		options[options.length]=new Option(Date.time[1],'Morning',false,false);
	}
	range.from.setHours(12,0,0);
	range.to.setHours(17,59,59);
	if(range.intersectsRanges(this.dateRanges)){
		if(this.hourRangeSelected&&range.withinRange(this.displayDate)&& selectedIndex == null){selectedIndex=options.length;}
		options[options.length]=new Option(Date.time[2],'Afternoon',false,false);
	}
	range.from.setHours(18,0,0);
	range.to.setHours(20,59,59);
	if(range.intersectsRanges(this.dateRanges)){
		if(this.hourRangeSelected&&range.withinRange(this.displayDate)&& selectedIndex == null){selectedIndex=options.length;}
		options[options.length]=new Option(Date.time[3],'Evening',false,false);

	}

	var temp=new Date(this.displayDate);
	for(var i=1;i<=23;++i){
		temp.setHours(i,0,0);
		if(temp.withinRanges(this.dateRanges)){
			if(selectedIndex==null&&i==this.displayDate.getHours()){selectedIndex=options.length;}
			options[options.length]=new Option((i<10?('0'+i+':00'):(i+':00')),i,false,false);
		}
	}
	this.hourField.selectedIndex=selectedIndex;
}
Calendar.prototype.updateFormInputs=function(){
	if(this.haveFieldsBeenInserted){
		this.timeField.value=this.displayDate.getTime();
		this.formattedField.value=this.displayDate.format('YYYYmmDDHH00');
		this.bookLeadFormattedField.value=this.startDate.format('YYYYmmDDHH00');
		this.yearField.value=this.displayDate.getFullYear();
		this.monthField.value=this.displayDate.getMonth()+1;
		if(this.showMonthYearField){
			this.updateMonthYearSelectOptions();
		}else{
			this.monthYearField.value=this.monthField.value+','+this.yearField.value;
		}
		if(this.showDayField){
			this.updateDaySelectOptions();
		}else{
			this.dayField.value=this.displayDate.getDate();
		}
		if(this.showHourField){
			this.updateHourSelectOptions();
		}else{
			this.hourField.value=this.displayDate.getHours();
		}
	}
}
Calendar.prototype.update=function(displayDate){ // This must be the only method to set 'this.displayDate'
	this.displayDate=new Date(displayDate.getTime()); // construct new date object as ie popup doesn't have date.js.
	if(!this.displayDate.withinRanges(this.dateRanges)){
		this.pullWithinRange();
	}
	this.updateFormInputs();
	this.divCalendar.innerHTML=this.createCalendarHtml();
	if(this.onChangeCallback!=null){
		this.onChangeCallback();
	}	
	if(this.popup!=null){
		if(this.useIePopup){
			this.popup.document.body.innerHTML=this.divCalendar.innerHTML; 
		}else{
			this.popup=this.divCalendar;
		}
	}
}
Calendar.prototype.pullWithinRange=function(){
	var done=false;
	var closestEarlier=null;
	var closestLater=null;
	var valueTime=this.displayDate.getTime();
	for(var i=0;i<this.dateRanges.length;++i){
		var from=this.dateRanges[i].from.getTime();
		var to=this.dateRanges[i].to.getTime();
		if(to<valueTime&&(closestEarlier==null||(valueTime-to)<(valueTime-closestEarlier.getTime()))){
			closestEarlier=new Date(to);
		}else if(valueTime<from&&(closestLater==null||(from-valueTime)<(closestLater.getTime()-valueTime))){
			closestLater=new Date(from);
		}
	}
	if(closestEarlier!=null&&closestEarlier.getMonth()==this.displayDate.getMonth()){
		this.displayDate=closestEarlier;
	}else if(closestLater!=null&&closestLater.getMonth()==this.displayDate.getMonth()){
		this.displayDate=closestLater;
	}else{
		this.displayDate=this.dateRanges[0].from;
	}
}
Calendar.prototype.updateDayOfMonth=function(dayOfMonth){
	var temp=new Date(this.displayDate);
	temp.setDate(dayOfMonth);
	if(this.hasUserSetHour==false&&this.defaultHour!=null&&this.defaultHour>=0&&this.defaultHour<=23){
		temp.setHours(this.defaultHour,0,0); // requirement to go back to a default hour, like morning, if available.
	}
	this.update(temp);
	this.adjustHourOfDay();
}
Calendar.prototype.updateMonthYear=function(monthCommaYear){
	var my=monthCommaYear.split(',');
	var m=my[0]-1;
	var y=my[1];
	var temp=new Date(this.displayDate);
	temp.setFullYear(y);
	temp.setMonth(m);
	while(m!=temp.getMonth()){
		temp.setTime(temp.getTime()-24*60*60*1000);
	}
	if(this.hasUserSetHour==false&&this.defaultHour!=null&&this.defaultHour>=0&&this.defaultHour<=23){
		temp.setHours(this.defaultHour,0,0); // requirement to go back to a default hour, like morning, if available.
	}
	this.update(temp);
	this.adjustHourOfDay();
}
Calendar.prototype.updateHourOfDay=function(hourOfDay){
	this.hasUserSetHour=true;
	this.hourRangeSelected=isNaN(parseInt(hourOfDay));
	var hourOfDayString=hourOfDay.toString().toLowerCase();

	if('morning'==hourOfDayString){hourOfDay=(this.isAnytime==true)?6:1;}
	else if('afternoon'==hourOfDayString){hourOfDay=(this.isAnytime==true)?15:12;}
	else if('evening'==hourOfDayString){hourOfDay=(this.isAnytime==true)?20:18;}

	if('anytime'==hourOfDayString){
		this.isAnytimeSelected = true;
		hourOfDay=12;
	} else {
		this.isAnytimeSelected = false;
	}
	var temp=new Date(this.displayDate);
	temp.setHours(hourOfDay);
	this.update(temp);
	this.adjustHourOfDay();
}
Calendar.prototype.adjustHourOfDay=function(){
	if(this.hourRangeSelected){
		var hourOfDay=this.hourField.value;
		var hourOfDayString=hourOfDay.toString().toLowerCase();

		if('morning'==hourOfDayString){hourOfDay=(this.isAnytime==true)?6:1;}
		else if('afternoon'==hourOfDayString){hourOfDay=(this.isAnytime==true)?15:12;}
		else if('evening'==hourOfDayString){hourOfDay=(this.isAnytime==true)?20:18;}
		if('anytime'==hourOfDayString){

			this.isAnytimeSelected = true;
			hourOfDay=12;
		} else {
			this.isAnytimeSelected = false;
		}
		if(hourOfDay!=this.displayDate.getHours()){
			var temp=new Date(this.displayDate);
			temp.setHours(hourOfDay);
			this.update(temp);
		}
	}
}

Calendar.prototype.createCalendarHtml=function(){	
	var raw='<table class="calendar" cellspacing="0" ';
	if(this.showCalendarIcon){
		raw+='onmouseout="javascript:'+this.popupVarName()+'.mouseOut();" onmouseover="javascript:'+this.popupVarName()+'.mouseOver();"';
	}
	raw+='>\n<tr>\n<td style="padding:0;">\n<table class="months" cellspacing="0">\n<tr>';

	var ddd=this.displayDate.getDate();
	var ddm=this.displayDate.getMonth();
	var ddy=this.displayDate.getFullYear();
	var endM=this.endDate.getMonth();
	var endY=this.endDate.getFullYear();
	var temp=new Date(this.startDate);
	temp.setDate(1);
	var m=temp.getMonth();
	var y=temp.getFullYear();
	var i=0; 
	while(y<endY||(m<=endM&&y<=endY)||i%7!=0){
		raw+='<th ';
		if(temp.monthWithinRanges(this.dateRanges)){
			var monthCommaYear=(m+1)+','+y;
			if(m==ddm&&y==ddy){
				raw+=' class="active"';
			}else{
				raw+=' class="month"';
				raw+=' onclick="javascript:'+this.popupVarName()+'.updateMonthYear(\''+monthCommaYear+'\');" title="'+temp.getShortMonth()+' '+y+'"';
				raw+=' onmouseover="javascript:this.className+=\' hover\';"';
				raw+=' onmouseout="javascript:this.className=this.className.replace(/ hover/,\'\');"';
			}
		}else{
			raw+=' class="disabled" ';
		}
		raw+='>'+temp.getShortMonth()+'</th>';
		temp.setMonth(m+1);
		m=temp.getMonth();
		y=temp.getFullYear();
		if(++i%7==0){
			raw+='\n</tr>\n<tr>';
		}
	}
	raw+='\n</tr>';
	raw+='\n</table>';
	raw+='\n<table class="date"><tr><th>'+this.displayDate.format(calendarDateDisplayFormat)+'</th></tr></table>';
	raw+='\n<table class="days">';
	raw+='\n<tr><th>'+temp.getShortDayIndex(0)+'</th><th>'+temp.getShortDayIndex(1)+'</th><th>'+temp.getShortDayIndex(2)+'</th><th>'+temp.getShortDayIndex(3)+'</th><th>'+temp.getShortDayIndex(4)+'</th><th>'+temp.getShortDayIndex(5)+'</th><th>'+temp.getShortDayIndex(6)+'</th></tr>';

	var temp=new Date(this.displayDate);
	temp.setDate(1);
	var startDay=temp.getDay();

	for(var i=0;i<6;++i){
		raw+='\n<tr>';
		for(var j=0;j<7;++j){
			if((j+7*i)>=startDay && temp.getMonth()==this.displayDate.getMonth()){
				raw+='<td ';
				if(this.dateRanges==null||temp.dateWithinRanges(this.dateRanges)){
					if(temp.getDate()==ddd&&temp.getMonth()==ddm&&temp.getYear()==ddy){
						raw+=' class="active"';
					}else{
						raw+=' class="date"';
						raw+=' onmouseover="javascript:this.className=this.className+\' hover\';"';
						raw+=' onmouseout="javascript:this.className=this.className.replace(/ hover/ig,\'\');"';
					}
					raw+=' onclick="javascript:'+this.popupVarName()+'.hidePopup();'+this.popupVarName()+'.updateDayOfMonth('+temp.getDate()+');"';
				}else{
					raw+=' class="disabled"';
				}
				raw+='>'+temp.getDate()+'</td>';
				temp.setDate((j+7*i)+2-startDay);
			}else{
				raw+='<td>&nbsp;</td>';
			}
		}
		raw+='</tr>';
	}
	raw+='\n</table>\n</td>\n</tr>\n</table>';
	return raw;
}

Calendar.prototype.millisecondTimeout=500;
Calendar.prototype.useIePopup=(window.createPopup?true:false); // IE-Popups used in IE 5.5 onwards
Calendar.prototype.popupVarName=function(){return(this.useIePopup?('parent.'+this.varName):this.varName);}
Calendar.prototype.popupCreate=function(){
	this.clearPopupTimers();
	this.mouseOverCounter=0;	
	this.popupX=0;
	this.popupY=this.dayField.offsetHeight+1;
	if(this.useIePopup){
		this.popup=this.win.createPopup();
		var link=this.popup.document.createElement('link');
		link.href=this.calendarCSS;
		link.rel='stylesheet';
		link.type='text/css';
		this.popup.document.body.parentNode.insertBefore(link,this.popup.document.body);
		this.popup.document.body.innerHTML=this.divCalendar.innerHTML; 
		this.popup.show(0,this.monthYearField.offsetHeight,$j(this.divCalendar).width(),$j(this.divCalendar).height()+2,this.monthYearField);
	}else{
		var temp = this.monthYearField;
		while(temp.offsetParent!=null){
			temp=temp.offsetParent;
		}
		this.popup=this.divCalendar;
		$j(this.popup).show();
	}
	this.mouseOver();
}
Calendar.prototype.mouseOver=function(){
	this.mouseOverCounter++;
}
Calendar.prototype.mouseOut=function(){
	this.mouseOverCounter--;
	var objName;
	
	if(($j('body').find('.searchFragment').html() != null)&& (this.useIePopup))
	{
		objName = this.popupVarName().split('.')[1];
	}
	else
	{
		objName = this.popupVarName();
	}
	
	this.popupTimers.push(window.setTimeout(objName+'.timeoutPopup();',this.millisecondTimeout));
}
Calendar.prototype.timeoutPopup=function(){
	if(this.mouseOverCounter<=0){
		this.hidePopup();
	}
}
Calendar.prototype.clearPopupTimers=function(){
	while(this.popupTimers.length>0){
		window.clearTimeout(this.popupTimers.shift());
	}
	this.mouseOverCounter=0;
}
Calendar.prototype.hidePopup=function(){
	this.clearPopupTimers();
	if(this.popup!=null){
		if(this.useIePopup){
			this.popup.hide();
		}else{
			$j(this.popup).hide();
		}
	}
	this.popup=null;
}
Calendar.prototype.popupToggle=function(){
	if(this.popup==null&&!this.dayField.disabled&&!this.monthYearField.disabled){
		this.popupCreate();
	}else{
		this.hidePopup();
	}
}
Calendar.prototype.setEnabled=function(enabled){
	if(this.dayField.type!='hidden'){this.dayField.disabled=(!enabled);}
	if(this.monthYearField.type!='hidden'){this.monthYearField.disabled=(!enabled);}
	if(this.hourField.type!='hidden'){this.hourField.disabled=(!enabled);}
	if(enabled){
		this.calendarIcon.className=this.calendarIcon.className.replace(/disabled/ig,'');
	}else{
		this.calendarIcon.className+=' disabled';
	}
}
Calendar.prototype.createCalendar=function(obj){
	this.fieldTag=this.doc.getElementById(this.fieldTagId);		
	while(this.fieldTag.hasChildNodes()){
		this.fieldTag.removeChild(this.fieldTag.firstChild);
	}
	this.calendarTag=((this.calendarTagId==null)?null:this.doc.getElementById(this.calendarTagId));
	
	while(this.calendarTag!=null&&this.calendarTag.hasChildNodes()){
		this.calendarTag.removeChild(this.calendarTag.firstChild);
	}
	
	var temp=this.doc.createElement('div');
	temp.className='clearit';
	temp.appendChild(this.monthYearField);
	temp.appendChild(this.dayField);
	if(this.showCalendarIcon){temp.appendChild(this.calendarIcon);}
	temp.appendChild(this.hourField);
	temp.appendChild(this.yearField);
	temp.appendChild(this.monthField);
	temp.appendChild(this.timeField);
	temp.appendChild(this.formattedField);
	temp.appendChild(this.bookLeadFormattedField);

	this.fieldTag.appendChild(temp);
	this.haveFieldsBeenInserted=true;
	this.update(this.startDate);
	

	if (obj)
	{
		if(this.showCalendarIcon||this.calendarTagId==null)
		{
			$j('#'+obj).prepend(this.divCalendar);
		}
		else
		{
			this.calendarTag.appendChild(this.divCalendar);
		}
	}
	else
	{
		if(this.showCalendarIcon||this.calendarTagId==null)
		{
			$j('#'+this.fieldTagId).prepend(this.divCalendar);
		}
		else
		{
			this.calendarTag.appendChild(this.divCalendar);
		}
	}
}
Calendar.prototype.setOnChangeCallback=function(onChangeCallback){
	this.onChangeCallback=onChangeCallback;
}
Calendar.prototype.getDate=function(){
	return(this.displayDate==null?this.startDate:this.displayDate);
}
Calendar.prototype.setCalendarCSS=function(calendarCSS){
	this.calendarCSS=calendarCSS;
}
Calendar.prototype.setDefaultHour=function(defaultHour){
	this.defaultHour=defaultHour;
}
Calendar.prototype.setAnytime=function(value){
	this.isAnytime=value;
	if(this.showHourField){
		this.updateHourSelectOptions();
	}else{
		this.hourField.value=this.displayDate.getHours();
	}
}
Calendar.prototype.serialize=function(){
	return ''+this.getDate().getTime()+'-'+(this.hourRangeSelected?1:0)+'-'+(this.hasUserSetHour?1:0)+'-'+(this.isAnytimeSelected?1:0);
}
Calendar.prototype.deserialize=function(value){
	var s=value.split('-');
	this.isAnytimeSelected=(s[3]=='1'?true:false);
	this.hasUserSetHour=(s[2]=='1'?true:false);
	this.hourRangeSelected=(s[1]=='1'?true:false);
	this.update(new Date(parseInt(s[0])));
}
Calendar.prototype.showHours=function(){
	this.hourField.style.visibility = 'visible';
}
Calendar.prototype.hideHours=function(){
	this.updateHourOfDay('Anytime');
	this.hourField.style.visibility = 'hidden';
}
function Calendar(varName,inputIdPrefix, inputNamePrefix,dateRanges,fieldTagId,showMonthYearField,showDayField,showHourField,showCalendarIcon,calendarTagId,fieldsToHide){	

	this.win=window;
	this.doc=document;
	this.varName=varName;
	this.fieldTagId=fieldTagId;
	this.calendarTagId=calendarTagId;
	this.isAnytime=false;
	this.isAnytimeSelected=true;
	this.dateRanges=dateRanges;
	this.startDate=dateRanges[0].from;
	this.endDate=dateRanges[dateRanges.length-1].to;
	this.displayDate=null;
	this.fieldsToHide = fieldsToHide;
	this.inputIdPrefix=inputIdPrefix;
	this.inputNamePrefix=inputNamePrefix;
	this.showMonthYearField=((showMonthYearField==true||showMonthYearField==null)?true:false);
	this.showDayField=((showDayField==true||showDayField==null)?true:false);
	this.showHourField=((showHourField==true||showHourField==null)?true:false);
	this.showCalendarIcon=((showCalendarIcon==true||showCalendarIcon==null)?true:false);
	this.contextURL=document.URL.substring(0,document.URL.indexOf('/',9));
	this.calendarCSS=this.contextURL+'/styles/themes/red08/common.css';	
	this.onChangeCallback=null;
	this.hourRangeSelected=true;
	this.defaultHour=null;
	this.hasUserSetHour=false;
	this.haveFieldsBeenInserted=false;	
	this.divCalendar=this.doc.createElement('div');
			
	this.divCalendar.id=this.inputIdPrefix+'CalendarPage';
	this.divCalendar.className='calendarPage';
	if(this.showCalendarIcon||this.calendarTagId==null)
	{
		$j(this.divCalendar).hide();
	}

	// The formated YYYYmmDDHH00 date-time.
	this.formattedField=this.doc.createElement('input');
	this.formattedField.type='hidden';
	this.formattedField.name=inputNamePrefix+'Formatted';
	this.formattedField.id=inputIdPrefix+'Formatted';
	

	// The minimum departure time formated YYYYmmDDHH00 date-time.
	this.bookLeadFormattedField=this.doc.createElement('input');
	this.bookLeadFormattedField.type='hidden';
	this.bookLeadFormattedField.name=inputNamePrefix+'BookLeadFormatted';
	this.bookLeadFormattedField.id=inputIdPrefix+'BookLeadFormatted';
	

	// The timeField stores the millisecond time since midnight 1st Jan 1970 (UTC).
	this.timeField=this.doc.createElement('input');
	this.timeField.type='hidden';
	this.timeField.name=inputNamePrefix+'Time';
	this.timeField.id=inputIdPrefix+'Time';
	

	this.yearField=this.doc.createElement('input');
	this.yearField.type='hidden';
	this.yearField.name=inputNamePrefix+'Year';
	this.yearField.id=inputIdPrefix+'Year';
	

	this.monthField=this.doc.createElement('input');
	this.monthField.type='hidden';
	this.monthField.name=inputNamePrefix+'Month';
	this.monthField.id=inputIdPrefix+'Month';
	

	if(this.showMonthYearField){
		this.monthYearField=this.doc.createElement('select');
		this.monthYearField.onchange=new Function(varName+'.updateMonthYear(this.options[this.selectedIndex].value);'+varName+'.hidePopup();');
	}else{
		this.monthYearField=this.doc.createElement('input');
		this.monthYearField.type='hidden';
	}

	if(this.showDayField){
		this.dayField=this.doc.createElement('select');
		this.dayField.onchange=new Function(varName+'.updateDayOfMonth(this.options[this.selectedIndex].value);'+varName+'.hidePopup();');
	}else{
		this.dayField=this.doc.createElement('input');
		this.dayField.type='hidden';
	}

	if(this.showHourField){
		this.hourField=this.doc.createElement('select');
		this.hourField.onchange=new Function(varName+'.updateHourOfDay(this.options[this.selectedIndex].value);'+varName+'.hidePopup();');
	}else{
		this.hourField=this.doc.createElement('input');
		this.hourField.type='hidden';
	}

	this.monthYearField.className='calMonthYear';
	//this.monthYearField.title="Select Month and Year";
	this.monthYearField.name=inputNamePrefix+'MonthYear';
	this.monthYearField.id=inputIdPrefix+'MonthYear';

	this.dayField.className='calDay';
	//this.dayField.title="Select Day";
	this.dayField.name=inputNamePrefix+'Day';
	this.dayField.id=inputIdPrefix+'Day';

	this.hourField.className='calHour';
	//this.hourField.title="Select Time of Day";
	this.hourField.name=inputNamePrefix+'Hour';
	this.hourField.id=inputIdPrefix+'Hour';

	if(navigator.userAgent.indexOf('Safari')>=0){
		this.calendarIcon=this.doc.createElement('a');
		this.calendarIcon.innerHTML='&nbsp;'
	}else{
		this.calendarIcon=this.doc.createElement('input');
		this.calendarIcon.type='text';
	}

	this.calendarIcon.readOnly='readOnly';
	this.calendarIcon.className='calendarIcon';
	this.calendarIcon.id=inputIdPrefix+'PopupCalendarIcon';
	this.calendarIcon.onclick=new Function(varName+'.popupToggle()');
	this.calendarIcon.onmouseover=new Function(varName+'.mouseOver()');
	this.calendarIcon.onmouseout=new Function(varName+'.mouseOut()');
	if(Calendar.title)	
		this.calendarIcon.title=Calendar.title;
	else
	    this.calendarIcon.title="Click for a month-by-month calendar";	


	this.mouseOverCounter=0;
	this.popupTimers=new Array();
	this.popup=null;
	this.popupX=0;
	this.popupY=0;
	this.popupW=0;
	this.popupH=0;
}
//This function will set the new Date Range  for the Calendar
Calendar.prototype.setDateRange=function(dateRanges){
	this.dateRanges=dateRanges;
	this.startDate=dateRanges[0].from;
	this.endDate=dateRanges[dateRanges.length-1].to;
	this.displayDate=null;
	this.update(this.startDate);
}
function submitTwice()
{
	document.intForm.submit();
}

/* FlightSearchValidator object */
function FlightSearchValidator(earliestBookingDate,formId,departCalendar,returnCalendar,dataContainer, region, intShowHideReturn){
	this.earliestBookingDate=earliestBookingDate;
	this.formId=formId;
	this.departCalendar=departCalendar;
	this.returnCalendar=returnCalendar;
	this.region=region;
	this.dataContainer = dataContainer;
	this.invalidLocationOptions=['','select a city','Select a City','selectacity','separator'];
	this.intShowHideReturn = intShowHideReturn;
}

FlightSearchValidator.prototype.isProduction=function(){
	return (window.location.host.indexOf('www.qantas')==0||window.location.host.indexOf('qantas')==0);
}
FlightSearchValidator.prototype.bookingEngineUrl=function(){
	return (this.isProduction()?'http://wftc3.e-travel.com':'http://siteacceptance.wftc3.e-travel.com');
}
FlightSearchValidator.prototype.isReturn=function(){
	for(var i=0;i<this.tripType.length;++i){
		if((this.tripType[i].value=='R'||this.tripType[i].value=='return')&&this.tripType[i].checked){
			return true;
		}
	}
	return false;
}
FlightSearchValidator.prototype.validateLocations=function(){
	for(var i=0;i<this.invalidLocationOptions.length;++i){
		if(this.from.value==this.invalidLocationOptions[i]){
			alert(this.dataContainer.errorMsgs['bookingForm.error.departurelocation']);
			this.from.focus();
			return false;
		}
	}
	for(var i=0;i<this.invalidLocationOptions.length;++i){
		if(this.to.value==this.invalidLocationOptions[i]||this.toBox.value==this.invalidLocationOptions[i]){
			alert(this.dataContainer.errorMsgs['bookingForm.error.arrivallocation']);
			this.toBox.focus();
			return false;
		}
	}
	if(this.from.value==this.to.value){
		alert(this.dataContainer.errorMsgs['bookingForm.error.departurearrivallocation']);
		this.from.focus();
		return false;
	}
	return true
}

FlightSearchValidator.prototype.validateDates=function(){
	if(this.departCalendar.getDate().getTime()<this.earliestBookingDate.getTime()){
		alert(this.dataContainer.errorMsgs['bookingForm.error.startdate']);
		this.departCalendar.monthYearField.focus();
		return false;
	}
	if(this.isReturn()&&this.returnCalendar.getDate().getTime()<this.departCalendar.getDate().getTime()){
		alert(this.dataContainer.errorMsgs['bookingForm.error.startenddate']);
		this.returnCalendar.monthYearField.focus();
		return false;
	}
	return true;
}

FlightSearchValidator.prototype.validatePax=function(){
	var numAdults=parseInt(this.adults.value);
	var numChild=parseInt(this.children.value);
	var numInfant=parseInt(this.infants.value);
	var totalPax=numAdults+numChild+numInfant;
	var maxPax=this.dataContainer.maxPax;
	if(totalPax>maxPax){
		alert(this.dataContainer.errorMsgs['bookingForm.error.maxpaxs']);
		this.adults.focus();
		return false;
	}
	if(numInfant>numAdults){
		alert(this.dataContainer.errorMsgs['bookingForm.error.infant']);
		this.infants.focus();
		return false;
	}
	return true;
}
FlightSearchValidator.prototype.isSearchByBestPrice=function(){
	return true;
}
FlightSearchValidator.prototype.isFlexible=function(){	
		if( this.flexiDates !=null  && this.flexiDates.value !=null )
		{
			if(this.flexiDates.value.indexOf('true') >-1 )
			{				
				return true;
			}
		}		
		
	return false;
}
FlightSearchValidator.prototype.createCommonQueryString=function(){
	var s=null;
	var officeId='';
	var s='';
	s+='LANGUAGE=GB';
	s+='&TRIP_TYPE='+(this.isReturn()?'R':'O');
	s+='&B_LOCATION_1='+this.from.value;
	s+='&E_LOCATION_1='+this.to.value;
	s+='&B_DATE_1='+this.departCalendar.getDate().format('YYYYmmDDHH00');
	s+='&B_DATE_2='+this.returnCalendar.getDate().format('YYYYmmDDHH00');
	var numAdults=parseInt(this.adults.value);
	var numChild=parseInt(this.children.value);
	var numInfant=parseInt(this.infants.value);
	var paxCount=1;
	for(var i=0;i<numAdults;++i){
		s+='&TRAVELLER_TYPE_'+paxCount+'=ADT';
		if(i<numInfant){
			s+='&HAS_INFANT_'+paxCount+'=TRUE'; //Infants get same paxCount as accompanying adult.
		}
		++paxCount;
	}
	for(var i=0;i<numChild;++i){
		s+='&TRAVELLER_TYPE_'+paxCount+'=CHD';
		++paxCount;
	}
	s+='&SEVEN_DAY_SEARCH=TRUE';
	s+='&CUSTOMER_TYPE=P';
	s+='&ARRANGE_BY=N';
	if(this.region=='sp'){
		s+='&SO_SITE_OFFICE_ID=AKLQF08AA';
	}
	s+='&PAGE_FROM='+"/regions/dyn/quickSearch";
	return s;
}
FlightSearchValidator.prototype.createDomesticQueryString=function(isFFLoggedIn){
	var s=this.createCommonQueryString();
	if(this.region=='au'){
		s+='&SITE=QFD';
		var bookingServlet='/pl/QFdomestic/en/FamilyPricerAvailabilityServlet';
	}else{
		s+='&SITE=QFN';
		var bookingServlet='/pl/QFdomestic/en/OverrideServlet';
		s+='&EMBEDDED_TRANSACTION=FamilyPricerAvailabilityServlet';
		s+='&SO_SITE_FD_INTERNA=FALSE';
	}
//	s+='&FARE_FAMILY='+this.fareFamily.value;
	
	// if date searched is after 24th May - redirect through Route Filter Server
	var cutoverDate=new Date(2004,4,25,0,0,0);

	if(isFFLoggedIn){
		var ffParam ="RF_FFCONLY=Y";		
		var servletAddress = "RF_SERVLET="+this.bookingEngineUrl()+bookingServlet;
		s = 'https://'+location.host+'/regions/dyns/routeFilter?'+s+'&'+servletAddress+'&'+ffParam;
	}
	else {
		s=this.bookingEngineUrl()+bookingServlet+'?'+s;
	}
	return s;
}
FlightSearchValidator.prototype.createInternationalQueryString=function(isFFLoggedIn){
	var s=this.createCommonQueryString();
	var tt=false;
	var flightDataItem = FlightDataCache.getFlightDataItem(this.dataContainer, this.from.value,this.to.value);
	if(this.region=='au'||this.region=='sp'){
		tt=(flightDataItem.isTransTasman());
	}
	if(tt){
		s+='&SITE=QFN';
//		s+='&FARE_FAMILY='+this.fareFamily.value;
		if(this.region=='au'){
			if(!isFFLoggedIn){
				s='FamilyPricerAvailabilityServlet?'+s;
			}
		}else{
			s+='&EMBEDDED_TRANSACTION=FamilyPricerAvailabilityServlet';
		}
	}else{
		s+='&SITE=QFI';
		if(this.region=='au'||this.region=='sp'){
//			s+='&CABIN='+this.fareFamily.value.substr(0,1);
		}else{
//			s+='&CABIN='+this.fareClass.value;
		}
		if(this.isSearchByBestPrice()){
			s+='&EMBEDDED_TRANSACTION=ValuePricerServlet';
		}else{
			s+='&EMBEDDED_TRANSACTION=AirAvailabilityServlet';
		}
		if(this.region=='au'||this.region=='sp'){
			if(this.region=='au'){
				s+='&SO_SITE_PREFERRED_CARRIER=QFAO';
				s+='&SO_SITE_FC_INCLUDE_AIRLINES=QFAO';
			}
		}else{
			if(this.region=='uk'){
				s+='&SO_SITE_OFFICE_ID=LONQF18AA';
				s+='&SO_SITE_PREFERRED_CARRIER=QFBA';
				s+='&SO_SITE_FC_INCLUDE_AIRLINES=QFBA';
			}else if(this.region=='sg'){
				s+='&SO_SITE_OFFICE_ID=SINQF18AA';
				s+='&SO_SITE_PREFERRED_CARRIER=QFBA';
				s+='&SO_SITE_FC_INCLUDE_AIRLINES=QFBA';
			}else if(this.region=='as'){
				s+='&SO_SITE_OFFICE_ID=SINQF18AA';
				s+='&SO_SITE_PREFERRED_CARRIER=QFBA';
				s+='&SO_SITE_FC_INCLUDE_AIRLINES=QFBA';
			}else if(this.region=='us'){
				s+='&SO_SITE_OFFICE_ID=LAXQF18AA';
			}
			s+='&SO_QUEUE_OFFICE_ID=SYDQF2RES';
			s+='&SO_SITE_FP_CC_CARDHOLDERNAME=';
			s+='&SO_GL=%3C%3Fxml+version%3D%271.0%27+encoding%3D%27iso-8859-1%27%3F%3E%3CSO_GL%3E%3CGLOBAL_LIST%3E%3CNAME%3ESITE_CREDIT_CARD%3C%2FNAME%3E%3CLIST_ELEMENT%3E%3CCODE%3EXX%3C%2FCODE%3E%3CLIST_VALUE%3E%3C%2FLIST_VALUE%3E%3C%2FLIST_ELEMENT%3E%3C%2FGLOBAL_LIST%3E%3C%2FSO_GL%3E';
		}
	}
	if(isFFLoggedIn){
		var ffParam ="RF_FFCONLY=Y";
		if(this.region=='au'&&tt){
			var servletAddress = "RF_SERVLET="+this.bookingEngineUrl()+"/pl/QFinternational/en/FamilyPricerAvailabilityServlet";
		}else{
			var servletAddress = "RF_SERVLET="+this.bookingEngineUrl()+"/pl/QFinternational/en/OverrideServlet";
		}
		s = 'https://'+location.host+'/regions/dyns/routeFilter?'+s+'&'+servletAddress+'&'+ffParam;
	}
	else {
		if(this.region=='au'&&tt){
			s=this.bookingEngineUrl()+'/pl/QFinternational/en/'+s;
		}else{
			s=this.bookingEngineUrl()+'/pl/QFinternational/en/OverrideServlet?'+s;
		}
	}
	return s;
}
/**
 * Creates a cookie to store the input of a flight search and sets it in the document
 */
FlightSearchValidator.prototype.setSelectionDetailsCke=function(type){
	var sortBy = "";
    if(this.region=='au'||this.region=='sp'){
//		var fare=this.fareFamily.value;
		var srchby="";
	}else{
		var fare=this.travelClass.value;
		var srchby="|SRCHBY:"+(this.isSearchByBestPrice()?'B':'S');
	}
	if ((this.region=='au' && type=='int') 
		|| (this.region=='sg') 
		|| (this.region=='uk') 
		|| (this.region=='eu') 
		|| (this.region=='us') 
		|| (this.region=='as') 
		|| (this.region=='sp' && type=='int')) {
		fare=this.travelClass.value;
		srchby="|SRCHBY:"+(this.isFlexible()?'T':'F');
        if(document.getElementById("intArrangeBy")!=null)
        {
            sortBy = document.getElementById("intArrangeBy").selectedIndex;
		    sortBy="|SORTBY:"+sortBy;
        }
	}
	if(type=='dom'){
		srchby="|SRCHBY:"+(this.isFlexible()?'T':'F');
		sortBy = document.getElementById("domArrangeBy").selectedIndex;
		sortBy="|SORTBY:"+sortBy;
	}
    
	var z="selections=DATES:"+this.departCalendar.serialize()+
			","+this.returnCalendar.serialize()+
			"|PORTS:"+this.from.value+
			","+this.to.value+
			"|PSGRS:"+this.adults.value+
			","+this.children.value+
			","+this.infants.value+
			"|TYPE:"+type+
			"|TRIP:"+(this.isReturn()?'R':'O')+srchby+
			"|REGION:"+this.region+
			"|FARE:"+fare+
            sortBy;
    document.cookie=z+";path=/";
    /* 
    	note that the path to the cookie has been set to /regions
    	this means that all requests to pages in the regions app
    	will have this cookie passed to them.  This is an overhead.
    	The reason for this change was that this cookie is used by the 
    	homepage ( non-struts, path regions/dyn) and the new quickSearch page
    	(struts, path regions/do/dyn).
    */
}


FlightSearchValidator.prototype.domesticInitialise=function(isFFLoggedIn){
	var form=document.getElementById(this.formId);
	this.tripType=form.domTripType;
	this.from=form.domFrom;
	this.to=form.domTo;
	this.adults=form.domAdults;
	this.children=form.domChildren;
	this.infants=form.domInfants;
//	this.fareFamily=form.domFareFamily;
	if(this.region=='au' || this.region=='sp')
	{
		this.flexiDates=form.domFlexiDates;
		this.sortFlightsBy=form.domArrangeBy;
	}

}

FlightSearchValidator.prototype.domesticValidateAndSubmit=function(isFFLoggedIn,submitForm){
	this.domesticInitialise();
	
	// The order these validate methods are called in is important.
	if(!this.validateLocations()){return false;}
	if(!this.validateDates()){return false;}
	if(!this.validatePax()){return false;}
	this.setSelectionDetailsCke('dom');
	if(!submitForm){
		var queryString=this.createDomesticQueryString(isFFLoggedIn);
		if(!this.isProduction()){
			alert(queryString);
		}
		document.location=queryString;
	}else{
		document.domForm.submit();
	}
	return true;
}


FlightSearchValidator.prototype.internationalInitialise=function(){
	var form=document.getElementById(this.formId);
	this.tripType=form.intTripType;
	this.from=form.intFrom;
	this.to=form.intTo;
	this.toBox=form.intToTextField;
	this.adults=form.intAdults;
	this.children=form.intChildren;
	this.infants=form.intInfants;
//	this.fareFamily=form.intFareFamily;
//	this.fareClass=form.intFareClass;
	this.travelClass=form.intTravelClass;
	this.flexiDates=form.intFlexiDatesCheckBox;
    this.sortFlightsBy=form.intArrangeBy;
}
FlightSearchValidator.prototype.internationalValidateAndSubmit=function(isFFLoggedIn,submitForm){
	this.internationalInitialise();
	
	// The order these validate methods are called in is important.
	if(!this.validateLocations()){return false;}
	if(!this.validateDates()){return false;}
	if(!this.validatePax()){return false;}
	this.setSelectionDetailsCke('int');
	if(this.isFlexible())
	{
			document.getElementById("intFlexiDates").value="true"
	}
	else
	{
			document.getElementById("intFlexiDates").value="false"
	}
	if(!submitForm){
		var queryString=this.createInternationalQueryString(isFFLoggedIn);
		if(!this.isProduction()){
			alert(queryString);
		}
		document.location=queryString;
	}else{
		this.setIntFormProperties();
		if ($j.browser.safari)
		{
			setTimeout('submitTwice()',10);
		}else if ( navigator.userAgent.toLowerCase().indexOf('chrome') > -1 )
		{
			setTimeout('submitTwice()',10);
		}
		document.getElementById(this.formId).submit();
	}
	addPastSearch();
	return true;
}


FlightSearchValidator.prototype.setIntFormProperties=function(){
	document.getElementById(this.formId).intTransTasman.value = "false";
	if(this.region == 'au' || this.region =='sp'){
		var flightDataItem = FlightDataCache.getFlightDataItem(this.dataContainer, this.from.value,this.to.value);
		if(flightDataItem.isTransTasman())
			document.getElementById(this.formId).intTransTasman.value = "true";
	}
}
FlightSearchValidator.prototype.domesticSetSelections=function(){
	this.setSelections(true);
}
FlightSearchValidator.prototype.internationalSetSelections=function(){
	this.setSelections(false);
}
/**
 * Parses the cookie string and populates corresponding fields in the flight search form
 * NB: the order in which form fields are set is important. 
 */
FlightSearchValidator.prototype.setSelections=function(isDomestic){
	
	//	departure and arrival airports are now stored in the UserContext
	//	so we must retrieve from there, not from the 'selections' cookie for these values.
	var depCity;
	var arrCity;
	
	if((document.cookie.indexOf("usercontext="))!=-1){
		var userContextCookie=getCookieValue("usercontext");	
		var depAirportInd = userContextCookie.indexOf("dep#");
		var arrAirportInd = userContextCookie.indexOf("arr#");
		depCity = userContextCookie.substring(depAirportInd+4,depAirportInd+7);
		arrCity = userContextCookie.substring(arrAirportInd+4,arrAirportInd+7);	
	}
	//	if we don't have either the departure or arrival airport, pre-populate nothing on the form
	
	if(depCity!=null || arrCity!=null){
		if((document.cookie.indexOf("selections="))!=-1){
			var val=readCookieValue("selections");
			var regionInd=val.indexOf("REGION:");
			var reg=val.substring(regionInd+7,regionInd+9);
			if(this.region==reg)
			{
				var datesInd=val.indexOf("DATES:");
				var portsInd=val.indexOf("PORTS:");
				var typeInd=val.indexOf("TYPE:");
				var fareInd=val.indexOf("FARE:");
				var psgrsInd=val.indexOf("PSGRS:");
				var tripInd=val.indexOf("TRIP:");
				var srchByInd=val.indexOf("SRCHBY:");
				var sortByInd=val.indexOf("SORTBY:");
				var dates=val.substring(datesInd+6,portsInd-1);
				var z=dates.split(",");
				var depDate=z[0];
				var retDate=z[1];			
				var type=val.substring(typeInd+5,typeInd+8);
				var fare;
				if (sortByInd != -1) {
					fare = val.substring(fareInd+5, sortByInd-1);
				} else {
					fare = val.substring(fareInd+5);
				}
				var fares=fare.split(",");
				var adults=val.substring(psgrsInd+6,psgrsInd+7);
				var children=val.substring(psgrsInd+8,psgrsInd+9);
				var infants=val.substring(psgrsInd+10,psgrsInd+11);
				var trip=val.substring(tripInd+5,tripInd+6);
				var srchBy=val.substring(srchByInd+7,srchByInd+8);
				var sortBy;
				if (sortByInd != -1) {				
					sortBy=val.substring(sortByInd+7,sortByInd+8);
				}
				if (type=="dom" && isDomestic) {
					this.domesticInitialise();
				
					this.departCalendar.deserialize(depDate);
					this.returnCalendar.deserialize(retDate);
					
//					this.set(this.fareFamily,fares[0]);
					this.setCommonFields(depCity, arrCity, adults, children, infants, srchBy, trip);
					if(!browser.isMSIE5x)
						this.intShowHideReturn();
					if(this.region=='au' || this.region=='sp'){
						this.sortFlightsBy.selectedIndex=sortBy;
					}
					this.intShowHideReturn();
					if (window.navigator.userAgent.toLowerCase().indexOf('msie 5.5') == -1)
						this.intShowHideReturn();
				} else if (type=="int" && !isDomestic) {
					this.internationalInitialise();
					this.departCalendar.deserialize(depDate);
					this.returnCalendar.deserialize(retDate);						
					/*
					if(this.region!='us'){
						changePanelTab('flightSearchTabbedPanels','internationalTab','internationalPanel');
					}
					*/
					
					if (this.region=='au' || this.region=='sp') {
						if (sortBy != null && sortBy != "")
							this.sortFlightsBy.selectedIndex=sortBy;
					}
					if (fares.length>1){
						this.set(this.travelClass, fares[1]);
					} else {
						this.set(this.travelClass, fares);
					}
					this.setCommonFields(depCity, arrCity, adults, children, infants, srchBy, trip);
					this.intShowHideReturn();
					if (window.navigator.userAgent.toLowerCase().indexOf('msie 5.5') == -1){
					this.intShowHideReturn();
				}
			}
		}
	}
	}
    // Start bodgy code - remove when NFS Trans Tasman return has cutover for good.
    // Fix for IE5.5 - on hitting back button the oneway radial was not cached but the sortby (NFS) is shown for return
    // This is a bodge for NFS issues where trans tasman one way and return cutover dates differ.
	if(document.getElementById('divSortBy')!=null && (window.navigator.userAgent.toLowerCase().indexOf('msie 5.5') != -1) && !isAfterTTReturnNfsCutover())
	{
		var flightDataItem = FlightDataCache.getFlightDataItem(this.dataContainer, document.getElementById('intFrom').value,document.getElementById('intTo').value);
		if(flightDataItem.isTransTasman())
		{
			document.getElementById('intTripTypeReturn').checked = true;
			if (this.sortFlightsBy != null)
				this.sortFlightsBy.selectedIndex = 0;
			checkT_Tasman();
		}
    }
    // End bodgy code
}
/**
 * Sets fields common to all regions in the flight search form
 */
FlightSearchValidator.prototype.setCommonFields=function(depCity, arrCity, adults, children, infants, srchBy, tripType){
	this.set(this.from, depCity);
	this.set(this.to, arrCity);
	this.set(this.adults, adults);
	this.set(this.children, children);
	this.set(this.infants, infants);
	if (this.tripType) {
		if (tripType == 'R') {
			this.tripType[0].checked=true;
		} else {
			this.tripType[1].checked=true;
		}
	}
//	if (this.searchType) {
//		if (srchBy == 'B') {
//			this.searchType[0].checked=true;
//		} else {
//			this.searchType[1].checked=true;
//		}
//	}
	if (this.flexiDates) {
		if (srchBy == 'T') {
			if(document.getElementById('transTasmanPostThrottleDate')!=null)
				document.getElementById('transTasmanPostThrottleDate').style.display="block";
			this.flexiDates.value=true;
			this.flexiDates.checked=true;
		} else {
			this.flexiDates.value=false;
			this.flexiDates.checked=false;
		}
	}
}
FlightSearchValidator.prototype.set=function(frmelem, value){
	if(value) {
		for(var i=0;i<frmelem.length;i++){
			if(frmelem.options[i].value==value) {
				frmelem.options[i].selected = true;
				break;
			}
		}
	}
}
FlightSearchValidator.prototype.preSelectSingleOpt=function(frmelem){
	if(frmelem != null && frmelem.options != null){
			if(frmelem.options.length == 3)
				frmelem.selectedIndex=2;
	}
}
/*
Look, this change is done by Zhan Zhang on 14/05/2007
What does this method do?
It validate the form and submit the request, no matter it is a domestic form or international form
*/
FlightSearchValidator.prototype.flightValidateAndSubmit=function(isFFLoggedIn,submitForm,isDomestic){
	this.flightInitialise();
	// The order these validate methods are called in is important.
	if(!this.validateLocations()){return false;}
	if(!this.validateDates()){return false;}
	if(!this.validatePax()){return false;}
	if (isDomestic)
		this.setSelectionDetailsCke('dom');
	else
		this.setSelectionDetailsCke('int');
	if(!submitForm){
		var queryString=this.createFlightQueryString(isFFLoggedIn,isDomestic);
		if(!this.isProduction()){
			alert(queryString);
		}
		document.location=queryString;
	}else{
		document.domForm.submit();
	}
	return true;
}

FlightSearchValidator.prototype.flightInitialise=function(isFFLoggedIn){
	var form=document.getElementById(this.formId);
	this.tripType=form.domTripType;
	this.from=form.domFrom;
	this.to=form.domTo;
	this.adults=form.domAdults;
	this.children=form.domChildren;
	this.infants=form.domInfants;
//	this.fareFamily=form.domFareFamily;
	this.flexiDates=form.domFlexiDates;
	this.sortFlightsBy=form.domArrangeBy;
	this.travelClass=form.intTravelClass;
}


FlightSearchValidator.prototype.createFlightQueryString=function(isFFLoggedIn,isDomestic){
	if (isDomestic) {
		return createDomesticQueryString(isFFLoggedIn);
	} else {
		return createInternationalQueryString(isFFLoggedIn);
	}
	return s;
}

//Zhan's code finish here
/**
 * This function is used to populate the select drop-down box with
 * options. The format of the options array should be:
 * 
 * It should be observed that the correct number of parameters should be
 * passed in always.
 *
 * In case of the value of 'selectedValue' is not exsits on the dropdown list,
 * the first item on the dropdown list shall be selected.
 *
 * var optionsArray=[['value0','label0'],['value1','label1'],['value2','label2']];
 */
function populateOptions(selectId,optionsArray,selectedValue){
	var select=document.getElementById(selectId);
	var selected=false;
	select.selectedIndex= -1;
	select.options.length=0;
	for (var i=0;i<optionsArray.length;++i){
		select.options[i]=new Option(optionsArray[i][1],optionsArray[i][0]);
		if(selected==false && optionsArray[i][0]==selectedValue){
			selected=true;
			select.selectedIndex=i;
		}
	}
    if (selected==false){
        select.selectedIndex=0;
    }
}
function populateNumericOptions(selectId,lower,upper,selectedValue){
	var select=document.getElementById(selectId);
	var selected=false;
	select.selectedIndex= -1;
	select.options.length=0;
	for (var i=lower;i<=upper;++i){
		select.options[i-lower]=new Option(i.toString(),i.toString());
		if(selected==false && i.toString()==selectedValue){
			selected=true;
			select.selectedIndex=i-lower;
		}
	}
    if (selected==false){
        select.selectedIndex=0;
    }
}

function populateOptionsMulti(selectId,optionsArray,selectedValue,multiplier){
	var selectedIndex=0;
	var select=document.getElementById(selectId);
	var selected=false;
	select.selectedIndex= -1;
	select.options.length=0;
	var j =0;
	for (var i=multiplier-1;i<optionsArray.length;i=i+multiplier){
		select.options[j]=new Option(optionsArray[i][1],optionsArray[i][0]);
		if(selected==false&&optionsArray[i][0]==selectedValue){
			selected=true;
			selectedIndex=j;
		}
		++j;
	}
	select.selectedIndex=selectedIndex;
}
/**
 * This function is used to populate the select drop-down box with
 * options. A "class" attribute can be added as well.
 *
 * The format of the options array should be:
 *
 * var optionsArray=[['value0','label0','class0'],['value1','label1','class1'],['value2','label2','class2']];
 *
 * If the class is empty it will not add a class attribute to that option.
 * 
 * It should be observed that the correct number of parameters should be
 * passed in always.
 *
 * In case of the value of 'selectedValue' is not exsits on the dropdown list,
 * the first item on the dropdown list shall be selected.
 */
function populateOptionsWithStyle(selectId,optionsArray,selectedValue){
	var select=document.getElementById(selectId);
	var selected=false;
	select.selectedIndex= -1;
	select.options.length=0;
	for (var i=0;i<optionsArray.length;++i){
		select.options[i]=new Option(optionsArray[i][1],optionsArray[i][0]);
		if(optionsArray[i][2]!=null && optionsArray[i][2]!="") {
			select.options[i].className=optionsArray[i][2];
		}
		if(selected==false && optionsArray[i][0]==selectedValue){
			selected=true;
			select.selectedIndex=i;
		}
	}
    if (selected==false){
        select.selectedIndex=0;
    }
}
function getAbsLeft(obj){
	var	l=obj.offsetLeft;
	while(obj=obj.offsetParent)
		l+=obj.offsetLeft;
	return l;
}

function getAbsTop(obj){
	var	t=obj.offsetTop;
	while(obj=obj.offsetParent)
		t+=obj.offsetTop;
	return	t;
}

function changeBkgrnd(obj){
	addClassName(obj, "selected");
}

function changeBkgrnd_Blur(obj){
	removeClassName(obj, "selected");
}

function addClassName(element, className) {
 	if (!Element.hasClassName(element, className)) element.className = (element.className+' '+className);
 }

function removeClassName(element, className) {
 	if (Element.hasClassName(element, className)) element.className = element.className.replace(className, '');
}


/*
 * this is a cache to hold flight data items so that we don't have to create them everytime
 */
var FlightDataCache = Class.create();
Object.extend(FlightDataCache.prototype, {
  initialize : function () {
  	this.flightDataCacheArray = new Object();
  },
  getFlightDataItem : function (dataContainer, from, to) {
	var itemFrom = this.flightDataCacheArray[from];
	if (itemFrom == null) {
		itemFrom = new Object();
		this.flightDataCacheArray[from] = itemFrom;
	}
  	var item = itemFrom[to];
	if (item == null) {
		item = new FlightData(dataContainer, from, to);
		itemFrom[to] = item;
	}
	
	return item;
  }
}
);

// initialise as a singleton
var FlightDataCache = new FlightDataCache();

/*
 * this object holds data for a flight combination, eg SYD-MEL
 * it uses a data container which holds all the information relevant to 
 * this airport pair combination.
 * 
 * This object can be queried for valid flights, valid classes and can be 
 * extended to hold further information by adding convenience methods and 
 * adding to the data matrix within the data container
 */
 
var FlightData = Class.create();
FlightData.prototype = {
  initialize : function (dataContainer, from, to) {
  	this.dataContainer = dataContainer;
  	this.airports = dataContainer.getAirports();
  	this.fromAirports = dataContainer.getFromAirports();
  	this.toAirports = dataContainer.getToAirports();
  	this.classes = dataContainer.getClasses();
  	this.matrix = dataContainer.getMatrix();
    this.fromAirport = getObjectFromArrayByCode(from, this.airports);
    this.toAirport = getObjectFromArrayByCode(to, this.airports);
    this.fromAirportIndex = indexOfAirportByCode(from, this.fromAirports);
    this.toAirportIndex = indexOfAirportByCode(to, this.toAirports);
	this.matrixItem = getMatrixItem(this.fromAirportIndex,this.toAirportIndex,this.matrix, this.fromAirports.length, this.toAirports.length);
 },
  isValidFlight : function (evt) {
  	if (this.matrixItem != null) {		
		// make assumption here that can't fly from and to the same city (SYD to SYD)
		if (this.fromAirport != this.toAirport) {
			if (determineBooleanValueFromMatrixItem(this.matrixItem, this.dataContainer.getValidFlightIndex())) {
				return true;
			}
		}
  	}
	return false;
  },
  // could move this data into matrix and thereby moving business logic out of front end
  isDomestic : function () {
	if (this.fromAirport.country == this.toAirport.country) {
		return true;
	}
	return false;
  },
  // could move this data into matrix and thereby moving business logic out of front end
  isInternational : function () {
	if (this.fromAirport.country != this.toAirport.country
		&& !this.isTransTasman()) {
		return true;
	}
	return false;
  },
  // could move this data into matrix and thereby moving business logic out of front end
  isTransTasman : function () {
	if ((this.fromAirport.country.code == 'AU' 
		 && this.toAirport.country.code == 'NZ')
		 ||
		(this.fromAirport.country.code == 'NZ' 
		 && this.toAirport.country.code == 'AU')) {
		return true;
	} else {
		return false;
	}
  },
  getClasses : function (departCalendar) {
  	if (this.matrixItem != null) {
  		return getClassesForFlight(this.matrixItem, this.dataContainer, departCalendar, this.fromAirport, this.toAirport);
  	}
  	
  	return new Array();
  	
  }
}

/* 
 * this object holds the basic airport data for a airport
 */
var Airport = Class.create();
Airport.prototype = {
  initialize : function (code, airportName, countryCode, countries) {
    this.code = code;
    this.airportName = airportName;
	this.country = getObjectFromArrayByCode(countryCode, countries);
  },
  getCountry : function () {
  	return this.country;
  },
  toStringNameOnly : function () {
  	return this.airportName;
  },
  toString : function () {
  	return this.toStringNoCode() + " (" + this.code + ")";
  },
  toStringAirportCodeOnly : function () {
	  return this.toStringNoCode() + "<span class=\'aCode\'>" + " (" + this.code + ")" + "</span>";
  },
  toStringNoCode : function () {
  	return this.airportName + ", " + this.country.countryName;
  },
  // this assumes toString format of Airport, Country (AirportCode)
  toStringWithHighlightedAirport : function (highlightValue) {
  	var airportText = this.toString();
	var indexOfMatch = airportText.toLowerCase().indexOf(highlightValue.toLowerCase());
	var countryMatchflag = "flagno";


	// check if index match is in airport name, if not then look for match in code
	if (indexOfMatch > this.airportName.length) {
		var lengthOfStringNoCode = this.toStringNoCode().length;
		var indexAfterCountry = airportText.substring(lengthOfStringNoCode).toLowerCase().indexOf(highlightValue.toLowerCase());
		indexOfMatch = lengthOfStringNoCode + indexAfterCountry;
		countryMatchflag = "flagyes";
	}
	if(countryMatchflag == "flagno"){
		var beforeHighlight = airportText.substring(0, indexOfMatch);
		var highlighted		= airportText.substring(indexOfMatch, indexOfMatch + highlightValue.length);
		var afterHighlight	= airportText.substring(indexOfMatch + highlightValue.length,airportText.length);
		var airportCodeAlone = afterHighlight.substring(afterHighlight.lastIndexOf("("),afterHighlight.lastIndexOf(")")+1);
		var afterHightlightCode  = afterHighlight.substring(0,afterHighlight.lastIndexOf("("));
		return beforeHighlight + "<strong>" + highlighted + "</strong>" +  afterHightlightCode + "<span class=\'aCode\'>" + airportCodeAlone + "</span>";
	} else {
		var beforeCodeHighlight	 = airportText.substring(0, indexOfMatch); // Takes the code upto where it matches (Rome , Italy ( --> when you type 'f')
		var lastHighlightedValue = beforeCodeHighlight.substring(airportText.lastIndexOf("("));// It gives the last index value where it matches "("
		var beforeHighlightSpan  = airportText.substring(0, (indexOfMatch-highlightValue.length)); // it will give now as (Rome , Italy ")
		var codeHighlighted      = airportText.substring(0, ((indexOfMatch+1) - (highlightValue.length)));
		var highlighted1		 = airportText.substring(indexOfMatch, indexOfMatch + highlightValue.length);
		var afterHighlight1		 = airportText.substring(indexOfMatch + highlightValue.length,airportText.length)
		if( highlightValue.length == 2){
			return beforeHighlightSpan + "<span class=\'aCode\'>" + lastHighlightedValue + "<strong>" + highlighted1 + "</strong>" +  afterHighlight1 +"</span>";
		} else if(highlightValue.length == 1){
			return beforeHighlightSpan + "<span class=\'aCode\'>"+ "(" + "<strong>" + highlighted1 + "</strong>" +  afterHighlight1 +"</span>";				
		} else {
			return codeHighlighted + "<span class=\'aCode\'>"+"(" + "<strong>" + highlighted1 + "</strong>" +  afterHighlight1 +"</span>";
		}
	}

  }
}

/**
 * this function takes a airport object and represents it as a hyperlinked String and highlights
 * the text entered to find it.
 */
function getAirportAsHTMLString(currentAirport, highlightValue, highlightMatch) {
	
//	var anchor = "";
	var highlight = "";
	if (currentAirport.airportName.toLowerCase().indexOf(highlightValue.toLowerCase())==0) {
//		anchor = "<font id=\"anchor\"></font>"
		if (currentAirport.airportName.toLowerCase()==(highlightValue.toLowerCase())) {
			highlight=" class=\"toBoxHighlight\" ";
		}
	}
	/*anchor + */
	var openingAnchorTag = "<a onFocus='changeBkgrnd(this)' onBlur='changeBkgrnd_Blur(this)' href='javascript:void(0)' id='to" + currentAirport.code + "'" + highlight + "/>";
	var airportText;
	if (highlightMatch) {
		airportText = currentAirport.toStringWithHighlightedAirport(highlightValue);
	} else {
		airportText = currentAirport.toStringAirportCodeOnly();
	}
	var closingAnchorTag = "</a>";
	return openingAnchorTag + airportText + closingAnchorTag;
}


/* 
 * this object holds the basic data for a booking class
 */
var BookingClass = Class.create();
BookingClass.prototype = {
  initialize : function (code, value, className) {
    this.code = code;
    this.value = value;
    this.className = className;
  }
}
  
/* 
 * this object holds the basic data for a country
 */
var Country = Class.create();
Country.prototype = {
  initialize : function (code, countryName) {
    this.code = code;
    this.countryName = countryName;
  }
}

/*
 * this object is the control object for the From Selection Box.
 * It sets up initial data and handles any expected events for the box.
 */
var FromBoxControl = Class.create();
FromBoxControl.prototype = {
  initialize : function (fromBoxId, dataContainer, defaultValue, showCountries, fromHeader) {
    this.fromBox = $(fromBoxId);
	this.popularFromAirports = dataContainer.getPopularFromAirports();
	this.fromAirports = dataContainer.getFromAirports();
	this.airports = dataContainer.getAirports();
	this.defaultValue = defaultValue;
	this.showCountries = showCountries;
	this.fromHeader = fromHeader;
	this.fromBox.onchange = this.fromBoxChange.bindAsEventListener(this);
	this.populateFromBox();
  },
  fromBoxChange : function (evt) {
  	
  	
  },
  populateFromBox : function () {
    var selected=false;
	var selectedIndex=0;
	this.fromBox.options.length=0;
	// place select from city at top
	var index = 0;
	this.fromBox.options[index]=new Option(this.fromHeader,'');
	index++;
	// put in seperator
	this.fromBox.options[index]=new Option('-----------------','separator');
	index++;
	// now put popular airports
	if (this.popularFromAirports != null) {
		
	
		var popArray = new Array();
		for (var i=0;i<this.popularFromAirports.length;++i){
			var currentAirport = getObjectFromArrayByCode(this.popularFromAirports[i], this.airports);
			popArray[i] = currentAirport;
		}
		//sorting removed since its handled at java end
		//popArray.sort(function(a,b) { return a.airportName-b.airportName; });
		for (var i=0;i<popArray.length;++i, index++){
		
			var currentAirport = popArray[i];
			this.fromBox.options[index]=new Option(currentAirport.airportName,currentAirport.code);
			if (!selected && this.defaultValue == currentAirport.code) {
				selectedIndex = index;
				selected = true;
			}
		}
		// put in seperator
		this.fromBox.options[index]=new Option('-----------------','separator');
		index++;
	}
	var lastDropDownCountry = "";
	// now put all airports
	var sortedArray = new Array();
 	for (var i=0;i<this.fromAirports.length;++i){
 		var currentAirport = getObjectFromArrayByCode(this.fromAirports[i], this.airports);
		sortedArray[i] = currentAirport;
 	}
	//sorting removed since its handled at java end
	//if (!this.showCountries) {
		//sortedArray.sort(compareAirportsByName);
	//}
 	for (var i=0;i<sortedArray.length;++i, index++){
 		var currentAirport = sortedArray[i];
 		if (this.showCountries && currentAirport.country.countryName != lastDropDownCountry) {
			this.fromBox.options[index]=new Option(currentAirport.country.countryName,"");
			this.fromBox.options[index].className = "cityDropDownCountry";
			index++;
			lastDropDownCountry = currentAirport.country.countryName;
 		}
		this.fromBox.options[index]=new Option(currentAirport.airportName,currentAirport.code);
		if (!selected && this.defaultValue == currentAirport.code) {
			selectedIndex = index;
			selected = true;
		}
 	}
	this.fromBox.selectedIndex = selectedIndex;
  }
}

	function compareAirportsByName(a,b) {
		if (a.airportName < b.airportName) {
			return -1;
		} else if (a.airportName > b.airportName) {
		 	return 1;
		} else {
		 	return 0;
		}
	}

/*
 * this object is the control object for the To Selection Box.
 * It sets up initial data and handles any expected events for the box.
 */
var ToDropControl = Class.create();
ToDropControl.prototype = {
  initialize : function (fromBoxId, toBoxId, dataContainer, departCalendar, showCountries, toHeader) {
    this.fromBox = $(fromBoxId);
    this.toBox = $(toBoxId);
    this.departCalendar = departCalendar;
    this.dataContainer = dataContainer;
	this.showCountries = showCountries;
	this.toHeader = toHeader;
	this.toAirports = this.dataContainer.getToAirports();
	this.popularToAirports = this.dataContainer.popularToAirports;
	this.airports = this.dataContainer.getAirports();
	this.toBox.onchange = this.toBoxChange.bindAsEventListener(this);
	this.inputType = 'selectBox';
	this.populateToBox();

  },
  toBoxChange : function (evt) {
  	
  	
  },
  populateToBox : function (initialValue) {
	this.toBox.options.length=0;
	// place select from city at top
	var index = 0;
	var selectedIndex = 0;
	this.toBox.options[index]=new Option(this.toHeader,'');
	index++;
	// put in seperator
	this.toBox.options[index]=new Option('-----------------','separator');
	index++;
	
	// now put popular airports
	if (this.popularToAirports != null) {
		for (var i=0;i<this.popularToAirports.length;++i, index++){
			var currentAirport = getObjectFromArrayByCode(this.popularToAirports[i], this.airports);
			this.toBox.options[index]=new Option(currentAirport.airportName,currentAirport.code);
			if (this.defaultValue == currentAirport.code) {
				selectedIndex = index;
			}
		}
		// put in seperator
		this.toBox.options[index]=new Option('-----------------','separator');
		index++;
	}

	var lastDropDownCountry = "";
	// now put all airports
 	for (var i=0;i<this.toAirports.length;i++){
 		var currentAirport = getObjectFromArrayByCode(this.toAirports[i], this.airports);
 		if (this.showCountries && currentAirport.country.countryName != lastDropDownCountry) {
			this.toBox.options[index]=new Option(currentAirport.country.countryName,"");
			this.toBox.options[index].className = "cityDropDownCountry";
			index++;
			lastDropDownCountry = currentAirport.country.countryName;
 		}
 		if (this.fromBox.value != '') {
			var flightDataItem = FlightDataCache.getFlightDataItem(this.dataContainer, this.fromBox.value, currentAirport.code);
			// check that flight combo is valid, if yes add to select
			if (flightDataItem.isValidFlight()) {
				this.toBox.options[index]=new Option(currentAirport.airportName,currentAirport.code);
				if (currentAirport.code == initialValue) {
					selectedIndex = index;
				}
				index++;
			}
 		} else {
			this.toBox.options[index]=new Option(currentAirport.airportName,currentAirport.code);
			if (currentAirport.code == initialValue) {
				selectedIndex = index;
			}
			index++;
 		}
 	}
 	
 	this.toBox.selectedIndex = selectedIndex;
 	
  }
}

/*
 * this object is the control object for the To text Box.
 * It sets up initial data and handles any expected events for the box.
 * 
 * Most importantly it handles the keyup event which will populate the available
 * to airports.
 */
var ToBoxControl = Class.create();
ToBoxControl.prototype = {
  initialize : function (fromBoxId, toBoxId, toBoxListDivId, toBoxPlusSign, toSelectionFieldId, thisForm, fieldsToHide, dataContainer,toBoxCloseButtonId,isHomePage) {
    this.fromBox = $(fromBoxId);
    this.toBox = $(toBoxId);
    this.toBoxListDiv = $(toBoxListDivId);
    this.toSelectionField = $(toSelectionFieldId);
    this.toBoxPlusSign = $(toBoxPlusSign);
	this.thisForm = $(thisForm);
	this.currentSelection = "";
	this.fieldsToHide = fieldsToHide;
	this.dataContainer = dataContainer;
	this.isHomePage = isHomePage;
	this.toBoxCloseButton = $(toBoxCloseButtonId);
	this.toBox.onkeydown = this.toBoxKeyDown.bindAsEventListener(this);
	this.toBox.onkeyup = this.toBoxKeyUp.bindAsEventListener(this);
	this.toBox.onfocus = this.toBoxFocus.bindAsEventListener(this);
	this.toBoxPlusSign.onclick = this.toBoxPlusSignClick.bindAsEventListener(this);
	this.popularFromAirports = dataContainer.getPopularFromAirports();
	this.boxOpen = false;
	this.inputType = 'textBox';
  },
  toBoxKeyDown : function (evt) {
	if(evt != null && (evt.keyCode==40)){  	
		var predictiveTable = $(this.toSelectionField.id+"predictiveLookUp");
		if(predictiveTable != null) {
			var anchorTags = predictiveTable.getElementsByTagName("a");
			if (this.currentSelection == "") {
				var firstItem = anchorTags[0];
				this.currentSelection = firstItem;
				changeBkgrnd(firstItem);
			} else {
				for (var i=0; i < anchorTags.length; i++) {
					if (Element.hasClassName(anchorTags[i], "selected")) {
						changeBkgrnd_Blur(anchorTags[i]);
						// if not the last item
						if (i < (anchorTags.length - 1)) {
							nextItem = anchorTags[i+1];
						// ie we are on the last item, go to first
						} else {
							nextItem = anchorTags[0];
						}
						this.currentSelection = nextItem;
						changeBkgrnd(nextItem);
						i = anchorTags.length;
					}
				}
			}
		}
		fixScrollPosition(this.toBoxListDiv, this.currentSelection);
		return false;
	} else if(evt != null && evt.keyCode==38) {  
		var predictiveTable = $(this.toSelectionField.id+"predictiveLookUp");
		if(predictiveTable != null) {
			var anchorTags = predictiveTable.getElementsByTagName("a");
			if (this.currentSelection != "") {
				for (var i=0; i < anchorTags.length; i++) {
					if (Element.hasClassName(anchorTags[i], "selected")) {
						changeBkgrnd_Blur(anchorTags[i]);
						// if not the last item
						if (i > 0) {
							nextItem = anchorTags[i-1];
						// on the first item, go to the last
						} else {
							nextItem = anchorTags[anchorTags.length - 1];
						}
						this.currentSelection = nextItem;
						changeBkgrnd(nextItem);
						i = anchorTags.length;
					}
				}
		// select last item
		} else {
			var lastItem = anchorTags[anchorTags.length - 1];
			this.currentSelection = lastItem;
			changeBkgrnd(lastItem);
			}
		}
		fixScrollPosition(this.toBoxListDiv, this.currentSelection);
		return false;
	} else if(evt != null && evt.keyCode==13) {
		if (this.currentSelection != "") {
			this.currentSelection.onclick();
		} else {
			if (this.toBoxListDiv.getElementsByTagName("a").length==1) {
				this.toBoxListDiv.getElementsByTagName("a")[0].onclick();
			}
		}
	}
  },
  toBoxKeyUp : function (evt) {
	if(evt == null || evt.keyCode==40 || evt.keyCode==38 || evt.keyCode==13 || evt.keyCode==9 || evt.keyCode==37 || evt.keyCode==39 ) {  
	} else {
		this.currentSelection = "";
		this.populateToMatchingAirports(evt);
	}
  },
  toBoxFocus : function (evt) {
  	this.toBox.select();
  	
  },
  toBoxPlusSignClick : function (evt) {
  	this.populateToAllAirports(evt);
  	this.toBox.focus();
	var predictiveTable = $(this.toSelectionField.id+"predictiveLookUp");
	var anchorTags = predictiveTable.getElementsByTagName("a");
	for (var i=0; i < anchorTags.length; i++) {
		if (("to" + this.toSelectionField.value) == anchorTags[i].id) {
			this.currentSelection = anchorTags[i];
			changeBkgrnd(anchorTags[i]);
			fixScrollPosition(this.toBoxListDiv,this.currentSelection);
		}
	}
  },
  populateToAllAirports : function (evt) {
	var toAirports = getAirportsFromAirportCodes(this.dataContainer.getToAirports(), this.dataContainer.getAirports());
	var validAirports = getValidToAirports(this.fromBox.value, toAirports, this.dataContainer);
  	this.populateToOptions(evt, validAirports, false);
  	
  },
  populateToMatchingAirports : function (evt) {
	var matchingAirports = getValidToAirportsThatMatchString(this.fromBox.value, this.toBox.value, this.dataContainer);
	this.populateToOptions(evt, matchingAirports, true);
  },
  populateToOptions : function (evt, airportsToRender, highlightMatch) {
 	var divString = '';
	this.setBoxOpen(true);
	if (airportsToRender.length == 0) {
		
		$j('.predictiveTextBox').parent().hide();
		$j(this.toBoxListDiv).attr('class','predictiveTextBox toCityBoxNoMatches');
		$j(this.toBoxListDiv).parent().show();
		
		this.toBoxListDiv.innerHTML=this.dataContainer.noMatchingCitiesText;
		this.toBoxCloseButton.onclick = this.closeToBoxListDiv.bindAsEventListener(this);
	} else {
		var toSelections = new Array();
		var optionListStrC1="";
		var optionListStrC2="";
		var singleColumnLength=5;
		var recordCount=0;
		singleColumnLength=(singleColumnLength<airportsToRender.length/2)?(airportsToRender.length/2):singleColumnLength;
		for (var x=0;x < airportsToRender.length; x++) {
			var currentAirport = airportsToRender[x];
			if (recordCount < singleColumnLength) {
				optionListStrC1=optionListStrC1+"<li>"+getAirportAsHTMLString(currentAirport, this.toBox.value, highlightMatch) + "</li>";
			} else {
				optionListStrC2=optionListStrC2+"<li>"+getAirportAsHTMLString(currentAirport, this.toBox.value, highlightMatch) + "</li>";
			}
			recordCount++;
		}
		optionList="<div id=\""+this.toSelectionField.id+"predictiveLookUp\" class=\"clearit\"><ul class=\"left\">"+optionListStrC1+"</ul>";
		
		if (optionListStrC2 != "")
		{
			optionList=optionList+"<ul class=\"left\">"+optionListStrC2+"</ul>";
		}

		optionList=optionList + "</div>";

		if(recordCount < "6")
		{
			$j('.predictiveTextBox').parent().hide();
			$j(this.toBoxListDiv).attr('class','predictiveTextBox toCityBoxSingleColumn');
			$j(this.toBoxListDiv).parent().show();
		}
		else if(recordCount > "5")
		{
			$j('.predictiveTextBox').parent().hide();
			$j(this.toBoxListDiv).attr('class','predictiveTextBox toCityBoxDoubleColumns');
			$j(this.toBoxListDiv).parent().show();
		}
		else
		{
		}

		this.toBoxListDiv.innerHTML = optionList;
		this.toBoxCloseButton.onclick = this.closeToBoxListDiv.bindAsEventListener(this);
				
		for (var x=0;x < airportsToRender.length; x++) {
			var currentAirport = airportsToRender[x];
			new ToSelection(currentAirport, this.toBox, this.toSelectionField, this.toBoxListDiv, this);
		}
		if (airportsToRender.length > 0) {
			document.onclick = this.closeToBoxListDiv.bindAsEventListener(this);
		}
	}

  },
  closeToBoxListDiv : function (evt) {
	  if (evt.target) targ = evt.target
		else if (evt.srcElement) targ = evt.srcElement
		if(targ.id != this.toBoxPlusSign.id){
			if (this.boxOpen)
			{
				
				$j('.predictiveTextBox').parent().hide();
				
				this.hideShowFields(false);
				if (this.toSelectionField.value == '')
				{
					this.toBox.value = '';
				}
				else
				{
					var previousAirport = getObjectFromArrayByCode(this.toSelectionField.value, this.dataContainer.getAirports());
					this.toBox.value = previousAirport.toStringNameOnly();
				}
				this.setBoxOpen(false);
			}
	}
  },
  setBoxOpen : function (boxOpen) {
  	this.boxOpen = boxOpen;
	this.hideShowFields(boxOpen);
	this.hideShowCloseButton(boxOpen);
	if (!boxOpen) {
		this.currentSelection = "";
	}
  },
  hideShowFields : function (hide) {
    for (var i=0; i < this.fieldsToHide.length; i++) {
		if (hide) {
			if($j.browser.version.substr(0,3) == '6.0' && $j.browser.msie) $j('#'+this.fieldsToHide[i]).css('visibility','hidden');
		} else {
			if($j.browser.version.substr(0,3) == '6.0' && $j.browser.msie) $j('#'+this.fieldsToHide[i]).css('visibility','visible');
		}
	}
  },
  hideShowCloseButton : function (hide) {
	if (hide) {
		$j(this.toBoxCloseButton).parent().show();
	} else {
		$j(this.toBoxCloseButton).parent().hide();
	}
  }
}

function fixScrollPosition(currentDiv, currentItem) {
	if(currentItem.offsetTop > (currentDiv.offsetHeight -20)){
		currentDiv.scrollTop = currentItem.offsetTop;
	
	}
	if(currentItem.offsetTop<currentDiv.scrollTop)
	{
		currentDiv.scrollTop = 0; 
	}
}
/*    

 * this object is the control object for when a 'from' or 'to' is selected and we are
 * required to do something.
 */
var FromToHandler = Class.create();
FromToHandler.prototype = {
  initialize : function (fromBoxControl, toBoxControl, classBoxId, intDomConvertFunction, dataContainer, departCalendar) {
	this.fromBoxControl = fromBoxControl;
	this.toBoxControl = toBoxControl;
	if (this.toBoxControl.inputType == 'textBox') {
		this.toSelectionField = this.toBoxControl.toSelectionField;
	} else {
		this.toSelectionField = this.toBoxControl.toBox;
	}
    this.toBox = this.toBoxControl.toBox;
	this.classBox = $(classBoxId);
	this.departCalendar = departCalendar;
	this.intDomConvertFunction = intDomConvertFunction;
	this.fromBoxControl.fromBox.onchange = this.fromToChange.bindAsEventListener(this);
	this.toSelectionField.onchange = this.fromToChange.bindAsEventListener(this);
	this.dataContainer = dataContainer;
  },
  fromToChange: function (evt) {
	// now if the box is open, reload the contents
	if (this.toBoxControl.inputType == 'textBox' && this.toBoxControl.boxOpen) {
		this.toBoxControl.populateToMatchingAirports(evt);
	} else {
		if (this.toBoxControl.inputType == 'selectBox') {
			this.toBoxControl.populateToBox(this.toSelectionField.value);
		}
		if (this.fromBoxControl.fromBox.value != '' && this.toSelectionField.value != '') {
			var flightDataItem = FlightDataCache.getFlightDataItem(this.dataContainer, this.fromBoxControl.fromBox.value, this.toSelectionField.value);
			// check that flight combo is still valid, if not clear the to box
			if (!flightDataItem.isValidFlight()) {
				if (this.toBoxControl.inputType == 'textBox') {
					this.toSelectionField.value = '';
					this.toBox.value = '';
				} else {
					this.toSelectionField.selectedIndex = 0;
				}
				this.intDomConvertFunction();
			} else {
				if (flightDataItem.isInternational()) {
					this.populateClasses(flightDataItem);
				}
				this.intDomConvertFunction(flightDataItem);
			}
		} else { // To get rid of 'Premium Economy' from the drop down, if its already present
			this.populateClassesForRoute();
			// call this method to setup default look (ie when we dont have the citypair)
			this.intDomConvertFunction();
		}
	}
  },
  populateClasses : function (flightDataItem) {
	if (this.classBox != null) {
	  	if (flightDataItem != null){
			var classes = flightDataItem.getClasses(this.departCalendar);
		}else{
			var classes = getClassesForFlight(null, this.dataContainer, this.departCalendar, this.fromAirport, this.toAirport);
		}
		var indexSelected = this.classBox.selectedIndex;
		this.classBox.options.length=0;
		for (var i=0;i<classes.length;i++){
			var currentClass = classes[i];
			this.classBox.options[i]=new Option(currentClass.className,currentClass.value);
		}
		if(indexSelected != -1){
			this.classBox.selectedIndex = indexSelected;
		}
  	}
  },
  populateClassesForRoute : function () {
	if (this.fromBoxControl.fromBox.value != "" && this.toSelectionField.value != ""){
		var flightDataItem = FlightDataCache.getFlightDataItem(this.dataContainer, this.fromBoxControl.fromBox.value, this.toSelectionField.value, this.toBoxControl.departCalendar);
		this.populateClasses(flightDataItem)
	}else{
		this.populateClasses();
	}
  },
  setInitialValues : function (from, to) {
	// setup frombox
	var valueMatched = false;
	for(var i=0;i<this.fromBoxControl.fromBox.options.length;++i){
		if(this.fromBoxControl.fromBox.options[i].value==from){
			this.fromBoxControl.fromBox.selectedIndex=i;
			valueMatched = true;
			break;
		}
	}
	if(valueMatched == false && from==''){
		// presumes element 0 is always the default eg "Select a City..."
		this.fromBoxControl.fromBox.selectedIndex=0;
	}

	if (this.toBoxControl.inputType == 'textBox' && to != null && to != '') {
		var toAirport = getObjectFromArrayByCode(to, this.dataContainer.getAirports());
		if (toAirport != null) {
			this.toBox.value = toAirport.airportName;
			this.toSelectionField.value = toAirport.code;
		}
	}
	
	// run the onchange method to ensure all is setup ok
	this.fromToChange();

	// setup tobox
	if (this.toBoxControl.inputType == 'textBox') {
//		var toAirport = getObjectFromArrayByCode(to, this.dataContainer.getAirports());
//		this.toBox.value = toAirport.airportName;
//		this.toSelectionField.value = toAirport.code;
	} else {
		var valueMatched = false;
		for(var i=0;i<this.toBoxControl.toBox.options.length;++i){
			if(this.toBoxControl.toBox.options[i].value==to){
				this.toBoxControl.toBox.selectedIndex=i;
				valueMatched = true;
				break;
			}
		}
		if(valueMatched == false && from==''){
			// presumes element 0 is always the default eg "Select a City..."
			this.toBoxControl.toBox.selectedIndex=0;
		}
		
	}
  }
}

/**
 * this is the control object for each anchor link in the 'to' selection list.
 */
var ToSelection = Class.create();
ToSelection.prototype = {
  initialize : function (airport, toBox, toSelectionField, toBoxListDiv, toBoxControl) {
    this.airport = airport;
    this.toBox = toBox;
    this.toSelectionField = toSelectionField;
    this.toBoxListDiv = toBoxListDiv;
    this.toBoxControl = toBoxControl;
    this.airportHref = $("to" + airport.code);
	this.airportHref.onclick = this.airportHrefClick.bindAsEventListener(this);
  },
  airportHrefClick : function (evt) {
	this.toBoxControl.setBoxOpen(false);
  	this.toSelectionField.value = this.airport.code;
  	this.toBox.value = this.airport.toStringNameOnly();
  	
  	this.toBoxListDiv.innerHTML = '';
	
	$j('.predictiveTextBox').parent().hide();
	
	if ($j('div').find('.majorCitySelected').length > 0)
	{
		var majorCitySelected = $j('div').find('.majorCitySelected').attr('class').indexOf('majorCitySelected')
		if (majorCitySelected > 0) 
		{
			var data = this.toBoxControl.popularFromAirports;
			arrivalCheckforMajorCities(data);
		}
		else
		{
			this.toSelectionField.onchange();
		}
	}
	else
	{
		this.toSelectionField.onchange();
	}
  }
}

/**
 * gets the matching airports and validates that the airport is valid for the 
 * from/to combination it will form.
 */
function getValidToAirportsThatMatchString(fromAirport, stringToMatch, dataContainer) {
	
	var airportCodeList = dataContainer.getToAirports();
	var airports = dataContainer.getAirports();
	var matchingAirports = getAirportsThatMatchString(stringToMatch, airportCodeList, airports);
	// ensure all matching airports are valid for this from/to combination
	var validAirports = getValidToAirports(fromAirport, matchingAirports, dataContainer)
	return validAirports;
	
}

/**
 * takes a list of airports and returms only those that are valid for the from/to combination
 */
function getValidToAirports(fromAirport, airports, dataContainer) {

	// ensure all matching airports are valid for this from/to combination
	var validAirports = new Array();
    for (var i=0; i<airports.length;i++) {
    	var currentAirport = airports[i];
		// check if airport pair valid
			var flightItem = FlightDataCache.getFlightDataItem(dataContainer, fromAirport, currentAirport.code);
			if (flightItem.isValidFlight() || fromAirport.length == "0") {
				validAirports.push(currentAirport);
			}
    }
	return validAirports;
}

/**
 * takes a list of airport codes and gets the airport objects for them out of the provided airport list
 *
 */
function getAirportsFromAirportCodes(airportCodes, allAirports) {
	var airports = new Array();
	for (var i=0; i<airportCodes.length;i++) {
		var currentAirport = getObjectFromArrayByCode(airportCodes[i], allAirports);
		airports.push(currentAirport);
	}
	return airports;
}

/**
 * search the airport list to find airports that match the provided string either by
 * full name or airport code.
*/
function getAirportsThatMatchString(stringToMatch, airportCodeList, airports) {
	
	var matchingAirports = new Array();

	if (stringToMatch != '' && stringToMatch != null) {

		if(stringToMatch.length == 1){
			var pattern = new RegExp("^" +stringToMatch , "i");
		} else {
				pattern = new RegExp("" +stringToMatch, "i");
		}

		for (var i=0; i<airportCodeList.length;i++) {
			var currentAirport = getObjectFromArrayByCode(airportCodeList[i], airports);
			// check if code matches
			if (pattern.test(currentAirport.code)) {
				matchingAirports.push(currentAirport);
			} else if (pattern.test(currentAirport.airportName)) {
				matchingAirports.push(currentAirport);
			}
		}
	}
		
	return matchingAirports;
	
}

/**
 * returns the index of the airport code within an array
 */
function indexOfAirportByCode(code,airportArray) {
    for (var i=0;i<airportArray.length;i++) {
       if (code == airportArray[i]) {
           return i;
       }
    }

    return -1;
}

/**
 * returns the full object from an array when searching by code.
 * Assumes that the object will have a 'code' property.
 */
function getObjectFromArrayByCode(code, ourArray)  {
	for (var i=0;i<ourArray.length;i++) {
	   if (code == ourArray[i].code) {
		   return ourArray[i];
	   }
	}

    return null;
}

function getMatrixItem(fromIndex, toIndex, matrix, numberOfFroms, numberOfTos) {
	var itemIndex = (fromIndex * numberOfTos) + toIndex;
	var item32 = matrix.charAt(itemIndex);
	var matrixItemDecimal = parseInt(item32, 32);
	var matrixItemBoolean = matrixItemDecimal.toString(2);
	
	return matrixItemBoolean.padLeft(5,'0');
}

/*
 * checks if a matrix item is representing true or false
 */
function determineBooleanValueFromMatrixItem(matrixItem, index) {
	if (matrixItem.charAt(index) == '1') {
		return true;
	} 
	return false;	
}

/*
 * checks the matrix item to see what classes are valid for a particular from/to
 * combination
 */
function getClassesForFlight(matrixItem, dataContainer, departCalendar, fromAirport, toAirport) {
	
	var classesForFlight = new Array();

	var travelClassObjectY = getObjectFromArrayByCode("Y", dataContainer.getClasses());
	var travelClassObjectP = getObjectFromArrayByCode("P", dataContainer.getClasses());
	var travelClassObjectJ = getObjectFromArrayByCode("J", dataContainer.getClasses());
	var travelClassObjectF = getObjectFromArrayByCode("F", dataContainer.getClasses());

	if (matrixItem == null){
		if (travelClassObjectY != null){
			classesForFlight.push(travelClassObjectY);
		}
		if (travelClassObjectJ != null){
			classesForFlight.push(travelClassObjectJ);
		}
		if (travelClassObjectF != null){
			classesForFlight.push(travelClassObjectF);
		}
	}else{
		if (determineBooleanValueFromMatrixItem(matrixItem, dataContainer.getEconomyClassIndex())) {
			if (travelClassObjectY != null){
				classesForFlight.push(travelClassObjectY);	
			}
		}
		if (determineBooleanValueFromMatrixItem(matrixItem, dataContainer.getPremiumClassIndex())) {
			if (travelClassObjectP != null){
				classesForFlight.push(travelClassObjectP);	
			}
		}
		if (determineBooleanValueFromMatrixItem(matrixItem, dataContainer.getBusinessClassIndex())) {
			if (travelClassObjectJ != null){
				classesForFlight.push(travelClassObjectJ);	
			}
		}
		if (determineBooleanValueFromMatrixItem(matrixItem, dataContainer.getFirstClassIndex())) {
			if (travelClassObjectF != null){
				classesForFlight.push(travelClassObjectF);	
			}
		}
	}
	
	return classesForFlight;
}


// Create the internal pad prototype
String.prototype._pad = function(width,padChar,side) {
	var str = [side ? "" : this, side ? this : ""];
	while (str[side].length < (width ? width : 0)
		&& (str[side] = str[1] +(padChar ? padChar : " ")+str[0] ));
	return str[side];
}

// Create pad functions for general use
// "width" is the total width to pad to,
// "padChar" is the optional pad character -- default " "
String.prototype.padLeft = function(width,padChar) {
	return this._pad(width,padChar,0) };
String.prototype.padRight = function(width,padChar) {
	return this._pad(width,padChar,1) };
Number.prototype.padLeft = function(width,padChar) {
	return (""+this).padLeft(width,padChar) };
Number.prototype.padRight = function(width,padChar) {
	return (""+this).padRight(width,padChar) };

  
function arrivalCheckforMajorCities(data)
{
	departurePort =	$j($j('.predictiveTextField')[0]).parent().find('input[type=hidden]').val();
	arrivalPort = $j($j('.predictiveTextField')[1]).parent().find('input[type=hidden]').val();
																						   
	var majorAirports = data;
	var isArrivalMajor = false;
	var isDepartureMajor = false;
	
	for (i = 0; i < majorAirports.length; i++)
	{
		if ( majorAirports[i]  == departurePort)
		{
			isDepartureMajor  = true;
		}
		
		if (majorAirports[i] == arrivalPort)
		{
			isArrivalMajor = true;
		}
	}
	
	var instance = document.getElementById('instanceLabel');
	
	if (instance)
	{
		instance=instance.value
	}
	else
	{
		instance="";
	}
	
	instance = instance + 'depHour';
	
	if (isDepartureMajor && isArrivalMajor)
	{
		$j('.majorCitySelected').show();
	}
	else
	{
		$j('.majorCitySelected').hide();
	}
	
}

function setGlobalCityInList(){
	if((document.cookie.indexOf("usercontext="))!=-1){
		//	parse cookie
		var userContextCookie=getCookieValue("usercontext");	
		var depAirportInd = userContextCookie.indexOf("dep#");
		var depAirportVal = userContextCookie.substring(depAirportInd+4,depAirportInd+7);

		var cityMatrixes = new Array();
		cityMatrixes[0] = [["ADL","ADL"],["BNE","BNE"],["CNS","CNS"],["DRW","DRW"],["OOL","OOL"],["MEL","MEL"],["PER","PER"],["SYD","SYD"],["ABX","SYD"],["ASP","DRW"],["ARM","SYD"],["AYQ","DRW"],["BNK","BNE"],["BCI","BNE"],["BKQ","BNE"],["BLT","BNE"],["BMP","CNS"],["BME","PER"],["BDB","BNE"],["BWT","MEL"],["CBR","CBR"],["CTL","BNE"],["CFS","SYD"],["DPO","MEL"],["DBO","SYD"],["EMD","BNE"],["GLT","BNE"],["GOV","CNS"],["HTI","CNS"],["HIS","CNS"],["HBA","HBA"],["HID","CNS"],["KGC","ADL"],["KGI","PER"],["KTA","PER"],["KNX","PER"],["LST","LST"],["LRE","BNE"],["LDH","SYD"],["MKY","BNE"],["MQL","MEL"],["MRZ","SYD"],["MHU","MEL"],["ISA","BNE"],["NAA","SYD"],["NTL","SYD"],["ZNE","PER"],["PBO","PER"],["PHE","PER"],["PLO","ADL"],["PQQ","SYD"],["PPP","CNS"],["ROK","BNE"],["RMA","BNE"],["MCY","BNE"],["TMW","SYD"],["TPR","PER"],["TSV","BNE"],["WGA","SYD"],["WEI","CNS"],["WOL","MEL"]];
		cityMatrixes[1] = [["AKL","AKL"],["CHC","CHC"],["ZQN","CHC"],["ROT","AKL"],["WLG","WLG"]];
		for(var i=0; i<cityMatrixes.length; i++){
			var cities = cityMatrixes[i];
			for(var j=0; j<cities.length; j++){
				//loop thro, get index of domestic city
				if(cities[j][0] == depAirportVal){
					for(var k=0;k<document.globaldeals.globalDealsList.options.length;++k){
						if(document.globaldeals.globalDealsList.options[k].value==cities[j][1]){
							document.globaldeals.globalDealsList.selectedIndex=k;
							return;
						}
					}
				}
			}
		}
	}
}