/* This files assume the following JavaScript files have been included:
 * - date.js
 * - popup-calendar.js
 * - transTasman.js
 */
function changeWizardPage(currentPageId,newPageId,invoker)
{
	if (invoker.nodeType == "1") invoker.blur();
	currentPageElement = document.getElementById(currentPageId);
	newPageElement     = document.getElementById(newPageId);
	currentPageElement.style.display = "none";
	newPageElement.style.display = "";
}

//selectTo function

//	note: do not set the 'to city' if we are previewing the 
//	bulletin boards - ( from appadmin )

function selectTo(city){
	if(bulletinBoardPreview == false){
		for(var i=0;i<document.itinerary.to.options.length;++i){
			if(document.itinerary.to.options[i].value==city){
				document.itinerary.to.selectedIndex=i;
				isShowSortBy('divSortBy');
				return;
				}
		}
	}
	return;
}


function gotoGlobalDealsPage(element){
	var sel = element;
	departureAirport = sel.value;
	if(departureAirport!=""){
		document.dealsFormBean.submit();
	}else{
		alert("Please select a Global Deals departure location.");
	}
}

var prevOpen=new Array(); // global array of open    IDs 
var currOpen=new Array(); // global array of current IDs 
var navlink=''; // id of the previously opened navlink


// opens and closes prices selection rows in results table
function foldupRow(destinationId,drLength,cityCode,prefix,invoker){
	arrayStep = 0;

	// -- populating destinations selection box
	selectTo(cityCode); 

	currOpen = new Array(); // resetting untouchable array 

	// -- opening necessary rows
	counter = 1;
	while(counter < drLength) {
		rowId = prefix + '-' + destinationId + '-' + counter;
		currOpen[arrayStep] = rowId;
		arrayStep++;
		rowElement=document.getElementById(rowId);			
		if(rowElement.style.display=='none'){
			rowElement.style.display='';
			invoker.className="globalDealsDestinationOpen";
			invoker.style.visibility='visible';
		}else{
			rowElement.style.display='none';
			invoker.className="globalDealsDestinationExpand";
		}		
		counter++;
	} // end while

	// -- closing open rows
	if (prevOpen[0] != null) // if there is something in previously open IDs array
	{
		for (var m=0;m<prevOpen.length;m++)	
		{
			if (prevOpen[m] != currOpen[m]) 
			{
				myElement = document.getElementById(prevOpen[m]);
				myElement.style.display='none';
			}
		}
	}
	prevOpen = currOpen; // previously open rows array takes IDs of the current one

	// -- closing previously opened arrows
	if (navlink != '' && navlink != invoker.id)
	{
		mylink = document.getElementById(navlink);
		mylink.className="globalDealsDestinationExpand";
	}
	navlink = invoker.id;

	// magic command which keeps the window at the point where you scrolled to
	//document.scrollTo(0,100);
}
/* Deal object - UPDATED v.2.2 */
function Deal(fareValue, currencyCode, currencySymbol, fromDateAsString,toDateAsString,saleName,saleType,fareFamilyCode,saleEndDate){
	this.fareValue=fareValue;
	this.currencyCode=currencyCode;
	this.currencySymbol=currencySymbol;
	this.fromDate=this.parseFromDate(fromDateAsString);
	this.toDate=this.parseToDate(toDateAsString);
	this.saleName=saleName;
	this.saleType=saleType;
	this.fareFamilyCode=fareFamilyCode;
	this.saleEndDate=saleEndDate;
}
Deal.prototype.parseDate=function(dateAsString){ // format is dd/mm/yyyy
	var portions=dateAsString.split('/');
	return new Date(portions[2],(parseInt(portions[1],10)-1),parseInt(portions[0],10));
}
Deal.prototype.parseFromDate=function(dateAsString){
	return this.parseDate(dateAsString);
}
Deal.prototype.parseToDate=function(dateAsString){
	var date=this.parseDate(dateAsString);
	date.setHours(23);
	date.setMinutes(59);
	date.setSeconds(23);
	return date;
}

/* Destination object */
function Destination(cityCode,cityName){
	this.cityCode=cityCode;
	this.cityName=cityName;
	this.deals=new Array();
}
// removed many params here
Destination.prototype.addDeal=function(fareValue,currencyCode,currencySymbol,fromDateAsString,toDateAsString,saleName,saleType,fareFamilyCode,saleEndDate){
	this.deals[this.deals.length]=new Deal(fareValue,currencyCode,currencySymbol,fromDateAsString,toDateAsString,saleName,saleType,fareFamilyCode,saleEndDate);
}

