var searchedRegion;
var searchedLocation;

$(document).ready(function() {
	/* loading lightbox effects*/
    var loadingAreas = new Array(
		'#pagePrevious',
		'#pageNext',
		'#changeToMapView',
		'#changeToListView',
		'#sortByDeals',
		'#sortByRecommend',
		'#sortByPriceLow',
		'#sortByPriceHigh',
		'#sortByStar',
		'#sortByAZ'
	);

	var loadingAreasMessages = new Array(
		'LOADING PREVIOUS RESULTS',
		'LOADING MORE RESULTS',
		'SWITCHING TO MAP VIEW',
		'SWITCHING TO LIST VIEW',
		'SORTING RESULTS BY DEALS',
		'SORTING RESULTS BY RECOMMENDED',
		'SORTING RESULTS BY LOWEST PRICE',
		'SORTING RESULTS BY HIGHEST PRICE',
		'SORTING RESULTS BY STAR RATING',
		'SORTING RESULTS FROM A - Z'
	);

	$(loadingAreas).each(function(i) {
		$(loadingAreas[i]).click(function() {
			var t = this.title || this.name || null;
			var a = this.href || this.alt;
			var g = this.rel || false;

			loader(loadingAreasMessages[i]);
			this.blur();
		});
	});

	if (!$.browser.msie || !/6.0/.test(navigator.userAgent)) {
		$('#HotelDestination').attr('autocomplete', 'off').keyup(destinationAutoComplete).blur(function() {
			setTimeout(function() {
				if ($('#HotelDestinationAutoComplete ul').length > 0) {
					$('#HotelDestinationAutoComplete ul').remove();
				}
			}, 100);
		});
	}

	$('.hotelResult').submit(function() {
		if ($('#roomCount').length > 0) {
			var selectedValue = 0;
			var requiredRooms = $('#roomCount').val();

			$('.numRoomsRequired').each(function() {
				selectedValue += parseInt(this.value);
			});

			if (selectedValue == 0) {
				alert('Please select a room to continue.');
				return false;
			}
			else if (PaxAllocations.available > 0) {
				alert('You have unassigned groups left, please assign all your groups to your selected hotel.');
				return false;
			}
			else if (requiredRooms > selectedValue) {
				alert('You have not select enough rooms for your configuration.');
				return false;
			}
			else if (requiredRooms < selectedValue) {
				alert('You have selected more rooms than specified, please correct.');
				return false;
			}
		}
		return true;
	});

	/*Automatic update of offers on homepage when dropdown changes*/
	$('#homepageOffersFilterLocation').change(function(){
		$('#sortOffers').submit();
	});

	/*Sticky search fields*/
	$('#stickyMoreOptionsLink').click(function() {
		//copy destination country region location checkinday checkinmonth nights
		var numRooms = $('#roomCount').val();
		var stickyArray = new Array(
			$('#HotelDestination').val(),
			$('#HotelCountry').val(),
			$('#HotelRegion').val(),
			$('#HotelLocation').val(),
			$('#HotelCheckInDay').val(),
			$('#HotelCheckInYearMonth').val(),
			$('#HotelNights').val(),
			numRooms
		);
		var stickyValues = '';

		for (var i = 0; i < stickyArray.length; ++i) {
			if (i != 0) stickyValues += ',';

			stickyValues += stickyArray[i];
		}

		for (var x = 0; x < numRooms; ++x) {
			var numChildren = $('#HotelChildren' + x).val();

			stickyValues += ',' + $('#HotelAdults' + x).val() + '_' + numChildren;

			if (numChildren > 0) {
				for (i = 0; i < numChildren; ++i) {
					stickyValues += '_' + $('#HotelChildAge' + x + i).val();
				}
			}
		}

		location = '/hotels/search/hotels/' + stickyValues;

		return false;
	});

	/* HOTEL SEARCH VALIDATION */
	$('#hotelSearch').submit(function() {
		var todayDate	= new Date;
		var bookingDate = new Date();
		var errMsgBase	= "Invalid Search Criteria";
		var errMsg		= '';
		var nights		= $('#HotelNights').val();
		var date		= $('#HotelCheckInYearMonth').val() + '-' +$('#HotelCheckInDay').val();
		var d			= date.split("-");
		var year		= parseInt(d[0], 10);
		var month		= parseInt(d[1], 10) - 1;
		var day			= parseInt(d[2], 10);

		bookingDate.setFullYear(year, month, day);

		if (todayDate >= bookingDate) errMsg += "<p>&middot; Booking date has to be in the future</p>";

		if (isNaN(nights)) {
			errMsg += "<p>&middot; Please only enter digits into the \"nights\" field</p>";
		}
		else if (nights.length == 0) {
			errMsg += '<p>&middot; Please enter number of nights you will be staying</p>';
		}

		var invalidAge = false;

		$('li.childAges select').each(function() {
			if (!invalidAge && isNaN(parseInt(this.value))) {
				errMsg += '<p>&middot; Please enter the ages of all the children that are travelling with you</p>';
				invalidAge = true;
			}
		});

		var destination = $('#HotelDestination').val() + $('#HotelCountry').val() + $('#HotelRegion').val() + $('#HotelLocation').val();

		if (destination == 'undefined' || destination == '') {
			errMsg += "<p>&middot; Please select destination criteria</p>";
		}

		if (errMsg != '') {
			unload();
			showLightBox(errMsgBase, '<br />' + errMsg, 300, 120);

			return false;
		}

		//loader('SEARCHING FOR HOTELS');
		loader('');

		return true;
	});

	/* RECOMMENDATIONS/OFFERS SEARCH VALIDATION */
	$('#recommendationsSearch, #offerSearch').submit(function() {
		var errMsgBase = "Invalid Search Criteria";
		var errMsg = '';

		if ($('#HotelCountry').val() + $('#HotelRegion').val() + $('#HotelLocation').val() == "") {
			errMsg += "<p>&middot; Please select destination criteria</p>";
		}

		if (errMsg != '') {
			unload();
			showLightBox(errMsgBase, '<br />' + errMsg, 300, 120);

			return false;
		}

		loader((this.id == 'recommendationsSearch') ? 'SEARCHING FOR RECOMMENDATIONS' : 'SEARCHING FOR OFFERS');

		return true;
	});

	/*SEARCH FILTERS*/
	$('#filterLocation').change(function() {
		location = '/hotels/search_availability/location/' + $('#filterLocation').val() + '/';
	});

	$('#filterStars').change(function() {
		location = '/hotels/search_availability/stars/' + $('#filterStars').val() + '/';
	});

	$('#priceDisplayPound').click(function() {
		location = '/hotels/search_availability/pound';
	});

	$('#priceDisplayRand').click(function() {
		location = '/hotels/search_availability/rand';
	});

	$('#starRatingSearch').change(function() {
		location = '/hotels/search_availability/star/' + $('#starRatingSearch').val();
	});

	var filterBy = 'all';

	$('#HotelCountry').change(function() {
  		var cityElem = document.getElementById('HotelLocation');

		cityElem.options.length = 0;

		if ($('#filterAjaxResultsBy').val()) filterBy = $('#filterAjaxResultsBy').val();

		$('#HotelRegion').attr('disabled','disabled');

		updateRegions($('#HotelCountry').val(), filterBy);
	});

	$('#HotelRegion').change(function() {
  		var cityElem = document.getElementById('HotelLocation');

		cityElem.options.length = 0;

		if ($('#filterAjaxResultsBy').val()) {
			filterBy = $('#filterAjaxResultsBy').val();
		}

		updateCities(new Array($('#HotelRegion').val()), filterBy, true);
	});

	$('#showDestinationDropdowns').click(function() {
		$('#HotelDestination').attr('title', $('#HotelDestination').val());
  		$('#HotelDestination').val('');
		$('#destinationInput').hide();
  		$('#destinationDropdowns').show();
		$('#HotelCountry option[value="' + $('#HotelCountry').attr('rel') + '"]').attr('selected', 'selected');
		$('#HotelRegion option[value="' + $('#HotelRegion').attr('rel') + '"]').attr('selected', 'selected');
		$('#HotelLocation option[value="' + $('#HotelLocation').attr('rel') + '"]').attr('selected', 'selected');

  		return false;
	});

	$('#showDestinationInput').click(function() {
		$('#HotelDestination').val($('#HotelDestination').attr('title'));
		$('#HotelCountry').attr('rel', $('#HotelCountry').val());
		$('#HotelRegion').attr('rel', $('#HotelRegion').val());
		$('#HotelLocation').attr('rel', $('#HotelLocation').val());
  		$('#HotelCountry').val('');
  		$('#HotelRegion').val('');
  		$('#HotelLocation').val('');
		$('#destinationDropdowns').hide();
  		$('#destinationInput').show();

  		return false;
	});

	$('select.childCount').bind('change', trackChildren);

	if ($('#roomCount, .roomCount').length > 0) {
		$('#roomCount, .roomCount').each(function(i) {
			trackRoomCount(this);

			$(this).change(function() {
				trackRoomCount(this);
			});
		});
	}

	/*FILTER THE DROPDOWNS IF JAVASCRIPT AVAILABLE*/
	if ($('#HotelCountry').val() != null && $('#HotelCountry').val() != '') {
		searchedRegion = $('#HotelRegion').val();
		searchedLocation = $('#HotelLocation').val();

		filterDropdowns();
	}

	/* UPDATE NUMBER OF DAYS IN THE SELECTED MONTH */
	$('#HotelCheckInYearMonth').change(function() {
		updateNumDaysInMonth(this);
	});

	if ($('#HotelCheckInYearMonth').length > 0) {
		updateNumDaysInMonth($('#HotelCheckInYearMonth'));
	}
});

