/*========================================================================================
  
$rcsfile: AvailabilitySearchInput.js $

$Revision: 1.4 $ $Date: 2006/09/07 17:25:26 $

Summary:	JavaScript file for the AvailabilitySearchInput control. Content moved from the C# code.

------------------------------------------------------------------------------------------
This file is part of the Navitaire NewSkies application.
Copyright (C) Navitaire.  All rights reserved.
========================================================================================*/

var ElementsState = new Array();
var ExistingMarkets = new Array();

function HideShowMarket(mktIx, disp)
{

	if(!document.getElementById || !document.createTextNode)
		return true;

	var labelDate = document.getElementById(applicationJavaScriptHtmlId + '_LabelMarketDate' + mktIx);
	var labelStation = document.getElementById(applicationJavaScriptHtmlId + '_LabelMarketStation' + mktIx);
	var orig = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketOrigin' + mktIx);
	var dest = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketDestination' + mktIx);
	var listOrigin = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + mktIx);
	var listDest = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + mktIx);
	//var day = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDay' + mktIx);
	//var month = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + mktIx);
	var dateRange = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDateRange' + mktIx);
	//var cal = document.getElementById(applicationJavaScriptHtmlId + '_HyperLinkMarketCalendar' + mktIx);
	var block = document.getElementById(applicationJavaScriptHtmlId + '_Market' + mktIx + 'Block');
	var labelOneWay = document.getElementById('labelOneWay');
  var divRoundTour = document.getElementById('roundTour');
	
	if (labelDate) labelDate.style.display=disp;
	if (labelStation) labelStation.style.display=disp;
	if (orig) orig.style.display=disp;
	if (dest) dest.style.display=disp;
	if (listOrigin) listOrigin.style.display=disp;
	if (listDest) listDest.style.display=disp;
//	if (day) day.style.display=disp;
//	if (month) month.style.display=disp;
	if (dateRange) dateRange.style.display=disp;
	//if (cal) cal.style.display=disp;
	if (block) block.style.display=disp;  
	if (labelOneWay) labelOneWay.style.display=disp;
  if (divRoundTour) divRoundTour.style.display=disp;
}

function marketChangeCheckChanged(checkBox, marketIndex)
{
	if (!checkBox.checked)
	{
		resetAirports();
	}
    DisableEnableMarket(marketIndex, !checkBox.checked);
}
function InitializeChange(eventArgs)
{
    DisableEnableMarket(1, true);
    DisableEnableMarket(2, true);
    
}

function DisableEnableMarket(mktIx, disableStatus)
{
	if(!document.getElementById || !document.createTextNode)
		return true;
	
	var preventAirportChanges = typeof bookingInfo != "undefined" && (!bookingInfo["0"]["changeFlight"]);
	
	var orig = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketOrigin' + mktIx);
	var dest = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketDestination' + mktIx);
	var listOrigin = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + mktIx);
	var listDest = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + mktIx);
	var day = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDay' + mktIx);
	var month = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + mktIx);
	var dateRange = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDateRange' + mktIx);
	var cal = document.getElementById(applicationJavaScriptHtmlId + '_HyperLinkMarketCalendar' + mktIx);
	var labelOneWay = document.getElementById('labelOneWay');

	if (orig) orig.disabled=disableStatus;
	if (dest) dest.disabled=disableStatus;
	// Wenn Änderungen an den Airports verboten sind, dann darf man die Select-Felder nur ausschalten, jedoch nicht einschalten.
	if (!preventAirportChanges || disableStatus)
	{
		if (listOrigin) listOrigin.disabled=disableStatus;
		if (listDest) listDest.disabled=disableStatus;
	}
	if (day) day.disabled=disableStatus;
	if (month) month.disabled=disableStatus;
	if (dateRange) dateRange.disabled=disableStatus;
	if (cal) cal.disabled=disableStatus;
	if (labelOneWay) labelOneWay.disabled=disableStatus;
}

function AvailabilitySearchValues_Validate(validateEventArgs)
{
	if (CheckPayment() && CheckCities() && CheckDates() && CheckPassengers() && CheckPaxCount() && CheckInfantCount())
	{
		return true;
	}

	return false;
}

function CheckPayment(){
	if($(":radio[name$=paymentMethod]").length > 0 && $(":radio[name$=paymentMethod]:checked").length == 0){
		alert(paymentMethodNeeded);
		return false;
	}
	return true;
}

function CheckPassengers()
{
	var tooManyInfants = localizedTextTooManyInfants;
	var ds = document['SkySales'];
	var adult = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListAdult')*1;
	var child = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListChild')*1; 
	var infant = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListInfant')*1; 

	if ((adult) && (infant) && (infant > adult))
	{
		alert(tooManyInfants);
		return false;
	}

	return true;
}

function UpdateCalendarDate(updateCalendarDateEventArgs)
{
	var ds = document['SkySales'];
	var dropDownListMarketDay = applicationJavaScriptHtmlId + '_DropDownListMarketDay' + updateCalendarDateEventArgs.passedInfo;
	var dropDownListMarketMonth = applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + updateCalendarDateEventArgs.passedInfo;
			
	var month = updateCalendarDateEventArgs.dateSelected.getMonth() + 1;
	if(month < 10)
	{
		month = '0' + month;
	}
	var day = updateCalendarDateEventArgs.dateSelected.getDate();
	if(day < 10)
	{
		day = '0' + day;
	}
			
	ds[dropDownListMarketMonth].value = updateCalendarDateEventArgs.dateSelected.getFullYear() + '-' + month;
	ds[dropDownListMarketDay].value = day;
}


// find the index of where value is in the list
// and returns the index.
function findIndexByValue(list, value)
{
	var i=0;
	while ( i< list.length )
	{
		if ( list[i].value == value )
			return i;
		i++;
	}
	return -1;
}

function addOption(list, text, value)
{
	var idx = list.length;
	list[idx]=new Option(text);
	list[idx].value=value;
	list.selectedIndex=idx;
	return idx;
}

function setDatesState(state, mktIx)
{
	ElementsState['DropDownListMarketDay'+mktIx] = state;
	ElementsState['DropDownListMarketMonth'+mktIx] = state;
	ElementsState['DropDownListMarketDateRange'+mktIx] = state;
	ElementsState['HyperLinkMarketCalendar'+mktIx] = state;
}

function setPaxsState(state)
{
	ElementsState['DropDownListAdult'] = state;
	ElementsState['DropDownListChild'] = state;
	ElementsState['DropDownListInfant'] = state;
	ElementsState['PassengersBlock'] = state;
}

