// Some globals
var trimmedOBdep;
var trimmedOBarr;
var trimmedIBdep;
var trimmedIBarr;
var depapt = new Array();
var arrapt = new Array();
var directonly;
var searchType = 'exact';

$.noConflict();

jQuery(document).ready(function(){
	// Default to return flights
	jQuery("[name=radioval]").attr("checked", false);
	jQuery("#return").attr("checked", true);

	// Popup calender initialization
	jQuery("#DepDate").datepicker({  
		showOn: 'both', 
		buttonImage: '/images/calendar2.gif', 
		buttonImageOnly: true, 
		showAnim: null,
		duration: '',
		buttonText: '-',
		minDate: 0 
	});
	jQuery("#ArrDate").datepicker({  
		showOn: 'both', 
		buttonImage: '/images/calendar2.gif', 
		buttonImageOnly: true, 
		showAnim: null,
		duration: '',
		minDate: 1,
		buttonText: '-',
		beforeShow: function() { getMinimumDays(); }
	});
	
	// Show tooltips
	jQuery('input,.ttip,label,.stdinput').tooltip({ 
		track: true, delay: 0, showURL: false, showBody: " - ", fade: 0 
	});

	// Autocomplete initilialization
	jQuery(".citySelect")
		.autocomplete(airports, {
			autoFill: false,
			selectFirst: true,
			max: 18,
			mustMatch: false,
			matchContains: true,
			scrollHeight: 220,
			width: 190
		})
		.result(function() {
		  completeAutofill();
		  if (jQuery(this).attr("id") == "OBdep")
			jQuery("#OBarr").focus();
		  if (jQuery(this).attr("id") == "OBarr") 
			jQuery("#DepDate").focus();
	});

	// Attach actions to the radio button options
	jQuery("#return").change(function() {
		showFlights();
		showReturn();
	});
	jQuery("#oneway").change(function() {
		showFlights();
		hideReturn();
	});
	jQuery("#multicity").change(function() {
	   top.location.href="http://www.wwgbe.com/eres/quicksearch-multi.aspx?lang=" + lang + "&agencyID=" + agencyID;
	});
	jQuery("#hotelsradio").change(function() {
	   hideFlights();
	});
	
	//hotels stuff
	jQuery("#hotelStartDate").datepicker({  
		showOn: 'both', 
		buttonImage: '/images/calendar2.gif', 
		buttonImageOnly: true, 
		showAnim: null,
		duration: '',
		minDate: 0,
		buttonText: '-',
		onSelect: function() { calculateDays(); }
	});
	jQuery("#hotelEndDate").datepicker({  
		showOn: 'both', 
		buttonImage: '/images/calendar2.gif', 
		buttonImageOnly: true, 
		showAnim: null,
		duration: '',
		minDate: 1,
		buttonText: '-',
		beforeShow: function() { getMinimumDaysHotel() },
		onSelect: function() { calculateDays(); }
	});
});

function fillFields(departureCity, arrivalCity) {
	jQuery("#OBdep").val(departureCity);
	jQuery("#OBarr").val(arrivalCity);
	createDialog(jQuery("#DepDate"), 'Please select your departure and return dates and then click search to continue.', 'Choose Dates to Continue');
}

function calculateDays() {
	date1 = jQuery.datepicker.parseDate('mm/dd/yy',jQuery("#hotelStartDate").val());
	date2 = jQuery.datepicker.parseDate('mm/dd/yy',jQuery("#hotelEndDate").val());

	if (date1 == null || date2 == null) 
		return false;
	//Set 1 day in milliseconds
	var one_day=1000*60*60*24;
	jQuery("#daysBetween").html( Math.ceil((date2.getTime()-date1.getTime())/(one_day)) );
	return true;
}

function init() { }

function getMinimumDays() { 
	try	{ jQuery("#ArrDate").datepicker("option", "minDate", jQuery("#DepDate").datepicker("getDate")); }
	catch (e) { }
}

function getMinimumDaysHotel() { 
	try { 
		var tempDate1 = jQuery.datepicker.parseDate('mm/dd/yy',jQuery("#hotelStartDate").val());
		tempDate1.addDays(1);
		jQuery( "#hotelEndDate" ).datepicker( "option", "minDate", tempDate1 ); 
	} catch(e) { }
}

