var MIN_DAYS_IN_FUTURE = 3;	// How many days in the future is the earliest date that's allowed?
var limit_airports;
// Builds dropdowns with entries restricted by availability.

// All drop-downs remember their last valid value and try to select it again
// We also save values in cookies on submit and remember them for later visits - see setDefaults()
// Default values here are used as the default if we can't get the values from the DOM or cookie
var lastArr,
	lastDate = new Date().addDays(MIN_DAYS_IN_FUTURE),
	lastDuration = 7,
	lastResort = null,
	lastDep,
	errorBox,
	errorBoxDefaultText,
	errorBoxDefaultClass,
	dataOK = true,
	searchData;

var DEFAULT_AIRPORT_CODE = "CYP";	// Which Arrival airport should we select by default if the user has not selected one?

// Set default values on the form, if we can
// First, we try any values that are still in the DOM (handles user clicking 'back')
// Then we try to get the remembered value out of a cookie
function setDefaults() {
//	// AB Testing
//	var displayType = $('DisplayType');
//
//	if ( displayType ) {
//		var lastDT = getCookie('lastDisplayType');
//		if ( lastDT == "" ) {
//			lastDT = Math.random() > 0.5 ? "Detailed" : "Compact";
//		}
//
//		displayType.value = lastDT;
//	}

	lastArr = "";
	if ( frm.OutArrAir && frm.OutArrAir.value != "" ) {
		lastArr = frm.OutArrAir.value;
	}
	else {
		if ( frm.Dest && frm.Dest.value != "" ) {
			lastArr = frm.Dest.value;
		}
		else {
			lastArr = getCookie('lastArr');

			if ( lastArr == "" ) {
				lastArr = DEFAULT_AIRPORT_CODE;
			}
		}
	}

	var cookieDateString = getCookie('lastDate');
	if ( frm.OutDepDate && frm.OutDepDate.value != "" ) {
		lastDate = new Date( Date.parse( frm.OutDepDate.value ) );
	} else if ( cookieDateString != "" ) {
		cookieDate = new Date( Date.parse( cookieDateString ) );
		if ( cookieDate >= lastDate ) {
			lastDate = cookieDate;
		}
	}

	if ( frm.OutDepDate && frm.OutDepDate.value != "" && frm.RetDepDate && frm.RetDepDate.value != "" ) {
		lastDuration = ( Date.parse( frm.RetDepDate.value ) - Date.parse( frm.OutDepDate.value ) ) / (1000 * 60 * 60 * 24);
	} else  {
		lastDuration = getCookie( 'lastDuration' );
	}

	if ( frm.routetype )
	{
		switch ( getCookie( 'lastroutetype' ) ){
			case "out" :
				 frm.routetype.selectedIndex=1;
			break;
			case "return" :
				 frm.routetype.selectedIndex=2;
			break;
		}
	}


	lastDep = "";
	if ( frm.OutDepAir && frm.OutDepAir.value != "" ) {
		lastDep = frm.OutDepAir.value;
	}
	else {
		if ( frm.Departure1 && frm.Departure1.value != "" ) {
			lastDep = frm.Departure1.value;
		}
		else {
			lastDep = getCookie('lastDep');
		}
	}

	// Set up the error message box, if poss
	errorBox = (typeof(document.getElementById) != 'undefined'?document.getElementById("searchformerror"):(typeof(document.all) != 'undefined'?document.all.searchformerror:null));	// Attempt to get a reference to the box - defaults to null in old browsers or if box doesn't exist
	if (errorBox) {
		// Default contents of the box
		errorBoxDefaultText = errorBox.innerHTML;
		errorBoxDefaultClass = errorBox.className;
	}


	// Test to see if flight data is actually available to us!
	if (typeof(searchData) == 'undefined' || !searchData || searchData._allFlights.length == 0) {
		if (typeof(allFlights) == 'undefined' || !allFlights || allFlights._allFlights.length == 0) {
			showError("Sorry, no flight data available.\nPlease try reloading page.");
			dataOK = false;
		}
		else
		{
			searchData = allFlights;
		}
	}
}

// Handling for error messages
function showError(msg) {
	modElementVisibility( 'submitbutton', false );
	if (errorBox) {
		errorBox.innerHTML = String(msg).replace(/\n/g, "<br>");
		//alert(errorBox.className);
		errorBox.className = "searchformerror";
	} else {
		alert(msg);	// Fall back on JS alerts, if box isn't defined or old browser
	}
}

function hideError() {
	if (errorBox) {
		errorBox.innerHTML = errorBoxDefaultText;
		errorBox.className = errorBoxDefaultClass;
	}
}



// Base year for all month&year->integer calculations; make it the same as the value in validate() in the calling page
var baseyear = 2002;

var monthName = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

function GetResortCodeFromResortName( resort_name ) {

	resort_name = String( resort_name ).toLowerCase();

	var resorts = [
		{ name: "alonissos", code: "AS" },
		{ name: "skopelos", code: "SP" },
		{ name: "ios", code: "IO" },
		{ name: "dehab", code: "DH" },
		{ name: "halkidiki", code: "" },
		{ name: "halki", code: "HA" },
		{ name: "symi", code: "SY" },
		{ name: "ithaka", code: "VT" },
		{ name: "ithaca", code: "VT" },
		{ name: "kelymnos", code: "KY" },
		{ name: "lefkada", code: "LF" },
		{ name: "sivota", code: "SV" },
		{ name: "parga", code: "PG" },
		{ name: "paxos", code: "PX" },
		{ name: "syros", code: "GS" },
		{ name: "naxos", code: "N2" },
		{ name: "paros", code: "RC1" }
	];

	for ( var i=0; i < resorts.length; i++ ) {
		if ( resort_name.indexOf( resorts[i].name ) > -1 ) {
			return resorts[i].code;
		}
	}

	return "";
}


