﻿/* ------------------------------------------------------------ */
/*                                                              */
/*                       jQuery : ready                         */
/*                                                              */
/* ------------------------------------------------------------ */

$(function(){
	$.require('jquery/date,jquery/datePicker',function(){
		var startDay = new Date();
		var sDate    = startDay.getFullYear() + '/' + String(startDay.getMonth()+1+100).substr(1,2) + '/' + String(startDay.getDate()+100).substr(1,2);
		var endDay   = new Date(startDay.getFullYear(), startDay.getMonth()+6, startDay.getDate());
		var eDate    = (endDay.getFullYear()) + '/' + String(endDay.getMonth()+1+100).substr(1,2) + '/' + String(endDay.getDate()+100).substr(1,2);
		var nextDay  = new Date(startDay.getTime() + (24*1)*60*60*1000);
		var nDate    = (nextDay.getFullYear()) + '/' + String(nextDay.getMonth()+1+100).substr(1,2) + '/' + String(nextDay.getDate()+100).substr(1,2);

		$('#date-pick')
				.datePicker(
					// associate the link with a date picker
					{
						createButton:false,
						startDate:nDate,
						endDate:eDate
					}
				).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]);
					}
				).dpSetOffset(40,-180);

				
			var updateSelects = function (selectedDate)
			{
				var d = selectedDate.getDate();
				var m = selectedDate.getMonth();
				var y = selectedDate.getFullYear();
				($('#d')[0]).selectedIndex = d - 1;
				($('#m')[0]).selectedIndex = m;
				($('#y')[0]).selectedIndex = y - 2007;
			}
			// listen for when the selects are changed and update the picker
			$('#d, #m, #y')
				.bind(
					'change',
					function()
					{
						var d = new Date(
									$('#y').val(),
									$('#m').val()-1,
									$('#d').val()
								);
						$('#date-pick').dpSetSelected(d.asString());
					}
				);
			
			// default the position of the selects to today
			var today = new Date();
//			var today = nextDay;
			($('#d')[0]).selectedIndex = today.getDate() - 1;
			($('#m')[0]).selectedIndex = today.getMonth();
			($('#y')[0]).selectedIndex = today.getFullYear() - 2007;
			
			// and update the datePicker to reflect it...
			$('#d').trigger('change');
	});
	$.requirecss('jquery/datePicker');
});
