/*========================================================================================

$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)
{
	$('#marketCityPair_' + mktIx).css('display', disp);
	HideShowMarketDate(mktIx, disp);
}

function HideShowMarketDate(mktIx, disp)
{
	$('#marketDate_' + mktIx).css('display', disp);
}
function marketChangeCheckChanged(checkBox, marketIndex)
{
    DisableEnableMarket(marketIndex, !checkBox.checked);
}
function InitializeChange(eventArgs)
{
    DisableEnableMarket(1, true);
    DisableEnableMarket(2, true);

}
function DisableEnableMarket(mktIx, disableStatus)
{
	$('#AVAILABILITYSEARCHINPUT_Market' + mktIx + 'Block')
	.find('input')
		.attr('disabled', disableStatus)
	.end()
	.find('select')
		.attr('disabled', disableStatus)
	.end();

	// Flughafen-Dropdownlisten deaktivieren
	var picker = $('#datePickerFlight_Market' + mktIx)
	picker.attr('disabled', disableStatus);
	if(disableStatus) {
		picker.addClass("disabled")
	} else {
		picker.removeClass("disabled")
	}
}
// S2-Anpassung, Aktivieren der input-Boxen im Change-Prozess
function EnableMarkets()
{
	$('#AVAILABILITYSEARCHINPUT_Market' + 1 + 'Block').find('input').attr('disabled', false).removeClass("disabled").end().find('select').attr('disabled', false).end();
	$('#AVAILABILITYSEARCHINPUT_Market' + 2 + 'Block').find('input').attr('disabled', false).removeClass("disabled").end().find('select').attr('disabled', false).end();
}
// Ende

function SynchronizeHiddenFields()
{
	// Synchronize adult fields
	var adultCount = $("#"+applicationJavaScriptHtmlId+"_DropDownListNewPassengerType_ADT").val();
	$("#"+applicationJavaScriptHtmlId+"_DropDownListPassengerType_ADT").val(adultCount);
}

function AvailabilitySearchValues_Validate(validateEventArgs)
{
	SynchronizeHiddenFields();

	if (AreDateCheckBoxesInValidState() && CheckCities() && CheckDates() && CheckPassengers() && CheckPaxCount() && s2.tuifly.promo.kidsflyfree.validate())
	{
		return true;
	}

	return false;
}

function AreDateCheckBoxesInValidState()
{
	var dateCheckBox1 = GetDateCheckBox('CheckBoxChangeMarket',1);
	var dateCheckBox2 = GetDateCheckBox('CheckBoxChangeMarket',2);
	// if no one checkbox exists, than the proof is not required
	if (!(dateCheckBox1 && dateCheckBox2))
		return true;
	// if one checkbox is checked, than state is valid
	if ((dateCheckBox1.checked) || (dateCheckBox2.checked))
		return true;
	// date checkboxes exists, but are not checked, this is valid state.
	s2.tuifly.widget.dialog.alert(noDateSpecified);
	return false;
}

function GetDateCheckBox(checkBox, mktIx)
{
	var dateCheckBox = document['SkySales'][applicationJavaScriptHtmlId + '_' + checkBox+ '_' + mktIx];
	return dateCheckBox;
}

function ValidatePassengerCountValue(c) {
	c = parseInt(c, 10);
	if(!c){ c = 0 }
	return c;
}

function GetAdultCount(){
	return ValidatePassengerCountValue($("#"+applicationJavaScriptHtmlId+"_DropDownListNewPassengerType_ADT").val());
}

function GetChildCount(){
	return ValidatePassengerCountValue($("#"+applicationJavaScriptHtmlId+"_DropDownListPassengerType_CHD").val());
}

function GetChildDiscountCount(){
	return ValidatePassengerCountValue($("#"+applicationJavaScriptHtmlId+"_DropDownListPassengerType_CHDD").val());
}

function GetInfantCount(){
	return ValidatePassengerCountValue($("#"+applicationJavaScriptHtmlId+"_DropDownListPassengerType_INFANT").val());
}

function GetOriginValue() {
	var ds = document['SkySales'];
	return GetValue(ds[applicationJavaScriptHtmlId+'_DropDownListMarketOrigin1']);
}

function GetDestinationValue() {
	var ds = document['SkySales'];
	return GetValue(ds[applicationJavaScriptHtmlId+'_DropDownListMarketDestination1']);
}

function GetMonthYearDepart(){
	return GetMonthYear(1)
}

function GetMonthYearReturning(){
	return GetMonthYear(2)
}

function GetMonthDepart(){
	var arr = GetMonthYearAsList(GetMonthYearDepart());
	return arr[1]
}

function GetMonthReturning(){
	var arr = GetMonthYearAsList(GetMonthYearReturning());
	return arr[1]
}

function GetYearDepart(){
	var arr = GetMonthYearAsList(GetMonthYearDepart());
	return arr[0]
}

function GetYearReturning(){
	var arr = GetMonthYearAsList(GetMonthYearReturning());
	return arr[0]
}

function GetMonthYearAsList(monthYear){
	return monthYear.split("-");
}

function GetDayDepart(){
	return GetDay(1)
}

function GetDayReturning(){
	return GetDay(2)
}

function GetMonthYear(index){
	var ds = document['SkySales'];
	return GetValue(ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth' + index]);
}

function GetDay(index){
	var ds = document['SkySales'];
	return GetValue(ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay' + index]);
}

function CheckPassengers()
{
	var tooManyInfants = localizedTextTooManyInfants;

	var adultCount = GetAdultCount();
	var infantCount = GetInfantCount();
	var chddCount = GetChildDiscountCount();
	var chdCount = GetChildCount();

	if (infantCount > adultCount)
	{
		s2.tuifly.widget.dialog.alert(tooManyInfants);
		return false;
	}

	// UAM check
	var adultOnFlight = adultCount > 0;
	var minorOnFlight = (infantCount > 0 || chddCount > 0 || chdCount > 0);

	if (!adultOnFlight && minorOnFlight) {
		s2.tuifly.widget.dialog.alert(message['UAM']); // message from culture-XML
		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['DropDownListPassengerType_ADT'] = state;
	ElementsState['DropDownListPassengerType_CHD'] = state;
	ElementsState['DropDownListPassengerType_CHDD'] = state;
	ElementsState['DropDownListPassengerType_INF'] = 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 = $("#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))
		{
			s2.tuifly.widget.dialog.alert(localizedTextInvalidDatePre + mktDay + localizedTextInvalidDateMid + mktMonthText + localizedTextInvalidDatePost);
			return false;
		}

		// don't check date if liftstatus is not default
		if(MarketLiftStatus[mktIx] == null)
		{
		    MarketLiftStatus[mktIx] = "Default";
		}

		if (mktDate < dateToCompare && MarketLiftStatus[mktIx]== applicationLiftStatus)
		{
			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;
					s2.tuifly.widget.dialog.alert(msg);
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options.selectedIndex = dayToday - 1;
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options.selectedIndex = findIndexByValue(ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx],monthYearValue);

					$(ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx]).change()
				}
				else
					s2.tuifly.widget.dialog.alert(msg);
				return false;
			}
			else
			{
				var msg=localizedTextEarlierDatePre;
				if (MarketAction[mktIx]=='New' || MarketAction[mktIx]=='Change')
				{
					msg=msg+localizedTextEarlierDatePost;
					s2.tuifly.widget.dialog.alert(msg);
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx].options.selectedIndex = parseInt(ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+(mktIx-1)].options.selectedIndex, 10) + mkt2Lines;
					ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+mktIx].options.selectedIndex = parseInt(ds[applicationJavaScriptHtmlId + '_DropDownListMarketMonth'+(mktIx-1)].options.selectedIndex, 10) + mkt2Lines;

					$(ds[applicationJavaScriptHtmlId + '_DropDownListMarketDay'+mktIx]).change()
				}
				else
					s2.tuifly.widget.dialog.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 (mktDate == dateToCompare)
		{
			var todayDateMsg = localizedTextTodaysDateMessage;
			if (todayDateMsg)
			{
				alert(todayDateMsg);
			}
		}
		*/
	break;
	}

	return true;
}

