var oWaitingImages = new Array("countryWait","fromWait","toWait");

function FlightSearchControl(control, highlightedAirports, displayText, defaultText) 
{
	this.control = control;
	this.defaultText = defaultText;
	
	// remember the highlighed airports and display text
	this.highlightedAirports = this.InitialiseHighlightedAirports(highlightedAirports);
	this.displayText = displayText;

	this.Initialise();

	
}


FlightSearchControl.prototype.Initialise = function()
{
	this.lstCountry = $("select.FromCountryList", this.control)[0];
	$(this.lstCountry).change(CallInContext(this, this.ChangeCountry));

	this.lstDepartureAirports = $("select.FromList", this.control)[0];
	$(this.lstDepartureAirports).change(CallInContext(this, this.ChangeDepartureAirport));

	this.lstArrivalAirports = $("select.ToList", this.control)[0];
	$(this.lstArrivalAirports).change(CallInContext(this, this.ChangeArrivalAirport));

	this.lstAdults = $("#" + this.control.id + "_Adults")[0];
	this.lstChildren = $("#" + this.control.id + "_Children")[0];
	this.lstInfants = $("#" + this.control.id + "_Infants")[0];
	this.lstCabin = $("#" + this.control.id + "_FareType")[0];

    this.Cabins = null;
    this.CabinNames = null;

    this.lstCRBookingType = $("#" + this.control.id + "_CompanyRewardsPurpose")[0];
    this.lstCRCompany = $("#" + this.control.id + "_CompanyRewardsCompany")[0];

	// get the label for the children
	this.lstChildrenLabel = $(this.lstChildren).prev("label")[0];
	this.lstChildrenLabelInitialHTML = this.lstChildrenLabel.innerHTML;

	$(this.lstAdults).change(CallInContext(this, this.OnPassengerNumberChange));
	$(this.lstChildren).change(CallInContext(this, this.OnPassengerNumberChange));
	$(this.lstInfants).change(CallInContext(this, this.OnPassengerNumberChange));

	this.btnSearch = $("input.Search,button.Search", this.control);
	this.btnSearch.click(CallInContext(this, this.OnSearchClick));

	var textBoxes = $("input:text", this.control);
	this.outboundDate = textBoxes[0];
	this.returnDate = textBoxes[1];
	this.promoCode = textBoxes[2];

    var oDate = new Date();
    oDate.setDate(oDate.getDate() + 1);
    this.outboundDate.value = oDate.localeFormat("ddd, dd MMM yyyy");
    oDate.setDate(oDate.getDate() + 1);
    this.returnDate.value = oDate.localeFormat("ddd, dd MMM yyyy");

	//$(this.promoCode).change(CallInContext(this, this.OnPromoCodeChanged));
	$(this.outboundDate).change(CallInContext(this, this.OnDateChange));
	$(this.returnDate).change(CallInContext(this, this.OnDateChange));
    //MyDatesAreFlexible
	//var checkBoxes = $(".OneWayOnly input:checkbox", this.control);
	
	this.oneWayOnly = $("#" + this.control.id + "_OneWayOnly")[0]; //checkBoxes[0];

	// revalidate the dates when the 'one way only' button is checked
	$(this.oneWayOnly).click(CallInContext(this, this.OnDateChange));


	//this.flexible = $("#" + this.control.id + "_Flexible");// checkBoxes[1];
	this.flexible =  $("#" + this.control.id + "_Flexible")[0];//checkBoxes[1];

	// handle the changing of the one way only checkbox
	$(this.oneWayOnly).click(CallInContext(this, this.OnOneWayOnlyClick));

	this.returnDate.disabled = this.oneWayOnly.checked ? "disabled" : "";

	// make sure the country is up to date
	this.ChangeCountry();

	// get the group booking controls
	this.groupBookingAnchor = $("a.GroupBooking", this.control)[0];
	this.originalPassengerText = this.groupBookingAnchor.innerHTML;
	this.originalPassengerGroupNumber = "10";

	// get the previous search control
	this.previousSearchControl = $("div.PreviousSearchControl", this.control)[0];

	// get the messaeg placeholder
	this.messagePlaceholder = $("div.MessagePlaceholder")[0];

	// remember the current message
	this.originalErrorMessage = this.messagePlaceholder.innerHTML;

	// update the promocodeValid flag
	//this.OnPromoCodeChanged();

};