function submitForm()
{
    globalDealsValidator.setSelectionDetailsCke();
    globalDealsValidator.validateAndSubmit(true);
}

function submitFormValidateOnly()
{
    globalDealsValidator.setSelectionDetailsCke();
    // only submit if all the validation was successfull
    if(globalDealsValidator.validateAndSubmit(false))
        document.itinerary.submit(); 
    return true;
}

/* GlobalDeals object */
function GlobalDeals(id,region,departureCityCode,departureCityName,destinations, destinationsR){
	this.id=id;
	this.region=region;
	this.departureCityCode=departureCityCode;
	this.departureCityName=departureCityName;
	this.destinations=destinations;
	this.destinationsR=destinationsR;
	this.tableId_cityNameSorted=this.id+'_cityNameSorted';
	this.tableId_cityNameReturn=this.id+'_cityNameReturn';
	this.tableId_fareValueSorted=this.id+'_fareValueSorted';
	this.tableId_fareValueSortedReturn=this.id+'_fareValueSortedReturn';
}

GlobalDeals.prototype.sortByDestinationNames=function(){
	this.destinations.sort(new Function('dest1','dest2','return (dest1.cityName<dest2.cityName?-1:(dest1.cityName>dest2.cityName?1:0));'));
}

// this is a special helper function
function helperComparatorByTravelDate(deal1,deal2){ 
	return deal1.fromDate.getTime() - deal2.fromDate.getTime();
}

// this function has been upgraded to compare by Fare Value and then additionally Travel Period
GlobalDeals.prototype.comparatorDestinationBlocksByCityNameThenFareValue=function(deal1,deal2){ 
	var x = deal1.fareValue;
    var y = deal2.fareValue;
	var res = x - y;
	return ((x < y) ? res : ((x > y) ? res : helperComparatorByTravelDate(deal1,deal2)));	
}

GlobalDeals.prototype.comparatorDestinationBlocksByLowestFareValue=function(dest1,dest2){ 
	var valueCompare=dest1.deals[0].fareValue-dest2.deals[0].fareValue;
	return (valueCompare==0?(dest1.cityName<dest2.cityName?-1:(dest1.cityName>dest2.cityName?1:0)):valueCompare);
}

GlobalDeals.prototype.sortDestinationsBlocksByCityNameThenFareValue=function(prefix){
	if (prefix=='oneway')
	{
		for (var i=0;i<destinations.length;++i){
			this.destinations[i].deals.sort(this.comparatorDestinationBlocksByCityNameThenFareValue);
		}
	} else {
		for (var i=0;i<destinationsR.length;++i){
			this.destinationsR[i].deals.sort(this.comparatorDestinationBlocksByCityNameThenFareValue);
		}
	}
}

GlobalDeals.prototype.sortDestinationsBlocksByLowestFareValue=function(prefix){
	this.sortDestinationsBlocksByCityNameThenFareValue(prefix);
	this.destinations.sort(this.comparatorDestinationBlocksByLowestFareValue);	
	if (prefix=='oneway')
	{
		//this.destinations[i].deals.sort(this.comparatorDestinationBlocksByCityNameThenFareValue);
		this.destinations.sort(this.comparatorDestinationBlocksByLowestFareValue);
	} else {
		//this.destinationsR[i].deals.sort(this.comparatorDestinationBlocksByCityNameThenFareValue);
		this.destinationsR.sort(this.comparatorDestinationBlocksByLowestFareValue);
	}
}

/**
 * This function uses functionality of /js/positioner.js
 * NB style.top is not supported by ie5 on Mac
 */
function updateRooPosition() {

	var isMac = (navigator.appVersion.indexOf("Mac") != -1);
	var isIE = (window.navigator.userAgent.toLowerCase().indexOf('msie') != -1);

	if (!(isMac && isIE)) {
		var redline = document.getElementById("specialsLine");
		var roo = document.getElementById("imageOnly");
		var offsetX = 650;
		var offsetY = 16;
		roo.style.top = findPosY(redline) - offsetY;
		roo.style.left = findPosX(redline) + offsetX;
	}
}

