$(function()
{
	// initialise the "Select date" link
	$('#date-pick')
		.datePicker(
			// associate the link with a date picker
			{
				createButton:false,
				startDate:'01/01/2008',
				endDate:'31/12/2015'
			}
		).bind(
			// when the link is clicked display the date picker
			'click',
			function()
			{
				updateSelects($(this).dpGetSelected()[0]);
				$(this).dpDisplay();
				return false;
			}
		).bind(
			// when a date is selected update the SELECTs
			'dateSelected',
			function(e, selectedDate, $td, state)
			{
				updateSelects(selectedDate);
			}
		).bind(
			'dpClosed',
			function(e, selected)
			{
				updateSelects(selected[0]);
			}
		);
	var updateSelects = function (selectedDate)
	{
		var selectedDate = new Date(selectedDate);
		$('#form_fd_day option[value=' + selectedDate.getDate() + ']').attr('selected', 'selected');
		$('#form_fd_month option[value=' + (selectedDate.getMonth()+1) + ']').attr('selected', 'selected');
		$('#form_fd_year option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
	}
	// listen for when the selects are changed and update the picker
	$('#form_fd_day, #form_fd_month, #form_fd_year')
		.bind(
			'change',
			function()
			{
				var d = new Date(
							$('#form_fd_year').val(),
							$('#form_fd_month').val()-1,
							$('#form_fd_day').val()
						);
				$('#date-pick').dpSetSelected(d.asString());
			}
		);

	// default the position of the selects to today
	var today = new Date();
	updateSelects(today.getTime());

	// and update the datePicker to reflect it...
	$('#form_fd_day').trigger('change');

});