function setMarketState(state, mktIx)
{
	ElementsState['Market'+mktIx+'Block'] = state;
}

function validateElement(elementName)
{
	if ((document['SkySales'][applicationJavaScriptHtmlId + '_' + elementName]) && (ElementsState[elementName]!= 'cancel') ) 
		return true;
	return false;
}

function GetMarketStructure()
{
	var selected = $("div#travelOptions input:checked").val();
	if (selected=='OneWay')
	{
		numMarketsToValidate=1;
		numDatesToValidate=1;
	}
	else if (selected=='RoundTrip')
	{
		numMarketsToValidate=1;
		numDatesToValidate=2;
	}
	else if (selected=='OpenJaw')
	{
		numMarketsToValidate=2;
		numDatesToValidate=2;
	}
	else 
	{
		numMarketsToValidate=applicationNumberOfMarketsToOffer; //set to max
		numDatesToValidate=applicationNumberOfMarketsToOffer;
	}

	return selected;			
}

/*
* Validates that the first departure date selected is not before the current date
* Validates that the date for marketN is not earlier than marketN-1
*/
function CheckDates()
{	
    
	var ds=document['SkySales'];					
	var dateToCompare = applicationFormatedDate; 
	var dayToday = applicationFormatedDay;
	var monthYearValue = applicationFormatedDateTime;
	for (var mktIx=1; mktIx<=numDatesToValidate; mktIx++)
	{
		if (MarketAction[mktIx] == 'Cancel')
			continue;

		if (!validateElement('DropDownListMarketDay' + mktIx))
			continue;

		var mktDay 	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].selectedIndex].value;
		var mktMonth	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].value.substring(5, 7);
		var mktYear	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].value.substring(0, 4);
		var mktMonthText	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].text;
		var mkt2Lines	= 0;	// TODO: set this to 1 if/when mkt2 month and day lists have a default '-' item at index 0.
		var mktDate = ''+mktYear+mktMonth+mktDay;
		
		if (! CheckDaysOfMonth(mktDay, mktMonth, mktYear))
		{
			alert(localizedTextInvalidDatePre + mktDay + localizedTextInvalidDateMid + mktMonthText + localizedTextInvalidDatePost);
			return false;
		}
		
		// don't check date if liftstatus is not default
		if(MarketLiftStatus[mktIx] == null)
		{
		    MarketLiftStatus[mktIx] = "Default";
		}
		
		var changeFlightAllowed = typeof bookingInfo == "undefined" || bookingInfo[(mktIx-1)+""].changeFlight==true;
		if (mktDate < dateToCompare && MarketLiftStatus[mktIx]==applicationLiftStatus && changeFlightAllowed)
		{
			if (mktIx == 1)
			{
				// if dptr of first market is past date, display alert and set to current date
				var msg=localizedTextPastDatePre;

				// don't want to reset the date when it's not 'change'
				// 'retain' is supposed to keep the old dates
				if (MarketAction[mktIx]=='New' || MarketAction[mktIx]=='Change')
				{
					msg=msg+localizedTextPastDatePost;
					alert(msg);
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options.selectedIndex = dayToday - 1;
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options.selectedIndex = findIndexByValue(ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx],monthYearValue);
				}
				else
					alert(msg);
				return false;
			}
			else
			{
				var msg=localizedTextEarlierDatePre;
				if (MarketAction[mktIx]=='New' || MarketAction[mktIx]=='Change')
				{
					msg=msg+localizedTextEarlierDatePost;
					alert(msg);
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options.selectedIndex = eval(ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+(mktIx-1)].options.selectedIndex) + mkt2Lines;
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options.selectedIndex = eval(ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+(mktIx-1)].options.selectedIndex) + mkt2Lines;
				}
				else
					alert(msg);
				return false;
			}
		}
		
		dateToCompare = mktDate;

	}

	dateToCompare = applicationFormatedDate;
	
	// look for first market that's not 'Cancel'and not 'Retain'
	// these are the markets where availability will be obtained
	for (var mktIx=1; mktIx<=numDatesToValidate; mktIx++)
	{
		if (MarketAction[mktIx] == 'Cancel' || MarketAction[mktIx] == 'Retain')
			continue;
		if (!validateElement('DropDownListMarketDay' + mktIx))
			continue;

	var mktDay 	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].selectedIndex].value;
	var mktMonth	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].value.substring(5, 7);
	var mktYear	= ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].selectedIndex].value.substring(0, 4);	
	var mktDate = ''+mktYear+mktMonth+mktDay;
	
	
	if(!CheckTravelPeriod(mktDate)){
		return false;
	}
	
	
	if (mktDate == dateToCompare)
	{
		var msg = localizedTextTodaysDateMessage;
		if($(":radio[name$=paymentMethod]:checked").attr("value") == "madBooking"){
			msg = localizedTextTodaysDateMessageMAD;
		}

		if (msg && !location.pathname.match(/GroupBooking\.aspx/))
		{
			alert(msg);
		}
	}
	break; 
	} // end loop to look for first market that's not 'Cancel'and not 'Retain'

	return true;
}

// Hier wir geprüft ob für eine bestimmte Strecke der gewünschte Flugzeitraum außerhalb des Angebots liegt.

// Hier wir geprüft ob für eine bestimmte Strecke der gewünschte Flugzeitraum außerhalb des Angebots liegt.

