// Some globals
var trimmedOBdep;
var trimmedOBarr;
var trimmedIBdep;
var trimmedIBarr;
var depapt = [];
var arrapt = [];
var directonly;
var searchType = 'exact';

$(document).ready(function(){
	// Default to return flights
	$("[name=radioval]").attr("checked", false);
	$("#return").attr("checked", true);

	// Popup calender initialization
	$("#DepDate").datepicker({  
		showOn: 'both', 
		buttonImage: '/images/calendar2.gif', 
		buttonImageOnly: true, 
		showAnim: null,
		duration: '',
		buttonText: '-',
		minDate: 0 
	});
	$("#ArrDate").datepicker({  
		showOn: 'both', 
		buttonImage: '/images/calendar2.gif', 
		buttonImageOnly: true, 
		showAnim: null,
		duration: '',
		minDate: 1,
		buttonText: '-',
		beforeShow: function() { getMinimumDays(); }
	});
	
	// Show tooltips
	$('input,.ttip,label,.stdinput').tooltip({ 
		track: true, delay: 0, showURL: false, showBody: " - ", fade: 0 
	});

	// Autocomplete initilialization
	$(".citySelect")
		.autocomplete(airports, {
			autoFill: false,
			selectFirst: true,
			max: 18,
			mustMatch: false,
			matchContains: true,
			scrollHeight: 220,
			width: 190
		})
		.result(function() {
		  completeAutofill();
		  if ($(this).attr("id") == "OBdep") {
			$("#OBarr").focus();
		  }
		  if ($(this).attr("id") == "OBarr")  {
			$("#DepDate").focus();
		  }
	});

	// Attach actions to the radio button options
	$("#return").change(function() {
		showReturn();
	});
	$("#oneway").change(function() {
		hideReturn();
	});
	$("#multicity").change(function() {
	   top.location.href="http://www.flylink.com/eres/quicksearch-multi.aspx?lang=" + lang + "&agencyID=" + agencyID;
	});

	//hotels stuff
	$("#hotelStartDate").datepicker({  
		showOn: 'both', 
		buttonImage: '/images/calendar2.gif', 
		buttonImageOnly: true, 
		showAnim: null,
		duration: '',
		minDate: 0,
		buttonText: '-',
		onSelect: function() { calculateDays(); }
	});
	$("#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) {
	$("#OBdep").val(departureCity);
	$("#OBarr").val(arrivalCity);
	createDialog($("#DepDate"), 'Please select your departure and return dates and then click search to continue.', 'Choose Dates to Continue');
}

function calculateDays() {
	date1 = $.datepicker.parseDate('mm/dd/yy',$("#hotelStartDate").val());
	date2 = $.datepicker.parseDate('mm/dd/yy',$("#hotelEndDate").val());

	if (date1 === null || date2 === null) 
		return false;
	//Set 1 day in milliseconds
	var one_day=1000*60*60*24;
	$("#daysBetween").html( Math.ceil((date2.getTime()-date1.getTime())/(one_day)) );
	return true;
}

function init() { }

function getMinimumDays() { 
	try	{ $("#ArrDate").datepicker("option", "minDate", $("#DepDate").datepicker("getDate")); }
	catch (e) { }
}

function getMinimumDaysHotel() { 
	try { 
		var tempDate1 = $.datepicker.parseDate('mm/dd/yy',$("#hotelStartDate").val());
		tempDate1.addDays(1);
		$( "#hotelEndDate" ).datepicker( "option", "minDate", tempDate1 ); 
	} catch(e) { }
}

function changeRooms() {
	numberOfRooms = parseInt($("#hotelRooms").val());
	if (numberOfRooms == 1) {
		$(".roomlist2,.roomlist3,.roomlist4").hide();
	}
	if (numberOfRooms == 2) {
		$(".roomlist2").show();
		$(".roomlist3,.roomlist4").hide();
	}
	if (numberOfRooms == 3) {
		$(".roomlist2,.roomlist3").show();
		$(".roomlist4").hide();
	}
	if (numberOfRooms == 4) {
		$(".roomlist2,.roomlist3,.roomlist4").show();
	}
}

// Check all field inputs for validity and, if correct, redirect the user.
function checkHotelsForm() {

	var temp;

	if ($("#hotelLocation").val() === "" || $("#hotelLocation").val() === " " || $("#hotelLocation").val() === null) {
		createDialog($("#hotelLocation"), "You must enter a city or airport code", "City Missing");
		return false;
	}
	
	if($("#hotelStartDate").val() === "" || $("hotelStartDate").val() === " ") {
		createDialog($("#hotelStartDate"), "You must enter a check-in date.", "Date Missing");
		return false;
	}
	
	try {
		temp = $.datepicker.parseDate('mm/dd/yy', $("#hotelStartDate").val());
	} catch (e) {
		if (e == "Invalid date") { 
			createDialog($("#hotelStartDate"), 'Your check-in date does not appear to be a valid date.', 'Check-In Date Error');
		} else {
			createDialog($("#hotelStartDate"), 'Please ensure that your check-in date follows the format mm/dd/yyyy.', 'Check-In Date Error');
		}
		return false;
	}
	
	if($("#hotelEndDate").val() == "" || $("hotelEndDate").val() == " ") {
		createDialog($("#hotelEndDate"), "You must enter a check-out date.", "Date Missing");
		return false;
	}
	
	try {
		temp = $.datepicker.parseDate('mm/dd/yy', $("#hotelEndDate").val());
	} catch (e) {
		if (e == "Invalid date") { 
			createDialog($("#hotelEndDate"), 'Your check-out date does not appear to be a valid date.', 'Check-Out Date Error');
		} else {
			createDialog($("#hotelEndDate"), 'Please ensure that your check-out date follows the format mm/dd/yyyy.', 'Check-Out Date Error');
		}
		return false;
	}

	var fullcity = $("#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($("#hotelLocation").val().toLowerCase()) != -1) {
				foundCities.push(airports[i]);
			}
		}
		for (var i = 0; i < foundCities.length; i ++) {
			citiesReturnedString += '<li><a href="#" onclick="$(\'#hotelLocation\').val(\'' + foundCities[i] + '\'); $(\'#dialog\').dialog(\'close\');">' + foundCities[i] + '</li>';
		}
	
		createDialog($("#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.flylink.com/eres/hotelsdisp.aspx?hotelStartDate=" + $("#hotelStartDate").val() +
				"&hotelEndDate="		+ $("#hotelEndDate").val() +
				"&cityCode="		+ trimmedCity +
				"&hotelGuests="		+ "1" +
				"&starRating="		+ $("#hotelStarRating").val() +
				"&hotelRooms="		+ $("#hotelRooms").val() +
				"&hotelName="		+ $("#hotelName").val() +
				"&adts1="		+ $("#adts1").val() +
				"&adts2="		+ $("#adts2").val() +
				"&adts3="		+ $("#adts3").val() +
				"&adts4="		+ $("#adts4").val() +
				"&BookingRef=" + $("#BookingRef").val() +
				"&agencyID="		+ agencyID;
	
	top.location.href=newURL;

	return false;
}

function showReturn() {
	$("#adatecol, #atimecol").fadeIn();
}
function hideReturn() {
	$("#adatecol, #atimecol").fadeOut();
}

/*
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 ($('[name=radioval]:checked').val() != "M") {
		$("#IBarr").val($("#OBdep").val());
		$("#IBdep").val($("#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 + "]+$", "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 = $("#OBarr").val();
	var n = arr.indexOf('(');
	var arrn = "";
	
	if(n>0) {
		arrn=arr.substring(n+1,arr.length-1);
		$("#OBarrvl").val(trim(arrn,' '));
	} else {
		$("#OBarrvl").val(arr);
	}

	arr = $("#OBdep").val();
	n = arr.indexOf('(');
	if(n>0) {
		arrn=arr.substring(n+1,arr.length-1);
		$("#OBdepart").val(trim(arrn,' '));
	} else {
		$("#OBdepart").val(arr);
	}
	
	arr = $("#IBdep").val();
	n = arr.indexOf('(');
	if(n>0) {
		arrn=arr.substring(n+1,arr.length-1);
		$("#IBdepart").val(trim(arrn,' '));
	} else {
		$("#IBdepart").val(arr);
	}
	
	arr = $("#IBarr").val();
	n = arr.indexOf('(');
	if(n>0) {
		arrn=arr.substring(n+1,arr.length-1);
		$("#IBarrvl").val(trim(arrn,' '));
	} else {
		$("#IBarrvl").val(arr);
	}
	return true;
}

function checkDepartAndArrivalDates() {
	var departureDate = $("#DepDate").val();
	var arrivalDate = $("#ArrDate").val();
	
	
	if (departureDate === null || departureDate === "") {
		createDialog($("#DepDate"), translations[lang].qsEnterDepDate, translations[lang].qsDateError);
		return false;
	}
	if ((arrivalDate === null || arrivalDate === "") && ($('[name=radioval]:checked').val() != "O")) {
		createDialog($("#ArrDate"), translations[lang].qsEnterArrDate, translations[lang].qsDateError);
		return false;
	}
	
	try {
		departureDate = $.datepicker.parseDate('mm/dd/yy', departureDate);
	} catch (e) {
		if (e == "Invalid date") { 
			createDialog($("#DepDate"), translations[lang].qsDepDateInvalid, translations[lang].qsDateError);
		} else {
			createDialog($("#DepDate"), translations[lang].qsInvalidDateFormat, translations[lang].qsDateError);
		}
		return false;
	}
	
	try {
		arrivalDate = $.datepicker.parseDate('mm/dd/yy', arrivalDate);
	} catch (e) {
		if (e == "Invalid date") { 
			createDialog($("#ArrDate"), translations[lang].qsArrDateInvalid, translations[lang].qsDateError);
		} else {
			createDialog($("#ArrDate"), translations[lang].qsInvalidDateFormat, translations[lang].qsDateError);
		}
		return false;
	}
	
	if ( (departureDate > arrivalDate) && ($('[name=radioval]:checked').val() != "O")) {
		createDialog($("#ArrDate"), translations[lang].qsDatesConflict, translations[lang].qsDateError);
		return false;
	}
	return true;
}

function checkTotPax() {
	if (parseInt($("#nbinfants").val(), 10) > parseInt($("#nbadults").val(), 10)) {
		createDialog($("#nbinfants"), translations[lang].qsPaxAdultsInfantsError, translations[lang].qsPaxErrorTitle);
		return false;
	}
	if ((parseInt($("#nbadults").val(), 10) + parseInt($("#nbchilds").val(), 10)) > 8) {
		createDialog($("#nbadults"), translations[lang].qsPaxAdultsChildrenError, translations[lang].qsPaxErrorTitle);
		return false;
	}
	if (parseInt($("#nbchilds").val(), 10) > (parseInt($("#nbadults").val(), 10) *2)) {
		createDialog($("#nbadults"), translations[lang].qsPaxTotalError, translations[lang].qsPaxErrorTitle);
		return false;
	}
	if ((parseInt($("#nbchilds").val(), 10) + parseInt($("#nbinfants").val(), 10)) > (parseInt($("#nbadults").val(), 10) *2)) {
		createDialog($("#nbadults"), translations[lang].qsPaxTotalError, translations[lang].qsPaxErrorTitle);
		return false;
	}
	if ((parseInt($("#nbchilds").val(), 10) + parseInt($("#nbinfants").val(), 10) + parseInt($("#nbadults").val(), 10)) > 9) {
		createDialog($("#nbadults"), translations[lang].qsPaxTotalError, translations[lang].qsPaxErrorTitle);
		return false;
	}

	return true;
}

// Requires $ 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 
	$('#dialog').dialog({
		autoOpen: false,
		title: errorTitle,
		buttons: { "Ok": function() { $(this).dialog("close"); } },
		modal: true,
		draggable: false,
		height: 'auto',
		bgiframe: true,
		position: [offsetX,offsetY]
	});
	
	if (element !== null) {
		$('#dialog').dialog({
			close: function(event,ui) { element.focus(); }
		});
	}
			
	$('#dialog').html(errorText);
	
	if (nonbubble) {
		$('#dialog').dialog( { dialogClass: 'nonbubble' } );
	}
	$('#dialog').dialog('open');
	
	var isMSIE = /*@cc_on!@*/false;
	if (isMSIE) { 
		window.scrollTo(1,1);
	}
}

// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
	var returnArray = [];
    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;
    }
	returnArray = [xScroll,yScroll];
    return returnArray;
}