function changeRooms() {
	numberOfRooms = parseInt(jQuery("#hotelRooms").val());
	if (numberOfRooms == 1) {
		jQuery(".roomlist2,.roomlist3,.roomlist4").hide();
	}
	if (numberOfRooms == 2) {
		jQuery(".roomlist2").show();
		jQuery(".roomlist3,.roomlist4").hide();
	}
	if (numberOfRooms == 3) {
		jQuery(".roomlist2,.roomlist3").show();
		jQuery(".roomlist4").hide();
	}
	if (numberOfRooms == 4) {
		jQuery(".roomlist2,.roomlist3,.roomlist4").show();
	}
}

// Check all field inputs for validity and, if correct, redirect the user.
function checkHotelsForm() {

	var temp;

	if (jQuery("#hotelLocation").val() == "" || jQuery("#hotelLocation").val() == " " || jQuery("#hotelLocation").val() == null) {
		createDialog(jQuery("#hotelLocation"), "You must enter a city or airport code", "City Missing");
		return false;
	}
	
	if(jQuery("#hotelStartDate").val() == "" || jQuery("hotelStartDate").val() == " ") {
		createDialog(jQuery("#hotelStartDate"), "You must enter a check-in date.", "Date Missing");
		return false;
	}
	
	try {
		temp = jQuery.datepicker.parseDate('mm/dd/yy', jQuery("#hotelStartDate").val());
	} catch (e) {
		if (e == "Invalid date") { 
			createDialog(jQuery("#hotelStartDate"), 'Your check-in date does not appear to be a valid date.', 'Check-In Date Error');
		} else {
			createDialog(jQuery("#hotelStartDate"), 'Please ensure that your check-in date follows the format mm/dd/yyyy.', 'Check-In Date Error');
		}
		return false;
	}
	
	if(jQuery("#hotelEndDate").val() == "" || jQuery("hotelEndDate").val() == " ") {
		createDialog(jQuery("#hotelEndDate"), "You must enter a check-out date.", "Date Missing");
		return false;
	}
	
	try {
		temp = jQuery.datepicker.parseDate('mm/dd/yy', jQuery("#hotelEndDate").val());
	} catch (e) {
		if (e == "Invalid date") { 
			createDialog(jQuery("#hotelEndDate"), 'Your check-out date does not appear to be a valid date.', 'Check-Out Date Error');
		} else {
			createDialog(jQuery("#hotelEndDate"), 'Please ensure that your check-out date follows the format mm/dd/yyyy.', 'Check-Out Date Error');
		}
		return false;
	}

	var fullcity = jQuery("#hotelLocation").val();
	var airportCode = "";
	var trimmedCity = "";

	n = fullcity.indexOf('(');
	if (n>0) {
		airportCode = fullcity.substring(n+1,fullcity.length-1);
		trimmedCity = trim(airportCode,' ');
	} else { 
		trimmedCity = fullcity.toUpperCase();
	}
	
	var foundCities = [];
	var citiesReturnedString = "";
	
	if (trimmedCity.length != 3) {
		for (var i = 0; i < airports.length; i ++) {
			if (airports[i].toLowerCase().indexOf(jQuery("#hotelLocation").val().toLowerCase()) != -1) {
				foundCities.push(airports[i]);
			}
		}
		for (var i = 0; i < foundCities.length; i ++) {
			citiesReturnedString += '<li><a href="#" onclick="jQuery(\'#hotelLocation\').val(\'' + foundCities[i] + '\'); jQuery(\'#dialog\').dialog(\'close\');">' + foundCities[i] + '</li>';
		}
	
		createDialog(jQuery("#hotelLocation"), 'Please select a city from the dropdown options or enter a 3 digit airport code for your city.<br /><strong>Did you mean:</strong><br /><ul>' + citiesReturnedString + '</ul>', "Unknown City");
		return false;
	}

	// Redirect the user
	var newURL = "http://www.wwgbe.com/eres/hotelsdisp.aspx?hotelStartDate=" + jQuery("#hotelStartDate").val() +
				"&hotelEndDate="		+ jQuery("#hotelEndDate").val() +
				"&cityCode="		+ trimmedCity +
				"&hotelGuests="		+ "1" +
				"&starRating="		+ jQuery("#hotelStarRating").val() +
				"&hotelRooms="		+ jQuery("#hotelRooms").val() +
				"&hotelName="		+ jQuery("#hotelName").val() +
				"&adts1="		+ jQuery("#adts1").val() +
				"&adts2="		+ jQuery("#adts2").val() +
				"&adts3="		+ jQuery("#adts3").val() +
				"&adts4="		+ jQuery("#adts4").val() +
				"&BookingRef=" + jQuery("#BookingRef").val() +
				"&agencyID="		+ agencyID;
	
	top.location.href=newURL;

	return false;
}