function CheckTravelPeriod(mktDate){	
    if(travelPeriodBODCMN && travelPeriodVCECMN){
	
		var orig = document.getElementById(applicationJavaScriptHtmlId+"_DropDownListMarketOrigin1")
		var dest = document.getElementById(applicationJavaScriptHtmlId + "_DropDownListMarketDestination1");
		
	    if(orig && dest){
			if (mktDate < travelPeriodVCECMN)
			{
				var mktYearVCECMN = travelPeriodVCECMN.substring(0, 4);
				var mktMonthVCECMN = travelPeriodVCECMN.substring(4, 6);
				var mktDayVCECMN = travelPeriodVCECMN.substring(6, 8);				
			
				var newDateVCECMN = new Date(mktYearVCECMN,mktMonthVCECMN-1,mktDayVCECMN);
				var newDateReturnVCECMN = new Date(mktYearVCECMN,mktMonthVCECMN-1,mktDayVCECMN);
				
				
				//neuer Rückflug erst in 7 Tagen für BODCMN
				newDateReturnVCECMN.add(7).days();		
				var strVCECMN = JooseX.Culture.Factory.get().formatDate(newDateVCECMN);
				var strReturnVCECMN = JooseX.Culture.Factory.get().formatDate(newDateReturnVCECMN);
			
				if(orig.value == "CMN" && dest.value == "VCE"){
							
					msg = localizedTextTravelPeriodMessageCMNVCE;									
					if (msg){	
						
						setNewDatePickerDate(newDateVCECMN, newDateReturnVCECMN, strVCECMN, strReturnVCECMN);											
						alert(msg);
						return false;
					}
										
				}
				
				if(orig.value == "VCE" && dest.value == "CMN"){
							
					msg = localizedTextTravelPeriodMessageVCECMN;									
					if (msg){												
						setNewDatePickerDate(newDateVCECMN, newDateReturnVCECMN, strVCECMN, strReturnVCECMN);											
						alert(msg);
						return false;
					}
										
				}
												
			}	
		    			
			if (mktDate < travelPeriodBODCMN){
			
				var mktYearBODCMN = travelPeriodBODCMN.substring(0, 4);
				var mktMonthBODCMN = travelPeriodBODCMN.substring(4, 6);
				var mktDayBODCMN = travelPeriodBODCMN.substring(6, 8);
		
				var newDateBODCMN = new Date(mktYearBODCMN,mktMonthBODCMN-1,mktDayBODCMN);
				var newDateReturnBODCMN = new Date(mktYearBODCMN,mktMonthBODCMN-1,mktDayBODCMN);
				//neuer Rückflug erst in 7 Tagen für BODCMN
				newDateReturnBODCMN.add(7).days();		
				var strBODCMN = JooseX.Culture.Factory.get().formatDate(newDateBODCMN);
				var strReturnBODCMN = JooseX.Culture.Factory.get().formatDate(newDateReturnBODCMN);
			
			
				if(orig.value == "CMN" && dest.value == "BOD"){					
						msg = localizedTextTravelPeriodMessageCMNBOD;									
						if (msg){	
							setNewDatePickerDate(newDateBODCMN, newDateReturnBODCMN, strBODCMN, strReturnBODCMN);											
							alert(msg);
							return false;
						}			
				}
				
				if(orig.value == "BOD" && dest.value == "CMN"){			
					
						msg = localizedTextTravelPeriodMessageBODCMN;
						if (msg){		
							setNewDatePickerDate(newDateBODCMN, newDateReturnBODCMN, strBODCMN, strReturnBODCMN);						
							alert(msg);
							return false;
						}						
				}	
				
			}
			
		}
	
	}
	
	return true;
	
}

function setNewDatePickerDate(newDate, newDateReturn, str, strReturn){
		var ds=document['SkySales'];
		var datePickerFlight = $("#datePickerFlight");
		var datePickerReturn = $("#datePickerReturn");
						
		ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay1'].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay1'].selectedIndex].value = newDate.toString("dd");
		ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth1'].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth1'].selectedIndex].value = newDate.toString("yyyy")+'-'+newDate.toString("MM");
		// Wenn es einen Rückflug geben soll wird das Datum auf plus 7 Tage gesetzt.
		if(ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay2'].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay2'].selectedIndex]){
			ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay2'].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay2'].selectedIndex].value = newDateReturn.toString("dd");
			ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth2'].options[ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth2'].selectedIndex].value = newDateReturn.toString("yyyy")+'-'+newDateReturn.toString("MM");
		}
						
		datePickerFlight.val(str);
		datePickerReturn.val(strReturn);	
}
/*
function OpenCalendar(market)
{
	// do nothing if market is not visible or disabled
	if (MarketAction[market]=='Cancel' || MarketAction[market]=='Retain')
	return;

	var ds = document['SkySales'];
	var dropDownListMarketDay = applicationJavaScriptHtmlId + '_DropDownListMarketDay' + market;
	var dropDownListMarketMonth = applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + market;
	var selectedMonth = ds[dropDownListMarketMonth].options[ds[dropDownListMarketMonth].options.selectedIndex].value;
	var selectedDay = ds[dropDownListMarketDay].options[ds[dropDownListMarketDay].options.selectedIndex].value; 
	var appendUrl = '';
	if(market > 1)
	{
		var dropDownListMarketDayPrev = applicationJavaScriptHtmlId + '_DropDownListMarketDay'+(market-1);
		var dropDownListMarketMonthPrev = applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+(market-1);
		var lockDownDay = ds[dropDownListMarketDayPrev].options[ds[dropDownListMarketDayPrev].options.selectedIndex].value;
		var lockDownMonth = ds[dropDownListMarketMonthPrev].options[ds[dropDownListMarketMonthPrev].options.selectedIndex].value;
		appendUrl = '&lockDownDay=' + lockDownDay + '&lockDownMonth=' + lockDownMonth;
	}
	var url = applicationCalendarUriQueryString + 'passedInfo=' + market + '&selectedMonth=' + selectedMonth + '&selectedDay=' + selectedDay + appendUrl;

	if (!window.calendarWindow || calendarWindow.closed)	// has not yet been defined
	{
		calendarWindow = window.open(url,'calendar','width=250,height=251,toolbar=0,status=0,location=0,menubar=0,scrollbars=0,resizable=0');
		//calendarWindow = window.open(url,'calendar','width=250,height=251,toolbar=1,status=1,location=1,menubar=1,scrollbars=1,resizable=1');
	}
	else	// has been defined
	{
		// still open
		calendarWindow.focus();
	}
}*/