// Build the departure airport drop-down
function buildDestinations() {

	if (!dataOK) return false;

	// Disable this and subsequent fields
	$("Arr").disabled = true;
	frm.Dep.disabled = true;
	frm.Month.disabled = true;
	frm.Day.disabled = true;

	var arrIsSelectBox = $("Arr").options ? true : false;

	if ( arrIsSelectBox ) {

		modElementVisibility( "imageField", false );

		frm.Duration.disabled = true;

		//document.getElementById('submitbutton').style.visibility = 'hidden';
		modElementVisibility( "submitbutton", false );

		// Remember current value, if valid
		if ( $("Arr").getValue() ) {
			lastArr = $("Arr").getValue();
		}

		if ( frm.Resort && frm.Resort.value ) {
			lastResort = frm.Resort.value;
		}

		// Clear old options
		while ( frm.Arr.options.length > 0 ) {
			frm.Arr.options[0] = null;
		}

		// Add new options
		var destinations = searchData.getDestinations();

		var selectedIndex = 0;
		var fallback_selectedIndex = 0;

		//sort the destinations alphabetically
		//destinations.sort( sortFunc );

		//alert( lastArr );

		var testStr = "";

		for ( var i = 0; i < destinations.length; i++ ) {

			// TODO: we should probably check to make sure that there are some (future) flights to this destination before including it, just to be on the safe side.
			var option_value = destinations[i].code + ( destinations[i].resortCode ? "|" + destinations[i].resortCode : "" );

			frm.Arr.options[i] = new Option(destinations[i].name, option_value, (destinations[i].code == lastArr), (destinations[i].code == lastArr));
			// Workaround for IE bug - setting selected option on Option() constructor sets selectedIndex off by 1, so instead we'll remember the index we want for later
			if (destinations[i].code == lastArr ) {
				var resort_code = destinations[i].resortCode ? destinations[i].resortCode : GetResortCodeFromResortName( destinations[i].name );

				if ( resort_code == lastResort ) {
					selectedIndex = i;
				}
				else {
					// Remember the first match so we can select it if we don't find anything better
					if ( fallback_selectedIndex == 0 ) {
						fallback_selectedIndex = i;
					}
				}
			}
			testStr += destinations[i].name + " (" + destinations[i].code + ")\n";
		}


		if ( selectedIndex == 0 && fallback_selectedIndex > 0 ) selectedIndex = fallback_selectedIndex;


		// Second part of workaround for IE bug: set the selectedIndex we got from earlier, if it isn't right
		if (frm.Arr.selectedIndex != selectedIndex) frm.Arr.selectedIndex = selectedIndex;

		// Check there are some destinations (this should never fail, but it's included for completeness)
		if ( frm.Arr.length > 0 ) {
			// Enable this field and build the next one
			frm.Arr.disabled = false;
			return buildDepartures();
		} else {
			showError("Sorry, there are currently no flights available.\nThis is probably due to a system error; please try later.");
			return false;
		}
	}
	else {
		return buildDepartures();
	}
}

function sortFunc( dest1, dest2 ) {
	// Used to sort the destinations alphabetically
	if ( String( dest1.name ) < String( dest2.name ) )
	{
		retVal=-1;
	}
	else
	{
		if ( String( dest1.name ) > String( dest2.name ) )
		{
			retVal=1;
		}
		else
		{
			retVal=0;
		}
	}

	return retVal;

}

function currentArrivalAirport() {
	var Arr = document.getElementById( "Arr" );

	if ( !Arr ) {
		Arr = document.getElementById( "OutArrAir" );
	}

	if ( !Arr ) return false;

	return ( Arr.options ? selected_value( Arr ) : Arr.value ).split("|")[0];
}

