function checkValidDate(fld,dateformat)
{
  if (fld.value.length > 0)
  {
    if (!isValidDate(fld.value,dateformat))
    {
      alert("La date n'est pas valide!");
      fld.value = "";
    }
  }
}

//Validate given date
function isValidDate(date,dateformat)
{
	//Valid formats: %1/%2/%3 where 1,2,3 can be %d for day, %m for month and %Y for year
	//Parse format string
	day_ind = 0;
	month_ind = 0;
	year_ind = 0;
	format_ind = new Array(3);
	format_ind[0] = dateformat.charAt(1);
	format_ind[1] = dateformat.charAt(4);
	format_ind[2] = dateformat.charAt(7);
	if (format_ind[0] == 'd') day_ind = format_ind[0];
	if (format_ind[0] == 'm') day_ind = format_ind[0];
	if (format_ind[0] == 'Y') day_ind = format_ind[0];
	if (format_ind[1] == 'd') month_ind = format_ind[1];
	if (format_ind[1] == 'm') month_ind = format_ind[1];
	if (format_ind[1] == 'Y') month_ind = format_ind[1];
	if (format_ind[2] == 'd') year_ind = format_ind[2];
	if (format_ind[2] == 'm') year_ind = format_ind[2];
	if (format_ind[2] == 'Y') year_ind = format_ind[2];
	if (day_ind == 0 || month_ind == 0 || year_ind == 0) return false;
	//Create date in format dd/mm/yyyy
	aux_str = '';
	grab = 0;
	date_day = '';
	date_month = '';
	date_year = '';
	for(i=0;i < date.length;i++)
	{
		this_char = date.charAt(i);
		if (format_ind[grab] == 'd')
		{
			if (this_char == '/')
			{
				grab++;
				date_day = aux_str;
				aux_str = '';
			}
			else aux_str += date.charAt(i);
		}
		else if (format_ind[grab] == 'm')
		{
			if (this_char == '/')
			{
				grab++;
				date_month = aux_str;
				aux_str = '';
			}
			else aux_str += date.charAt(i);
		}
		else if (format_ind[grab] == 'Y')
		{
			aux_str += date.charAt(i);
		}
	}
	date_year = aux_str;
	if (date_day == '' || date_month == '' || date_year == '') return false;
	_date = date_day + '/' + date_month + '/' + date_year;
	return isDate(_date);
}


/*
 ================================CHECK DATE MODULE============================================== 
 * DHTML date validation script for dd/mm/yyyy. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 * Modified by Renato Arnellas Coelho 2006
 ================================================================================================== 
*/
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1;
var maxYear=3000;

function stripCharsInBag(s, bag){
	var i;
	var returnString = "";
   	// Search through string's characters one by one.
   	// If character is not in bag, append to returnString.
   	for (i = 0; i < s.length; i++)
	{   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
	}
	return returnString;
}

function daysInFebruary (year){
// February has 29 days in any year evenly divisible by four,
// EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++)
	{
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30};
		if (i==2) {this[i] = 29};
   	} 
   	return this;
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strDay=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) 
	{
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
//		alert("The date format should be : dd/mm/yyyy")
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
//		alert("Please enter a valid month")
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
//		alert("Please enter a valid day")
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
//		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
//		alert("Please enter a valid date")
		return false;
	}
	return true;
}

//Receives date in format dd/mm/yyyy and returns number whose value is yyyymmdd
function DateToNumber(date)
{
	//Format d/m/yyyy to dd/mm/yyyy
   	var date_num = 0;
	var num_bars = 0;
	var day = 0;
	var missing_day_slot = false;
	var month = 0;
	var missing_month_slot = false;
	var index = 0; // auxiliar index
	var year = 0;
   	for (i=0;i<date.length;i++)
	{
	    if (date.charAt(i) == "/") 
	    {
			if (num_bars == 0) //get day
			{
				day = date.substring(0,i);
	            if (i != 2) missing_day_slot = true;
			}
			if (num_bars == 1) //get month
			{
				index = 3; //in theory
				if (missing_day_slot) index = 2;
				month = date.substring(index,i);
				if ((i - index) != 2) missing_month_slot = true;
			}
			num_bars++;
	    }
	    if (num_bars == 2) //get year
	    {
			year = date.substr(i+1,4);
			break; //exit loop
	    }
	}    
    date_num = year * 10000; //cast to integer and shift it to the right place
	date_num += month * 100; //cast to integer and shift it to the right place
    date_num += day * 1; //cast to integer and shift it to the right place
	return date_num;
}

//Compare two dates (start,end) and return whether they are valid
//End >= Start (returns true else returns false )
function checkStartEnd(start,end)
{
	//Change dd/mm/yyyy to yyyymmdd in order to make comparison
	start_num = DateToNumber(start);
	end_num = DateToNumber(end);
	if (start_num > end_num) return false;
	else return true;
}
/* ================================ END OF CHECK DATE MODULE =============================== */