FlightSearchControl.prototype.OnSearchClick = function(eventObject)
{
	if (this.Validate())
	{
		// get the form that created the event
		var form = $(eventObject.target)[0];

		// is this a BMIBaby
		if (this.bmiBabySelected)
		{
			this.HandlePostToBmiBaby(form);
		}
		else
		{
			// is it a group booking
			// get the total number of passengers - not including infants
			var totalPassengers = parseInt(this.lstAdults.value, 10) + parseInt(this.lstChildren.value, 10);

			if (totalPassengers > this.maxPassengers)
			{
				// redirect to the group booking url
				window.location = this.groupBookingAnchor.href;

				// don't submit
				eventObject.preventDefault();
			}
			else
			{
			    
			    this.HandlePostToBmiBook(form);

			}
		}
	}
	else
	{
		// don't submit
		eventObject.preventDefault();
	}
};

FlightSearchControl.prototype.OnOneWayOnlyClick = function(eventObject)
{
	this.returnDate.disabled = this.oneWayOnly.checked ? "disabled" : "";
};

FlightSearchControl.prototype.ChangeCountry = function(eventObject)
{
	// get the country
	var countryCode = this.lstCountry.value;
    Wait('true',0);
    this.DisableDropdowns();
	// get the departure airports
	ExecuteJsonRequest(null, "FlightSearchFunction=GetDepartureAirports&CountryCode=" + countryCode, this, this.HandleDepartureAirports, null);
};


FlightSearchControl.prototype.HandleDepartureAirports = function(response)
{

	// get the current airport
	var currentCode = this.lstDepartureAirports.value;
	var currentCodeValid = false;

	this.lstDepartureAirports.options.length = 0;

	// add the please select line
	this.lstDepartureAirports.options.add(new Option(this.displayText["PleaseSelect"], 0));
	this.lstDepartureAirports.options.add(new Option(this.displayText["SeparatorLine"], 0));

	//	response.sort(this.SortByName);
	
	// create the airport disctionary
	var airportDictionary = new Object();
	for (var iAirport = 0; iAirport < response.length; iAirport++)
	{
		var airport = response[iAirport];
		airportDictionary[airport.Code] = airport.Name;
	}

	// add any special airports
	this.AddHighlighedAirports(this.lstDepartureAirports, airportDictionary);
	
	for (iAirport = 0; iAirport < response.length; iAirport++)
	{
		airport = response[iAirport];

		var option = new Option(airport.Name, airport.Code);

		this.lstDepartureAirports.options.add(option);

		currentCodeValid = currentCodeValid || (airport.Code == currentCode);
	}

	// set the previous value if it's valid
	if (currentCodeValid)
	{
		// set the value
		this.lstDepartureAirports.value = currentCode;
	}
	else if (response.length == 1)
	{
		this.lstDepartureAirports.value = response[0].Code;
	}

	// make sure the arrival is up to date
	if (response.length > 0)
	{
		this.ChangeDepartureAirport();
	}
	else
	{
		// there isn't a departure airport, so there can't be an arrival one
		this.lstArrivalAirports.options.length = 0;
	}
	Wait('false',0);
	this.EnableDropdowns();


};


FlightSearchControl.prototype.ChangeDepartureAirport = function(eventObject)
{
    
    Wait('true',1);
    this.DisableDropdowns();

	// get the airport code
	var fromCode = this.lstDepartureAirports.value;

	if (fromCode.length == 3)
	{
		// get the departure airports
		ExecuteJsonRequest(null, "FlightSearchFunction=GetArrivalAirports&FromCode=" + fromCode, this, this.HandleArrivalAirports, null);
	}
	else if (fromCode == -1)
	{
		// just do a change country to reset the departure airports
		this.ChangeCountry();
	}else
	{
	    Wait('false',1);
        this.EnableDropdowns();
        this.SetSearchButtonState(false);

	}
};


