﻿var Search = new function () {

	var me = this;

	this.GeographyLevel3ID = 0;

	//speedup on first load.
	this.bFirstSearchSelect = true;

	//option to keep the cookie but not load it.
	this.bLoadCookie = true;

	//setup
	this.Setup = function () {

		//set up date picker control
		var dMinDate = new Date();
		var iBookAheadDays = parseInt(f.GetValue('hidBookAheadDays'));
		d.AddDays(dMinDate, iBookAheadDays);

		var sDepartureDate = f.GetValue('hidDepartureDate');
		var sReturnDate = f.GetValue('hidReturnDate')

		var dDepartureDate = new Date(sDepartureDate.split(',')[0], sDepartureDate.split(',')[1] - 1, sDepartureDate.split(',')[2]);
		var dReturnDate = new Date(sReturnDate.split(',')[0], sReturnDate.split(',')[1] - 1, sReturnDate.split(',')[2]);

		$(function () {
			$("#txtDepartureDate").datepicker({ numberOfMonths: 1, dateFormat: 'dd/mm/yy', minDate: dMinDate, defaultDate: dDepartureDate,
				onSelect: function () { Search.SetCheckOutDate(); }
			}); constrainInput: true
		});

		$(function () { $("#txtReturnDate").datepicker({ numberOfMonths: 1, dateFormat: 'dd/mm/yy', minDate: dMinDate, defaultDate: dReturnDate, onSelect: function () { Search.SetDuration(); } }); });

		f.SetValue('txtDepartureDate', ((d.Day(dDepartureDate) < 10) ? '0' : '') + d.Day(dDepartureDate) + '/' + ((d.Month(dDepartureDate) < 10) ? '0' : '') + d.Month(dDepartureDate) + '/' + d.Year(dDepartureDate));
		f.SetValue('txtReturnDate', ((d.Day(dReturnDate) < 10) ? '0' : '') + d.Day(dReturnDate) + '/' + ((d.Month(dReturnDate) < 10) ? '0' : '') + d.Month(dReturnDate) + '/' + d.Year(dReturnDate));
		Search.SetDuration();

		//restore from cookie if set
		if (c.Get('searchrestore') && me.bLoadCookie) {
			var sSearchMode = c.Get('searchrestore').split('#')[0];

			if (dd.GetValue('sddGeographyLevel2ID') == 0) {
				dd.SetValue('sddGeographyLevel2ID', c.Get('searchrestore').split('#')[1]);

				me.GeographyLevel3ID = c.Get('searchrestore').split('#')[2]; //we have to let the level2select take care of setting the resort dropdown to this as we don't know when the webservice will return.
				//me.Level2Select(c.Get('searchrestore').split('#')[1]);

				dd.SetText('ddlRooms', c.Get('searchrestore').split('#')[6]);
				var sRoomValues = (c.Get('searchrestore').split('#')[8]);
				dd.SetText('ddl_1_Children', sRoomValues.split('|')[0]);
				dd.SetText('ddl_2_Children', sRoomValues.split('|')[1]);
				dd.SetText('ddl_3_Children', sRoomValues.split('|')[2]);
			}

			if (dd.GetValue('sddDepartureAirportID') == 0) {
				dd.SetValue('sddDepartureAirportID', c.Get('searchrestore').split('#')[3]);
				dd.SetValue('sddFlightOnlyDepartureAirportID', c.Get('searchrestore').split('#')[4]);
				dd.SetValue('sddArrivalAirportID', c.Get('searchrestore').split('#')[5]);
				dd.SetText('ddlFlightChildren', c.Get('searchrestore').split('#')[7]);
			}

			//show the correct buttons and options.
			//me.SearchSelect(c.Get('searchrestore').split('#')[0]);
		} else {
			me.SetDurationOptions();

			//we don't know if the page search options have been changed in the code so we must do this too...
			//the if blocks are a speedup.
			if (dd.GetValue('sddGeographyLevel2ID') != 0) {
				me.GeographyLevel3ID = dd.GetValue('sddGeographyLevel3ID'); // This is important! We sometimes set this in the codebehind so we don't want it overwritten!
				me.Level2Select(dd.GetValue('sddGeographyLevel2ID'));
			}
		}

		//attach event handlers to show child age dropdowns when necessary
		var aChildDropdowns = f.GetElementsByClassName('select', 'child');

		for (var i = 0; i < aChildDropdowns.length; i++) {
			f.AttachEvent(aChildDropdowns[i], 'change',
                function () {
                	Search.SearchShow();
                });
		}

		Search.SearchShow();
	}


	//set checkout date
	this.SetCheckOutDate = function () {
		var dCheckInDate = $("#txtDepartureDate").datepicker("getDate");
		var dMinCheckOutDate = d.AddDays(dCheckInDate, 1);
		$("#txtReturnDate").datepicker("option", "minDate", dMinCheckOutDate);
		Search.SetDuration();
	}


	//set duration
	this.SetDuration = function () {

		var sDepartureDate = f.GetValue('txtDepartureDate');
		var sReturnDate = f.GetValue('txtReturnDate');

		var dDepartureDate = d.New(sDepartureDate.split('/')[0], sDepartureDate.split('/')[1], sDepartureDate.split('/')[2]);
		var dReturnDate = d.New(sReturnDate.split('/')[0], sReturnDate.split('/')[1], sReturnDate.split('/')[2]);

		var iNights = d.DateDiff(dDepartureDate, dReturnDate);

		f.SetClassIf('txtReturnDate', 'error', iNights < 1);

		if (iNights < 1) {
			FormHandler.ShowWarning(f.GetValue('hidMLInvalidCheckOutDate'));
			return
		}

		dd.SetText('ddlDuration', iNights);
		var sNights = (iNights > 1) ? iNights + ' ' + f.GetValue('hidMLNights') : iNights + ' ' + f.GetValue('hidMLNight');
		f.SetHTML('spNights', sNights);

	}



	//set options for duration dropdown
	this.SetDurationOptions = function () {
		var sDurationText = dd.GetText('ddlDuration');

		if (me.SearchType() == 'Flight') {
			dd.SetOptions('ddlDuration', '0#1#2#3#4#5#6#7#8#9#10#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#27#28#29');
		} else {
			dd.SetOptions('ddlDuration', '1#2#3#4#5#6#7#8#9#10#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#27#28#29');
			if (sDurationText == '0') {
				sDurationText = '1';
			}
		}

		dd.SetText('ddlDuration', sDurationText);
	}



	//toggle extra rooms
	this.AddRoom = function () {
		var iRooms = me.SelectedRooms();
		iRooms++;
		dd.SetText('ddlRooms', iRooms);
		me.SearchShow();
	}


	this.RemoveRoom = function () {
		var iRooms = me.SelectedRooms();
		iRooms--;
		dd.SetText('ddlRooms', iRooms);
		me.SearchShow();
	}

	this.SearchShow = function () {
		var iRooms = me.SelectedRooms();

		f.SetHTML('tdRoom1', iRooms == 1 ? f.GetValue('hidMLGuests') : f.GetValue('hidMLRoom') + ' 1');

		for (var i = 1; i <= 5; i++) {

			var iChildren = me.ChildCount(i);

			f.ShowIf('trGuests_' + i, iRooms >= i);
			f.ShowIf('trAges_' + i, iRooms >= i && iChildren > 0);
			f.ShowIf('aRemoveRoom_' + i, i == iRooms);

			for (var j = 1; j <= 4; j++) {
				f.ShowIf('txtC_' + i + '_' + j, iChildren >= j);

				//clear error class
				f.RemoveClass('txtC_' + i + '_' + j, 'error');
			}
		}

	}


	//Search Validation
	this.SearchValidate = function () {

		FormHandler.CloseInfo();

		var bHotel = me.SearchType() == 'Hotel';
		var bFlight = me.SearchType() == 'Flight';
		var bFlightPlusHotel = me.SearchType() == 'FlightPlusHotel';

		if (bFlightPlusHotel) {
			f.SetClassIf('sddDepartureAirportID', 'error', f.GetValue('sddDepartureAirportID') == 0);
		}

		if (bFlight) {
			f.SetClassIf('sddFlightOnlyDepartureAirportID', 'error', f.GetValue('sddFlightOnlyDepartureAirportID') == 0);
			f.SetClassIf('sddArrivalAirportID', 'error', f.GetValue('sddArrivalAirportID') == '');
		}

		if (bHotel || bFlightPlusHotel) {
			f.SetClassIf('sddGeographyLevel2ID', 'error', f.GetValue('sddGeographyLevel2ID') == 0 && f.GetValue('acpGeographyLevel2IDHidden') == 0);
			f.SetClassIf('acpGeographyLevel2ID', 'error', f.GetValue('sddGeographyLevel2ID') == 0 && f.GetValue('acpGeographyLevel2IDHidden') == 0);
		}


		//make sure the correct duration is set from the dates that have been typed in
		Search.SetDuration();


		//check date and duration
		var sDepartureDate = f.GetValue('txtDepartureDate');
		var sReturnDate = f.GetValue('txtReturnDate');

		var dDepartureDate = d.New(sDepartureDate.split('/')[0], sDepartureDate.split('/')[1], sDepartureDate.split('/')[2]);
		var dReturnDate = d.New(sReturnDate.split('/')[0], sReturnDate.split('/')[1], sReturnDate.split('/')[2]);

		var iNights = d.DateDiff(dDepartureDate, dReturnDate);

		f.SetClassIf('txtReturnDate', 'error', iNights < 1);

		f.SetClassIf('txtDepartureDate', 'error', !d.IsDate(dDepartureDate) || f.GetValue('txtDepartureDate') == '');
		f.SetClassIf('txtReturnDate', 'error', !d.IsDate(dReturnDate) || f.GetValue('txtReturnDate') == '' || iNights < 1);


		//check child ages
		if (bFlight == true) {

			//flights
			iChildren = n.SafeInt(dd.GetText('ddlFlightChildren'));

			for (var iChild = 1; iChild <= iChildren; iChild++) {

				f.SetClassIf('txtFC_' + iChild, 'error', dd.GetText('txtC_' + iChild) == '');

			}

		} else {

			//rooms
			var iRooms = me.SelectedRooms();

			for (var i = 1; i <= iRooms; i++) {

				var iChildren = dd.GetText('ddl_' + i + '_Children');

				for (var j = 1; j <= iChildren; j++) {
					f.SetClassIf('txtC_' + i + '_' + j, 'error', dd.GetText('txtC_' + i + '_' + j) == '');
				}
			}
		}


		var aErrorControls = f.GetElementsByClassName('*', 'error', 'divSearch');

		if (aErrorControls.length == 0) {

			var sKeyValuePairString = f.GetContainerQueryString('divSearch');


			var sDepartureDate = f.GetValue('txtDepartureDate');
			var dDepartureDate = d.New(sDepartureDate.split('/')[0], sDepartureDate.split('/')[1], sDepartureDate.split('/')[2]);

			var sCalDepartureDate_MonthYear = 'calDepartureDate_MonthYear=' + d.Month(dDepartureDate) + '_' + d.Year(dDepartureDate);
			var sCalDepartureDate_Day = 'calDepartureDate_Day=' + d.Day(dDepartureDate);

			sKeyValuePairString += '&' + sCalDepartureDate_MonthYear + '&' + sCalDepartureDate_Day;


			ShowWaitMessage();

			//if ie6, hide the dropdowns!
			if (navigator.appName == 'Microsoft Internet Explorer' && parseFloat(navigator.appVersion.split('MSIE')[1]) < 7) {
				var aSelect = document.getElementsByTagName('select');
				for (var i = 0; i < aSelect.length; i++) {
					aSelect[i].style.visibility = 'hidden';

				}
			}

			ff.Call('Widgets.SearchTool.GenerateSearch', function (sJSON) { Search.SearchComplete(sJSON); }, sKeyValuePairString);

		} else {
			FormHandler.ShowWarning(f.GetValue('hidMLInvalidSearch'));
		}

	}



	//search results complete
	this.SearchComplete = function (sJSON) {

		var oSearchResults = eval('(' + sJSON + ')');

		if (oSearchResults['SearchMode'] == 'FlightPlusHotel') {

			if (oSearchResults['TotalFlightCount'] > 0 && oSearchResults['PropertyCount'] > 0) {
				window.location = '/flight.aspx';
			} else {
				//close wait message and show warning
				e.ModalPopup.Close();
				FormHandler.ShowWarning(f.GetValue('hidMLNoResultsMessage'));
			}

		} else if (oSearchResults['SearchMode'] == 'Flight') {

			if (oSearchResults['TotalFlightCount'] > 0) {
				window.location = '/flight.aspx';
			} else {

				//close wait message and show warning
				e.ModalPopup.Close();
				FormHandler.ShowWarning(f.GetValue('hidMLNoResultsMessage'));
			}

		} else if (oSearchResults['SearchMode'] == 'Hotel') {

			if (oSearchResults['PropertyCount'] > 0) {
				window.location = '/propertyresults.aspx';
			} else {

				//close wait message and show warning
				e.ModalPopup.Close();
				FormHandler.ShowWarning(f.GetValue('hidMLNoResultsMessage'));
			}

		}

	}


	// More Search Options
	this.ShowMoreOptions = function () {
		f.Show('divAdvancedSearch');
		f.Hide('aMoreOptions');

		Search.EnableHotelSearch();
	}


	// hide more search options
	this.HideMoreOptions = function () {
		f.Hide('divAdvancedSearch');
		f.Show('aMoreOptions');
	}


	this.ResetHotelSearch = function () {
		f.SetValue('acpPropertyID', '');
		Search.EnableHotelSearch();
	}


	this.EnableHotelSearch = function () {
		//disable hotel search field if no region set

		if (f.GetValue('acpGeographyLevel2ID') == '') {
			f.GetObject('acpPropertyID').disabled = true;
			f.Show('pHotelSearchWarning');
			f.SetValue('acpPropertyID', '');
		} else {
			f.GetObject('acpPropertyID').disabled = false;
			f.Hide('pHotelSearchWarning');
		}

	}

	// helper properties
	this.SelectedRooms = function () { return n.SafeInt(dd.GetText('ddlRooms')); }
	this.ChildCount = function (iRoom) { return n.SafeInt(dd.GetText('ddl_' + iRoom + '_Children')); }
	this.SearchType = function () { return f.GetValue('hidSearchMode'); }

	this.HasCompressedSearch = function () {
		var aElements = f.GetElementsByClassName('div', 'CompressedSearch');
		for (var i = 0; i < aElements.length; i++) {
			if (aElements[i].id = 'divSearch') return true;
		}
		return false;
	}


	//clear
	this.ClearCookie = function () {
		c.Delete('searchrestore');
	}


}