/*
 ===============================AUTOMATIC DATE FORMAT MODULE============================================== 
All the events below must appear together:
onkeyup="checkCharModifier(this,event)" onkeydown="return filterChar(event)" onkeypress="return checkDateSlash(this,event)" onblur="checkValidDate(this,null,'%(date_format)s')"
*/
//Save global date field value in order to avoid automatic text-cursor positioning in IE and to do some verifications
var __lastDate = '';
var __lastDate_id = ''; //don't mix different date inputs!
var __shift = false;
//onkeyup="checkCharModifier(this,event)"
function checkCharModifier(field,e)
{
	var charCode=0;
	if (!e) var e = window.event;
	if (e.keyCode) charCode = e.keyCode;
	else if (e.which) charCode = e.which;
	if (charCode == 16) __shift = false;
	//Checks how many slashes we already have
	num_slashes = 0;
	ind = field.value.indexOf("/");
	if (ind != -1)
	{
		num_slashes++;
		ind_two = field.value.indexOf("/",ind+1);
		if (ind_two != -1) num_slashes++;
	}
	//Check if we need to rollback field value
	if (num_slashes == 0)
	{
		if (field.value.length > 2) field.value = __lastDate;
	}
	else if (num_slashes == 1)
	{
		v_content = field.value.split("/");
		if (v_content[0].length > 2 || v_content[0].length == 0) field.value = __lastDate;
		else if (v_content[1].length > 2) field.value = __lastDate;
	}
	else if (num_slashes == 2)
	{
		v_content = field.value.split("/");
		if (v_content[0].length > 2 || v_content[0].length == 0) field.value = __lastDate;
		else if (v_content[1].length > 2 || v_content[1].length == 0) field.value = __lastDate;
		else if (v_content[2].length > 4) field.value = __lastDate;
	}
	//Update last field value
	__lastDate = field.value;
	__lastDate_id = field.id;
}

//onkeydown="return filterChar(event)"
function filterChar(e)
{
	/*Javascript debug functions:
	String.fromCharCode(0x30); //returns char
	String.charCodeAt('A'); //returns int
	*/
	var charCode=0;
	if (!e) var e = window.event;
	if (e.keyCode) charCode = e.keyCode;
	else if (e.which) charCode = e.which;
	if (charCode == 16) __shift = true;
	//Eliminate ambiguos characters
	validchars = new Array();
	validchars.push(48); //0
	validchars.push(49); //1
	validchars.push(50); //2
	validchars.push(51); //3
	validchars.push(52); //4
	validchars.push(53); //5
	validchars.push(54); //6
	validchars.push(55); //7
	validchars.push(56); //8
	validchars.push(57); //9
	validchars.push(96); //0(from numpad)
	validchars.push(97); //1(from numpad)
	validchars.push(98); //2(from numpad)
	validchars.push(99); //3(from numpad)
	validchars.push(100); //4(from numpad)
	validchars.push(101); //5(from numpad)
	validchars.push(102); //6(from numpad)
	validchars.push(103); //7(from numpad)
	validchars.push(104); //8(from numpad)
	validchars.push(105); //9(from numpad)
	validchars.push(37); //left arrow
	validchars.push(39); //right arrow
	validchars.push(8); //backspace
	validchars.push(9); //Tab
	validchars.push(46); //delete
	validchars.push(193); //'/'
	validchars.push(111); // '/' (from numpad)
	validchars.push(116); // 'F5'
	validchars.push(36); // Home
	validchars.push(35); // End
	//Ignore invalid characters
	validcode = false;
	for(number in validchars)
	{
		if (charCode == validchars[number])
		{
			validcode = true;
		}
	}
	if (!validcode) return false;
}
 
//onkeypress="return checkDateSlash(this,event)"
function checkDateSlash(field,e)
{
	/* find out which key has been pressed */
	var charCode=0;
	if (!e) var e = window.event;
	if (e.keyCode) charCode = e.keyCode;
	else if (e.which) charCode = e.which;
	if (field.id != __lastDate_id)
	{
		__lastDate = '';
		__lastDate_id = '';
	}
	//Block invalid chars
    if (charCode > 31 && (charCode < 48 || charCode > 57))
	{
		//Do nothing if we are using control characters
		if (!(charCode == 47 || charCode == 111 || charCode == 193 || charCode == 116 || charCode == 37 || charCode == 39 || charCode == 8 || charCode == 46 || charCode == 36 || charCode == 35)) return false;
	}
	//Block invalid shifted chars
	if ((__shift) && (charCode == 35 || charCode == 36 || charCode == 37)) return false;
	//Checks how many slashes we already have
	num_slashes = 0;
	ind = field.value.indexOf("/");
	if (ind != -1)
	{
		num_slashes++;
		ind_two = field.value.indexOf("/",ind+1);
		if (ind_two != -1) num_slashes++;
	}
	if (String.fromCharCode(charCode) == '/')
	{
		//Ignore exceeding slash
		if (num_slashes == 2) return false;
		if (num_slashes == 1)
		{
			v_content = field.value.split("/");
			if (v_content[1].length == 0) return false;
		}
		else if (num_slashes == 0)
		{
			if (field.value.length == 0) return false;
		}
	}
	else //user pressed a number
	{
		numbers = "0123456789";
		if (num_slashes == 2)
		{
			v_content = field.value.split("/");
			if (v_content[2].length > 4 && (numbers.indexOf(String.fromCharCode(charCode)) != -1) ) return false; //ignore user edit
		}
		if (num_slashes == 1)
		{
			v_content = field.value.split("/");
			if (v_content[1].length > 2 && (numbers.indexOf(String.fromCharCode(charCode)) != -1) ) return false; //ignore user edit
			if (v_content[1].length == 2 && charCode != 8) field.value = field.value + '/';
		}
		else if (num_slashes == 0)
		{
			if (field.value.length > 2 && (numbers.indexOf(String.fromCharCode(charCode)) != -1) ) return false; //ignore user edit
			if (field.value.length == 2 && charCode != 8) field.value = field.value + '/';
		}
	}
	return true;
}
/* ================================ END OF AUTOMATIC DATE FORMAT  MODULE =============================== */