FlightSearchControl.prototype.HandleArrivalAirports = function(response)
{

	var currentCode = this.lstArrivalAirports.value;
	var currentCodeValid = false;

	this.lstArrivalAirports.options.length = 0;

	// add the please select line
	this.lstArrivalAirports.options.add(new Option(this.displayText["PleaseSelect"], 0));
	this.lstArrivalAirports.options.add(new Option(this.displayText["SeparatorLine"], 0));


	//	response.sort(this.SortByTo);

	// create the airport disctionary
	var airportDictionary = new Object();
	for (var iAirport = 0; iAirport < response.length; iAirport++)
	{
		var airport = response[iAirport].To;
		airportDictionary[airport.Code] = airport.Name;
	}

	// add any special airports
	this.AddHighlighedAirports(this.lstArrivalAirports, airportDictionary);

	var selectedRoute = null;

	for (iAirport = 0; iAirport < response.length; iAirport++)
	{
		airport = response[iAirport].To;

		var option = new Option(airport.Name, airport.Code);

		this.lstArrivalAirports.options.add(option);

		if (airport.Code == currentCode)
		{
			selectedRoute = response[iAirport];
			currentCodeValid = true;
		}
	}

	if (currentCodeValid)
	{
		// set the value
		this.lstArrivalAirports.value = currentCode;
	}
	else if (response.length == 1)
	{
		this.lstArrivalAirports.value = response[0].To;
	}
	
    Wait('false',1);
    this.EnableDropdowns();


	// update the routes (might be null)
	this.UpdateControlsFromRoute(selectedRoute);
};

FlightSearchControl.prototype.ChangeArrivalAirport = function(eventObject)
{
    Wait('true',2);
    this.DisableDropdowns();

	// get the country
	var countryCode = this.lstCountry.value;

	// get the airport code
	var toCode = this.lstArrivalAirports.value;

	if (toCode.length == 3)
	{
		// get the departure airports
		ExecuteJsonRequest(null, "FlightSearchFunction=GetDepartureAirportsGivenArrival&ToCode=" + toCode + "&CountryCode=" + countryCode, this, this.HandleDepartureAirportsGivenArrival, null);
	}
	else
	{
        Wait('false', 2);
        this.EnableDropdowns();

        this.SetSearchButtonState(false);
	}
};

FlightSearchControl.prototype.HandleDepartureAirportsGivenArrival = function(response)
{
	var currentCode = this.lstDepartureAirports.value;
	var currentCodeValid = false;

	this.lstDepartureAirports.options.length = 0;

	//	response.sort(this.SortByFrom);
	// add the please select line
	this.lstDepartureAirports.options.add(new Option(this.displayText["PleaseSelect"], 0));

	// add the 'select all airports in ' country
	var countryName = this.lstCountry.options[this.lstCountry.selectedIndex].text;
	this.lstDepartureAirports.options.add(new Option(this.displayText["ShowAll"].replace("{0}", countryName), -1));

	this.lstDepartureAirports.options.add(new Option(this.displayText["SeparatorLine"], 0));

	// create the airport disctionary
	var airportDictionary = new Object();
	for (var iAirport = 0; iAirport < response.length; iAirport++)
	{
		var airport = response[iAirport].From;
		airportDictionary[airport.Code] = airport.Name;
	}

	// add any special airports
	this.AddHighlighedAirports(this.lstDepartureAirports, airportDictionary);

	var selectedRoute = null;

	for (iAirport = 0; iAirport < response.length; iAirport++)
	{
		airport = response[iAirport].From;

		var option = new Option(airport.Name, airport.Code);

		this.lstDepartureAirports.options.add(option);

		if (airport.Code == currentCode)
		{
			selectedRoute = response[iAirport];
			currentCodeValid = true;
		}
	}

	if (currentCodeValid)
	{
		// set the value
		this.lstDepartureAirports.value = currentCode;
	}
    Wait('false',2);
        this.EnableDropdowns();


	// update the routes (might be null)
	this.UpdateControlsFromRoute(selectedRoute);
};

