/* This script is for use on the Consultations page, so that when someone enters two valid dates for searching in a date range it automatically checks the 'Filter by date' checkbox for them.

Relies on jQuery.

*/

var jq2 = jQuery.noConflict(); //make our own instancey thing of jQuery to stop us ruining other things

function check_stuff(){//called each time one of the date fields or the drop down wotsit is changed
	if(document.getElementById('df').checked == "checked")//if it's already checked
		return
	fv = from_field.value;
	tv = to_field.value
	date_pattern = /(0[0-9]|1[0-2]|[0-9])\/(0[0-9]|1[0-2]|[0-9])\/[1-2][0-9]{3}/g; 
	if(fv.match(date_pattern) && tv.match(date_pattern)){ //if both dates have a valid date in them
		if(check_chronology()){//if the two fields ARE in chronological order
			from_field.checked="checked"; //check that checkbox
			//now remove any red color setting from the fields - if a user had entered non-chronological dates before
			from_field.style.color = '';
			to_field.style.color = '';
		}
		else{
			from_field.style.color = 'red';
			to_field.style.color = 'red';
		}
	}
}


function check_chronology(){//checks to make sure that the two dates are in chronological order
	var from_date = new Date();
	var to_date = new Date();
	from_date.setFullYear(fv.substr(6,4),fv.substr(3,2),fv.substr(0,2));
	to_date.setFullYear(tv.substr(6,4),tv.substr(3,2),tv.substr(0,2));
	if(from_date.getTime()<to_date.getTime())
		return true;
	else
		return false
}




jq2(document).ready(function(){
	from_field = document.getElementById('fd');
	to_field = document.getElementById('td');
	if(from_field == null || to_field == null) //if we're on a page that doesn't have those fields
		return;
	//set onchange functions for the 2 date fields and the drop down
	from_field.onchange = function(){ check_stuff(); };
	to_field.onchange = function(){ check_stuff(); };
	document.getElementById('dk').onchange = function(){ check_stuff(); };
});