function showReturn() {
	jQuery("#adatecol, #atimecol").fadeIn();
}
function hideReturn() {
	jQuery("#adatecol, #atimecol").fadeOut();
}

function hideFlights() {
	jQuery("#flightstable").hide();
	jQuery("#hotelstable").show();
}

function showFlights() {
	jQuery("#hotelstable").hide();
	jQuery("#flightstable").show();
}

/*
Begin form processing scripts.
The following scripts process the submission form and error check before sending.
*/

//Return flights auto fill the inbound destinations.
function completeAutofill() {
	if (jQuery('[name=radioval]:checked').val() != "M") {
		jQuery("#IBarr").val(jQuery("#OBdep").val());
		jQuery("#IBdep").val(jQuery("#OBarr").val());
	}
}

// Generic trimming functions to pull the airport code out of city names
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+jQuery", "g"), "");
}

// Trim the city names to include only the three character airport code for form submission,
// then assign the trimmed airport codes to hidden fields.
function trimCities() {

	var arr = jQuery("#OBarr").val();
	var n = arr.indexOf('(');
	var arrn = "";
	
	if(n>0) {
		arrn=arr.substring(n+1,arr.length-1);
		jQuery("#OBarrvl").val(trim(arrn,' '));
	} else {
		jQuery("#OBarrvl").val(arr);
	}

	arr = jQuery("#OBdep").val();
	n = arr.indexOf('(');
	if(n>0) {
		arrn=arr.substring(n+1,arr.length-1);
		jQuery("#OBdepart").val(trim(arrn,' '));
	} else {
		jQuery("#OBdepart").val(arr);
	}
	
	arr = jQuery("#IBdep").val();
	n = arr.indexOf('(');
	if(n>0) {
		arrn=arr.substring(n+1,arr.length-1);
		jQuery("#IBdepart").val(trim(arrn,' '));
	} else {
		jQuery("#IBdepart").val(arr);
	}
	
	arr = jQuery("#IBarr").val();
	n = arr.indexOf('(');
	if(n>0) {
		arrn=arr.substring(n+1,arr.length-1);
		jQuery("#IBarrvl").val(trim(arrn,' '));
	} else {
		jQuery("#IBarrvl").val(arr);
	}
	return true;
}

function checkDepartAndArrivalDates() {
	var departureDate = jQuery("#DepDate").val();
	var arrivalDate = jQuery("#ArrDate").val();
	
	
	if (departureDate == null || departureDate == "") {
		createDialog(jQuery("#DepDate"), translations[lang].qsEnterDepDate, translations[lang].qsDateError);
		return false;
	}
	if ((arrivalDate == null || arrivalDate == "") && (jQuery('[name=radioval]:checked').val() != "O")) {
		createDialog(jQuery("#ArrDate"), translations[lang].qsEnterArrDate, translations[lang].qsDateError);
		return false;
	}
	
	try {
		departureDate = jQuery.datepicker.parseDate('mm/dd/yy', departureDate);
	} catch (e) {
		if (e == "Invalid date") { 
			createDialog(jQuery("#DepDate"), translations[lang].qsDepDateInvalid, translations[lang].qsDateError);
		} else {
			createDialog(jQuery("#DepDate"), translations[lang].qsInvalidDateFormat, translations[lang].qsDateError);
		}
		return false;
	}
	
	try {
		arrivalDate = jQuery.datepicker.parseDate('mm/dd/yy', arrivalDate);
	} catch (e) {
		if (e == "Invalid date") { 
			createDialog(jQuery("#ArrDate"), translations[lang].qsArrDateInvalid, translations[lang].qsDateError);
		} else {
			createDialog(jQuery("#ArrDate"), translations[lang].qsInvalidDateFormat, translations[lang].qsDateError);
		}
		return false;
	}
	
	if ( (departureDate > arrivalDate) && (jQuery('[name=radioval]:checked').val() != "O")) {
		createDialog(jQuery("#ArrDate"), translations[lang].qsDatesConflict, translations[lang].qsDateError);
		return false;
	}
	return true;
}