FlightSearchControl.prototype.SetMaxPassengers = function(maxPassengers)
{

	this.groupBookingAnchor.innerHTML = this.originalPassengerText.replace(this.originalPassengerGroupNumber, maxPassengers.toString());

	SetSelectNumbers(this.lstAdults, 1, maxPassengers, this.lstAdults.value);
	if (maxPassengers > 4)
	{
		// add the pluss on the end of the adults
		this.lstAdults.options[this.lstAdults.options.length - 1].text += "+";

		$(this.groupBookingAnchor).css("visibility", "visible");
		if (maxPassengers == 10)
		{
			this.maxPassengers = 9;
			this.groupBookingAnchor.href = this.displayText["BmiGroupBooking"];
		}
		else if (maxPassengers == 15)
		{
			this.maxPassengers = 14;
			this.groupBookingAnchor.href = this.displayText["BabyGroupBooking"];
		}
	}
	else
	{
		$(this.groupBookingAnchor).css("visibility", "hidden");
		this.maxPassengers = 4;
	}

	SetSelectNumbers(this.lstChildren, 0, maxPassengers - 1, this.lstChildren.value);
	SetSelectNumbers(this.lstInfants, 0, this.lstAdults.value, this.lstInfants.value);
};

FlightSearchControl.prototype.SetGroupBookingHref = function(hRef)
{
	this.groupBookingAnchor.href = hRef;
};

FlightSearchControl.prototype.HideFareType = function(hide)
{
	if (hide === undefined || hide)
	{
		$("div.FareType", this.control).css("visibility", "hidden");
	}
	else
	{
		$("div.FareType", this.control).css("visibility", "visible");
	}
};

FlightSearchControl.prototype.InitialiseHighlightedAirports = function(highlightedAirports)
{
	var highlightedAirportsDictionary = new Object();

	// split on #
	var countries = highlightedAirports.split("#");

	// for each country
	for (var iCountry = 0; iCountry < countries.length; iCountry++)
	{
		// split on |
		var splitCountry = countries[iCountry].split("|");

		// for the airports list
		// split on , and add to the dictionary of highlighted airports
		highlightedAirportsDictionary[splitCountry[0]] = splitCountry[1].split(",");
	}

	return highlightedAirportsDictionary;
};

FlightSearchControl.prototype.AddHighlighedAirports = function(listbox, airportDictionary)
{
	// get the country
	var countryCode = this.lstCountry.value;

	// get the list of highlighted airpotrs for this country
	var highlightedAirports = this.highlightedAirports[countryCode];

	// if we have a list
	if (highlightedAirports)
	{
		var bSpearatorRequired = false;

		// for each special airport
		for (var iHighlightedAirport = 0; iHighlightedAirport < highlightedAirports.length; iHighlightedAirport++)
		{
			// see if the name is in the dictionary of airports returned
			var airport = airportDictionary[highlightedAirports[iHighlightedAirport]];
			if (airport)
			{
				// if it is, add it to the list of airports
				listbox.options.add(new Option(airport, highlightedAirports[iHighlightedAirport]));

				// and add a separator
				bSpearatorRequired = true;
			}
		}

		if (bSpearatorRequired)
		{
			listbox.options.add(new Option(this.displayText["SeparatorLine"], 0));
		}
	}
};

FlightSearchControl.prototype.Validate = function()
{
    var bValid = true;

    // show the default message (the route message returned from the server)
    this.UpdateMessage(this.selectedRoute ? this.selectedRoute.Message : null);

    // Disable the getFlights button if no departure airport is selected.
    if (this.lstDepartureAirports.value.length != 3) {
        this.SetSearchButtonState(false);
        return false;
    }

    // Disable the getFlights button if no arrival airport is selected.
    if (this.lstArrivalAirports.value.length != 3) {
        this.SetSearchButtonState(false);
        return false;
    }

    if (!this.selectedRoute) {
        // disable the getFlights button
        this.SetSearchButtonState(false);
        return false;
    }
    else {
        if (this.selectedRoute.IsBookableOnline) {
            // enable the getFlights button
            this.SetSearchButtonState(true);
        }
        else {
            this.SetSearchButtonState(false);
            this.UpdateMessage(this.displayText["NotBookableOnline"]);
            return false;
        }
    }

    // valid so far
    bValid = this.ValidateDates();

	if (bValid)
	{
//		// if everything's OK so far
//		// and we've got a promo code - and we don't know if it's valid
//		if (this.promoCode.value.length > 0 && this.promocodeValid === null && this.promoCode.value != this.defaultText)
//		{
//			//// check the promocode
//			//this.CheckPromoCode();
//			// bValid = false;
//		}
//		else
//		{
//			// bValid = this.promocodeValid;
//			if (!this.promocodeValid)
//			{
//				this.UpdateMessage(this.displayText["PromocodeInvalid"]);
//			}
//		}
	}

    // set the search button state
    this.SetSearchButtonState(bValid);

	return bValid;
};


