/* file: DateFilterWidget.js */
function ajaxifyDateFilter() {
	console.log("ajaxify DateFilter...");
	
	// Date options->deltaTime map
	var options = {};

	options['1 day'] = 60 * 60 * 24;
	options['1 week'] = options['1 day'] * 7;
	options['2 weeks'] = options['1 week'] * 2;
	options['1 month'] = options['1 day'] * 30;

	// Sets the date range by parsing and rebuilding the querystring
	function setDateRange(startDate, endDate) {		
		addArgs({
			'start' : startDate,
			'end' : endDate
		});
	};

	// Attach event handlers to date options and set onSelect to the DateFields' datepicker.
	$(".filter.DateFilter").each(function() {
		var dateFilterElement = $(this);
	
		var startInputElement = $(this).find('input[name="start"][type!="hidden"]');
		var endInputElement = $(this).find('input[name="end"][type!="hidden"]');	

		dateFilterElement.find("input.DateField")
			.dateTimeInput({
				"onClose" : function(event) {							
					var startVal = startInputElement.val().replace(/^\W+/,'').replace(/\W+$/,'');
					var endVal = endInputElement.val().replace(/^\W+/,'').replace(/\W+$/,'');				
				
					if(event.changed && startVal != '' && endVal != '') {
						setDateRange(
							startVal,
							endVal
						);
					}
				}
			});

		dateFilterElement.find("a").each(function() {
			$(this).click(function() {
				var deltaTime = options[$(this).text()];

				startInputElement.val(
					PHPJS.date("d/m/Y H:i O", new Date().getTime() / 1000 - deltaTime)
				);

				endInputElement.val(
					PHPJS.date("d/m/Y H:i O", new Date().getTime() / 1000)
				);

				if(!dateFilterElement.hasClass("wizard")) { // Slight bit of coupling with ReportWizardWidget... couldn't be helped because jquery wont allow you to set event callback prioritites/ordering... :\ <--- not impressed - RA
					setDateRange(startInputElement.val(), endInputElement.val());
				}

				return false;
			});
		});
	});

	console.log("... ajaxify DateFilter done.");
};

console.log("registering ajaxify DateFilter...");

ajaxifyFunctions.push(ajaxifyDateFilter);

$(ajaxifyDateFilter);