// Adding sale types to the DIVs "saleTypesContainer_oneway" and "saleTypesContainer_return"
function addSale(type) {
	var searchid = 'saleTypesContainer';
	var div=document.getElementById(searchid);
	if (div == null)
	{
		return true;
	}
	var html = div.innerHTML;
	var classStr = "sale" + type;
	if (html.indexOf(classStr)==-1){
		addHtml = '<a class="'+ classStr +'" href="javascript:void(null)" onClick="javascript:window.open(\'/deals/do/dyn/specials/spotsaledetail?spotSaleCode='+spotSaleCode[type-1] +'&dealBundleId='+dealBundleId+'\',\'NewWin\',\'width=640,height=490,status=yes,scrollbars=yes,resizable=yes\')">&nbsp;<img src="'+ spotSaleIcon[type-1] +'" border="0" hspace="5" vspace="0">&nbsp;'+ spotSaleText[type-1] +'</a>';
		div.innerHTML = addHtml + html;
	}
	
}

GlobalDeals.prototype.writeTable=function(id,display,prefix,sortedCol){

	var d=window.document;
	var region = this.region;

	var show_sale1 = 0;	
	var show_sale2 = 0;	
	var show_sale3 = 0;	
	var show_sale4 = 0;

	var currDestinations = new Array(); // empty array of destinations
	
	

	d.write('\n<table class="results" id="'+id+'" cellspacing="0" '+(display?'':'style="display:none;"')+'>');
	d.write('\n<colgroup><col class="first"><col class="second"><col class="third"><col class="fourth"><col class="fifth"></colgroup>');
	
	// -- header row, sortings, etc.
	d.write('\n\t<tr>');
	if (prefix.indexOf('oneway')>-1){
		if(this.destinations.length==1){
			d.write('\n\t\t<th><strong>'+this.departureCityName+'</strong> to </th>');
		}
		else{
			if(sortedCol==1){
				d.write('\n\t\t<th><a class="sortByOn" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_fareValueSorted+'\',\''+this.tableId_cityNameSorted+'\',this)" title="sort by city"><strong>'+this.departureCityName+' to</strong></a></th>');
			}
			else{
				d.write('\n\t\t<th><a class="sortByOff" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_fareValueSorted+'\',\''+this.tableId_cityNameSorted+'\',this)" title="sort by city">'+this.departureCityName+' to</a></th>');
			}
		}
	}
	else{
		if(this.destinationsR.length==1){
			d.write('\n\t\t<th><strong>'+this.departureCityName+'</strong> to </th>');
		}
		else{
			if(sortedCol==1){
				d.write('\n\t\t<th><a class="sortByOn" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_fareValueSortedReturn+'\',\''+this.tableId_cityNameReturn+'\',this)" title="sort by city"><strong>'+this.departureCityName+' to</strong></a></th>');
			}
			else{
				d.write('\n\t\t<th><a class="sortByOff" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_fareValueSortedReturn+'\',\''+this.tableId_cityNameReturn+'\',this)" title="sort by city">'+this.departureCityName+' to</a></th>');
			}
		}
	}
	// -- new column, which will contain prices
	d.write('\n\t\t<th colspan="2">');
	if (prefix.indexOf('oneway')>-1){
		if(this.destinations.length==1){
			d.write('One-way fare from </th>');
		}
		else{
			if(sortedCol==1){
				if(region=="au")d.write('<a class="sortByOff" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_cityNameSorted+'\',\''+this.tableId_fareValueSorted+'\',this)">One-way fare from</a></th>');
				else	d.write('<a class="sortByOff" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_cityNameSorted+'\',\''+this.tableId_fareValueSorted+'\',this)">One-way fare from</a></th>');
			}
			else{
				if(region=="au") d.write('<a class="sortByOn" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_cityNameSorted+'\',\''+this.tableId_fareValueSorted+'\',this)"><strong>One-way fare from</strong></a></th>');
				else	d.write('<a class="sortByOn" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_cityNameSorted+'\',\''+this.tableId_fareValueSorted+'\',this)"><strong>One-way fare</strong> from</a></th>');
			}
		}
	} else {
			if(this.destinationsR.length==1){
				d.write('Return fare from </th>');
			}
			else{
				if(sortedCol==1){
					d.write('<a class="sortByOff" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_cityNameReturn+'\',\''+this.tableId_fareValueSortedReturn+'\',this)">Return fare from</a></th>');
				}
				else{
					d.write('<a class="sortByOn" href="javascript://void" onclick="javascript:changeWizardPage(\''+this.tableId_cityNameReturn+'\',\''+this.tableId_fareValueSortedReturn+'\',this)"><strong>Return fare from</strong></a></th>');
				}
			}
	}
	//d.write(' Price from</th>');
	if (prefix.indexOf('oneway')>-1){
		d.write('\n\t\t<th class="travelBetween">Travel between</th>');	
	}
	else{
		d.write('\n\t\t<th class="travelBetween">Depart between</th>');
	}	
	d.write('\n\t\t<th class="conditions">Conditions</th>');
	d.write('\n\t</tr>');
	
	// prefix says which destinations array should be taken for processing 
	if (prefix.indexOf('oneway')>-1)
	{
		currDestinations = destinations; // one way deals
	} else {
		currDestinations = destinationsR; // return deals
	}
	
	// -- processing the rest of data rows
	var destination=null;
	var dealsLastIndex=null;
	var deals=null;
	var deal=null;

	for (var i=0;i<currDestinations.length;++i){
	
		destination=currDestinations[i];
		deals=destination.deals;
		dealsLastIndex=deals.length-1;
		
		for (var j=0;j<deals.length;++j){

			deal=deals[j];

			// -- row starts...
			d.write('<tr id="'+prefix+'-'+i+'-'+j+'"');
			if(i%2==0){d.write(' class="header"');}
			if(j>0){d.write(' style="display:none;"');}
			d.write('>'); 
		
		// -1- Navigation and destination name
			if (j>0){
				d.write('<td>&nbsp;</td>'); 
			} else {
				if (j==0 && deals.length > 1) {
					d.write('<td><a id="'+prefix+'A-'+i+'-'+j+'" class="globalDealsDestinationExpand" href="javascript://void" onClick="javascript:foldupRow('+i+','+deals.length+',\''+destination.cityCode+'\',\''+prefix+'\', this);">'+destination.cityName+'</a></td>');
				} else {
					d.write('<td><a class="globalDealsDestination" href="javascript://void" onClick="javascript:selectTo(\''+destination.cityCode+'\');">'+destination.cityName+'</a></td>');
				}
			} 

		// -2- PRICE
			d.write('<td ');
			if (deal.saleType=='1')
			{
				d.write('class="globalDealsPriceSale1" ');
				show_sale1 = 1; // show orange banner
			}
			if (deal.saleType=="2")
			{
				d.write('class="globalDealsPriceSale2" ');
				show_sale2 = 1; // show red banner
			}
			if (deal.saleType=="3")
			{
				d.write('class="globalDealsPriceSale3" ');
				show_sale3 = 1; // show sale_type_3 banner
			}
			if (deal.saleType=="4")
			{
				d.write('class="globalDealsPriceSale4" ');
				show_sale4 = 1; // show sale_type_4 banner
			}
			if (deal.saleType!='1' && deal.SaleType!='2' && deal.SaleType!='3' && deal.SaleType!='4')
			{
				d.write('class="globalDealsPrice" ');
			}
			// ** changed the below line to remove direct ref
			// ** d.write('>$'+deal.fareValue+(deal.direct==''?'&nbsp;':deal.direct)+'</td>');
			// change so currency code is never displayed
			// d.write('>'+(deal.currencySymbol==''?'':deal.currencySymbol)+deal.fareValue+(deal.currencySymbol==''?'&nbsp;'+deal.currencyCode:'')+'</td>');	
			d.write('>'+deal.currencySymbol+deal.fareValue+'</td>');
			
		// -3- SALE ICON
			
			d.write('<td class="saleIcon">');
				if (deal.saleType=='1') { 
					d.write('<img src="'+ spotSaleIcon[0] +'" alt="'+ spotSaleText[0] +'">');	
				} else { 
					if (deal.saleType=="2")	{ 
						d.write('<img src="'+ spotSaleIcon[1] +'" alt="'+ spotSaleText[1] +'">'); 
					} else { 
						if (deal.saleType=="3")	{ 
							d.write('<img src="'+ spotSaleIcon[2] +'" alt="'+ spotSaleText[2] +'">'); 
						} else { 
							if (deal.saleType=="4")	{ 
								d.write('<img src="'+ spotSaleIcon[3] +'" alt="'+ spotSaleText[3] +'">'); 
							} else { 
								d.write('&nbsp;'); 
							}
						}
					}
				}//d.write('<img src="/img/icons/icon_salesdollar.gif">');	
			d.write('</td>');
		
		
		// -5- TRAVEL BETWEEN
			var fromDateString =deal.toDate.padded(deal.fromDate.getDate()) +' ' + deal.fromDate.getShortMonth() + ' ' +  deal.fromDate.getFullYear().toString().substring(2,4);
			var toDateString =deal.toDate.padded(deal.toDate.getDate()) +' ' + deal.toDate.getShortMonth() + ' ' +  deal.toDate.getFullYear().toString().substring(2,4);
		 	
			if (fromDateString != toDateString) {
				d.write('<td class="travelDates">'+fromDateString+' - '+toDateString+'</td>');
			} else {
				d.write('<td class="travelDates">'+fromDateString+' only</td>');
			}

		// -6- CONDITIONS
			if(j>0&&deal.saleName==deals[j-1].saleName){
				d.write('<td>&nbsp;</td>');
			}else{
				
				//var filename = deal.saleName.replace(/\s/g, '_') + "_fc"; // filename without extension
				//filename = filename.replace(/&/g, 'and');


				/*
				d.write('<td class="globalDealsConditions"><a class="globalDealsConditions" href="javascript:void(null)" onClick="javascript:window.open(\'/regions/dyn/'+this.region+'/globaldeals/'+filename+'\',\'NewWin\',\'width=640,height=550,status=yes,scrollbars=yes,resizable=yes\')">'+deal.saleName+'</a></td>');
				d.write('<td class="globalDealsConditions"><a class="globalDealsConditions" href="javascript:void(null)" onClick="javascript:window.open(\'http://'+serverName+'/regions/dyn/amadeus/minirules/'+deal.fareFamilyCode+'?ffcText='+fareFamilyDisplayText+'&saleEndDate='+deal.saleEndDate+'\',\'NewWin\',\'width=640,height=550,status=yes,scrollbars=yes,resizable=yes\')">'+deal.saleName+'</a></td>');
				*/
        d.write('<td class="globalDealsConditions"><a class="globalDealsConditions" href="javascript:void(null)" onClick="javascript:window.open(\'http://'+serverName+'/regions/amadeus/minirules/'+deal.fareFamilyCode+'/index.html?ffcText='+fareFamilyDisplayText+'&saleEndDate='+deal.saleEndDate+'\',\'NewWin\',\'width=640,height=550,status=yes,scrollbars=yes,resizable=yes\')">'+deal.saleName+'</a></td>');
			}

			// -- row closes here...
			d.write('</tr>');
	
		} // end for deals
	
	} // end destinations

	d.write('</tbody></table>');

	// -- now checking if the flags for sale banners were changed
	if (show_sale1 == 1) { addSale(1); }
	if (show_sale2 == 1) { addSale(2); }
	if (show_sale3 == 1) { addSale(3); }
	if (show_sale4 == 1) { addSale(4); }
	
}