function langSelect() {
	var lang = $("#langBox").val();
	top.location.href= "index.aspx?lang=" + lang + "&agencyID=" + agencyID;
}

function langSelect2() {
	var lang = $("#langBox").val();
	top.location.href= "index-flights+hotels.aspx?lang=" + lang + "&agencyID=" + agencyID;
}

function setSearchType(searchType) {
	this.searchType = searchType;
}

function swapTab(tab,bgoffset) {
	$('.q-panel').hide();
	$('#'+tab+'-panel').show();
	$('.searchNAVicons li a').css('color','#000066');
	$('.searchNAVicons li a').css('background','transparent no-repeat');
	$('#search'+tab+' a').css('color','#ff6600');
	$('#search'+tab+' a').css('background-image','url("/images/searchNAV.gif")');
	$('#search'+tab+' a').css('background-position',bgoffset + ' -40px');
}

// Check all field inputs for validity and, if correct, redirect the user.
function checkWholeForm() {
	var newURL = "";

	directonly = $('#directOnly').attr('checked')?1:0;

	if (!checkTotPax())
		return false;
	
	if ($("#OBdep").val() === "") {
		createDialog($("#OBdep"), translations[lang].qsDepLocationError, translations[lang].qsLocationsError);
		return false;
	}
	
	if ($("#OBdep").val().length < 3) {
		createDialog($("#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 ($("#OBarr").val() === "") {
		createDialog($("#OBarr"), translations[lang].qsArrLocationError, translations[lang].qsLocationsError);
		return false;
	}
	
	if ($("#OBarr").val().length < 3) {
		createDialog($("#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 = $("#OBdep").val();
	n = fullcity.indexOf('(');
	if (n>0) {
		airportCode = fullcity.substring(n+1,fullcity.length-1);
		trimmedOBdep = trim(airportCode,' ');
	} else { 
		trimmedOBdep = fullcity.toUpperCase();
	}
	
	fullcity = $("#OBarr").val();
	n = fullcity.indexOf('(');
	if (n>0) {
		airportCode = fullcity.substring(n+1,fullcity.length-1);
		trimmedOBarr = trim(airportCode,' ');
	} else { 
		trimmedOBarr = fullcity.toUpperCase();
	}
	
	fullcity = $("#IBdep").val();
	n = fullcity.indexOf('(');
	if (n>0) {
		airportCode = fullcity.substring(n+1,fullcity.length-1);
		trimmedIBdep = trim(airportCode,' ');
	} else { 
		trimmedIBdep = fullcity.toUpperCase();
	}
	
	fullcity = $("#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($("#OBdep").val().toLowerCase()) != -1) {
				foundAirports.push(airports[i]);
			}
		}
		for (var i = 0; i < foundAirports.length; i ++) {
			airportsReturnedString += '<li><a href="#" onclick="$(\'#OBdep\').val(\'' + foundAirports[i] + '\'); $(\'#dialog\').dialog(\'close\');">' + foundAirports[i] + '</li>';
		}

		createDialog($("#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($("#OBarr").val().toLowerCase()) != -1) {
				foundAirports.push(airports[i]);
			}
		}
		for (var i = 0; i < foundAirports.length; i ++) {
			airportsReturnedString += '<li><a href="#" onclick="$(\'#OBarr\').val(\'' + foundAirports[i] + '\'); $(\'#dialog\').dialog(\'close\');">' + foundAirports[i] + '</li>';
		}

		createDialog($("#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.
	$(".citySelect").removeAttr("autocomplete");
	
	newURL = "";
	
	if (searchType == 'flexi') {
		newURL = "http://www.flylink.com/eres/faresdisp_3day.aspx";
	} else {
		newURL = "http://www.flylink.com/eres/faresdisp.aspx";
	}
	
	// Redirect the user
	newURL +=	"?OBDep="		+ trimmedOBdep +
				"&OBArr="		+ trimmedOBarr +
				"&IBDep="		+ trimmedIBdep +
				"&IBArr="		+ trimmedIBarr +
				"&Airline="		+ $("#Airline").val() +
				"&DepDate="		+ $("#DepDate").val() +
				"&ArrDate="		+ $("#ArrDate").val() +
				"&FareType="	+ $("#FareType").val() +
				"&radioval="	+ $('[name=radioval]:checked').val() +
				"&LowestFares="	+ "" +
				"&nbadults="	+ $("#nbadults").val() +
				"&nbchilds="	+ $("#nbchilds").val() +
				"&nbinfants="	+ $("#nbinfants").val() +
				"&OBtime="		+ $("#OBtime").val() +
				"&IBtime="		+ $("#IBtime").val() +
				"&directOnly="	+ directonly +
				"&lang="		+ lang +
				"&agencyID="	+ agencyID;
	
	top.location.href=newURL;

	return false;
}
