$(document).ready(function(){

	var lists = $("#tertiary .box ul:first");
	$(">li:has(ul li.location)",lists).addClass("initial");
	$("li:not(.location,.initial)>ul:visible",lists).hide();
	
	function showSubMenu(){
		$(this).siblings(":has(ul:visible)").find("ul:first").slideUp("normal");
		$("ul:hidden",this).slideDown("normal");
	}
	
	var config = {    
		sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
		interval: 200, // number = milliseconds for onMouseOver polling interval    
		over: showSubMenu, // function = onMouseOver callback (REQUIRED)    
		timeout: 0, // number = milliseconds delay before onMouseOut    
		out: function(){return false;} // function = onMouseOut callback (REQUIRED)    
	};
	$("li:has(ul)",lists).hoverIntent(config);
	
	$.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("li");
		$(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("li");
		$('.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("li");
		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));
	}

});