GlobalDeals.prototype.writeGlobalDealsTable=function(prefix){
	window.document.write('\n<div id="'+this.id+'">');
	this.sortDestinationsBlocksByCityNameThenFareValue(prefix);
	if (prefix=="oneway") { 
		this.writeTable(this.tableId_cityNameSorted,true,prefix+"City",1);
	} else {
		this.writeTable(this.tableId_cityNameReturn,true,prefix+"CityReturn",1);
	}
	this.sortDestinationsBlocksByLowestFareValue(prefix);
	if (prefix=="oneway") { 
		this.writeTable(this.tableId_fareValueSorted,false,prefix+"Fare",2);
	} else {
		this.writeTable(this.tableId_fareValueSortedReturn,false,prefix+"FareReturn",2);
	}
	window.document.write('\n</div>');
}


/* GlobalDealsValidator object */
function GlobalDealsValidator(earliestBookingDate,globalDeals,formId,departCalendar,returnCalendar,isFFLoggedIn){
	this.earliestBookingDate=earliestBookingDate;
	this.globalDeals=globalDeals;
	this.formId=formId;
	this.departCalendar=departCalendar;
	this.returnCalendar=returnCalendar;
	this.isFFLoggedIn=isFFLoggedIn;


	// Convenience members to keep file size down	
	this.region=globalDeals.region;
	this.depCityName=globalDeals.departureCityName;
	this.destCityName=null;
	this.destination=null;
	this.form=null;
	this.deal=null;
	this.depTs=null;	// millisecond timestamp
	this.depY=null;	// year
	this.depM=null;	// month
	this.depD=null;	// day
	this.depDoW=null;	// day of week
	this.retTs=null;	// ...likewise...
	this.retY=null;
	this.retM=null;
	this.retD=null;
	this.retDoW=null;
}