function checkTotPax() {
	if (parseInt(jQuery("#nbinfants").val()) > parseInt(jQuery("#nbadults").val())) {
		createDialog(jQuery("#nbinfants"), translations[lang].qsPaxAdultsInfantsError, translations[lang].qsPaxErrorTitle);
		return false;
	}
	if ((parseInt(jQuery("#nbadults").val()) + parseInt(jQuery("#nbchilds").val())) > 8) {
		createDialog(jQuery("#nbadults"), translations[lang].qsPaxAdultsChildrenError, translations[lang].qsPaxErrorTitle);
		return false;
	}
	if (parseInt(jQuery("#nbchilds").val()) > (parseInt(jQuery("#nbadults").val()) *2)) {
		createDialog(jQuery("#nbadults"), translations[lang].qsPaxTotalError, translations[lang].qsPaxErrorTitle);
		return false;
	}
	if ((parseInt(jQuery("#nbchilds").val()) + parseInt(jQuery("#nbinfants").val())) > (parseInt(jQuery("#nbadults").val()) *2)) {
		createDialog(jQuery("#nbadults"), translations[lang].qsPaxTotalError, translations[lang].qsPaxErrorTitle);
		return false;
	}
	if ((parseInt(jQuery("#nbchilds").val()) + parseInt(jQuery("#nbinfants").val()) + parseInt(jQuery("#nbadults").val())) > 9) {
		createDialog(jQuery("#nbadults"), translations[lang].qsPaxTotalError, translations[lang].qsPaxErrorTitle);
		return false;
	}

	return true;
}

// Requires jQuery UI with dialog.
function createDialog(element, errorText, errorTitle) {
	if (!errorTitle) 
		errorTitle = "Error";
		
	// If no element is passed for the alert, put the box somwhere in the middle of the viewport.
	var offsetX = "45%";
	var offsetY = "50%";
	var pageScroll = getPageScroll();
	var nonbubble = true;
	
	//For positioning the popup box, use offsets of the passed element.
	if (element != null) {
		var offsetBox = element;
		offsetX = offsetBox.offset().left + 75 - pageScroll[0];
		offsetY = offsetBox.offset().top - 8 - pageScroll[1];
		nonbubble = false; 
	}

	//Custom alert dialog initilialization 
	jQuery('#dialog').dialog({
		autoOpen: false,
		title: errorTitle,
		buttons: { "Ok": function() { jQuery(this).dialog("close"); } },
		modal: true,
		draggable: false,
		height: 190,
		bgiframe: true,
		position: [offsetX,offsetY]
	});
	
	if (element != null) {
		jQuery('#dialog').dialog({
			close: function(event,ui) { element.focus(); }
		});
	}
			
	jQuery('#dialog').html(errorText);
	
	if (nonbubble) {
		jQuery('#dialog').dialog( { dialogClass: 'nonbubble' } );
	}
	jQuery('#dialog').dialog('open');
	
	var isMSIE = /*@cc_on!@*/false;
	if (isMSIE) { 
		window.scrollTo(1,1);
	}
}

// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll);
}

function langSelect() {
	var lang = jQuery("#langBox").val();
	top.location.href= "index.aspx?lang=" + lang + "&agencyID=" + agencyID;
}

function langSelect2() {
	var lang = jQuery("#langBox").val();
	top.location.href= "index-flights+hotels.aspx?lang=" + lang + "&agencyID=" + agencyID;
}

function setSearchType(searchType) {
	this.searchType = searchType
}