FlightSearchControl.prototype.ValidateDates = function()
{
	var bValid = true;

	// parse the dates
	this.parsedOutboundDate = Date.parseLocale(this.outboundDate.value, this.displayText["DateFormatString"]);
	this.parsedReturnDate = Date.parseLocale(this.returnDate.value, this.displayText["DateFormatString"]);

	if (this.parsedOutboundDate === null)
	{
		// only show the message if it's not empty
		if (this.outboundDate.value.length !== 0)
		{
			this.UpdateMessage(this.displayText["OutboundDateInvalid"], true);
		}
		bValid = false;
	}
	else if (!this.oneWayOnly.checked)
	{
		if (this.parsedReturnDate === null)
		{
			// only show the message if it's not empty
			if (this.returnDate.value.length !== 0)
			{
				this.UpdateMessage(this.displayText["ReturnDateInvalid"], true);
			}
			bValid = false;
		}
		else if (this.parsedReturnDate < this.parsedOutboundDate)
		{
			this.UpdateMessage(this.displayText["ReturnDateBeforeOutward"], true);
			bValid = false;
		}
	}

	return bValid;
};


FlightSearchControl.prototype.UpdateControlsFromRoute = function(route)
{
	this.selectedRoute = route;
    Wait('true',1);
    Wait('true',2);
    this.DisableDropdowns();

	if (route)
	{
		this.UpdateCabin(route.Cabins);

		// remember the message
		this.routeMessage = route.Message;
		this.UpdateMessage(this.routeMessage);

		this.bmiBabySelected = route.IsBmiBaby;

		if (route.IsBmiBaby)
		{
			SetInnerHtml(this.lstChildrenLabel, this.lstChildrenLabelInitialHTML.replace("2-11", "2-13"));

			this.HideFareType(true);

			// the maximum is 15 passengers
			this.SetMaxPassengers(15);

			// hide the cabin
			// set the child ages to 2-13
		}
		else if (route.IsRegional)
		{
			SetInnerHtml(this.lstChildrenLabel, this.lstChildrenLabelInitialHTML);

			this.HideFareType(true);

			// the maximum is 10 passengers
			this.SetMaxPassengers(10);
		}
		else if (route.IsCodeshare)
		{
			SetInnerHtml(this.lstChildrenLabel, this.lstChildrenLabelInitialHTML);

			this.HideFareType(false);

			this.SetMaxPassengers(4);
			this.OnPassengerNumberChange();
		}
		else
		{
			SetInnerHtml(this.lstChildrenLabel, this.lstChildrenLabelInitialHTML);

			this.HideFareType(false);

			// a normal BMI flight
			// the maximum is 10 passengers
			this.SetMaxPassengers(10);

			// show the cabin
			// set the child ages to 2-11
		}
	}
	else
	{
		// the maximum is 10 passengers
		this.SetMaxPassengers(10);
	}
    Wait('false',1);
    Wait('false',2);
    this.EnableDropdowns();

	 this.Validate();
};

FlightSearchControl.prototype.OnPromoCodeChanged = function(eventObject)
{
    if (this.promoCode.value.length === 0 || this.promoCode.value == this.defaultText)
	{
		// an empty promo code is alway valid
		this.promocodeValid = true;
	}
	else
	{
		// we don't know whether it's valid
		this.promocodeValid = null;
	}
	
	this.Validate();
};



FlightSearchControl.prototype.CheckPromoCode = function()
{
	var strRequest = "Adults=" + this.lstAdults.value + 
					"&Children=" + this.lstChildren.value + 
					"&Infants=" + this.lstInfants.value + 
					"&FromCode=" + this.lstDepartureAirports.value +
					"&ToCode=" + this.lstArrivalAirports.value +
					"&OutboundDate=" + this.parsedOutboundDate.format("yyyyMMdd") +
					(!this.oneWayOnly.checked ? "&ReturnDate=" + this.parsedReturnDate.format("yyyyMMdd") : "") +
					"&FareType=" + this.lstCabin.value + 
					"&PromoCode=" + this.promoCode.value;

	// find ou whether the promo code is valid
	ExecuteJsonRequest(null, "FlightSearchFunction=CheckPromoCode&" + strRequest, this, this.HandleCheckPromoCode, null);
};