var tempEventArgs;
var retryCount = 0;
function UpdateFlightSearch(eventArgs)
{
    //alert('In Update');
	//Safe retry if the object hasn't been initialized yet
	if (ExistingMarkets == null || ExistingMarkets.length == 0)
	{
	    //alert(ExistingMarkets.length);
	    //alert('In Retry');    
		tempEventArgs = eventArgs;
		retryCount++;
		if (retryCount < 4)
		{
			setTimeout('UpdateFlightSearch(tempEventArgs)',50);
		}
		
		return;
	}
	
	//alert('Passed Retry'); 
	var allowOpenJaw = applicationOpenJawEnabled;
	var ds = document['SkySales'];

	for (var i=0; i<eventArgs.SelectedModificationsArray.length; i++)
	{

		var orig = ds[applicationJavaScriptHtmlId + '_TextBoxMarketOrigin' + (i+1)];
		var dest = ds[applicationJavaScriptHtmlId + '_TextBoxMarketDestination' + (i+1)]; 
		var listOrigin = ds[applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + (i+1)]; 
		var listDest = ds[applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + (i+1)]; 
		var day = ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay' + (i+1)];
		var month = ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + (i+1)];

		if ( eventArgs.SelectedModificationsArray[i] == 'Retain')
		{
			var ds = document['SkySales'];
			var idx=-1;
			// revert values to market from existing booking 
			if (orig) orig.value=ExistingMarkets[i+1].orig;
			if (dest) dest.value=ExistingMarkets[i+1].dest;

		 	if (listOrigin)
			{
					listOrigin.selectedIndex=findIndexByValue(listOrigin,ExistingMarkets[i+1].orig);
					changeDest(listOrigin, listDest, listOrigin,ExistingMarkets[i+1].orig);
					//alert("huh");
					idx= findIndexByValue(listDest,ExistingMarkets[i+1].dest);
					if (idx== '-1')
						addOption(listDest,ExistingMarkets[i+1].dest, ExistingMarkets[i+1].dest);
					else
						listDest.selectedIndex=idx;
			}
			if (day) day.selectedIndex=findIndexByValue(day,ExistingMarkets[i+1].day);
			if (month)
			{
			
				idx=findIndexByValue(month,ExistingMarkets[i+1].monthYearValue);
				if (idx== '-1')
					addOption(month, ExistingMarkets[i+1].monthYear, ExistingMarkets[i+1].monthYearValue);
				else
					month.selectedIndex=idx;
					
			}
			// diabled = retained
			setStationsState('retain', i+1);
			setDatesState('retain', i+1);
			setMarketState('retain', i+1);
			setPaxsState('retain');
			MarketAction[i+1] = 'Retain';
		}
		else if ( eventArgs.SelectedModificationsArray[i] == 'Change')
		{
			// enabled = change
			setDatesState('change', i+1);
			setMarketState('change', i+1);
			MarketAction[i+1] = 'Change';
			if (exists('Retain'))
			{
				setPaxsState('retain');
				if (allowOpenJaw)
					setStationsState('change', i+1);
				else
					setStationsState('cancel', i+1);
			}
			else //if all other mkts == Change or Cancel
			{
				setStationsState('change', i+1);
				setPaxsState('change');
			}
		}
		else // mkt == 'Cancel'
		{

			if (orig) orig.value=localizedTextTextBoxMarketOrigin;
			if (dest) dest.value=localizedTextTextBoxMarketDestination;

			if (listOrigin)
			{
					listOrigin.selectedIndex=findIndexByValue(listOrigin,'none');
					listDest.selectedIndex=findIndexByValue(listDest,'none');
			}

			// hidden = cancel
			setStationsState('cancel', i+1);
			setDatesState('cancel', i+1);
			setMarketState('cancel', i+1);
			MarketAction[i+1] = 'Cancel';
			if (all('Cancel'))
				setPaxsState('cancel');
		}
	}

	changeInterface();

}

function changeInterface()
{
	if(!document.getElementById || !document.createTextNode)
		return true;

	var ds = document['SkySales'];
	for (var id in ElementsState)
	{
		if (ElementsState[id] == 'retain')
		{
			if (document.getElementById(applicationJavaScriptHtmlId + '_'+id)) document.getElementById(applicationJavaScriptHtmlId + '_'+id).style.display = 'inline';
			if (ds[applicationJavaScriptHtmlId + '_'+id]) ds[applicationJavaScriptHtmlId + '_'+id].disabled = true;
		}
		else if (ElementsState[id] == 'change')
		{
			if (document.getElementById(applicationJavaScriptHtmlId + '_'+id)) document.getElementById(applicationJavaScriptHtmlId + '_'+id).style.display = 'inline';
			if (ds[applicationJavaScriptHtmlId + '_'+id]) ds[applicationJavaScriptHtmlId + '_'+id].disabled = false;
		}
		else if (ElementsState[id] == 'cancel')
		{
			if (document.getElementById(applicationJavaScriptHtmlId + '_'+id)) document.getElementById(applicationJavaScriptHtmlId + '_'+id).style.display = 'none';
		}
	}
}

function ExistingMarket(orig,dest,day,monthYear,monthYearValue)
{
	this.orig = orig;
	this.dest = dest;
	this.day = day;
	this.monthYear = monthYear;
	this.monthYearValue = monthYearValue;
}

function all(action)
{
	var radioGroupCount = applicationNumberOfMarketsToOffer;
	for (var i=1; i<=radioGroupCount; i++)
	{
		if ( GetCheckedValue(applicationHtmlId + 'RadioGroupMarket'+i) != action) return false;
	}
	return true;
}

function exists(action)
{
	var radioGroupCount = applicationNumberOfMarketsToOffer;
	for (var i=1; i<=radioGroupCount; i++)
	{ 
		if ( GetCheckedValue(applicationHtmlId + 'RadioGroupMarket'+i) == action) return true;
	}
	return false;
}

function CheckPaxCount()
{
	var dropDownNames = applicationPassengerArrayValues.split(",");
	var ds = document['SkySales'];
	var paxDropdownRendered = false;
	
	if(document.getElementById && document.createTextNode)
	{
		var paxCount = 0;
		var undefined;

		for(var i=0; i < dropDownNames.length; i++)
		{
			if (ds[dropDownNames[i]] != undefined)
			{
				paxDropdownRendered = true;
				paxCount = paxCount + parseInt(ds[dropDownNames[i]].value);
			}
		}

		if (paxDropdownRendered && paxCount == 0)
		{
			alert(localizedTextLessThanOnePassenger);
			return false;
		}
		else if (paxCount > applicationBookingMaxPassengers)
		{
			alert(localizedTextExceedsMaxPaxAllowed + applicationBookingMaxPassengers);
			return false;
		}
	}
	
	return true;
}

// S2: copy from version 1.3
function CheckInfantCount()
{
	var dropDownNameAdult =  applicationJavaScriptHtmlId + "_DropDownListPassengerType_ADT";
	var dropDownNameInfant = applicationJavaScriptHtmlId + "_DropDownListPassengerType_INFANT";
	
	var ds = document['SkySales'];
	var paxDropdownRendered = false;
	
	if(document.getElementById && document.createTextNode)
	{
		var adultCount = 0;
		var infantCount = 0;
		var undefined;
		
		if (ds[dropDownNameAdult] != undefined)
		{
			paxDropdownRendered = true;
			adultCount = adultCount + parseInt(ds[dropDownNameAdult].value);
		}
		
		if (ds[dropDownNameInfant] != undefined)
		{
			paxDropdownRendered = true;
			infantCount = infantCount + parseInt(ds[dropDownNameInfant].value);
		}
		
		if (paxDropdownRendered && (infantCount > adultCount))
		{
			alert(localizedTextTooManyInfants);
			return false;
		}
	}
	
	return true;
}
//End S2