//autocomplete
var AutoComplete = new function () {

	var oASTextbox;
	var oASTimer;

	// auto suggest key up
	this.AutoSuggestKeyUp = function (oEvent, oTextbox, sFunction) {

		iKeyCode = iif(oEvent.keyCode, oEvent.keyCode, oEvent.which);

		if (iKeyCode < 41 && iKeyCode != 32 && iKeyCode != 8) { return; }

		var oDiv = document.getElementById(oTextbox.id + 'Container');

		if (oTextbox.value.length > 1) {

			if (oASTimer) {
				clearTimeout(oASTimer);
			}
			oASTextbox = oTextbox;
			ooASTimer = setTimeout('AutoComplete.' + sFunction, 300);
		} else {

			//clear the value
			AutoSuggestClear(oTextbox);
		}
	}


	//get regions and resorts
	this.GetRegionsResorts = function () {
		var aParams = document.getElementById(oASTextbox.id + 'Params').value.split('|');
		oASTextbox.className += ' autocompleteworking';

		if (oASTextbox.value.length < 3) { return; }

		var sParams = oASTextbox.id + '|' + oASTextbox.value + '|' + aParams[0] + '|' + aParams[1]
		+ '|' + aParams[4] + '|' + aParams[5] + '|' + aParams[6];

		ff.Call('Widgets.SearchTool.GetDropdownList', function (sHTML) { AutoSuggestDisplayResults(sHTML); }, sParams, 'Region');
	}


	//get properties
	this.GetProperties = function () {

		oASTextbox.className += ' autocompleteworking';

		if (oASTextbox.value.length < 3) { return; }

		var iRegionID = f.GetValue('acpGeographyLevel2IDHidden');
		if (iRegionID != 0) {
			var sParams = oASTextbox.id + '|' + oASTextbox.value + '|' + iRegionID;

			ff.Call('Widgets.SearchTool.GetDropdownList', function (sHTML) { AutoSuggestDisplayResults(sHTML); }, sParams, 'Property');
		} else {
			//            f.SetValue('acpPropertyID', '');
		}

	}


}