// Build the list of valid departure points for the selected arrival, date and duration
function buildDepartures( skipDurationStep ) {
	if (!dataOK) return false;

	HidePleaseWait();

	skipDurationStep = skipDurationStep ? true : false;

	// Disable this field and the submit button
	frm.Dep.disabled = true;
	frm.Month.disabled = true;
	frm.Day.disabled = true;
	modElementVisibility( 'imageField', false );
	frm.Duration.disabled = true;
	modElementVisibility( 'submitbutton', false );

	// Remember current value, if valid
	if ( frm.OutDepAir && frm.OutDepAir.value != "" ) {
		lastDep = frm.OutDepAir.value;
	}
	else {
		if (frm.Dep.options.length > 0 && frm.Dep.selectedIndex >= 0 && frm.Dep.options[frm.Dep.selectedIndex].value) {
			lastDep = frm.Dep.options[frm.Dep.selectedIndex].value;
		}
	}

	// Clear current values from drop-down
	while (frm.Dep.length > 0) {
		frm.Dep.options[0] = null;
	}

	var ArrivalAirportCode = currentArrivalAirport();

	// Get the available departure points for the selected options
	var departureAirports = searchData.getAvailableDepartures( ArrivalAirportCode );


	// Populate the drop-down with the allowed departure points
	for (var i = 0; i < departureAirports.length; i++) {
		if(	limit_airports && limit_airports.length > 0 ) {
			for( var limitIndex = 0; limitIndex < limit_airports.length; limitIndex++ ) {
				if( departureAirports[i].code === limit_airports[limitIndex] ){
					frm.Dep.options[frm.Dep.options.length] = new Option( departureAirports[i].name, departureAirports[i].code, ( departureAirports[i].code == lastDep ), ( departureAirports[i].code == lastDep ) );
				}
			}
		} else {
			frm.Dep.options[frm.Dep.options.length] = new Option( departureAirports[i].name, departureAirports[i].code, ( departureAirports[i].code == lastDep ), ( departureAirports[i].code == lastDep ) );
		}
	}

	// Test to see if we got any values (this shouldn't fail, because we should never show a combination of options earlier that aren't allowed)
	if (frm.Dep.length > 0) {
		// Enable this field and build the next one
		frm.Dep.disabled = false;
		return buildDates( skipDurationStep );
	} else {
		showError("Sorry, there are no flights available to that destination.\nPlease choose another destination.");
		return false;
	}
}


// Build the list of valid departure dates for the selected destination
function buildDates( skipDurationStep ) {
	if (!dataOK) return false;

	skipDurationStep = skipDurationStep ? true : false;

	// Remember current value, if valid
	if (frm.Month.options.length > 0 && frm.Month.selectedIndex >= 0 && frm.Month.options[frm.Month.selectedIndex].value && frm.Day.options.length > 0 && frm.Day.selectedIndex >= 0 && frm.Day.options[frm.Day.selectedIndex].value ) {
		lastDate = selectedDate();
	}

	// Disable this and subsequent fields
	frm.Month.disabled = true;
	frm.Day.disabled = true;
	modElementVisibility( 'imageField', false );
	frm.Duration.disabled = true;
	modElementVisibility( 'submitbutton', false );

	// Clear old options
	while (frm.Month.options.length > 0) {
		frm.Month.options[0] = null;
	}

	// Find the earliest and latest dates this destination is available
	// NOTE: Potentially there could be several disjoint date ranges where this destination is available.
	// However, we show a range from earliest to latest because the calendar control won't work with disjoint ranges.
	// This means that it is possible to select a date for which no flights to the selected destination are available; this will throw an error to the user at the end of buildDurations()
	// If we change this function in future so it only shows available ranges in the drop-down, the rest of the code should work with no modification.
	var ArrivalAirportCode = currentArrivalAirport();
	var dateranges = searchData.getAvailableDates(ArrivalAirportCode, frm.Dep.options[frm.Dep.selectedIndex].value);

	// Check we found a date range (should never fail)
	if (dateranges.length == 0) {
		showError("Sorry, there are no flights available to that destination");
		return false;
	}

	var mindate = dateranges[0][0], maxdate = dateranges[dateranges.length - 1][1];

	// If the max date we found is in the past, also throw an error
	if ( maxdate < new Date() ) {
		showError("Sorry, there are currently no flights available to that destination");
		return false;
	}

	/* Not longer using the old horrid way of rendering out dates

	// For each month between min and max, flag which ones are actually available
	// (we use this to indicate to the user)
	var allowedMonths = new Array();



	for (var i = monthNumber(mindate) - 1; i <= monthNumber(maxdate); i++) allowedMonths[i] = false;

	for (var i = 0; i < dateranges.length; i++) {
		for (var j = monthNumber(dateranges[i][0]); j <= monthNumber(dateranges[i][1]); j++) allowedMonths[j] = true;
	}

	// Special case for Lates form - we only show dates 8 months ahead
	if (frm.formtype && frm.formtype.value == 'SpecialOffer') {
		// Reset maxdate to the latest available date that's <= 8 months ahead
		while ((monthNumber(maxdate) >= monthNumber() + 9 || !allowedMonths[monthNumber(maxdate)])
				&& monthNumber(maxdate) >= monthNumber(mindate)	// Make sure loop terminates if there's no availability at all in next 8 months
			) {
			maxdate.setMonth(maxdate.getMonth() - 1);
		}
	}

	// Populate the Month drop-down
	for (var i = monthNumber(mindate); i <= monthNumber(maxdate); i++) {
		frm.Month.options[frm.Month.options.length] = new Option(monthName[(i-1) % 12] + ' ' + String(Math.floor((i - 1) / 12) + baseyear) + (!allowedMonths[i]?' (n/a)':''), i, (i==monthNumber(lastDate)), (i==monthNumber(lastDate)));
	}

	*/

	var temp_date = mindate;
	temp_date.setDate( 1 );

	while( temp_date <= maxdate ) {
		for ( var i=0; i < dateranges.length; i++ ) {
			var month_year_text = monthName[ temp_date.getMonth() ] + ' ' + temp_date.getFullYear();
			var month_year_value = temp_date.getMonth() + '/' + temp_date.getFullYear();

			// Check we've not already added this option, getting a bit messy this...
			var new_option = true;
			for( var x=0; x < frm.Month.options.length; x++ ) {
				if ( frm.Month.options[ x ].text.indexOf( month_year_text ) > -1 ) {
					if ( frm.Month.options[ x ].text.indexOf( "(n/a)" ) > -1 ) {
						frm.Month.options[ x ] = null;
					}
					else
					{
						new_option = false;
					}
					break;
				}
			}

			if ( new_option ) {
				if (  temp_date >= dateranges[i][0] && temp_date <= dateranges[i][1] ) {
					frm.Month.options[frm.Month.options.length] = new Option( month_year_text, month_year_value, ( monthNumber( temp_date ) == monthNumber( lastDate ) ), ( monthNumber( temp_date ) == monthNumber( lastDate ) ) );
				}
				else
				{
					frm.Month.options[frm.Month.options.length] = new Option( month_year_text + " (n/a)", month_year_value, ( monthNumber( temp_date ) == monthNumber( lastDate ) ), ( monthNumber( temp_date ) == monthNumber( lastDate  ) ) );
				}
			}
		}

		temp_date.setMonth( temp_date.getMonth() + 1 );
	}

	// Check we have some allowed dates
	if (frm.Month.length > 0) {

		// Populate the day drop-down
		buildDays();

		// Enable the date selection
		frm.Month.disabled = false;
		frm.Day.disabled = false;
		modElementVisibility( 'imageField', true );

		// Now we have a value here, we can build the durations
		if ( skipDurationStep )
		{
			modElementVisibility( 'Duration', true );
			frm.Duration.disabled = false;

			return true;
		}
		else
		{
			return buildDurations();
		}
	} else {
		showError("Sorry, there are no flights available to that destination");
		return false;
	}

	//clear dest
	if ( frm.Destination1 ) frm.Destination1.value = "";
}