/*
* Validates that there's 1 set of O&D entered if one way is selected
* Validates that there's 1 set of O&D entered if round trip is selected
* Validates that there's 2 sets of O&D entered if open jaw is selected
* For TripPlanner, the number of markets to search is however many was entered
* For Round trip, validates that the origin is the same as the ultimate/last
* destination
* Validates that Origin is not the same as destination
* Sets the global variables numDatesToValidate and numMarketsToValidate
*/
function CheckCities()
{
	var selected   = GetMarketStructure();
		
	var ds = document['SkySales'];
	var stations = new Array();

	var i=-1;
	for (var mktIx=1; mktIx<=numMarketsToValidate; mktIx++)
	{
		if (MarketAction[mktIx] == 'Cancel')
			continue;
			
		if (applicationUseDropDownForStations)
		{
			if (validateElement('DropDownListMarketOrigin' + mktIx))
				{
					i+=1;
					stations[i] = ds[applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + mktIx];
				//	if (IsEmpty(stations[i], '???'))
					if (IsEmpty(stations[i]))
					{
						if ( selected=='TripPlanner' && mktIx>1)
						{
							// an empty origin signals the end of the requested market
							numMarketsToValidate = mktIx-1;
							numDatesToValidate = mktIx-1;
							break;
						}
						else
						{
							alert(localizedMissingOrigin);
							return false;
						}
					}
				}
				else if (selected=='TripPlanner' && mktIx>1)
				{
					// an empty origin signals the end of the requested market
					numMarketsToValidate = mktIx-1;
					numDatesToValidate = mktIx-1;
					break;
					
				}

				if (validateElement('DropDownListMarketDestination' + mktIx))
				{
					i+=1;
					stations[i] = ds[applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + mktIx];
					//if (IsEmpty(stations[i], '???'))
					if (IsEmpty(stations[i]))
					{
						alert(localizedMissingDest);
						return false;
					}
					
				}
		
		}
		else
		{
			if (validateElement('TextBoxMarketOrigin' + mktIx))
				{
					i+=1;
					stations[i] = ds[applicationJavaScriptHtmlId + '_TextBoxMarketOrigin' + mktIx];
					if (IsEmpty(stations[i], localizedTextTextBoxMarketOrigin))
					{
						if (selected=='TripPlanner' && mktIx>1)
						{
							// an empty origin signals the end of the requested market
							numMarketsToValidate = mktIx-1;
							numDatesToValidate = mktIx-1;
							break;
						}
						else
						{
							alert(localizedMissingOrigin);
							return false;
						}
					}
				}
				else if (selected=='TripPlanner' && mktIx>1)
				{
					// an empty origin signals the end of the requested market
					numMarketsToValidate = mktIx-1;
					numDatesToValidate = mktIx-1;
					break;
					
				}

				if (validateElement('TextBoxMarketDestination' + mktIx))
				{
					i+=1;
					stations[i] = ds[applicationJavaScriptHtmlId + '_TextBoxMarketDestination' + mktIx];
					if (IsEmpty(stations[i], localizedTextTextBoxMarketDestination))
					{
						alert(localizedMissingDest);
						return false;
					}
					
					if (stations[i].value.toUpperCase() == stations[i-1].value.toUpperCase())
					{
						alert(localizedSameOriginDestination);
						return false;
					}
				}
		}
	} // end loop mktIx<=numMarketsToValidate
	
	if (!applicationOpenJawEnabled)
	{
		var ok = true;
		if (stations.length > 2) 
		{
			for (var i=1; i<stations.length-1; i+=2)
			{
				if (stations[i].value.toUpperCase() != stations[i+1].value.toUpperCase()) 
				{
					ok = false;
					break;
				}
			}
			if (stations[0].value.toUpperCase() != stations[stations.length-1].value.toUpperCase())
			{
				ok = false;
			}
		}
		if (!ok)
		{
			alert (localizedInvalidCityPairs);
			return false;
		}
	}
	
	return true;
} // end of AVAILABILITYSEARCH_checkCities

function setStationsState(state, mktIx)
{
	if (applicationUseDropDownForStations)
	{
		ElementsState['DropDownListMarketOrigin'+mktIx] = state;
		ElementsState['DropDownListMarketDestination'+mktIx] = state;
	}
	else
	{
		ElementsState['TextBoxMarketOrigin'+mktIx] = state;
		ElementsState['TextBoxMarketDestination'+mktIx] = state;
	}
}

function OriginMac(object)
{
    var index =  object.id.substring(object.id.length - 1);
    if(index > 0)
    {
        var checkbox = document.getElementById(applicationJavaScriptHtmlId + '_CheckBoxUseMacOrigin' + index);        
        var checkboxLabel = document.getElementById(applicationJavaScriptHtmlId + '_LabelUseMacOrigin' + index);

        if (checkbox && checkboxLabel)
        {
            setMac(object, checkbox, checkboxLabel);
            // reset the destination macs items
            var destId = object.id;
            destId = destId.replace(/Origin/, "Destination");
            var dest = document.getElementById(destId);
            DestinationMac(dest);
        }
    }
}

function DestinationMac(object)
{
    var index =  object.id.substring(object.id.length - 1);
    if(index > 0)
    {        
        var checkbox = document.getElementById(applicationJavaScriptHtmlId + '_CheckBoxUseMacDestination' + index);        
        var checkboxLabel = document.getElementById(applicationJavaScriptHtmlId + '_LabelUseMacDestination' + index);        
        if (checkbox && checkboxLabel) setMac(object, checkbox, checkboxLabel);
    }
}

function setMac(object, checkbox, checkboxLabel)
{
    if(Stations && object && checkbox && checkboxLabel && object.value &&
     Stations[object.value.toUpperCase()] != null && Stations[object.value.toUpperCase()].macCode.length > 0)
    {	        
	    // hide just the checkbox because the mac code is the selected market (station)
	    if (checkbox)
	    {
	        if ((Stations[object.value.toUpperCase()] != null) && (object.value.toUpperCase() == Stations[object.value.toUpperCase()].macCode.toUpperCase()))
	            checkbox.style.display='none';
	        else
	            checkbox.style.display='block';
	    }
	        
	    if (checkboxLabel)
	    {
	        checkboxLabel.innerHTML = macSearchAllText + Stations[object.value.toUpperCase()].macCode + macCodeSeparator;
	        checkboxLabel.style.display = "block";
	    }
	    
	        
        if (Stations[object.value.toUpperCase()] != null)
        {
	        for(var i in MacsArray[Stations[object.value.toUpperCase()].macCode])
	        {
	            if(i > 0)
	            {
	                checkboxLabel.innerHTML += macCitySeparator;
	                
	            }
	            checkboxLabel.innerHTML +=  MacsArray[Stations[object.value.toUpperCase()].macCode][i];	            
	        }
	    }
	}
	else
	{
	    if (checkbox) 
	    {
	        checkbox.checked = false;	        
	        checkbox.style.display = "none";
	    }
	    if (checkboxLabel) 
	    {
	        checkboxLabel.innerHtml = "";
	        checkboxLabel.style.display = "none";
	    }
	}    
}