function trackRoomCount(element)
{
	var activeForm = $(element).parents('form');
	var value = $(element).val();
	var roomConfigCount = $('.roomConfig', activeForm).length;
	var layout = '';
	var i;

	if (value > roomConfigCount) {
  		for (i = roomConfigCount; i < value; ++i) {
  			layout += '<ol class="roomConfig" id="configRoom' + i + '">' +
					  	'<li><label>Room ' + (i + 1) + ':</label> <select id="HotelAdults' + i + '" class="fixed100" name="data[Hotel][adults' + i + ']">' +
						'<option value="1">1 ADULT</option>' +
						'<option value="2">2 ADULTS</option>' +
						'<option value="3">3 ADULTS</option>' +
						'<option value="4">4 ADULTS</option>' +
						'<option value="5">5 ADULTS</option>' +
						'<option value="6">6 ADULTS</option>' +
						'</select></li>' +
						'<li><select id="HotelChildren' + i + '" class="fixed100 childCount" name="data[Hotel][children' + i + ']">' +
						'<option value="0">0 CHILDREN</option>' +
						'<option value="1">1 CHILD</option>' +
						'<option value="2">2 CHILDREN</option>' +
						'<option value="3">3 CHILDREN</option>' +
						'<option value="4">4 CHILDREN</option>' +
						'</select></li>' +
						'</ol>';
  		}

  		$('.roomConfig', activeForm).eq(roomConfigCount - 1).after(layout);
		$('select.childCount', activeForm).unbind('change');
  		$('select.childCount', activeForm).bind('change', trackChildren);
	}
	else {
		for (i = roomConfigCount; i >= value; --i) $('.roomConfig', activeForm).eq(i).remove();
	}

	$('.roomConfig', activeForm).removeClass('last');
	$('.roomConfig', activeForm).eq(($('.roomConfig', activeForm).length - 1)).addClass('last');
}