FlightSearchControl.prototype.HandleCheckPromoCode = function(isValid)
{
	this.promocodeValid = isValid;
	
	this.Validate();
};

FlightSearchControl.prototype.UpdateMessage = function(message, error)
{
	// clear the current div
	DeleteChildren(this.messagePlaceholder);

	if (message)
	{
		// create a div
		// set the inner HTML of the created div
		var newDiv = document.createElement("div");

		newDiv.className = (error ? "MessageContentError" : "MessageContentInfo");

		SetInnerHtml(newDiv, message);

		// add the div to the DOM
		this.messagePlaceholder.appendChild(newDiv);
	}
	else if (this.originalErrorMessage != null)
	{
		// show the original message
		SetInnerHtml(this.messagePlaceholder, this.originalErrorMessage);
	}
};


FlightSearchControl.prototype.UpdateCabin = function(cabins)
{
    var selectedCabin;

    if(this.lstCabin.length != 0){
	    // get the current value
	    selectedCabin = this.lstCabin.options[this.lstCabin.selectedIndex].text;
	    }
	
	// reinitialise the list
	this.lstCabin.options.length = 0;
	//this.lstCabin.options.add(new Option(this.displayText["AnyCabin"], '-1'));

    this.Cabins = new Array();
    this.CabinNames = new Array();
    
	for (var iCabin = 0; iCabin < cabins.length; iCabin++)
	{
		this.lstCabin.options.add(new Option(cabins[iCabin].Name, iCabin));
		
		this.Cabins[iCabin] = cabins[iCabin].Family;
		this.CabinNames[iCabin] = cabins[iCabin].Name;
		
		if (cabins[iCabin].Name == selectedCabin)
		{
			this.lstCabin.value = iCabin;//cabins[iCabin].Family;
		}
	}
};

FlightSearchControl.prototype.UpdatePreviousSearches = function(response)
{
	// delete all the current children
	DeleteChildren(this.previousSearchControl);

	// set the new data
	SetInnerHtml(this.previousSearchControl, response);
};


FlightSearchControl.prototype.ShowDepartureDate = function(calendar) {

    // update the selected date
    var parsedOutboundDate = Date.parseLocale(flightSearchControl.outboundDate.value, flightSearchControl.displayText["DateFormatString"]);
    calendar.set_selectedDate(parsedOutboundDate.localeFormat("MM/dd/yyyy"));

    $(".ajax__calendar_container", calendar._container).bgiframe();
};

FlightSearchControl.prototype.ShowReturnDate = function(calendar) {

    // update the selected date
    var parsedReturnDate = Date.parseLocale(flightSearchControl.returnDate.value, flightSearchControl.displayText["DateFormatString"]);
    calendar.set_selectedDate(parsedReturnDate.localeFormat("MM/dd/yyyy"));

    $(".ajax__calendar_container", calendar._container).bgiframe();
};

FlightSearchControl.prototype.OnDateChange = function(eventObject)
{

	// get the dates for the current controls
	var parsedOutboundDate = Date.parseLocale(this.outboundDate.value, this.displayText["DateFormatString"]);
	var parsedReturnDate = Date.parseLocale(this.returnDate.value, this.displayText["DateFormatString"]);

	if (eventObject.target == this.outboundDate)
	{
		if (parsedOutboundDate > parsedReturnDate)
		{
			this.returnDate.value = parsedOutboundDate.localeFormat("ddd, dd MMM yyyy"); //.format(this.displayText["DateFormatString"]);
		}
	}
	else
	{
		if (parsedOutboundDate > parsedReturnDate)
		{
			this.outboundDate.value = parsedReturnDate.localeFormat("ddd, dd MMM yyyy");//.format(this.displayText["DateFormatString"]);
		}
	}

	// if the dates are valid
	if (this.ValidateDates())
	{
		// validate everything
		this.Validate();
	}
	else
	{
		this.btnSearch.addClass("disabled");
		this.btnSearch[0].disabled = "disabled";
		
	}
};