var tempEventArgs;
var retryCount = 0;

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);
			}
		}

		var skin = s2.tuifly.util.Skin.get().toString();

		if (paxDropdownRendered && paxCount == 0)
		{
			s2.tuifly.widget.dialog.alert(localizedTextLessThanOnePassenger);
			return false;
		}
		else if (skin != 'HLXPepAgent' && paxCount > applicationBookingMaxPassengers)// Pep-Pruefung wird in AvailabilitySearchInput_Default gemacht "AvailabilitySearchInput_Validate()"
		{
			var text = localizedTextExceedsMaxPaxAllowed;
			text = text.replace(/({#})/g, applicationBookingMaxPassengers);
			s2.tuifly.widget.dialog.confirm(text, {
				dialogClass: "confirmBox confirmBoxExceedsMaxPaxAllowed",
				okButtonText: localizedTextExceedsMaxPaxAllowedOkButton,
				cancelButtonText: localizedTextExceedsMaxPaxAllowedCancelButton,
				okCallback: function () {location.href="/BookGroup.aspx";},
				cancelCallback: function () {s2.tuifly.widget.dialog.divLayerClose();}
			});
			return false;
		}
	}

	return true;
}

/*
* 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;
					if (ds[applicationJavaScriptHtmlId + '_DropDownListMarketOrigin' + mktIx].selectedIndex == 0)
					{
						if ( selected=='TripPlanner' && mktIx>1)
						{
							// an empty origin signals the end of the requested market
							numMarketsToValidate = mktIx-1;
							numDatesToValidate = mktIx-1;
							break;
						}
						else
						{
							s2.tuifly.widget.dialog.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;
					if (ds[applicationJavaScriptHtmlId + '_DropDownListMarketDestination' + mktIx].selectedIndex == 0)
					{
						s2.tuifly.widget.dialog.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
						{
							s2.tuifly.widget.dialog.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))
					{
						s2.tuifly.widget.dialog.alert(localizedMissingDest);
						return false;
					}

					if (stations[i].value.toUpperCase() == stations[i-1].value.toUpperCase())
					{
						s2.tuifly.widget.dialog.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 (!ok)
		{
			s2.tuifly.widget.dialog.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 = window["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 = window["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 = window["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;
	            }
	        }
	    }
	}
}

AvailabilitySearchInput = new Object();

function pad(number,length) {
        var str = "" + number;
        while (str.length < length)
          str = '0' + str;
        return str;
    }


function ReturnDateDisplay()
{   
      if(document.getElementById('searchLanding')) {
        AvailabilitySearchInput.ToggleMarketOptions('slow');
      }
      else {   
        AvailabilitySearchInput.ToggleMarketOptions();
      }
}

AvailabilitySearchInput.ToggleMarketOptions = function(speed){
    GetMarketStructure();
    var travelOptionContainer = $('#travelOptions');
    var selectedTravelOption = $(':checked', $(travelOptionContainer));
    if(selectedTravelOption.val() == 'RoundTrip')
    {
        $('#marketCityPair_2').hide();
        $('#marketDate_2').show(speed);
    }
    else if(selectedTravelOption.val() == 'OpenJaw')
    {
        $('#marketCityPair_2').show();
        $('#marketDate_2').show(speed);
    }
    else{
        $('input[value=OneWay]', travelOptionContainer).select();
        $('#marketCityPair_2').hide();
        $('#marketDate_2').hide(speed);
    }
};

//populate the stations
$(document).ready(function(){
    if(!document.getElementById("#availabilitySearchInput") || window.applicationNumberOfMarketsToOffer != null) return // s2: execute only on pages with a search control
    initMacs();
});

//hide the car search onload
$(document).ready(function(){
    if(!document.getElementById("#availabilitySearchInput")) return // s2: execute only on pages with a search control
    $('#aosAvailabilitySearchDivBody').hide();
    $('#aosAvailbilitySearchDivHeader').hide();
});

var mode = 'initial';

AvailabilitySearchInput.ToggleAvailabilitySearchForm = function(){

                $('#searchDivHeader').toggle();
                $('#searchDivHeaderBody').toggle();
                $('#SearchDivHeaderFooter').toggle();

                //hide the ssr div to avoid confusion
                $('#ssrSearchDivHeader').toggle();
                $('#ssrSearchDivBody').toggle();
                $('#ssrSearchDivFooter').toggle();

                $('#aosAvailabilitySearchDivBody').toggle();
                $('#aosAvailbilitySearchDivFooter').toggle();
                $('#aosAvailbilitySearchDivHeader').toggle();
};

/*
// s2 Not used
$(document).ready(function(){

    if(!document.getElementById("#availabilitySearchInput")) return // s2: execute only on pages with a search control
    //check to see if we recieved any parameters from AOS for car availability

    if($("#aosAvailabilitySearchDivBody :input:visible[type!='submit']").size() != 0)
    {
        $("#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';
            }
        });

        $("#flowType input[id*=_flowSelectFlight]").click(function(){
            if(mode=='swapped'){
                //put the div below the search header
                $('#flowType').remove().insertBefore($('#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)
        $("#flowType input[id$=_flowSelectFlight]").attr('checked','checked');
        //hide flowtype node if we didn't get any query parameters for cars
        $('#flowType').hide();
    }
});*/


$(document).ready(function(){
    if(!document.getElementById("#availabilitySearchInput")) return // s2: execute only on pages with a search control
    AvailabilitySearchInput.ToggleMarketOptions();
    $("#travelOptions > input").click(function(){
        AvailabilitySearchInput.ToggleMarketOptions();
    });
});


//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, '');
//});

var jsLoaded = true;



/*-----------------------------------------------------------------------------
CustomFunctions added by SinnerSchrader
-----------------------------------------------------------------------------*/

function showFlightSearch()
{
	// do nothing, always visible
}

/*-----------------------------------------------------------------------------
CustomFunctions added by SinnerSchrader
African routes
-----------------------------------------------------------------------------*/

function africanRouteSelected()
{
	var listOriginValue = GetOriginValue();
	var listDestinationValue = GetDestinationValue();

	if(africanRoutes)
	{
		if(africanRoutes[listOriginValue])
		{
			for( var k=0; k < africanRoutes[listOriginValue].length; k++ )
			{
				if(africanRoutes[listOriginValue][k] == listDestinationValue )
				{
					return true;
				}
			}
		}

		if (africanRoutes[listDestinationValue])
		{
			for( var k=0; k < africanRoutes[listDestinationValue].length; k++ )
			{
				if(africanRoutes[listDestinationValue][k] == listOriginValue )
				{
					return true;
				}
			}
		}
	}

	return false;
}


var AFRICA_NOTE_DISPLAYED = false;

function validateAfricanAirports()
{
	if(africanRouteSelected())
	{
		var ds = document['SkySales'];
		var origin = GetValue(ds[applicationJavaScriptHtmlId+'_DropDownListMarketOrigin1']);
		
		if(jQuery.inArray(origin, notAllowedAfricanDeparture) != -1)
		{
			s2.tuifly.widget.dialog.alert(message["africanAlert"]);
			return false;
		}

		if(!AFRICA_NOTE_DISPLAYED) {
			var callback = function () {
				AFRICA_NOTE_DISPLAYED = true;
				s2.tuifly.widget.submittableForm.clickButton( $("#flugsucheButton a") );
			};
			s2.tuifly.widget.dialog.alert(message["africanAlert"], { okCallback: callback });
			return false;
		}

		return true;
	}

	return true;
}


// Removes return flights of African routes
// Example: The host defines the flights FRA-HRG and HRG-FRA
// In 'africanRoutes' there's the route FRA-HRG
// => It's not allowed to book HRG-FRA (with optional FRA-HRG as return flight),
// so remove this route
function removeAfricanRoutes()
{
	//alert("removeAfricanRoutes " +  SortedStations);

	if(SortedStations == null || SortedStations.length<=0)
		return;

	for (i = 0; i < SortedStations.length; i++)
	{
		currentStation = Stations[SortedStations[i]];
		if(currentStation && currentStation.mkts)
		{
			for (k = 0; k < currentStation.mkts.length; k++)
			{
				currentStationMarket = currentStation.mkts[k];
				if (africanRoutes[currentStationMarket])
				{
					for (l = 0; l < africanRoutes[currentStationMarket].length; l++)
					{
						if (africanRoutes[currentStationMarket][l] == currentStation.code)
						{
							currentStation.mkts.splice(k,1);
							k--;
							break;
						}
					}
				}
			}
		}
	}
	//alert("removeAfricanRoutes - ende");
}