GlobalDealsValidator.prototype.isReturn=function(){
	for(var i=0;i<this.form.tripType.length;++i){
		if(this.form.tripType[i].value=='R'&&this.form.tripType[i].checked){
			return true;
		}
	}
	return false;
}
GlobalDealsValidator.prototype.isFlexibleDate=function(){
	
		if(this.form.flexibleDate.checked){
			return true;
		}
	return false;
}

// this function has been modified to support multiple destination arrays on the global deals page
GlobalDealsValidator.prototype.validateDestination=function(destinations){
	var destination=null;
	var deal=null;
	var foundDestination=false;
	for(var i=0;i<destinations.length;++i){ // Loop thru passed destinations array argument...
		destination=destinations[i];
		if(destination.cityCode==this.form.to.value){
			foundDestination=true;
			break;		
		}
	}
	if(foundDestination==false){
		alert("Please select an arrival location.");
		this.form.to.focus();
		return false;
	}
	return true;
}

GlobalDealsValidator.prototype.validateDates=function(){
	var today=new Date(this.earliestBookingDate.getFullYear(),this.earliestBookingDate.getMonth(),this.earliestBookingDate.getDate());
	if(departCalendar.displayDate.getTime()<today.getTime()){
		alert('Departure date cannot be before '+this.earliestBookingDate.format('DDDD D mmmm YYYY')+'.');
		this.form.dep_d.focus();
		return false;
	}
	if((returnCalendar.displayDate.getTime()<departCalendar.displayDate.getTime()) && this.isReturn()){
		alert('Returning date cannot be before departure date.');
		//this.form.ret_d.focus();
		return false;
	}
	return true;
}
GlobalDealsValidator.prototype.validatePax=function(){
	var numAdults=parseInt(this.form.adt.value);
	var numChild=parseInt(this.form.chd.value);
	var numInfant=parseInt(this.form.infant.value);
	var totalPax=numAdults+numChild+numInfant;
	var maxPax=9;
	if(totalPax>maxPax){
		alert("Only "+maxPax+" passengers can be booked at a time.");
		this.form.adt.focus();
		return false;
	}
	if(numInfant>numAdults){
		alert("Only 1 infant can be booked for every 1 adult.");
		this.form.infant.focus();
		return false;
	}
	return true;
}
GlobalDealsValidator.prototype.setFormProperties=function(){
	/*
	if('au'==this.region||'sp'==this.region){
		this.form.transTasman.value="false";
		this.form.intTransTasman.value="false";
		if(isTransTasmanTrip(this.region,this.globalDeals.departureCityCode,this.form.to.value)){
				this.form.intTransTasman.value="true";
				this.form.transTasman.value="true";
		}
	}
	*/
}