FlightSearchControl.prototype.OnPassengerNumberChange = function(eventObject)
{
	// make sure there are no more infants than adults
	if (this.lstInfants.value > this.lstAdults.value)
	{
		this.lstInfants.value = this.lstAdults.value;
	}

	// if codeshare, make sure there are no more then 4 passengers
	if (this.selectedRoute && this.selectedRoute.IsCodeshare)
	{
		// get the total number of passengers - not including infants
		var totalPassengers = parseInt(this.lstAdults.value, 10) + parseInt(this.lstChildren.value, 10);

		var passengersRemaining = 4 - totalPassengers;

		this.SetAdditionalPassengers(this.lstAdults, 1, passengersRemaining);
		this.SetAdditionalPassengers(this.lstChildren, 0, passengersRemaining);

		// set the maximum number of infants
		SetSelectNumbers(this.lstInfants, 0, this.lstAdults.value, this.lstInfants.value);
	}
	else
	{
		SetSelectNumbers(this.lstInfants, 0, this.lstAdults.value, this.lstInfants.value);
	}
};

FlightSearchControl.prototype.SetAdditionalPassengers = function(listbox, start, numberOfAdditionalPassengers)
{
	var maxPassengers = parseInt(listbox.value, 10) + numberOfAdditionalPassengers;

	SetSelectNumbers(listbox, start, maxPassengers, listbox.value);
};

FlightSearchControl.prototype.HandlePostToBmiBook = function(form)
{

    this.SetCookie();
    
	$("#cityfrominput0", this.control)[0].value = this.lstDepartureAirports.value;
	$("#citytoinput0", this.control)[0].value = this.lstArrivalAirports.value;
	$("#cityfrominput1", this.control)[0].value = this.lstArrivalAirports.value;
	$("#citytoinput1", this.control)[0].value = this.lstDepartureAirports.value;

	$("#cabin", this.control)[0].value = '';
	
	if(this.lstCabin.value != '-1')
	{
	    $("#cabin", this.control)[0].value = this.Cabins[this.lstCabin.value];
	}
	$("#day0", this.control)[0].value = this.FormatBmiDay(this.parsedOutboundDate);
	$("#month0", this.control)[0].value = this.FormatBmiMonth(this.parsedOutboundDate);

	if (this.oneWayOnly.checked)
	{
	    $("#day1", this.control)[0].value = '';
	    $("#month1", this.control)[0].value = '';
	    $("#oneway", this.control)[0].value = '1';
	    $("#cityfrominput1", this.control)[0].value = '';//this.lstArrivalAirports.value;
	    $("#citytoinput1", this.control)[0].value = '';//this.lstDepartureAirports.value;

	}
	else
	{
		//$("#ReturnDate", this.control)[0].value = this.FormatBmiBabyDate(this.parsedReturnDate);
	    $("#day1", this.control)[0].value = this.FormatBmiDay(this.parsedReturnDate);
	    $("#month1", this.control)[0].value = this.FormatBmiMonth(this.parsedReturnDate);
	    $("#oneway", this.control)[0].value = '';

	}

	$("#fb_numpaxadt", this.control)[0].value = this.lstAdults.value;
	$("#fb_numpaxchd", this.control)[0].value = this.lstChildren.value;
	$("#fb_numpaxinf", this.control)[0].value = this.lstInfants.value;

    // Check for company rewards and business being selected, if they are then fetch the OSIPin
    if(this.lstCRBookingType != null)
    {
        if(this.lstCRBookingType.value == 'business')
        {
            $("#osipin", this.control)[0].value = this.lstCRCompany.value;
        }
    }    
    else
    {
        $("#osipin", this.control)[0].value = '';
    }

    $("#promocode", this.control)[0].value = '';
    
	if (this.promoCode.value.length > 0 && this.promoCode.value != this.defaultText)
	{
        $("#promocode", this.control)[0].value = this.promoCode.value.replace(/^\s+|\s+$/g,"");
	}

	$("#flexibledates", this.control)[0].value = this.flexible.checked ? '1' : '';

	// hide the viwestate
	$("#__VIEWSTATE")[0].name = 'NOVIEWSTATE';

	form.form.action = this.displayText["BookPostUrl"];
};

