/*************************************************************************************

/**
 * Copyright (c) 2007 Kelvin Luck (http://www.kelvinluck.com/)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * $Id: jquery.datePicker.js 3739 2007-10-25 13:55:30Z kelvin.luck $
 **/

$(function()
{
	
	// initialise the "Select date" link
	$('#date-pick')
	// associate the link with a date picker
		.datePicker(
			{
				createButton:false,
				startDate:'01/01/2007',
				endDate:'31/12/2015'
			}
	// when the link is clicked display the date picker
		).bind(
			'click',
			function()
			{
				updateSelects($(this).dpGetSelected()[0]);
				$(this).dpDisplay();
				return false;
			}
	// when a date is selected update the SELECTs
		).bind(
			'dateSelected',
			function(e, selectedDate, $td, state)
			{
				updateSelects(selectedDate);
			}
		).bind(
			'dpClosed',
			function(e, selected)
			{
				updateSelects(selected[0]);
			}
		);
		
	var updateSelects = function (selectedDate)
	{
		selectedDate = new Date(selectedDate);
		var d = selectedDate.getDate();
		var m = selectedDate.getMonth();
		var y = selectedDate.getFullYear();
		($('#selectDay2')[0]).selectedIndex = d - 1;
		($('#selectMonth2')[0]).selectedIndex = m;
		($('#selectYear2')[0]).selectedIndex = y - 2009;
	}
	// listen for when the selects are changed and update the picker
	$('#selectDay2, #selectMonth2, #selectYear2')
		.bind(
			'change',
			function()
			{
				var d = new Date(
							$('#selectYear2').val(),
							$('#selectMonth2').val()-1,
							$('#selectDay2').val()
						);
				$('#date-pick').dpSetSelected(d.asString());
			}
		);
	
	// default the position of the selects to today
	var today = new Date();
	($('#selectDay2')[0]).selectedIndex = today.getDate() - 1;
	($('#selectMonth2')[0]).selectedIndex = today.getMonth();
	($('#selectYear2')[0]).selectedIndex = today.getFullYear() - 2009;
	
	// and update the datePicker to reflect it...
	$('#selectDay2').trigger('change');
});