function trackChildren()
{
	var value = this.value;
	var currentRoomConfig = $(this).parents('ol');
	var childAgesElement = currentRoomConfig.children('li.childAges');
	var x;

	if (childAgesElement.length > 0) {
		if (value == 0) {
			childAgesElement.remove();
		}
		else {
			if (value > $('li.childAges ul', currentRoomConfig).children('li').length) {
				for (x = $('li.childAges ul', currentRoomConfig).children('li').length; x < value; ++x) {
					$('li.childAges ul', currentRoomConfig).append(getChildAgeSelectField($(this).parents('ol').attr('id').replace('configRoom', ''), x));
				}
			}
			else {
				for (x = $('li.childAges ul', currentRoomConfig).children('li').length; x >= value; --x) {
					$('li.childAges ul li', currentRoomConfig).eq(x).remove();
				}
			}
		}
	}
	else {
		var initHtml  = '<li class="childAges"><ul>';
			initHtml += '</ul></li>';

		$(this).parents('ol').append(initHtml);

		for (x = 0; x < value; ++x) {
			$('li.childAges ul', currentRoomConfig).append(getChildAgeSelectField($(this).parents('ol').attr('id').replace('configRoom', ''), x));
		}
	}
}

function getChildAgeSelectField(room, index)
{
	var html  = '<li>';

		if (index == 0) html += '<label>Child ages:</label> ';

		html += '<select id="HotelChildAge' + room + index + '" name="data[Hotel][child_age' + room + '][' + index + ']">';
		html += '<option value="">---</option>';
		html += '<option value="0">< 1</option>';
		html += '<option value="1">1</option>';
		html += '<option value="2">2</option>';
		html += '<option value="3">3</option>';
		html += '<option value="4">4</option>';
		html += '<option value="5">5</option>';
		html += '<option value="6">6</option>';
		html += '<option value="7">7</option>';
		html += '<option value="8">8</option>';
		html += '<option value="9">9</option>';
		html += '<option value="10">10</option>';
		html += '<option value="11">11</option>';
		html += '<option value="12">12</option>';
		html += '<option value="13">13</option>';
		html += '<option value="14">14</option>';
		html += '<option value="15">15</option>';
		html += '</select>';
		html += '</li>';

	return html;
}