GlobalDealsValidator.prototype.isProduction=function(){
	return (window.location.host.indexOf('www.qantas')==0||window.location.host.indexOf('qantas')==0);
}



GlobalDealsValidator.prototype.validateAndSubmit=function(redirect){
	this.form=document.getElementById(this.formId);
	var temp=this.departCalendar.displayDate;
	this.depTs=temp.getTime();
	this.depY=temp.getFullYear();
	this.depM=temp.getMonth()+1;
	this.depD=temp.getDate();
	this.depDoW=temp.getDay();
	temp=this.returnCalendar.displayDate;
	this.retTs=temp.getTime();
	this.retY=temp.getFullYear();
	this.retM=temp.getMonth()+1;
	this.retD=temp.getDate();
	this.retDoW=temp.getDay();
	
	
	// The order these validate methods are called in is important.
	var dests=new Array().concat(this.globalDeals.destinations,this.globalDeals.destinationsR);
	if(!this.validateDestination(dests)){return false;}
	if(!this.validateDates()){return false;}
	if(!this.validatePax()){return false;}
	
	if(redirect){
		var queryString=this.createQueryString();
		if(!this.isProduction()){
			alert(queryString);
		}
		document.location=queryString;
	}else{
		this.setFormProperties();
	}
	return true;
}