// Populate the days drop-down based on the selected month
function buildDays() {
	if (!dataOK) return false;

	// Remember current value, if valid
	if (frm.Month.options.length > 0 && frm.Month.selectedIndex >= 0 && frm.Month.options[frm.Month.selectedIndex].value && frm.Day.options.length > 0 && frm.Day.selectedIndex >= 0 && frm.Day.options[frm.Day.selectedIndex].value ) {
		lastDate = selectedDate();
	}

	// Make sure the start day can't be set too early
	var earliest_date = new Date().addDays( MIN_DAYS_IN_FUTURE );
//	console.debug( "Earliest Date: " + earliest_date );

	var month_year = $('Month').getValue().split( "/" );
	var month = month_year[0];
	var year = month_year[1];
	var current_date = new Date( year, month, 1 );

	if ( current_date < earliest_date ) {
		current_date = earliest_date;
	}

//	console.debug( "Current Selected Date: " + earliest_date );

	// Clear old options
	while (frm.Day.options.length > 0) {
		frm.Day.options[0] = null;
	}

	// Using JS to work it out the last day of the month, set day to 1, add a month, then -1 day from the new date, that should be max day of the previous month...?
	var latest_date = new Date( current_date );
	latest_date.setMonth( latest_date.getMonth() + 1, 0 );

	var days_of_week = [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" ];

	var temp_date = new Date( current_date );

	// Populate new values
	while ( temp_date <= latest_date ) {
		var today = temp_date.getDate();
		var today_text = days_of_week[ temp_date.getDay() ] + " " + today + ( ( Math.floor( ( today % 100 ) / 10 ) == 1 ) ? "th" : ["th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"][ today % 10 ] ); // Fancy way of adding th, nd, rd to dates, See http://codingforums.com/showthread.php?t=24871&page=2
		frm.Day.options[ frm.Day.options.length ] = new Option( today_text, today, ( today == lastDate.getDate() ), ( today == lastDate.getDate() ) );
		temp_date.setDate( temp_date.getDate() + 1 );
	}
}

// Build a set of available durations for the selected date and destination
function buildDurations() {
	if (!dataOK) return false;

	// Disable this and subsequent fields
	frm.Duration.disabled = true;
	modElementVisibility( 'submitbutton', false );

	// Remember current value, if valid
	if (frm.Duration.options.length > 0 && frm.Duration.selectedIndex >= 0 && frm.Duration.options[frm.Duration.selectedIndex].value) {
		lastDuration = frm.Duration.options[frm.Duration.selectedIndex].value;
	}

	// Clear old options
	while (frm.Duration.options.length > 0) {
		frm.Duration.options[0] = null;
	}

	var ArrivalAirportCode = currentArrivalAirport();

	// Populate dropdown with all of the allowed durations
	var allowedDurations = searchData.getAvailableDurations(ArrivalAirportCode, frm.Dep.options[frm.Dep.selectedIndex].value, selectedDate())
	for (var i = 0; i < allowedDurations.length; i++) {
		frm.Duration.options[frm.Duration.options.length] = new Option(allowedDurations[i], allowedDurations[i], (String(allowedDurations[i])==String(lastDuration)), (String(allowedDurations[i])==String(lastDuration)));
	}

	// Test to see if we got any values (this is likely to fail sometimes - see note in buildDates(), above)
	if ( frm.Duration.length > 0 ) {
		// Enable this field and the submit button
		frm.Duration.disabled = false;
		modElementVisibility( 'submitbutton', true );
		hideError();	// If we get this far, we are no longer in an error state
		settriptype()
		return true;
	} else {

		showError("Sorry, there are no flights for that route on that date.\n\nPlease choose another destination, departure point or date.\n");

		return false;
	}

}

// Safe way of showing/hiding elements, true = visible, false = hidden
function modElementVisibility( eleName, isVisible )
{
	var ele = $(eleName);

	if ( ele )
	{
		ele.setStyle( "visibility", "visible" );	// Backwards compat

		if ( isVisible )
		{
			ele.setStyle( "display", "inline" );
		}
		else
		{
			ele.setStyle( "display", "none" );
		}
	}
}


// Convert a date to an integer representing month and year
// If no value given, return value for current date
// Jan 2002 = 1, Feb 2002 = 2, etc. (see baseyear variable)
function monthNumber(date) {
	if (! date) {
		return ((new Date().getFullYear() - baseyear) * 12) + new Date().getMonth() + 1;
	} else {
		return ((new Date(date).getFullYear() - baseyear) * 12) + new Date(date).getMonth() + 1;
	}
}

// Convert a month number from the above function back to a date (day is 1st of month, time 00:00:00.000)
function monthNumberToDate(num) {
	return new Date(Math.floor((parseInt(num) - 1) / 12) + baseyear, (parseInt(num) - 1) % 12, 1, 0, 0, 0, 0);
}

// Utility functions used by Calendar stuff
function numToMonth(num) {
	return monthNumberToDate(num).getMonth();
}
function numToYear(num) {
	return monthNumberToDate(num).getFullYear();
}

// Convert the selected date from the form into a Date object
function selectedDate() {
	var the_date = new Date();

	if ( selected_value( frm.Month ).indexOf( "/" ) > -1 )
	{
		monthYear = selected_value( frm.Month ).split("/");
		the_date = new Date( Date.parse( ( parseInt( monthYear[0] ) + 1 ) + "/" + selected_value( frm.Day ) + "/" + monthYear[1] ) );
	}
	else
	{
		the_date = new Date(Math.floor((parseInt(frm.Month.options[frm.Month.selectedIndex].value) - 1) / 12) + baseyear, (parseInt(frm.Month.options[frm.Month.selectedIndex].value) - 1) % 12, parseInt(frm.Day.options[frm.Day.selectedIndex].value), 0, 0, 0, 0);
	}

	return the_date;
}

// Validate the form before submission (not much in here; it's impossible to submit the form until all values are selected)
function validate() {

	// Validate pax
	if (parseInt(frm.AdultPax[frm.AdultPax.selectedIndex].value) + parseInt(frm.ChildPax[frm.ChildPax.selectedIndex].value) + parseInt(frm.InfantPax[frm.InfantPax.selectedIndex].value) >= 10) {
		showError("Sorry, a maximum of 9 passengers are allowed.");
		frm.AdultPax.focus();
		return false;
	}

	return true;

}


function DisplayPleaseWait() {
	var spinner = $( "Spinner" );
	if ( spinner ) {
		spinner.setStyle( "display", "block" );
	}

	//window.onunload = HidePleaseWait();
}

function HidePleaseWait() {
	modElementVisibility( "spinner_place_holder", false );
}

function SetLegacyDates() {
	// Set dates
	if ( frm ) {
		if ( frm.OutDepDate && frm.RetDepDate )	{
			frm.OutDepDate.value = selectedDate().getDate() + ' ' + monthName[selectedDate().getMonth()] + ' ' + selectedDate().getFullYear();

			var tdate = selectedDate().addDays(parseInt(frm.Duration[frm.Duration.selectedIndex].value));
			frm.RetDepDate.value = tdate.getDate() + ' ' + monthName[tdate.getMonth()] + ' ' + tdate.getFullYear();
		}
	}
}


function set_resort_code() {

}


function getCompCodeForAirport( airport_code, options ) {

	// Given an arrival airport code and a search type this function will return the correct Company Code for that flight
	// Options:
	//	search_type - The type of search the airport if for FlightOnly, AccomOnly, Availability/Lates (default)

	options = options ? options : {};

	var search_type = options[ "search_type" ] ? options[ "search_type" ] : "";

	var company_code = "";

	switch ( search_type ) {
		case "FlightOnly" : {
			switch ( airport_code ) {
				case "CYP": // Cyprus all resorts
				case "PFO":
				case "LCA":
				case "LTN":
				{
					company_code = "B";
					break;
				}

				case "SSH":
				case "GOI":
				case "MCE":
				case "DXB":
				case "LRM":
				case "POP":
				case "BJL":
				case "CMB":
				case "HRG":
				case "MBA":
				case "CUN":
				case "LXR":
				case "EGY": // Red Sea All Resorts
				case "CAI" : // Cairo
				{
					company_code = "K";
					break;
				}

				// Turkey
				case "AYT":
				case "DLM":
				case "BJV":
				case "TUR": // Turkey all resorts

				// Bulgaria
				case "BOJ":
				case "VAR":
				// Tunisia
				case "TUN":
				case "MIR":

				// Croatia
				case "CRO":
				case "DBV":
				case "PUY":

				// Italy
				case "FCO": // Rome
				{
					company_code = "Y";
					break;
				}

				// Spain
				case "AGP":
				case "ALC": // Alicante
				case "BCN": // Barcelona
				case "LEI": // Almeria
				case "MJV": // Murcia

				// Canary Islands
				case "CA": // All Resorts
				case "TFS": // Tenerife
				case "LPA": // Gran Canaria - Las Palmas
				case "ACE": // Lanzarote - Arrecife
				case "FUE": // Fuerteventura

				// Belearic Islands
				case "PMI": // Majorca - Palma
				case "IBZ": // Ibiza
				case "MAH": // Menorca - Mahon

				// Portugal
				case "FAO": // Algarve - Faro
				case "GIB": // Gibraltar
				{
					company_code = "T";
					break;
				}

				case "MRU": // Mauritius
				case "MLA": // Malta
				{
					company_code = "S";
					break;
				}

				default: {
					company_code = "F";
				}
			}

			break;
		}

		case "AccomOnly" : {
			switch( airport_code ) {

				case "CYP" :
				case "LCA" :
				case "PFO" :
				{
					company_code = "E";
					break;
				}
				
				case "GOI" :
				case "BJL" :
				case "SSH" :
				case "HRG" :
				case "LXR" :
				case "CAI" : // Cairo
				{
					company_code = "M";
					break;
				}

				case "BJV" :
				case "BOJ" :
				case "DLM" :
				case "MIR" :
				case "AYT" :

				// Croatia
				case "CRO":
				case "DBV":
				case "PUY":

				case "MRU": // Mauritius
				case "MLA": // Malta
				{
					company_code = "Z";
					break;
				}

				// Spain
				case "AGP":
				case "ALC": // Alicante
				case "BCN": // Barcelona
				case "LEI": // Almeria
				case "MJV": // Murcia

				// Canary Islands
				case "CA": // All Resorts
				case "TFS": // Tenerife
				case "LPA": // Gran Canaria - Las Palmas
				case "ACE": // Lanzarote - Arrecife
				case "FUE": // Fuerteventura

				// Belearic Islands
				case "BA" : // All Resorts
				case "PMI": // Majorca - Palma
				case "IBZ": // Ibiza
				case "MAH": // Menorca - Mahon

				// Portugal
				case "FAO": // Algarve - Faro
				case "GIB": // Gibraltar
				{
					company_code = "V";
					break;
				}
				default: {
					company_code = "H";
					break;
				}
			}

			break;
		}

		default : {
			switch ( airport_code ) {
				case "CYP":
				case "PFO":
				case "LCA": {
					company_code = "C";
					if (frm.FOCompCode) frm.FOCompCode.value="B";
					break;
				}
				case "ODY":
				case "SSH":
				case "GOI":
				case "MCE":
				case "LRM":
				case "POP":
				case "MLE":
				case "BJL":
				case "CMB":

				case "HRG":
				case "MBA":
				case "CUN":
				case "LXR":
				case "EGY":
				case "CAI" : // Cairo
				{
					company_code = "L";
					if (frm.FOCompCode) frm.FOCompCode.value = "K";
					break;
				}
				case "ATH" :
				case "GRE": {
					company_code = "G";
					if (frm.FOCompCode) frm.FOCompCode.value = "F";
					break;
				}

				case "MRU": // Mauritius
				case "MLA": // Malta
				case "DXB": {
					company_code = "S";
					if (frm.FOCompCode) frm.FOCompCode.value = "S";
					break;
				}


				// "TURKEY":  ATY BJV DLM TUR (Turkey all resorts)
				// "BULGARIA":   BOJ VAR  BUL (Bulgaria all resorts)

				// "TUNISIA":  TUN   MIR

				// X - Olympic Other package
				// Y - olympic other flights only
				// Z - olympic other accommodation only

				case "AYT":
				case "BJV":
				case "DLM":
				case "TUR":

				case "TUN":
				case "MIR":

				case "BOJ":
				case "VAR":
				case "BUL":

				// Croatia
				case "CRO":
				case "DBV":
				case "PUY":

				case "TUR": // Turkey all resorts

				case "FCO": // Rome
					{
					company_code = "X";
					if (frm.FOCompCode) frm.FOCompCode.value = "Y";
					break;
				}


				// Spain
				case "AGP":
				case "ALC": // Alicante
				case "BCN": // Barcelona
				case "LEI": // Almeria
				case "MJV": // Murcia

				// Canary Islands
				case "CA": // All Resorts
				case "TFS": // Tenerife
				case "LPA": // Gran Canaria - Las Palmas
				case "ACE": // Lanzarote - Arrecife
				case "FUE": // Fuerteventura

				// Belearic Islands
				case "BA" : // All Resorts
				case "PMI": // Majorca - Palma
				case "IBZ": // Ibiza
				case "MAH": // Menorca - Mahon

				// Portugal
				case "FAO": // Algarve - Faro
				case "GIB": // Gibraltar

				{
					company_code = "U";
					if (frm.FOCompCode) frm.FOCompCode.value = "T";
					break;
				}

				default: {
					company_code = "G";
					if (frm.FOCompCode) frm.FOCompCode.value = "F";
				}
			}

			break;
		}
	}

	return company_code;
}

function getFOCompCode( comp_code ) {
	// When doing an inclusive search ATOP needs to know which flight company code to us so it can try to
	// find you an alternative flight if the day you wanted is not available, given the inclusive company code
	// this function will return the right flight only company code for you

	var fo_comp_code = "";

	switch( comp_code ) {
		case "G" : {
			fo_comp_code = "F";
			break;
		}
		case "U" : {
			fo_comp_code = "T";
			break;
		}
		case "X" : {
			fo_comp_code = "Y";
			break;
		}
		case "C" : {
			fo_comp_code = "B";
			break;
		}
		case "L" : {
			fo_comp_code = "K";
			break;
		}
		case "G" : {
			fo_comp_code = "F";
			break;
		}
		case "S" : {
			fo_comp_code = "S";
			break;
		}
	}

	return fo_comp_code;
}

// Set the hidden fields in the form for ATOP
function setHiddenFields()
{
	DisplayPleaseWait();

	// hide the submit button
	modElementVisibility( 'submitbutton', false );

	SetLegacyDates();

	var form_type = frm.formtype ? frm.formtype.value : "";

	switch( form_type ) {

		case 'FlightOnly' : {
			// Flight Only form is dfferent

			// Set airports
			frm.OutDepAir.value = frm.Dep[frm.Dep.selectedIndex].value;
			frm.OutArrAir.value = frm.Arr[frm.Arr.selectedIndex].value;
			frm.RetDepAir.value = frm.OutArrAir.value;
			frm.RetArrAir.value = frm.OutDepAir.value;

			// Compatability stuff with old and new booking engine
			var route_type;
			if ( frm.RouteType ) {
				route_type = frm.RouteType;
			} else if ( frm.routetype ) {
				route_type = frm.routetype;
			}

			// Apply route type - if applicable
			if ( route_type ){

				switch ( selected_value( route_type ) ) {
					case "out" :
						if ( frm.JourneyType ) {
							frm.JourneyType.value="oneway";
						}
						frm.RetArrAir.value="";
						frm.RetDepDate.value="";
						frm.RetDepAir.value="";
					break;

					case "return" :
						if ( frm.JourneyType ) {
							frm.JourneyType.value="oneway";
						}
						frm.OutArrAir.value=frm.RetArrAir.value;
						frm.OutDepAir.value=frm.RetDepAir.value;

						frm.RetDepDate.value="";
						frm.RetArrAir.value="";
						frm.RetDepAir.value="";

					break;

					default:
						if ( frm.JourneyType ) {
							frm.JourneyType.value="";
						}
				}
			}


			// Check for a reverse flight first ie Larnca to Gatwick - then set the airport code to match with to get the compcode

			var target_airport;
			switch( String( frm.Arr[frm.Arr.selectedIndex].value).toUpperCase() )
			{
				case "LGW":	// Gatwick
				case "LHR":	// Heathrow
				case "LTN":	// Luton
				case "STN":	// Stansted
				case "BFS":	// Belfast
				case "BHX":	// Birmingham
				case "BRS":	// Bristol
				case "EMA":	// East Midlands
				case "EXT":	// Exeter
				case "GLA":	// Glasgow
				case "HUY":	// Humberside
				case "LBA":	// Leeds Bradford
				case "MAN":	// Manchester
				case "NCL":	// Newcastle
				{
					target_airport = String( frm.Dep[frm.Dep.selectedIndex].value).toUpperCase();
					break;
				}

				default:
				{
					target_airport = String( frm.Arr[frm.Arr.selectedIndex].value).toUpperCase();
					break;
				}
			}

			// Set company codes
			frm.compcode.value = getCompCodeForAirport( target_airport, { search_type: frm.formtype.value } );

			break;
		}

		case 'AccomOnly' : {

			// Set Comp Code, which is different as its Accom Only
			if ( frm.Arr ) {
				frm.compcode.value = getCompCodeForAirport( String( selected_value( frm.Arr ).split("|")[0] ).toUpperCase(), { search_type: "AccomOnly" } );

				if ( selected_value( frm.Arr ).indexOf( "|" ) > -1 ) {
					var values = selected_value( frm.Arr ).split( "|" );
					frm.OutArrAir.value = values[0];
					if ( frm.Resort ) {
						if ( values[1] != null ) {
							frm.Resort.value = values[1];
						}
						else
						{
							frm.Resort = "";
						}
					}
				}
				else
				{
					frm.OutArrAir.value = selected_value( frm.Arr );
				}
			} else {
				frm.compcode.value = getCompCodeForAirport( String( frm.OutArrAir.value ).toUpperCase(), { search_type: "AccomOnly" } );
			}


			break;
		}

		default : {
			// Inclusive: Availability/Lates

			// Set airports

			// Merged search form mod
			// Check if we need to change the forms action depending on what option is selected on the form - fails gracefully it not
			if ( frm.zolv_DisplayType )
			{
				switch ( String( frm.zolv_DisplayType[ frm.zolv_DisplayType.selectedIndex ].value ).toLowerCase() )
				{
					case "price" :
					{
						frm.action = ECOMURL + "/atopweb/live/en/inclusive/ATOPWeb.ASP?WCU=New&bst=Late";
						break;
					}

					case "duration" :
					{
						frm.action = ECOMURL + "/atopweb/live/en/inclusive/ATOPWeb.ASP?WCU=New&bst=Avail";
						break;
					}
				}
			}

			var arr_airport = frm.Arr ? $("Arr").getValue() : frm.OutArrAir.value;

			// Old booking system requirement
			if ( frm.Destination1 ) frm.Destination1.value = arr_airport;
			if ( frm.Departure1 ) frm.Departure1.value = frm.Dep[frm.Dep.selectedIndex].value;
			if ( frm.Dest ) frm.Dest.value = arr_airport;

			// Set new fields for XML search
			if ( frm.OutDepAir && frm.OutArrAir && frm.RetDepAir && frm.RetArrAir ) {
				if ( frm.Dep ) {
					frm.OutDepAir.value = selected_value( frm.Dep );
				}
				if ( frm.Arr ) {
					frm.OutArrAir.value = arr_airport;
				}

				frm.RetDepAir.value = frm.OutArrAir.value;
				frm.RetArrAir.value = frm.OutDepAir.value;
			}

			// Set company codes
			frm.compcode.value = getCompCodeForAirport( arr_airport.toUpperCase() );
// Now done via the getCompCodeForAiport funciton?
//			if ( frm.FOCompCode ) {
//				frm.FOCompCode.value = getFOCompCode( frm.compcode.value );
//			}

			// Set Resort Field for resorts that use a gateway airport
			if ( frm.Resort ) {

				// Reset Resort value
				frm.Resort.disabled = false;
				frm.Resort.value = "";

				frm.Resort.value = GetResortCodeFromResortName( frm.Arr.options[ frm.Arr.selectedIndex ].text );

				if ( frm.Resort.value == "" )
				{
					frm.Resort.disabled = true;
				}

				/*

					RESORT CODE	RESORT NAME		AIRPORT CODE	AIRPORT NAME
					===========	===========		============	============
					AS	(AL)	ALONISSOS		JSI		SANTORINI
					SP		SKOPELOS		JSI		SANTORINI
					DH		*DAHAB			SSH		SHARM
					HA		HALKI ISLE		RHO		RHODES
					SY		SYMI			RHO		RHODES
					IO		IOS			JTR		SANTORINI
					VT	(IT)	ITHACA			EFL		KEFALONIA
					KL	???	KALYMNOS		KGS		KOS
					TL		*TELENDOS		KGS		KOS - Not used on Availability
					NY	(LF)	LEFKADA			PVK		PREVEZA
					PG		PARGA			PVK		PREVEZA
					PZ		PARGA,SIVOTA OR LEFKADA	PVK		PREVEZA
					SIV	(SV)	SIVOTA			PVK		PREVEZA
					PX		PAXOS			CFU		CORFU
					SR		SYROS			JMK		MYKONOS - Deleted from CMS

					() old code
					* currently not on search dropdowns

				*/
			}
		}

	}

	// Overwrite the Company code based on the Departure airport
	// This is new for flights from Dublin as they are booked in Euros

	if ( frm.Dep )
	{
		switch( String( frm.Dep[ frm.Dep.selectedIndex ].value ).toUpperCase() )
		{
			case "DUB":
			{
				frm.compcode.value = "T";
				break;
			}
		}
	}

	// New booking system compatability - compcode is now known as Company, just used as a catch just in case
	if ( frm.Company ) {
		frm.Company.value = frm.compcode.value;
	}

	// Set the Branch Code if we can - 04 July 2006
	if ( frm.branchCode && frm.compcode )
	{
		if ( location.href.indexOf( "olympic" ) > -1 )
		{
			frm.branchCode.value = frm.compcode.value + "IN";
		}
		else if ( location.href.indexOf( "odyssey" ) > -1 )
		{
			frm.branchCode.value = frm.compcode.value + "ON";
		}
	}

	// Remember these values in cookies for next visit or if user hits back button
	var expireDate = new Date().addDays(400),
	path = '/';
	//alert(frm.OutArrAir?frm.OutArrAir.value:frm.Destination1.value);
	setCookie('lastArr', (frm.OutArrAir?frm.OutArrAir.value:(frm.Dest?frm.Dest.value:frm.Destination1.value)), expireDate, path);
	setCookie('lastDate', frm.OutDepDate.value, expireDate, path);
	setCookie('lastResort', (frm.Resort?frm.Resort.value:null), expireDate, path);
	setCookie('lastDuration', selected_value( frm.Duration ), expireDate, path);
	var lastDep = "";
	if ( frm.OutDepAir ) {
		lastDep = frm.OutDepAir.value;
	} else if ( frm.Departure1 ) {
		lastDep = selected_value( frm.Departure1 );
	} else if ( frm.Dep ) {
		lastDep = selected_value( frm.Dep );
	}
	setCookie('lastDep', lastDep, expireDate, path );
	setCookie('lastAdultPax', selected_value( frm.AdultPax ), expireDate, path);
	setCookie('lastChildPax', selected_value( frm.ChildPax ), expireDate, path);
	setCookie('lastInfantPax', selected_value( frm.InfantPax ), expireDate, path);
	if (frm.routetype) setCookie('lastroutetype', selected_value( frm.routetype ), expireDate, path );
	if (frm.Price) setCookie('lastPrice', frm.Price.value, expireDate, path);	// Only applies to Lates

	// AB Tracking
//	var displayType = $('DisplayType');
//	if ( displayType ) {
//		var origDisplayType = $('OriginalDisplayType');
//		if ( origDisplayType ) {
//			origDisplayType.value = displayType.getValue();
//			$("ResultsPerPage").value = displayType.getValue() == "Compact" ? "25" : "5";
//			//$("debug").value = "true";
//		}
//		setCookie( 'lastDisplayType', displayType.getValue(), expireDate, path );

//	}

	check_for_debug_info( frm );

	//pageTracker._linkByPost( frm );

	return true;
}

function settriptype(){
	 	if (frm.routetype){
			if (frm.routetype[frm.routetype.selectedIndex].value=="round" ){
				frm.Duration.disabled = false;
			}
			else
			{
				frm.Duration.disabled = true;
			}
		}
}

function AssertJSLoadedOk() {
	return true;
}