FlightSearchControl.prototype.HandlePostToBmiBaby = function(form)
{

	$("#From", this.control)[0].value = this.lstDepartureAirports.value;
	$("#To", this.control)[0].value = this.lstArrivalAirports.value;

	$("#OutboundDate", this.control)[0].value = this.FormatBmiBabyDate(this.parsedOutboundDate);

	if (this.oneWayOnly.checked)
	{
		$("#ReturnDate", this.control)[0].value = "";
	}
	else
	{
		$("#ReturnDate", this.control)[0].value = this.FormatBmiBabyDate(this.parsedReturnDate);
	}
	$("#Adt", this.control)[0].value = this.lstAdults.value;
	$("#Chd", this.control)[0].value = this.lstChildren.value;
	$("#Inf", this.control)[0].value = this.lstInfants.value;

	// hide the viwestate
	$("#__VIEWSTATE")[0].name = 'NOVIEWSTATE';

	form.form.action = this.displayText["BabyPostUrl"];
};


FlightSearchControl.prototype.FormatBmiBabyDate = function(date)
{
	var iDay = date.getDate();
	var iMonth = date.getMonth() + 1;
	var iYear = date.getFullYear();

	return ConvertIntToString(iDay, 2) + "/" + ConvertIntToString(iMonth, 2) + "/" + ConvertIntToString(iYear, 4);
};

FlightSearchControl.prototype.FormatBmiDay = function(date)
{
	var iDay = date.getDate();
	return ConvertIntToString(iDay, 2);// + "/" + ConvertIntToString(iMonth, 2) + "/" + ConvertIntToString(iYear, 4);
};
FlightSearchControl.prototype.FormatBmiMonth = function(date)
{
	var iMonth = date.getMonth() + 1;
	return ConvertIntToString(iMonth, 2);// + "/" + ConvertIntToString(iMonth, 2) + "/" + ConvertIntToString(iYear, 4);
};


function ConvertIntToString(val, length)
{
	var strVal = val.toString();
	if (strVal.length < length)
	{
		strVal = Repeat("0", length - strVal.length) + strVal;
	}
	return strVal;
}


FlightSearchControl.prototype.SortByTo = function(a, b)
{
	return StringCompare(a.To.Name, b.To.Name);
};

FlightSearchControl.prototype.SortByFrom = function(a, b)
{
	return StringCompare(a.From.Name, b.From.Name);
};

FlightSearchControl.prototype.SortByName = function(a, b)
{
	return StringCompare(a.Name, b.Name);
};
FlightSearchControl.prototype.SetSearchButtonState = function(enabled) {
    if (enabled) {
        if (this.btnSearch.hasClass("button")) {
            this.btnSearch.removeClass("disabled");

        } 
        //this.btnSearch.removeAttr("disabled");
    } else {
        if (this.btnSearch.hasClass("button2")) {
            this.btnSearch.addClass("disabled2");

        } else {
            this.btnSearch.addClass("disabled");

        }
        //this.btnSearch.attr("disabled", "disabled");
    }
};
FlightSearchControl.prototype.EnableDropdowns =  function()
{
    this.UpdateDropdowns(false);
}
FlightSearchControl.prototype.DisableDropdowns  = function()
{
    this.UpdateDropdowns(true);
}

FlightSearchControl.prototype.UpdateDropdowns = function(theValue)
{
    this.lstCountry.disabled = theValue;
    this.lstDepartureAirports.disabled = theValue;
    this.lstArrivalAirports.disabled = theValue;
    this.lstCabin.disabled = theValue;
}
FlightSearchControl.prototype.SetCookie = function()
{   
    var params = '';
    params += '&DepartCountry='+this.lstCountry.value;
    params += '&Depart='+this.lstDepartureAirports.value;
    params += '&Arrive='+this.lstArrivalAirports.value;
    params += '&Flexible='+this.flexible.checked;
    
    if(this.lstCabin.value != -1)
        params += '&fareType='+this.CabinNames[this.lstCabin.value];
    else
        params += '&fareType=';
        
    params += '&oneWay='+this.oneWayOnly.checked;
    params += '&Adults='+this.lstAdults.value;
    params += '&Children='+this.lstChildren.value;
    params += '&Infants='+this.lstInfants.value;
    
    ExecuteJsonRequest(null, "FlightSearchFunction=SetCookie"+params, this, null, null);
}

function Wait(show,element)
{   
    if(show == 'true')
    {  
        document.getElementById(oWaitingImages[element]).style.display = '';  
    }
    else
    {
        for(var i = 0; i < oWaitingImages.length; i++)
        {
            document.getElementById(oWaitingImages[i]).style.display = 'none';
        }  
    }
}

