$(document).ready(function(){

	// tell jQuery not to cache AJAX calls.
	$.ajaxSetup ({
		cache: false
	});
	
	// determine which calendar the user is viewing
	// by checking the body ID
	var cal = ($('body#wec1').length > 0) ? 'cal1' : 'cal2';

	// beforeShowDay callback function as used by datepicker. Checks
	// whether a particular date exists within a lookup table (unavailable_dates)
	// and if so, this means that this particular date is reserved.
	var unavailableDates = function(date) {
		if (unavailable_dates[date.toString('yyyy-MM-dd')]) return [false, 'wec_booked'];
		return [true, ''];
	};
	
	// create an instance of the datepicker (inline)
	$('#availability').datepick({
		numberOfMonths: 3,
		stepMonths: 2,
		showCurrentAtPos: 1, 
		prevText: '&laquo; Back 2 months',
		nextText: 'Forward 2 months &raquo;',
		currentText: 'Jump to Today',
		beforeShowDay: unavailableDates,
		mandatory: true,
		changeMonth: false,
		changeYear: false,
		firstDay: 1,
		minDate: Date.today(),
		dateFormat: 'dd/mm/yy'
	});
	
	// function to check whether the two selected booking dates
	// do not overlap with any other existing bookings
	var bookingDateCheck = function(value, dates) {
		var start_date = dates[0];
		var end_date = dates[1];
		var bookings_exist_in_selection = false;
		while (start_date.equals(end_date) !== true && bookings_exist_in_selection == false) {
			if (unavailable_dates[start_date.toString('yyyy-MM-dd')]) bookings_exist_in_selection = true; 
			start_date = start_date.add(1).days();
		}

		if (bookings_exist_in_selection) {
			$('#stay_dates').val('');
			alert("\nBookings exist in between your selected dates!\nPlease try alternative dates or get in touch with us.");
		}
	}
	
	// stay dates selector in reservation form
	$('#stay_dates').datepick({
		rangeSelect: true,
		numberOfMonths: 3,
		stepMonths: 2,
		showCurrentAtPos: 1, 
		prevText: '&laquo; Back 2 months',
		nextText: 'Forward 2 months &raquo;',
		currentText: 'Jump to Today',
		beforeShowDay: unavailableDates,
		mandatory: true,
		changeMonth: false,
		changeYear: false,
		firstDay: 1,
		minDate: Date.today(),
		showOn: 'both',
		buttonImageOnly: true,
		buttonImage: '/public/themes/wec/img/calendar.png',
		onClose: bookingDateCheck,
		dateFormat: 'dd/mm/yy'
	});
	

	// reservation form validator
	$("#res_form").validate({
		errorLabelContainer: $('#res_errors'),
		meta: 'validate'
	});
});
