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

// validation helper for the search form
var validator = {
	instance: null,
	suggestedCity: [],
	emailRegExp: /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/i,
	errorCount: 0,
	searchErrorStack : new Array(),
	resetErrorStack: function() {
		this.searchErrorStack = new Array();
		this.errorCount = 0;
	},
	isValidEmail: function(testString) {
		return testString.match(this.emailRegExp);
	},
	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 + this.instance);
			if (room.is(':visible')) {
				peopleCount += parseInt(room.val());
				if (parseInt(room.val()) == 2) {
					var extraBed = $('#extra-room-' + roomId + this.instance);
					if (extraBed.is(':checked')) {
						peopleCount += 1;
					}
				}
			}
		}

		if (peopleCount > MAX_PEOPLE) {
			this.pushErrorMessage(whsGlobalMessages['hsm_too_much_people']);
		}
		
		if (this.errorCount > 0) {
			return false;
		} else {
			// finally, if no suggested city was picked
			if (($('#search-city-id' + this.instance).val().length < 1) || (
				$('#search-city-name' + this.instance).length
				&& this.suggestedCity[this.instance] != $('#search-city-name' + this.instance).val()
			)) {
				if ($('#search-city-name' + this.instance).val().length >= 3) {
					cityMatches.show(this.instance, function() {
						validator.pushErrorMessage(whsGlobalMessages['hsm_city_id_null']);
						alert(validator.getErrorMessage());
					});
				} else {
					validator.pushErrorMessage(whsGlobalMessages['hsm_city_id_null']);
				}
				return false;
			}
		}
		
		return true;
	},
	validateReservationForm: function() {
		this.resetErrorStack();

		// if no email or UID
		if ( ($('#email').val().length < 1) || !this.isValidEmail($('#email').val()) ) {
			this.pushErrorMessage(whsGlobalMessages['hsm_email_null']);
		}
		// if no UID
		if ( ($('#cod_rezervare').val().length < 1) ) {
			this.pushErrorMessage(whsGlobalMessages['hsm_uid_null']);
		}
		
		return (this.errorCount > 0) ? false : true;
	},
	getErrorMessage: function()
	{
		var errorString = '';
		for (var i in this.searchErrorStack) {
			errorString = errorString + "- " + this.searchErrorStack[i] + "\n";
		}

		return errorString;
	}
};

var cityMatches = {
	loaded: [],
	
	load: function(instance, userInput, callback) {
		this.showLoader(instance);
		var that = this;
		$.ajax({
			type: 'GET',
			url: 'hotels/search-city-suggest/' + encodeURIComponent(userInput),
			dataType: 'html',
			success: function(html) {
				that.loaded[instance] = {
					userInput: userInput,
					html: html
				};
				if ($.isFunction(callback)) {
					callback();
				}
			}
		});
	},
	
	showLoader: function(instance) {
		$('#hotel-search-form' + instance + ' .loader').show();
	},
	
	hideLoader: function(instance) {
		$('#hotel-search-form' + instance + ' .loader').hide();
	},
	
	refreshDestinationField: function(instance, selectedCheckbox) {
		if (typeof selectedCheckbox == 'undefined') {
			selectedCheckbox = $('#step2' + instance + ' .suggested_cities input:checked');
		}
		
		var textValue = $('.hidden', selectedCheckbox.parent()).text();
		$('#search-city-name' + instance).val(textValue);
		$('#search-city-id' + instance).val(selectedCheckbox.val());
		validator.suggestedCity[instance] = textValue;
	},
	
	show: function(instance, emptyResponseClbk) {
		var userInput	   = $('#search-city-name' + instance).val();
		var step1Container = $('#step1' + instance);
		var step2Container = $('#step2' + instance);
		var isLoaded	   = this.loaded[instance] != ''
			&& this.loaded[instance].userInput == userInput;
		
		if (! isLoaded) {
			this.load(instance, userInput, function() {
				if ($.isFunction(emptyResponseClbk)
					&& cityMatches.loaded[instance].html == '') {
					emptyResponseClbk();
					return;
				}
				
				$('.suggested_cities', step2Container)
					.html(cityMatches.loaded[instance].html);
				$('.suggested_cities input', step2Container).click(function() {
					cityMatches.refreshDestinationField(instance, $(this));
				});
				
				step1Container.hide();
				step2Container.show();
				cityMatches.hideLoader(instance);
				
				// make the destination field the first selected option
				cityMatches.refreshDestinationField(instance);
			});
		} else {
			step1Container.hide();
			step2Container.show();
		}
	},
	
	hide: function(instance) {
		$('#step2' + instance).hide();
		$('#step1' + instance).show();
	}
};

