// date formatting function
Date.prototype.getFormattedDate = function() {
	var dateYear  = this.getFullYear();
	var dateMonth = this.getMonth() + 1;
	var dateDay   = this.getDate();
	if (dateDay < 10) {
		dateDay = '0' + new String(dateDay);
	}
	if (dateMonth < 10) {
		dateMonth = '0' + new String(dateMonth);
	}
	return  dateDay + '/' + dateMonth + '/' + dateYear;
}

// passes a date from dd/mm/yyyy to mm/dd/yyyy format
Date.toCanonicalFormat = function(oldDate) {
	var dateParts = oldDate.split('/');
	return dateParts[1] + '/' + dateParts[0] + '/' + dateParts[2];
}

// input the number of days between 2 dates
Date.prototype.daysBetween = function( pastDate ) {
	var diff      = this.getTime() - pastDate.getTime();
	var daysBetween = Math.floor(diff / (1000 * 60 * 60 * 24) );
	return daysBetween;
}

var MAX_ROOMS = 5;
var MAX_PEOPLE = 9;
Date.MAX_NIGHTS = 30;

var messages = new Array();
messages['too_much_people'] = 'Numarul maxim admis de persoane la o cautare este 9 (incluzând copiii). Va rugam sa reduceti numarul de persoane sau numarul de camere';

// validation helper for the search form
var validator = {
	errorCount: 0,
	searchErrorStack : new Array(),
	resetErrorStack: function() {
		this.searchErrorStack = new Array();
		this.errorCount = 0;
	},
	pushErrorMessage: function(errorMessage) {
		this.errorCount++;
		this.searchErrorStack.push(errorMessage);
	},
	validateSearchForm: function() {
		this.resetErrorStack();

		// if MAX_PEOPLE was exceeded
		var peopleCount = 0;
		for (roomId = 1; roomId <= MAX_ROOMS; roomId++) {
			var room = $('#room-' + roomId);
			if (room.is(':visible')) {
				peopleCount += parseInt(room.val());
				if (parseInt(room.val()) == 2) {
					var extraBed = $('#extra-room-' + roomId);
					if (extraBed.is(':checked')) {
						peopleCount += 1;
					}
				}
			}
		}

		if (peopleCount > MAX_PEOPLE) {
			this.pushErrorMessage(messages['too_much_people']);
		}
		
		return (this.errorCount > 0) ? false : true;
	},
	getErrorMessage: function()
	{
		var errorString = '';
		for (var i in this.searchErrorStack) {
			errorString = errorString + "- " + this.searchErrorStack[i] + "\n";
		}

		return errorString;
	}
};

// document ready
$().ready(function() {
	
	// make sure to change city-id's value when select changes
	$("#search-city-name").change(function() {
		var cityName = $("#search-city-name").val().replace(', Bulgaria', '');
		$("#search-city-id").val(cityIds[cityName]);
	});
	$("#search-city-name").change();
	
	// hide other rooms except the first one
	for (roomId = parseInt($('#search-rooms').val()) + 1; roomId <= MAX_ROOMS; roomId++) {
		$('#room-container-' + roomId).hide();
	}

	// hide extra bed option for each room
	for (roomId = 1; roomId <= MAX_ROOMS; roomId++) {
		if ($('#room-' + roomId).val() != 2) {
			$('#container-extra-room-' + roomId).hide();
		}
	}

	// setup the calendar for the checkin date
	$('#search-checkin').datepicker({
		minDate: 0,
		numberOfMonths: 2,
		showButtonPanel: true,
		showOn: 'both',
		buttonImage: 'images/calendar.gif',
		buttonImageOnly: true,
		dateFormat: 'dd/mm/yy',
		duration: ''
	});

	// setup the calendar for the checkout date
	$('#search-checkout').datepicker({
		minDate: +1,
		maxDate: Date.MAX_NIGHTS,
		numberOfMonths: 2,
		showButtonPanel: true,
		showOn: 'both',
		buttonImage: 'images/calendar.gif',
		buttonImageOnly: true,
		dateFormat: 'dd/mm/yy',
		duration: ''
	});

	// fix the way the calendar icon is displayed
	$('.ui-datepicker-trigger').each(function(i) {
		$(this).addClass('calendar_icon');
	});


	if ($('#search-checkin').val().length < 1) {
		var today = new Date();
		$('#search-checkin').val(today.getFormattedDate());
	}

	if ($('#search-checkout').val().length < 1) {
		var tomorrow = new Date();
		tomorrow.setDate( tomorrow.getDate() + 1 );
		$('#search-checkout').val(tomorrow.getFormattedDate());
	}

	// if the user changes the number of nights
	$('#search-nights').change( function() {
		var checkinDate  = new Date( Date.toCanonicalFormat($('#search-checkin').val()) );
		var nights       = parseInt( $('#search-nights').val() );
		var checkoutDate = new Date( checkinDate );
		checkoutDate.setDate( checkinDate.getDate() + nights );
		$('#search-checkout').val( checkoutDate.getFormattedDate() );
	});

	// if the user changes the checkin date
	$('#search-checkin').change( function() {
		var checkinDate  = new Date( Date.toCanonicalFormat($('#search-checkin').val()) );
		var nights       = parseInt( $('#search-nights').val() );

		var minCheckoutDate = new Date ( checkinDate );
		var maxCheckoutDate = new Date ( checkinDate );
		minCheckoutDate.setDate( checkinDate.getDate() + 1 );
		maxCheckoutDate.setDate( checkinDate.getDate() + Date.MAX_NIGHTS );
		$('#search-checkout').datepicker('option', 'minDate', minCheckoutDate);
		$('#search-checkout').datepicker('option', 'maxDate', maxCheckoutDate);

		var checkoutDate = new Date( checkinDate );
		checkoutDate.setDate( checkinDate.getDate() + nights );
		$('#search-checkout').val( checkoutDate.getFormattedDate() );
	});

	// if the user changes the checkout date
	$('#search-checkout').change( function() {
		var checkinDate  = new Date( Date.toCanonicalFormat($('#search-checkin').val()) );
		var nights       = parseInt( $('#search-nights').val() );
		var checkoutDate = new Date( Date.toCanonicalFormat($('#search-checkout').val()) );
		if (checkinDate > checkoutDate) {
			alert('The checkin date must be before the checkout date');
			checkoutDate = new Date ( checkinDate );
			checkoutDate.setDate( checkinDate.getDate() + 1);
			$('#search-checkout').val( checkoutDate.getFormattedDate() );
		} else {
			var selectId = "#search-nights option[value='";
			selectId += checkoutDate.daysBetween(checkinDate);
			selectId += "']";
			$(selectId).attr('selected', 'selected');
		}
	});

	$('#search-rooms').change(function() {
		var totalRooms  = parseInt($(this).val());
		for (roomId = 1; roomId <= totalRooms; roomId++) {
			$('#room-container-' + roomId).show();
		}
		for (roomId = totalRooms + 1; roomId <= MAX_ROOMS; roomId++) {
			$('#room-container-' + roomId).hide();
		}
	});

	$('#hotel-search-submit').click(function(event) {
		if (validator.validateSearchForm()) {
			$('#hotel-search-form').submit();
		} else {
			alert(validator.getErrorMessage());
		}
	});

	for (roomId = 1; roomId <= MAX_ROOMS; roomId++) {
		$('#room-' + roomId).change(function(){
			var elementId = $(this).attr('id');
			var extraBedId = 'container-extra-' + elementId;
			if (parseInt($(this).val()) == 2) {
				$('#' + extraBedId).show();
			} else {
				$('#' + extraBedId).hide();
			}
		});
	}
});