$(document).ready(function(){

	$.datepicker.setDefaults({
		showOn: 'both',
		buttonImageOnly: true,
		buttonImage: '/utils/template-bits/gfx/silky/calendar.png',
		buttonText: 'Calendar',
		dateFormat: 'dd/mm/yy',
		mandatory: true
	});
	
	var min = new Date();
	var minLead = $("#min-lead-time").val();
	min = min.setDate(min.getDate() + parseInt(minLead));
	$("form .date-field")
		.append('<input type="hidden" class="linkedDates" name="ld" value="" />');
	$(".linkedDates").datepicker({
		minDate: new Date(min),
		beforeShow: readLinked,
		onSelect: updateLinked
	});
	
	$("form .date-and-time")
		.append('<input type="hidden" class="customLinkedDates" name="ld" value="" />');
	$(".customLinkedDates").datepicker({
		beforeShow: readLinked,
		onSelect: updateLinked
	});
		
	// Prepare to show a date picker linked to three select controls
	function readLinked(input) {
		var e = $(input).parents("label");
		$(input).val(
			( parseInt($('.day',e).val()) > 9 ? $('.day',e).val() : "0" + $('.day',e).val() ) + '/' +
			( parseInt($('.month',e).val()) > 9 ? $('.month',e).val() : "0" + $('.month',e).val() ) + '/' +
			$('.year',e).val()
		);
		return {};
	}
		 
	// Update three select controls to match a date picker selection 
	function updateLinked() {
		var date = $(this).datepicker("getDate");
		var e = $(this).parents("label");
		$('.day',e).val(date.getDate());
		$('.month',e).val(date.getMonth()+1);
		$('.year',e).val(date.getFullYear());
	}
	
	$('.month, .year').change(checkLinkedDays).change(); 
		 
	// Prevent selection of invalid dates through the select controls 
	function checkLinkedDays() {
		var $current = $(this).parents("label");
		var daysInMonth = 32 - new Date($('.year',$current).val(), 
		$('.month',$current).val() - 1, 32).getDate(); 
		$('.day option',$current).attr('disabled', ''); 
		$('.day option:gt(' + (daysInMonth - 1) +')',$current).attr('disabled', 'disabled'); 
		if ($('.day',$current).val() > daysInMonth) { 
			$('.day',$current).val(daysInMonth); 
		}
		readLinked($(".linkedDates",$current));
	}

});