GlobalDealsValidator.prototype.setSelectionDetailsCke=function()
{
    var flexible="Y";
    var ckeTrip="";
    var ckeSortby="";
    if('undefined'!=typeof(document.itinerary.flexibleDate)&&null!=document.itinerary.flexibleDate) {
        if(document.itinerary.flexibleDate.checked) {
            flexible="Y";
        }
		else
		{
			flexible="N";
		}
   	}

	if(this.region=='au' || this.region=='sp' || this.region=='as' || this.region=='eu' || this.region=='af' || this.region=='am')
	{
		ckeTrip = "|TRIP:"+(document.itinerary.tripType[0].checked?'R':'O');

		if("undefined"!= typeof(document.itinerary.arrangeBy)&&null!=document.itinerary.arrangeBy)
		{
			ckeSortby = "|SORTBY:"+document.itinerary.arrangeBy.value;
		}
	}
    var z=  "selectionsGlobal=DATES:"+this.departCalendar.serialize()+","+this.returnCalendar.serialize()+
            "|TO:"+document.itinerary.to.value+
            "|PSGRS:"+document.itinerary.adt.value+
            ","+document.itinerary.chd.value+
            ","+document.itinerary.infant.value+
            ckeTrip+ckeSortby+
            "|FLEX:"+flexible+
            "|REGION:"+this.region;
	//document.cookie=z+";path=/regions/dyn/"+this.region+"/globaldeals/";
    //document.cookie=z+";path=/travel/page/airline/bookings_flights_globaldeals/";
	document.cookie=z+";";
}
/* Methods added to allow storing of preferences */
GlobalDealsValidator.prototype.setSelections=function()
{
    if((document.cookie.indexOf("selectionsGlobal="))!=-1){
        var val=getCookieValue("selectionsGlobal");
        var datesInd=val.indexOf("DATES:");
        var toInd=val.indexOf("TO:");
        var psgrsInd=val.indexOf("PSGRS:");
        var flexInd=val.indexOf("FLEX:");
        var tripInd=val.indexOf("TRIP:");
        var sortInd=val.indexOf("SORTBY:");
        var dates=val.substring(datesInd+6,toInd-1);
        var z=dates.split(",");
        var depDate=z[0];
        var retDate=z[1];
        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 arrCity=val.substring(toInd+3,toInd+6);
        var flex=val.substring(flexInd+5,flexInd+6);
        var trip=val.substring(tripInd+5,tripInd+6);
        var sortby=val.substring(sortInd+7,sortInd+8);
        if("undefined"!= typeof(document.itinerary.flexibleDate)&&null!=document.itinerary.flexibleDate){
            if(flex=="Y") {
                document.itinerary.flexibleDate.checked=true;
                if (window.navigator.userAgent.toLowerCase().indexOf('msie 5.5') == -1)
                	document.getElementById("arrangeBy").selectedIndex = 1;
            }
        }
            
        if("undefined"!= typeof(document.itinerary.arrangeBy)&&null!=document.itinerary.arrangeBy && sortInd!=-1)
            document.itinerary.arrangeBy.value=(sortby=='|')?'':sortby;
        if('undefined'!= typeof(document.itinerary.tripType)&&null!=document.itinerary.tripType){
			if(trip=="R"){
				document.itinerary.tripType[0].checked=true;
				returnCalendar.setEnabled(true);
			}else{
				document.itinerary.tripType[1].checked=true;
				returnCalendar.setEnabled(false);
			}
		}
        this.set(document.itinerary.adt,adults)
        this.set(document.itinerary.chd,children)
        this.set(document.itinerary.infant,infants)
        departCalendar.deserialize(depDate);
        returnCalendar.deserialize(retDate);    
    }
}
GlobalDealsValidator.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;
			}
        }
    }
}
/**
 * Shows or hides the div containing the sort by drop down depending on the selected itinerary
 */
function isShowSortBy(divSortBy) {
	var isTransTasman = isTransTasmanTrip(this.region,this.globalDeals.departureCityCode,document.getElementById('selectDestinationCity').value);
	if (isTransTasman) {
        if(document.getElementById(divSortBy)!=null) 
        	document.getElementById(divSortBy).style.display="block";
    } else {
        if(document.getElementById(divSortBy)!=null) 
        	document.getElementById(divSortBy).style.display="none";
    }
}