function initMacs()
{
    for(var i = 1; i <= applicationNumberOfMarketsToOffer; i++)
    {
	    var orig = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketOrigin' + i);
	    var dest = document.getElementById(applicationJavaScriptHtmlId + '_TextBoxMarketDestination' + i);
	    var listOrigin = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + i);
	    var listDest = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + i);
	    
	    if (orig) OriginMac(orig);
	    if (dest) DestinationMac(dest);
	    if (listOrigin) OriginMac(listOrigin);
	    if (listDest) DestinationMac(listDest);
    }
}

function highlightMoveDays(list, className)
{
	var marketIndex = list.id.charAt(list.id.length - 1);
	try
	{
	    var moveDays = eval("moveDepartureDays" + marketIndex);
	}
	catch(e)
	{
	    return;
	}
	if(moveDays != null)
	{
	    var day = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDay' + marketIndex);
        for(var x = 0; x < day.options.length; x++)
        {
            day.options[x].className = '';
        }
	    if(moveDays[list.value] != null)
	    {
            var moveDaysArray = moveDays[list.value].split(',');
            for(var i = 0; i < moveDaysArray.length; i++)
            {
                day.options[moveDaysArray[i] - 1].className = className;
            }
        }
    }
}

function highlightMoveOriginCities(marketIndex, className)
{
	// origin city
	try
	{
	    var moveDepartureCities = eval("moveDepartureCities" + marketIndex);
	}
	catch(e)
	{
	    return;
	}
	if(moveDepartureCities != null)
	{
	    var listOrigin = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + marketIndex);
	    for(var i = 0; i < moveDepartureCities.length; i++)
	    {
	        for(var j = 0; j < listOrigin.options.length; j++)
	        {
	            if(moveDepartureCities[i] == listOrigin.options[j].value)
	            {
	                listOrigin.options[j].className = className;
	                break;
	            }
	        }
	    }
	}
}

function highlightMoveDestinationCities(marketIndex, className)
{
	// destination city
	try
	{
	    var moveDepartureCities = eval("moveArrivalCities" + marketIndex);
	}
	catch(e)
	{
	    return;
	}
	if(moveDepartureCities != null)
	{
	    var listOrigin = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + marketIndex);
	    
	    for(var i = 0; i < moveDepartureCities.length; i++)
	    {
	        for(var j = 0; j < listOrigin.options.length; j++)
	        {
	            if(moveDepartureCities[i] == listOrigin.options[j].value)
	            {
	                listOrigin.options[j].className = className;
	                break;
	            }
	        }
	    }
	}
}



$(document).ready(function(){
    var updateDates = new Function("AvailabilitySearchInput.dateSelected(this);");
    $("input.Date", $("div#searchDivHeader").next()).change(updateDates);    
    $("input.Date", $('#AVAILABILITYSEARCHINPUT_Market1Block')).change(updateDates);    
    $("input.Date", $('#AVAILABILITYSEARCHINPUT_Market2Block')).change(updateDates);
});

AvailabilitySearchInput = new Object();

function pad(number,length) {
        var str = "" + number;
        while (str.length < length)
          str = '0' + str;
        return str;
    }   

AvailabilitySearchInput.dateSelected = function(obj)
{
    var monthNames = cultureMonths;
    var day = "";
	var month = "";
	var year = "";
	var whichMkt = "";
		    
	if (obj != null)
    {
        var ds = document['SkySales'];
        var objValue = obj.value;
        var objId = obj.id;
        if (objValue.indexOf(datePickerDelimiter) > -1)
        {
            var datePickerArray = objValue.split(datePickerDelimiter);
	        for (var i = 0; i < datePickerFormat.length; i++)
	        {
	            var dateData = datePickerArray[i];
	            if (dateData.charAt(0) == '0')
	            {
	                dateData = dateData.substring(1);
	            }
	            var formatChar = datePickerFormat.charAt(i);
	            switch(formatChar)
	            {
	                case 'm': month = dateData; break;
	                case 'd': day = dateData; break;
	                case 'y': year = dateData; break;
	            }
	        }
	        whichMkt = parseInt(objId.substring(objId.length - 1));
	        month = parseInt(month);
	        month = monthNames[--month];
        }
                
        //Get the day and month controls to update. whichMkt is hidden field in form.
        var dropDownListMarketDay = applicationJavaScriptHtmlId + '_DropDownListMarketDay' + whichMkt;
        var dropDownListMarketMonth = applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + whichMkt;         
                
        //Get the index number of the month selected, start at -2 so you don't just return 0 or Jan.
        var x = 0;
        var monthIndex = -2;
        for(x=0; x< monthNames.length; x++)
	    {
          if ( monthNames[x] == month )
          {
            monthIndex = x;
            break;
          }
        }     
        
        //Since array starts at 0 add one and then send it to the padding function for 02 instead of 2.
        monthIndex++;        
        monthIndex = pad( monthIndex,2);
        
        dayIndex = day;
        dayIndex = pad(dayIndex, 2);
        
        ds[dropDownListMarketDay].value = '' + dayIndex;
        ds[dropDownListMarketMonth].value = year + '-' + monthIndex;

        var calendarLayerObj = document.getElementById("calendarLayer");
        if (calendarLayerObj != null)
        {
            calendarLayerObj.style.display = 'none';
        }
    }
}

