/*
	Based on http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerIntoSelects.html
*/

$(function()
{	
	var selectDay = "#tripdateDay";
	var selectMonth = "#tripdateMonth";
	var selectYear = "#tripdateYear";
	var picker = "datePicker";
	var pickerId = "#"+picker;
	if (!$(pickerId).length) {
		$(selectYear).after('<a id="'+picker+'"><img src="/img/cal.gif" class="pickerimg" alt="" title="click to show/hide calendar" /></div>');
	}
	// initialise the "Select date" link to today's date
	var today = new Date();
	var startd = today.getDate();
	var startm = today.getMonth() + 1;
	if(startm < 10) startm = "0"+startm;
	var starty = today.getFullYear();
	
	$(pickerId)	
		.datePicker(
			// associate the link with a date picker
			{
				createButton:false,
				startDate:startd+'/'+startm+'/'+starty,
				endDate:'31/12/2011'
			}
		).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)
	{
		// days and months need leading zeros
		var selectedDate = new Date(selectedDate);
		var selectedDay = selectedDate.getDate();
		if(selectedDay < 10) selectedDay = "0"+selectedDay;
		var selectedMonth = (selectedDate.getMonth()+1);
		if(selectedMonth < 10) selectedMonth = "0"+selectedMonth;
		
		$(selectDay+' option[value=' + selectedDay + ']').attr('selected', 'selected');
		$(selectMonth+' option[value=' + selectedMonth + ']').attr('selected', 'selected');
		$(selectYear+' option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
	}
	// listen for when the selects are changed and update the picker
	$(selectDay,selectMonth,selectYear)
		.bind(
			'change',
			function()
			{
				var d = new Date(
							$(selectYear).val(),
							$(selectMonth).val()-1,
							$(selectDay).val()
						);
				$(pickerId).dpSetSelected(d.asString());
			}
		);	
	
	
	// and update the datePicker to reflect it...
	$(pickerId).trigger('change');
});