function searchForm(instance, callback, options) {
	if (typeof instance != 'undefined') {
		if (instance !== '') {
			instance = '-' + instance;
		}
	} else {
		instance = '';
	}
	
	if (typeof options == 'undefined') {
		options = {};
	}
	options = $.extend({datepickerButtonImage: true}, options);
	
	validator.suggestedCity[instance] = $('#search-city-name' + instance).val();
	cityMatches.loaded[instance] = '';
    
	if ($('#search-checkin' + instance).val().length < 1) {
		var today = new Date();
		$('#search-checkin' + instance).val(today.getFormattedDate());
	}

	if ($('#search-checkout' + instance).val().length < 1) {
		var tomorrow;
		if ($('#search-checkin' + instance).val().length < 1) {
			tomorrow = new Date();
		} else {
			tomorrow = new Date(Date.toCanonicalFormat($('#search-checkin' + instance).val()));
		}
		tomorrow.setDate(tomorrow.getDate() + 1);
		$('#search-checkout' + instance).val(tomorrow.getFormattedDate());
	}
	
    // load checkoutDate
    var currentCheckinDate = new Date(Date.toCanonicalFormat($('#search-checkin' + instance).val()));
    var startCheckoutDate = currentCheckinDate.daysBetween(new Date());
    
	// hide other rooms except the first one
	for (roomId = parseInt($('#search-rooms' + instance).val()) + 1; roomId <= MAX_ROOMS; roomId++) {
		$('#room-container-' + roomId + instance).hide();
	}

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

	// initiate the city autocomplete on a text field
	$('#search-city-name' + instance).autocomplete('cities/autocomplete', {
		width: 260,
		autoFill: true,
		mustMatch: false,
		selectFirst: true,
		max: 8
	});

	// parse the result of an auto-complete request
	$('#search-city-name' + instance).result(function(event, data, formatted) {
		// sets the city id to a hidden form value
		$('#search-city-name' + instance).val($.trim(data[0]));
		$('#search-city-id' + instance).val($.trim(data[1]));
		validator.suggestedCity[instance] = $.trim(data[0]);
	});

	// setup the calendars for the checkin date and checkout date
	checkinOptions = {
		minDate: 0,
		numberOfMonths: 2,
		showButtonPanel: true,
		showOn: 'focus',
		dateFormat: 'dd/mm/yy',
		duration: '',
		firstDay: 1
	};
	checkoutOptions = {
		minDate: startCheckoutDate + 2,
		maxDate: Date.MAX_NIGHTS + startCheckoutDate,
		numberOfMonths: 2,
		showButtonPanel: true,
		showOn: 'focus',
		dateFormat: 'dd/mm/yy',
		duration: '',
		firstDay: 1
	};
	if (options.datepickerButtonImage) {
		$.extend(checkinOptions, {
			buttonImage: themeName + '/images/calendar.gif',
			buttonImageOnly: true,
			showOn: 'both'
		});
		$.extend(checkoutOptions, {
			buttonImage: themeName + '/images/calendar.gif',
			buttonImageOnly: true,
			showOn: 'both'
		});
	}
	
	$('#search-checkin' + instance).datepicker(checkinOptions);
	$('#search-checkout' + instance).datepicker(checkoutOptions);

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

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

	// if the user changes the checkin date
	$('#search-checkin' + instance).change( function() {
		var checkinDate  = new Date( Date.toCanonicalFormat($('#search-checkin' + instance).val()) );
		var nights       = parseInt( $('#search-nights' + instance).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' + instance).datepicker('option', 'minDate', minCheckoutDate);
		$('#search-checkout' + instance).datepicker('option', 'maxDate', maxCheckoutDate);

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

	// if the user changes the checkout date
	$('#search-checkout' + instance).change( function() {
		var checkinDate  = new Date( Date.toCanonicalFormat($('#search-checkin' + instance).val()) );
		var nights       = parseInt( $('#search-nights' + instance).val() );
		var checkoutDate = new Date( Date.toCanonicalFormat($('#search-checkout' + instance).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' + instance).val( checkoutDate.getFormattedDate() );
		} else {
			var selectId = '#search-nights' + instance + " option[value='";
			selectId += checkoutDate.daysBetween(checkinDate);
			selectId += "']";
			$(selectId).attr('selected', 'selected');
		}
	});

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

	$('#hotel-search-submit' + instance).click(function() {
		validator.instance = instance;
		if (validator.validateSearchForm()) {
			$('#hotel-search-form' + instance).submit();
			if (typeof _gaq != 'undefined') {
				_gaq.push(['_trackEvent', 'Hotels', 'Search']);
			}
		} else {
			if ((errorMessage = validator.getErrorMessage()) != '') {
				alert(validator.getErrorMessage());
			}
		}
	});
	
	$('#hotel-search-submit-step2' + instance).click(function() {
		$('#hotel-search-submit' + instance).click();
		return false;
	});
	
	if ($('#pick-city' + instance)) {
		$('#pick-city' + instance).click(function (e) {
			var instance = $(this).attr('id').replace('pick-city', '');
			var width = 420;
			var height = 470;
			var top = (window.screen.height - height) / 2;
			var left = (window.screen.width - width) / 2;
			var features = 'menubar=no,location=no,resizable=no,scrollbars=no,'
				+ 'status=no,width=' + width + ',height=' + height + ','
				+ 'top=' + top + ',left=' + left;
			
			window.open('/cities/list', 'pickcity' + instance, features);
			return false;
		});
	}

	for (roomId = 1; roomId <= MAX_ROOMS; roomId++) {
		$('#room-' + roomId  + instance).change(function(){
			var elementId = $(this).attr('id');
			var extraBedId = '#container-extra-' + elementId
			if (parseInt($(this).val()) == 2) {
				$(extraBedId).show();
			} else {
				$(extraBedId).hide();
			}
		});
	}
	
	$('#goto-step1' + instance).click(function() {
		cityMatches.hide(instance);
		return false;
	});
	
	if ($.isFunction(callback)) {
		callback();
	}
}

function homeSearchForm()
{
	searchForm('', null, {
		datepickerButtonImage: false
	});
}

$().ready(function() {
	if ($('#check-reservation-toggle')) {
		$('#check-reservation-toggle').click(function (e) {
			$('#check-reservation-container').toggle('fast');
			return false;
		});

		$('#check-reservation-submit').click(function (e) {
    		if (validator.validateReservationForm()) {
    			$('#check-reservation-form').submit();
    		} else {
    			alert(validator.getErrorMessage());
    		}
			return false;
		})
	}
});