function ReturnDateDisplay()
{
	if(!document.getElementById || !document.createTextNode)
		return true;

	var selected   = GetMarketStructure();

	if (selected == 'OneWay')
	{
		for (mktIx=2; mktIx<=applicationNumberOfMarketsToOffer; mktIx++)
			HideShowMarket(mktIx, 'none');
	}
	else  if (selected == 'RoundTrip')
	{
		for (mktIx=2; mktIx<=applicationNumberOfMarketsToOffer; mktIx++)
			HideShowMarket(mktIx, 'none');
		var mktIx = 2;
		var disp = 'inline';
		var labelDate = document.getElementById(applicationJavaScriptHtmlId + '_LabelMarketDate' + mktIx);
		// var day = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDay' + mktIx);
		// var month = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + mktIx);
		var dateRange = document.getElementById(applicationJavaScriptHtmlId + '_DropDownListMarketDateRange' + mktIx);
		//var cal = document.getElementById(applicationJavaScriptHtmlId + '_HyperLinkMarketCalendar' + mktIx);
		var labelOneWay = document.getElementById('labelOneWay');
    var divRoundTour = document.getElementById('roundTour');

		if (labelDate) labelDate.style.display=disp;
		// if (day) day.style.display=disp;
		// if (month) month.style.display=disp;
		if (dateRange) dateRange.style.display=disp;
		//if (cal) cal.style.display=disp;
		if (labelOneWay) labelOneWay.style.display="";
    if (divRoundTour) divRoundTour.style.display="";

	}
	else  if (selected == 'OpenJaw')
	{
		for (mktIx=1; mktIx<3; mktIx++)
			HideShowMarket(mktIx, 'inline');
		for (mktIx=3; mktIx<=applicationNumberOfMarketsToOffer; mktIx++)
			HideShowMarket(mktIx, 'none');
	}
	else
	{
		for (mktIx=2; mktIx<=applicationNumberOfMarketsToOffer; mktIx++)
			HideShowMarket(mktIx, 'inline');
	}	
}

//populate the stations
$(document).ready(function(){
    initMacs();
});

//hide the car search onload
$(document).ready(function(){
    $('div#aosAvailabilitySearchDivBody').hide();
    $('div#aosAvailabilitySearchDivBody + div').hide();
    $('div#aosAvailbilitySearchDivHeader').hide();
});

var mode = 'initial';

AvailabilitySearchInput.ToggleAvailabilitySearchForm = function(){
                
                $('div#searchDivHeader').toggle();
                $('div#searchDivHeaderBody').toggle();
                $('div#SearchDivHeaderFooter').toggle();
                
                //hide the ssr div to avoid confusion
                $('div#ssrSearchDivHeader').toggle();
                $('div#ssrSearchDivBody').toggle();
                $('div#ssrSearchDivFooter').toggle();
                
                $('div#aosAvailabilitySearchDivBody').toggle();
                $('div#aosAvailbilitySearchDivFooter').toggle();
                $('div#aosAvailbilitySearchDivHeader').toggle();
};

$(document).ready(function(){
    //check to see if we recieved any parameters from AOS for car availability
    if($("div#aosAvailabilitySearchDivBody :input:visible[type!='submit']").size() != 0)
    {
        $("div#flowType input[id*=_flowSelectCar]").click(function(){        
            if(mode == 'initial'){
                $('#flowType').remove().insertBefore( $('div#aosAvailabilitySearchDivBody div:eq(0)') );
                //With IE the value gets cleared on the remove option so we need to move it first
                $(this).attr('checked','checked');
                AvailabilitySearchInput.ToggleAvailabilitySearchForm();
                mode='swapped';
            }
        });
        
        $("div#flowType input[id*=_flowSelectFlight]").click(function(){
            if(mode=='swapped'){
                //put the div below the search header
                $('#flowType').remove().insertBefore($('div#searchDivHeaderBody div:eq(0)'));
                //With IE the value gets cleared on the remove option so we need to move it first
                $(this).attr('checked','checked');            
                AvailabilitySearchInput.ToggleAvailabilitySearchForm();
                mode = 'initial';
            }
            
        });
    }
    else
    {
        //but by default select flight in this instance (no car parameters)
        $("div#flowType input[id$=_flowSelectFlight]").attr('checked','checked');
        //hide flowtype node if we didn't get any query parameters for cars
        $('div#flowType').hide();
    }
});

//populates the resident country input field
/*
$(document).ready(function(){
    var options = '';
    var selectedItem = '';
    if(countryInfo)
    {
        var selectBox = $('p#AvailabilitySearchInputResidentCountry :input');
        for(var i = 0; i < countryInfo.length; i++)
        {
            if(i == 0)selectedItem = countryInfo[i].ResidentCountryCode;
            options += '<option value="' + countryInfo[i].ResidentCountryCode + '">' + countryInfo[i].ResidentCountry+ '</option>';
        }
        $(selectBox).append(options);
        $(selectBox).val(selectedItem);
        //give it another class
   }    
});
*/

//fill the station drop down lists
//$(document).ready(function(){

//    var marketCityPairs = $("#searchDivHeaderBody div[@id*='marketCityPair']")
//    $("select[@id*='DropDownListMarketOrigin']",marketCityPairs).each(function(){
//        fillList(this,'');
//    });
//    
//    $("select[@id*='DropDownListMarketDestination']",marketCityPairs).each(function(){
//        fillList(this,'');
//    });
//    
//    highlightMoveOriginCities(marketCityPairs.length, '');
//    highlightMoveDestinationCities(marketCityPairs.length, '');
//});