// Check all field inputs for validity and, if correct, redirect the user.
function checkWholeForm() {
	var newURL = "";

	directonly = jQuery('#directOnly').attr('checked')?1:0;

	if (!checkTotPax())
		return false;
	
	if (jQuery("#OBdep").val() == "") {
		createDialog(jQuery("#OBdep"), translations[lang].qsDepLocationError, translations[lang].qsLocationsError);
		return false;
	}
	
	if (jQuery("#OBdep").val().length < 3) {
		createDialog(jQuery("#OBdep"), "Your departure city name is too short.<br /><br /> Please try again and pick a city from the list of options, or enter a 3 letter aiport code before continuing.", "Departure City Incorrect");
		return false;
	}
	
	if (jQuery("#OBarr").val() == "") {
		createDialog(jQuery("#OBarr"), translations[lang].qsArrLocationError, translations[lang].qsLocationsError);
		return false;
	}
	
	if (jQuery("#OBarr").val().length < 3) {
		createDialog(jQuery("#OBarr"), "Your arrival city name is too short.<br /><br /> Please try again and pick a city from the list of options, or enter a 3 letter aiport code before continuing.", "Arrival City Incorrect");
		return false;
	}
	
	if (!checkDepartAndArrivalDates()) 
		return false;
		
	// Trim the city names to get airport codes
	var fullcity = "";
	var airportCode = "";
	var n = 0;
	
	fullcity = jQuery("#OBdep").val();
	n = fullcity.indexOf('(');
	if (n>0) {
		airportCode = fullcity.substring(n+1,fullcity.length-1);
		trimmedOBdep = trim(airportCode,' ');
	} else { 
		trimmedOBdep = fullcity.toUpperCase();
	}
	
	fullcity = jQuery("#OBarr").val();
	n = fullcity.indexOf('(');
	if (n>0) {
		airportCode = fullcity.substring(n+1,fullcity.length-1);
		trimmedOBarr = trim(airportCode,' ');
	} else { 
		trimmedOBarr = fullcity.toUpperCase();
	}
	
	fullcity = jQuery("#IBdep").val();
	n = fullcity.indexOf('(');
	if (n>0) {
		airportCode = fullcity.substring(n+1,fullcity.length-1);
		trimmedIBdep = trim(airportCode,' ');
	} else { 
		trimmedIBdep = fullcity.toUpperCase();
	}
	
	fullcity = jQuery("#IBarr").val();
	n = fullcity.indexOf('(');
	if (n>0) {
		airportCode = fullcity.substring(n+1,fullcity.length-1);
		trimmedIBarr = trim(airportCode,' ');
	} else { 
		trimmedIBarr = fullcity.toUpperCase();
	}
	
	
	var foundAirports = [];
	var airportsReturnedString = "";
	
	if (trimmedOBdep.length !=3) {
		for (var i = 0; i < airports.length; i ++) {
			if (airports[i].toLowerCase().indexOf(jQuery("#OBdep").val().toLowerCase()) != -1) {
				foundAirports.push(airports[i]);
			}
		}
		for (var i = 0; i < foundAirports.length; i ++) {
			airportsReturnedString += '<li><a href="#" onclick="jQuery(\'#OBdep\').val(\'' + foundAirports[i] + '\'); jQuery(\'#dialog\').dialog(\'close\');">' + foundAirports[i] + '</li>';
		}

		createDialog(jQuery("#OBdep"), 'We require an airport code for your departure city.<br /><br /><strong>Did you mean:</strong><br /><ul>' + airportsReturnedString + '</ul>', "Which aiport did you mean?");
		return false;

	}
	
	foundAirports = [];
	airportsReturnedString = "";
	
	if (trimmedOBarr.length !=3) {
		for (var i = 0; i < airports.length; i ++) {
			if (airports[i].toLowerCase().indexOf(jQuery("#OBarr").val().toLowerCase()) != -1) {
				foundAirports.push(airports[i]);
			}
		}
		for (var i = 0; i < foundAirports.length; i ++) {
			airportsReturnedString += '<li><a href="#" onclick="jQuery(\'#OBarr\').val(\'' + foundAirports[i] + '\'); jQuery(\'#dialog\').dialog(\'close\');">' + foundAirports[i] + '</li>';
		}

		createDialog(jQuery("#OBarr"), 'We require an airport code for your departure city.<br /><br /><strong>Did you mean:</strong><br /><ul>' + airportsReturnedString + '</ul>', "Which airport did you mean?");
		return false;

	}
	
	// Autocomplete fix to stop it from blanking out the fields in firefox
	// when the user hits the back button.
	jQuery(".citySelect").removeAttr("autocomplete");
	
	newURL = "";
	
	if (searchType == 'flexi') {
		newURL = "http://www.wwgbe.com/eres/faresdisp_3day.aspx";
	} else {
		newURL = "http://www.wwgbe.com/eres/faresdisp.aspx";
	}
	
	// Redirect the user
	newURL +=	"?OBDep="		+ trimmedOBdep +
				"&OBArr="		+ trimmedOBarr +
				"&IBDep="		+ trimmedIBdep +
				"&IBArr="		+ trimmedIBarr +
				"&Airline="		+ jQuery("#Airline").val() +
				"&DepDate="		+ jQuery("#DepDate").val() +
				"&ArrDate="		+ jQuery("#ArrDate").val() +
				"&FareType="	+ jQuery("#FareType").val() +
				"&radioval="	+ jQuery('[name=radioval]:checked').val() +
				"&LowestFares="	+ "" +
				"&nbadults="	+ jQuery("#nbadults").val() +
				"&nbchilds="	+ jQuery("#nbchilds").val() +
				"&nbinfants="	+ jQuery("#nbinfants").val() +
				"&OBtime="		+ jQuery("#OBtime").val() +
				"&IBtime="		+ jQuery("#IBtime").val() +
				"&directOnly="	+ directonly +
				"&lang="		+ lang +
				"&agencyID="	+ agencyID;
	
	top.location.href=newURL;

	return false;
}