var previousPhrase = null;
var selectedValue = null;

function destinationAutoComplete()
{
	var phrase = $('#HotelDestination').val();

	if (phrase.length > 0) {
		if (phrase != previousPhrase && phrase != selectedValue) {
			previousPhrase = phrase;

			$.getJSON('/hotels/find_locations/' + phrase, {}, function(locations) {
				if ($('#HotelDestinationAutoComplete ul').length > 0) {
					$('#HotelDestinationAutoComplete ul').empty();
				}
				else {
					$('#HotelDestinationAutoComplete').append('<ul></ul>');
				}

				for (var x = 0; x < locations.length; ++x) {
					$('#HotelDestinationAutoComplete ul').append('<li><a href="#" class="autocomplete">' + locations[x] + '</a></li>');
				}

				$('#HotelDestinationAutoComplete li a.autocomplete').mousedown(function() {
					$('#HotelDestination').val($(this).text());
					$('#HotelDestinationAutoComplete ul').remove();

					selectedValue = $(this).text();

					return false;
				});
			});
		}
	}
	else {
		$('#HotelDestinationAutoComplete ul').remove();
	}
}

function updateNumDaysInMonth(element)
{
	var selectedDay = $('#HotelCheckInDay option:selected').val();
	var yearMonth = $(element).children('option:selected').val().split('-');

	$('#HotelCheckInDay').attr('disabled', 'disabled');

	$('input.searchbut').attr('disabled', 'disabled');

	$.getJSON('/hotels/days_in_month/' + yearMonth[0] + '/' + yearMonth[1], {}, function(daysInMonth) {
		if ($('#HotelCheckInDay').children('option').length != daysInMonth) {
			var optionsList = '';

			for (var x = 1; x <= daysInMonth; x++) {
				optionsList += '<option value="' + x + '">' + x + '</option>';
			}

			$('#HotelCheckInDay').html(optionsList);
		}

		if (selectedDay > daysInMonth) {
			$('#HotelCheckInDay option[value="' + daysInMonth + '"]').attr('selected', 'selected');
		}
		else {
			$('#HotelCheckInDay option[value="' + selectedDay + '"]').attr('selected', 'selected');
		}

		$('#HotelCheckInDay').attr('disabled', '');

		$('input.searchbut').attr('disabled', '');
	});
}

function filterDropdowns()
{
	var loadFilter;

	if ($('#filterAjaxResultsBy').val() != '' && $('#filterAjaxResultsBy').val() != null) {
		loadFilter = $('#filterAjaxResultsBy').val();
	}
	else {
		loadFilter = 'all';
	}

	updateRegions($('#HotelCountry').val(), loadFilter, true);
}

