/*
** validate the date range of a given pair of input elements
** usage:
** requires input paired elements to have attributes of rel="start" and rel="end"
** attach with $('input.classname').validateDates();
** Important: the selector must be based on input.classname, and this classname must be the first in the list if there is more than one
*/
jQuery.fn.validateDates = function() {
	
	// extends the Date object to output a simple short date string (DD/MM/YYYY)
	Date.prototype.shortFormat = function() {
		return isNaN (this) ? 'NaN' : [
										this.getDate() > 9 ? this.getDate() : '0' + this.getDate(), 
										this.getMonth()+1 > 9 ? (this.getMonth()+1) : '0' + (this.getMonth() + 1), 
										this.getFullYear()
										].join('/');
	}
	
	checkValues = function() {
		var arrivalField = jQuery('input.'+jQuery(this).attr('class').split(' ')[0]+'[@rel=start]');
		var departureField = jQuery('input.'+jQuery(this).attr('class').split(' ')[0]+'[@rel=end]');
		
		if (arrivalField.val() != null && departureField.val() != null)
		{
			var boundary = jQuery(this).attr('rel');

			var arrival = arrivalField.val().split('/');
			var departure = departureField.val().split('/');

			var arrivalDate = new Date(parseInt(arrival[2],10), parseInt(arrival[1],10)-1, parseInt(arrival[0],10));
			var departureDate = new Date(parseInt(departure[2],10), parseInt(departure[1],10)-1, parseInt(departure[0],10));

			var daysApart = (departureDate.getTime() - arrivalDate.getTime()) / 86400000;

			// update the relevant input if they're less than a day apart
			if (daysApart < 1)
			{
				// depending on which boundary (start or end) we're looking at, determine what values to use
				switch (boundary)
				{
					case 'start':
						// user changed end date; ensure arrival date is at least 24 hours earlier
						newDate = new Date(departureDate.getTime() - 86400000);
						arrivalField.val(newDate.shortFormat());
						break;
					case 'end':
						// user changed the start date; ensure departure date is at least 24 hours later
						newDate = new Date(arrivalDate.getTime() + 86400000);
						departureField.val(newDate.shortFormat());
						break;
				}
			}	
		}
		else
		{
			//if (console) { console.log('[jquery.validateDates] arrival and departure inputs not found. Are rel attributes set?'); }
		}
	}
	
	// bind to the change event of the selected input
	jQuery(this).bind('change', checkValues);
}