//copy functions from version 1.3
function AffiliateRoutes_initialize()
{
	var routeCheck = 0;
	try {
		if (affiliateRoutes)
		{
			routeCheck = 1;
		}
	} catch (ex) {}
	if (routeCheck == 0)
	{
		return;
	}
	
	//carrierCode is the shortcut for affiliate partner. e.g. HF, IG
	for( var carrierCode in affiliateRoutes )
	{
		// Add stations/routes if missing
		for( var airportCode in affiliateRoutes[carrierCode] )
		{
			if( !Stations[airportCode] )//if airport doesnt exist in Stations
			{
				if (customStationNames[airportCode])
				{
					//add new airport
					Stations[airportCode] = new Station(airportCode, '', customStationNames[airportCode], true, true, affiliateRoutes[carrierCode][airportCode]);
				}
				else
				{
					Stations[airportCode] = new Station(airportCode, '', airportCode, true, true, affiliateRoutes[carrierCode][airportCode]);
				}
				// Create array of all affiliates
				SortedStations = SortedStations.concat(airportCode);
			}
			else
			{
				//create a deep copy of that array for editing purpose in the for-loop
				//var deepCopyaffiliateRoutes = affiliateRoutes[carrierCode][airportCode].concat(new Array());
				//traverse dest. airports for current partner and current origin e.g. HF->CTA
				for(var i = 0; i < affiliateRoutes[carrierCode][airportCode].length; i++)
				{
					//unshiftStation=true --> add new destination airport to mkts
					var unshiftStation = true;
					//traverse existing dest. airports(TUIfly original and other partners can be here already)
					for(var k = 0; k < Stations[airportCode].mkts.length; k++ )
					{
						// If route is already present in original mkts array, omit affiliate route
						if(Stations[airportCode].mkts[k]==affiliateRoutes[carrierCode][airportCode][i])
						{
							//remove from copy rather from orig-array - orig-array.length should not change!!!
							//deepCopyaffiliateRoutes.splice(i, 1);
							//dont add to mkts - exists already
							unshiftStation = false;
							break;
						}
					}
					if(unshiftStation)
					{
						Stations[airportCode].mkts.unshift(affiliateRoutes[carrierCode][airportCode][i]);
					}
				}
				// swap copies - deepCopyaffiliateRoutes is without TUIfly-routes
				//affiliateRoutes[carrierCode][airportCode] = deepCopyaffiliateRoutes;
			}
		}
	}
	

	/*// sort stations
	var changed = true;
	while (changed) {
		changed = false;
		for( var i=0; i < SortedStations.length-1; i++ ) 
		{
			var code1 = SortedStations[i];
			var name1 = Stations[code1].name.toLowerCase();
			var code2 = SortedStations[i+1];
			var name2 = Stations[code2].name.toLowerCase();
			if(name1 > name2)
			{
				SortedStations[i] = code2;
				SortedStations[i+1] = code1;
				changed = true;
			}
		}
	}*/

	try
	{
		AvailabilityCompactSearchInputViewType_initialize();
	}
	catch (ex)
	{
	}
	try
	{
		ControlGroupSearchView_AvailabilitySearchInputSearchView_initialize();
	}
	catch (ex)
	{
	}
}

function CheckAffiliates()
{
	var routeCheck = 0;
	try {
		if (affiliateRoutes)
		{
			routeCheck = 1;
		}
	} catch (ex) {}
	if (routeCheck == 0)
	{
		return true;
	}
	
	var dropDownOrigin =  applicationJavaScriptHtmlId + "_DropDownListMarketOrigin1";
	var dropDownDestination = applicationJavaScriptHtmlId + "_DropDownListMarketDestination1";
	
	var origin = GetSelectedValue(dropDownOrigin);
	var destination = GetSelectedValue(dropDownDestination);
	
	for( var carrierCode in affiliateRoutes )
	{
		//alert("affiliateRoutes[\"" + carrierCode + "\"][\"" + origin + "\"] : " + affiliateRoutes[carrierCode][origin]);
	//alert("affiliateRoutes[\"" + carrierCode + "\"][\"" + origin + "\"].indexOf(\"" + destination +"\") : " + Array.indexOf(affiliateRoutes[carrierCode][origin], destination));
		//if (affiliateRoutes[carrierCode][origin] && Array.indexOf(affiliateRoutes[carrierCode][origin], destination))
		
		if (affiliateRoutes[carrierCode][origin] && affiliateRoutes[carrierCode][destination])
		{
			for (var i=0; i < affiliateRoutes[carrierCode][origin].length; i++)
			{
				var affiliateDestination = affiliateRoutes[carrierCode][origin][i];
				if (affiliateDestination == destination)
				{
					alert (affiliateConfirmMessages[carrierCode]);
					
					// gather other information
					var roundTrip = (GetMarketStructure() == 'RoundTrip');
					var adult = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListPassengerType_ADT')*1;
					var child = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListPassengerType_CHD')*1; 
					var infant = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListPassengerType_INFANT')*1; 
					var outgoingDate = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListMarketMonth1') + '-' + GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListMarketDay1');
					var incomingDate = '';
					if (roundTrip)
					{
						incomingDate = GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListMarketMonth2') + '-' + GetSelectedValue(applicationJavaScriptHtmlId + '_DropDownListMarketDay2');
					}
					
					var parameter = '';
					if (carrierCode == 'TUIfly')
					{
						parameter += '?AD=J4U';
						parameter += '&culture=' + cultureCode;
						parameter += '&expanded=1';
						parameter += '&__EVENTTARGET=ControlGroupSearchView$AvailabilitySearchInputSearchView$LinkButtonNewSearch';
						parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketDateRange1=2|2';
						parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$RadioButtonMarketStructure=' + (roundTrip?'RoundTrip':'OneWay');
						parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketOrigin1=' + origin;
						parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketDestination1=' + destination;
						parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketDay1=' + outgoingDate.substr(8,2);
						parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketMonth1=' + outgoingDate.substr(0,7);
						parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_ADT=' + adult;
						parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_CDT=' + child;
						parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListPassengerType_INFANT=' + infant;
						if (roundTrip)
						{
							parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketDateRange2=2|2';
							parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketOrigin2=' + destination;
							parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketDestination2=' + origin;
							parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketDay2=' + incomingDate.substr(8,2);
							parameter += '&ControlGroupSearchView$AvailabilitySearchInputSearchView$DropDownListMarketMonth2=' + incomingDate.substr(0,7);
						}
					}
					else if (carrierCode == 'jetairfly') {
						
						if (cultureCode = "fr-FR"){
							parameter += 'fr/';
						}
						else if (cultureCode = "en-GB"){
							parameter += 'en/';
						}
						else{
							parameter += 'en/';
						}
						parameter += '?ow_type=' + (roundTrip?'R':'O');
						parameter += '&oVan=' + origin;
						parameter += '&oDest=' + destination;
						
						parameter += '&oDag=' + outgoingDate.substr(8,2);
						parameter += '&oMaand_Jaar=' + outgoingDate.substr(5,2) + '_' + outgoingDate.substr(0,4);

						if (roundTrip)
						{
							parameter += '&rDag=' + incomingDate.substr(8,2);
							parameter += '&rMaand_Jaar=' + incomingDate.substr(5,2) + '_' + incomingDate.substr(0,4);
					}
				
						parameter += '&Pax=' + adult;
						parameter += '&Child=' + child;
						parameter += '&Infant=' + infant;
						
						
					}
				//document.write(affiliateURLs[carrierCode] + parameter)
				var partnerLink = affiliateURLs[carrierCode] + parameter;				
				top.location.href =  partnerLink;
				
					return false;
				}
			}
		}
	}
	
	return true;
}

function RegisterAffiliates()
{
	var originalOnLoadAffiliates = window.onload;
	window.onload = function()
  {
  	if (originalOnLoadAffiliates)
		{
			originalOnLoadAffiliates();
		}
		AffiliateRoutes_initialize();
	}
}

RegisterAffiliates();

// custom S2
// end custom S2
//end copy

var jsLoaded = true;