function updateRegions(countryExternalId, filterBy, autoCitiesUpdate)
{
	disableAllDestinationDropdowns();

	$.post('/hotels/getChildAreas/' + countryExternalId + '/' + filterBy + '/' + searchedRegion + '/', function(data) {
		eval(data);

		var regionIds = new Array();
		var regionElem = document.getElementById('HotelRegion');
		var cityElem = document.getElementById('HotelLocation');
		var selIndex = '';
		regionElem.options.length = 0;
		cityElem.options.length = 0;

		if (res.length > 0) {
			regionElem.options.add(new Option('Optional Region', ''));

			for (var r = 0; r < res.length; r++) {
				if (res[r].external_id == searchedRegion) {
					selIndex = searchedRegion;
				}

				regionElem.options.add(new Option(res[r].name, res[r].external_id));
			}

			regionElem.value = selIndex;

			if(cityElem.options.length == 0) cityElem.options.add(new Option('Optional Location',''));
		}
		else {
			regionElem.options.add(new Option('Optional Region', ''));
			cityElem.options.add(new Option('Optional Location', ''));
		}

		if (autoCitiesUpdate) {
			updateCities(new Array($('#HotelRegion').val()), filterBy, false);
		}

		enableAllDestinationDropdowns();
	});
}

function updateCities(regionExternalIds, filterBy, checkEmpty)
{
	var cityElem = document.getElementById('HotelLocation');

	disableAllDestinationDropdowns();

	for (var a = 0; a < regionExternalIds.length; a++) {
		$.post('/hotels/getChildAreas/' + regionExternalIds[a] + '/' + filterBy + '/', function(data) {
			eval(data);

			var selIndex = '';

			if (res.length > 0) {
				if (cityElem.options.length == 0) cityElem.options.add(new Option('Optional Location',''));

				for (var r = 0; r < res.length; r++) {
					if (res[r].external_id == searchedLocation) {
						selIndex = searchedLocation;
					}

					cityElem.options.add(new Option(res[r].name, res[r].external_id));
				}

				cityElem.value = selIndex;
			}
			else {
				if(checkEmpty && cityElem.options.length == 0) cityElem.options.add(new Option('No sub locations', ''));
			}

			if (a == regionExternalIds.length) {
				enableAllDestinationDropdowns();
			}
		});
	}
}

function disableAllDestinationDropdowns()
{
	$('#HotelCountry').attr('disabled', 'disabled');
	$('#HotelRegion').attr('disabled', 'disabled');
	$('#HotelLocation').attr('disabled', 'disabled');
}

function enableAllDestinationDropdowns()
{
	$('#HotelCountry').attr('disabled', '');
	$('#HotelRegion').attr('disabled', '');
	$('#HotelLocation').attr('disabled', '');
}

function paxGroupToRoom(paxGroupId, roomId, action, adults, children, infants)
{
	var url;

	switch (action) {
		case 'add':
			url = '/hotels/searchedMultipleRooms/setPaxGroupToRoom/' + roomId + '/' + paxGroupId + '/' + adults + ',' + children;

			currentRoomSelectionLimit++;
			break;

		case 'remove':
			url = '/hotels/searchedMultipleRooms/clearForRoomId/' + roomId + '/';
			break;
	}

	$.post(url, function(data) {});

	if (currentRoomSelectionLimit >= roomSelectionLimit || currentRoomSelectionLimit >= maxSelectionLimit) {
		//if number of rooms selected equals the number of rooms required on the dropdown
		$('#setConfiguration').remove();
	}
}

function roomRequiredChange(roomRequired, roomId)
{
	$('#setConfiguration').remove();

	if (roomRequired == 0) {
		$.post('/hotels/searchedMultipleRooms/clearForRoomId/' + roomId + '/', function(data) {
			//cleared the groups assigned to this room
		});
	}
	else {
		//if multiple rooms
		if ($('#roomCount').val() > 1) {
			//element.parents('tr').after('<tr id="setConfiguration"><td colspan="3"><h5>Who goes in this room?</h5><div id="assignRoomsDiv" align="center">Loading....</div></td></tr>');
			showLightBox('Who goes in this room?', '<div id="assignRoomsDiv" align="center"><h3>loading ... </h3></div>', 400, 200);

			$.post('/hotels/searchedMultipleRooms/getAvailable/' + roomId + '/', function(data) {
				//if no more rooms available to show tell the user they have already selected more rooms than searched for
				currentRoomSelectionLimit = 0;
				roomSelectionLimit = roomRequired;

				//show all the rooms still available
				$('#assignRoomsDiv').html(data);
			});
		}
		else {
			//don't assign handle with php
		}
	}

	this.blur();
}
