/**
 * For checkbox in class FORM
 */
function setValue(obj){
	var formCheckboxControl = eval(obj);
	if ( !formCheckboxControl ) return;
	var object = document.getElementById(formCheckboxControl.name);
	var ObjArray = document.all[ formCheckboxControl.name ];
	//alert(ObjArray.length); 
	//alert(object); 
	var i = 0;
	while( i < ObjArray.length-1 && ObjArray[i+1] != formCheckboxControl ) i++;
	if (i == ObjArray.length-1) {
		//alert(i); 
		return;
	}	
	object = ObjArray[i];
	//alert(object.type);
	if (object.type != 'hidden') {
		//alert(i+":"+object.type); 
		return;
	}	
	if(formCheckboxControl.checked){
		object.value = 1;
	}else{
		object.value = 0;
	}
	//alert(object.value);
}

function check_format(obj,format,notnull,message){
	if (!obj) return true;
	//alert("check_format:" + format + ":" + notnull + ":" + message);
	if ((notnull)&&(!check_notnull(obj,message))) return false;
	//if ((!notnull)&&(!check_notnull(obj,null))) return true;
	
	var length = toNumber("" + notnull, false);
	if ( !isNaN(length) && !check_length(obj, message, length ) ) return false;  // length requis of field
	if (format==null) return true;

	var sFormat = format;
	if (sFormat.toLowerCase()=="date"){
		return check_date(obj,message);
	}else if (sFormat.toLowerCase() =="datetime"){
		return check_datetime(obj,message);
	}else if (sFormat.toLowerCase() =="time"){
		return check_time(obj,message);
	}else if (sFormat.toLowerCase() =="number"){
		return check_number(obj,message,"+-");
	}else if (sFormat.toLowerCase() =="number+"){
		return check_number(obj,message,"+");
	}else if (sFormat.toLowerCase() =="number-"){
		return check_number(obj,message,"-");
	}else if (sFormat.toLowerCase() =="integer"){
		return check_integer (obj,message,"+-");
	}else if (sFormat.toLowerCase() =="integer+"){
		return check_integer (obj,message,"+");
	}else if (sFormat.toLowerCase() =="integer-"){
		return check_integer (obj,message,"-");
	}else if (sFormat.toLowerCase() =="email"){
		return check_email (obj, message);
	}else if (sFormat.toLowerCase() =="password"){
		return check_password (obj, message);
	}else if (sFormat.toLowerCase() =="alphanumeric"){
		return check_alphanumeric (obj, message);
	}else{
		alert("Function hasn't construct yet");
		return false;
	}
}

function check_length(obj, message, length ) {
	if (!obj || !obj.value || ! obj.value.length) return true;
	if ( obj.value.length >= length ) return true;
	alert( message );
	obj.focus();
	return false;
}

function check_email(obj, message ) {
	if (!obj) return true;
	if (isNull(obj)) return true;
	var goodEmail = obj.value.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
	if ( goodEmail ) return true;
	alert( message );
	obj.focus();
	return false;
}

function check_alphanumeric(obj, message ) {
	if (!obj) return true;
	if (isNull(obj)) return true;
	var AlphaNumeric = "_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	for (i=0;i < obj.value.length;i++)
		if (AlphaNumeric.indexOf (obj.value.charAt(i)) < 0 )  {
			alert( message );
			obj.focus();
			return false;
		}
	return true;
}

function check_password(obj, message ) {
	if (!obj) return true;
	if (isNull(obj)) return true;

	if (obj.value.length < 6) {
		alert( message );
		obj.focus();
		return false;
	}

	var Alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
	var Numeric = "0123456789";
	var nAlpha=0, nNumeric = 0;
	for (i=0;i < obj.value.length;i++)
		if (Alpha.indexOf (obj.value.charAt(i)) >= 0)
			nAlpha++;
		else if (Numeric.indexOf (obj.value.charAt(i)) >= 0)
			nNumeric++
		else {
			alert( message );
			obj.focus();
			return false;
		}

	if (nAlpha < 2 || nNumeric < 2) {
		alert( message );
		obj.focus();
		return false;
	}

	return true;
}

function check_datetime(obj,message) {
	if (!obj) return true;
	if (isNull(obj)) return true;
	var str_datetime = trim(obj.value);
	var re_datetime = /^(\d+)\/(\d+)\/(\d+)\s+(\d+)\:(\d+)\:(\d+)$/;
	if (re_datetime.exec(str_datetime))
		return true;
	
	str_datetime += ":00";
	if (re_datetime.exec(str_datetime)) {
		obj.value = str_datetime;
		return true;
	}	
	str_datetime += ":00";
	if (re_datetime.exec(str_datetime)) {
		obj.value = str_datetime;
		return true;
	}	
		
	if ( message == null )	 return false; // not popup
	if (message=="") message = "Invalid datetime format (dd/MM/yyyy[ hh[:mm[:ss]]]): "+ str_datetime;
	alert(message);
	obj.focus();
	return false;
}

function check_date(obj,message) {
	if (!obj) return true;
	if (isNull(obj)) return true;
	var str_datetime = trim(obj.value);
	var re_date = /^(\d+)\/(\d+)\/(\d+)$/;
	var re_date1 = /^(\d+)\.(\d+)\.(\d+)$/;
	if (re_date.exec(str_datetime) || re_date1.exec(str_datetime) ) {
		if ( obj.value.charAt(1) == '/' )
			obj.value = '0' + obj.value;
		if ( obj.value.charAt(4) == '/' )
			obj.value = obj.value.substr(0, 3) + '0' + obj.value.substr(3);
		return true;
	}
	if ( message == null )	 return false; // not popup
	if (message=="") message = "Invalid date format: "+ str_datetime;
	alert(message);
	obj.focus();
	return false;
}

function check_time(obj,message) {
	if (!obj) return true;
	if (isNull(obj)) return true;
	var str_datetime = trim(obj.value);
	var re_time = /^(\d+)\:(\d+)\:(\d+)$/;
	if (re_time.exec(str_datetime)) {
		return true;
	}
	if ( message == null )	 return false; // not popup
	if (message=="") message = "Invalid time format: "+ str_datetime;
	alert(message);
	obj.focus();
	return false;
}
function check_number (obj,message,sign) {
	if (!obj) return true;
	if (isNull(obj)) return true;
	var str_number = trim(obj.value);
	if (!isNaN(str_number)){
		var re_num = /^[+-0123456789,.]+$/;
		if(sign=="+") re_num = /^[+0123456789,.]+$/;
		if(sign=="-") re_num = /^[-0123456789,.]+$/;
		if (re_num.exec(str_number)) return true;
	}
	if ( message == null )	 return false; // not popup
	if (message=="") message = "Invalid numeric format: " + str_number;
	alert(message);
	obj.focus();
	return false;
}
function check_integer (obj,message,sign) {
	if (!obj) return true;
	if (isNull(obj)) return true;
	var str_number = trim(obj.value);
	if (!isNaN(str_number)){
		var re_num = /^[+-0123456789]+$/;
		if(sign=="+") re_num = /^[+0123456789]+$/;
		if(sign=="-") re_num = /^[-0123456789]+$/;
		if (re_num.exec(str_number)) return true;
	}
	if ( message == null )	 return false; // not popup
	if (message=="") message = "Invalid numeric format: " + str_number;
	alert(message);
	obj.focus();
	return false;
}
function check_notnull(obj,message) {
	if (!obj) return true;
	
	/* if type radio and array*/
	//if (obj.type == 'radio') alert(obj.length);
//		alert(obj&& obj.length && obj.length > 0&& obj[0]&& obj[0].type && obj[0].type == 'radio');
	var noFocusable = false;
	if (obj && obj.length && obj.length > 0 && obj[0] && obj[0].type && obj[0].type == 'radio') {
		var i = 0;
		for(i = 0;i < obj.length; i++)
			if (obj[i].checked) break;
		if (i<obj.length) return true;
		noFocusable = true;
	} 
	else if (!isNull(obj)) return true;

	if ( message == null )	 return false; // not popup
	alert(message);
	if (!noFocusable) obj.focus();
	return false;
}

function isNull(obj) {
	if (!obj) return true;
	if (trim(obj.value)=="") {
		return true;
	}else{
		return false;
	}
}

function NaN2Empty(obj) {
	if (!obj) return "";
	if (typeof(obj) != "object" ) return obj;
	if (isNaN(obj.value)) obj.value = "";
	return obj.value;
}

function delSpace( str ) {
	if (str==null) return "";
	while(str.indexOf(" ")>-1){
		str=str.replace(" ","");
	}
	return str;
}

function trim (str) {
	while ((str!=null)&&(str.length>0)&&(str.substring(0,1)==" ")){str = str.substring(1,str.lenght);}
	while ((str!=null)&&(str.length>0)&&(str.substring(str.length-1)==" ")){str = str.substring(0,str.length-1);}
	return str;
}

/*
Hai 2005/06/10
true if Str is ended by subStr
else false
*/
function endsWith(Str, subStr) {
	if ( Str == '' || subStr == '' )
		return false;
	var pos = Str.lastIndexOf(subStr);
	if ( pos < 0 ) return false;
	if ( pos + subStr.length == Str.length )
		return true;
	return false;
}

// whitespace characters
var whitespace = " \t\n\r";
// Check whether string s is empty.
function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}
// Returns true if string s is empty or
// whitespace characters only.
function isWhitespace (s)

{   var i;

	// Is s empty?
	if (isEmpty(s)) return true;

	// Search through string's characters one by one
	// until we find a non-whitespace character.
	// When we do, return false; if we don't, return true.

	for (i = 0; i < s.length; i++)
	{
		// Check that current character isn't whitespace.
		var c = s.charAt(i);

		if (whitespace.indexOf(c) == -1) return false;
	}

	// All characters are whitespace.
	return true;
}
/********************************************************/
function isFieldNumericPossitive(theField)
{
	var teststr = "1234567890,. ";
	for (i=0;i < theField.value.length;i++)
	{
		if (teststr.indexOf (theField.value.charAt(i)) == -1)
			return false;
	}
	return true;
}
/********************************************************/
function isFieldNumericNoComma(theField)
{
	var teststr = "1234567890. ";
	for (i=0;i < theField.value.length;i++)
	{
		if (teststr.indexOf (theField.value.charAt(i)) == -1)
			return false;
	}
	return true;
}
/********************************************************/
function isFieldNumeric(theField)
{
	var teststr = "-1234567890 ";
	for (i=0;i < theField.value.length;i++)
	{
		if (teststr.indexOf (theField.value.charAt(i)) == -1)
			return false;
	}
	return true;
}
/********************************************************/
function isFieldFloat(theField)
{
	var teststr = "-1234567890,. ";
	for (i=0;i < theField.value.length;i++)
	{
		if (teststr.indexOf (theField.value.charAt(i)) == -1)
			return false;
	}
	return true;
}

/********************************************************/
// Round : round(8.56475, 2) => 8.56
// Round :
/********************************************************/
function roundFloat( value, n_precision ) {
	if (value=="") return value; // compare 0 == "" -> true
	if ( typeof (value) != "number" )
		value = parseFloat(value);
	var T = Math.pow(10, n_precision);  // bug 0.6.toFixed(0) = 0 instead of 1
  	value = Math.round(value*T)/T;
	//alert(Number().toFixed);
	var retval = Number().toFixed ? 1*value.toFixed(n_precision) : value; // <--- return String type
	return retval;
}


/********************************************************/
// Input Str, OldChar, NewChar
// Output Replace OldChar by NewChar in Str
/********************************************************/
function replaceStr( Str, oldChar, newChar) {
	while ( Str.indexOf(oldChar) >= 0 ) {
		Str = Str.replace( oldChar, newChar);
	}
	return Str;
}

/********************************************************/
/*
 * Description: replace special charters :
 *	if pbl=true : ' --> ´ , " --> ª
 *	if pbl=false : ´ --> ' , ª --> "
 * Example :
 * Copyright:    Copyright (c) 2002
 * Company:      VnTeam
 * @author NGUYEN Trung Hieu
 * @version 1.0
 */
/********************************************************/
function doReplace(theControl,pbl){
	if(pbl){
		theControl.value=theControl.value.replace(/[']/g,"´");
		theControl.value=theControl.value.replace(/["]/g,"ª");
	}else{
		theControl.value=theControl.value.replace(/[´]/g,"'");
		theControl.value=theControl.value.replace(/[ª]/g,"\"");
	}
}
/********************************************************/
/*
 * Description: check or uncheck all check box in a form
 * Example :
 * 	checkall(chk,true) :
 * 		Check all check box whose name is chk
 * 	checkall(chk,false) :
 * 		Uncheck all check box whose name is chk
 *
 * Copyright:    Copyright (c) 2001
 * Company:      VnTeam
 * @author NGUYEN Trung Hieu
 * @version 1.0
 */
/********************************************************/
function checkall(pobjcheck,pblflag) {
	if (pblflag == false) {
		for (i = 0; i < pobjcheck.length; i++) {
			pobjcheck[i].checked = pblflag;
		}
	}
	else {
		for (i = 0; i < pobjcheck.length; i++) {
			pobjcheck[i].checked = pblflag;
		}
	}
}
/********************************************************
NGUYEN Duc Hai
today in format dd/mm/yyyy
********************************************************/
function todayStr() {
  var today = new Date();
  return Date2Str( today );
}

/**************************************************************/
/*
 * Description: Calculate differences between 2 dates
 * Input : laterday,earlierday : days to calculate
 * Output: return the difference
 * Example :
 * 	a = daydifference(new Date(2000,02,01),new Date(2000,01,01)) :
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author : from Internet
 * @version 1.0
 */
/********************************************************/

function daydifference(laterdate,earlierdate) {
	var difference = laterdate.getTime() - earlierdate.getTime();
//    var daysDifference = Math.floor(difference/1000/60/60/24);
	var daysDifference = Math.round(difference/1000/60/60/24);
	return daysDifference;
}

/**************************************************************/
/* NGUYEN Duc Hai
/* input date object
/* ouput date Str dd/mm/yyyy
/**************************************************************/
function Date2Str( date ) {
  var month = date.getMonth()+1;
  var year = date.getYear();
  var day = date.getDate();
  if (day < 10 ) day = "0" + day;
  if ( month < 10 ) month = "0" + month ;
  if ( year < 1000 ) year +=1900;
  return day + "/" + month + "/" + year;
}
/**************************************************************/
/* NGUYEN Duc Hai
/* input date Str dd/mm/yyyy or  dd.mm.yyyy
/* output date object
/**************************************************************/
function Str2Date( dateStr )  {
	   dateStr1 = replaceStr( dateStr, '.', '/').split('/');
//	alert(dateStr1[2] + dateStr1[1] + dateStr1[0] );
//	alert ( new Date(dateStr1[2] ,dateStr1[1] , dateStr1[0] ) ) ;
	return new Date(dateStr1[2] ,dateStr1[1] - 1 , dateStr1[0] );
}
/**************************************************************/
/*
 *  Input : 2 dates mm/dd/yyyy
 *  Input : date supérieure
 *  @author :  NGUYEN Duc Hai
 */
/**************************************************************/
function maxDate( date1, date2 ) {
	if ( date1 == '' ) return date2;
	if ( date2 == '' ) return date1;
	return ( daydifferenceStr(date1, date2) > 0  ) ? date1 : date2;
}
/**************************************************************/
/*
 *  Input : 2 dates mm/dd/yyyy
 *  Input : date supérieure
 *  @author :  NGUYEN Duc Hai
 */
/**************************************************************/
function minDate( date1, date2 ) {
	if ( date1 == '' ) return date2;
	if ( date2 == '' ) return date1;
	return ( daydifferenceStr(date1, date2) > 0  ) ? date2 : date1;
}
/**************************************************************/
function daydifferenceStr(laterdate,earlierdate) {
	return daydifference( Str2Date(laterdate), Str2Date(earlierdate) );
}

/**************************************************************/
function timedifferenceStr(laterTime,earlierTime) {
	timeStr1 = laterTime.split(':');
	timeStr2 = earlierTime.split(':');
	var date1 = new Date( 01, 01, 01 , timeStr1[0], timeStr1[1], timeStr1[2]) ;
	var date2 = new Date( 01, 01, 01 , timeStr2[0], timeStr2[1], timeStr2[2]) ;
	return ( date1 - date2);
}

/**************************************************************/
/*
 *  Input : sdate format dd/mm/yyyy
 *          nday plus into sdate
 *	Example : sdate = 22/12/2000
 *			  nday = 10
 *			  plusdate = 01/01/2001
 *	@author : Hunh Ngoc Tuan
 *  updated :  NGUYEN Duc Hai: nday may be <, =, > 0
 */
function plusdate(sdate,nday) {
  	var date = Str2Date(sdate);
	date.setDate(date.getDate()+nday);
  	return Date2Str( date );
}
 /**************************************************************/
/*
 *  Input : nyear
 *	Example : nyear = 2000
 *			  totaldayofyear = 366
 *	@author : Hunh Ngoc Tuan
 */
function totaldayofyear(nyear)
 {
   if((nyear % 400 == 0) || ((nyear % 4 == 0) && (nyear % 100 != 0)))
	return 366;
   return 365;
 }
 /**************************************************************/
/*
 *  Input : nmonth,nyear
 *	Example : nmonth = 2,nyear = 2000
 *			  totaldayofmonth = 29
 *	@author : Hunh Ngoc Tuan
 */
function totaldayofmonth(nmonth,nyear)
 { var nDay;
   switch(nmonth)
		  { case 2 :
					  if((nyear % 400 == 0) || ((nyear % 4 == 0) && (nyear % 100 != 0)))
						nDay = 29;
					else
					 nDay = 28;
					break;
			case 1: case 3: case 5: case 7: case 8: case 10: case 12 :
						nDay = 31;
					 break;
			case 4: case 6: case 9: case 11:
					 nDay = 30;
					 break;
		  }
   return nDay;
 }
/********************************************************/
/*
 *  Input : str, ???
 *	@author : NGUYEN Duc Hai
	 toNumber( "", true ) => 0
	 toNumber( "", false ) => isNaN
	 toNumber( "15", false ) => 15
 */


/********************************************************/
function toNumber( str, convertIfNull ) {
	str = delSpace(str);
	if ( convertIfNull && (str == "" ||str == null)) return 0;
	return parseFloat( str.replace(',','.'), 10 );
}

/**************************************************************/
/*
 * Description:
 * 		Dates are validated and formatted in your form.
 * 	    Supports over a dozen different date formats, and formats
 *		the date properly in United States or European date formatting
 *		styles depending on how the script is configured. A dateCheck
 *		function also is included if you wish to compare two dates.
 * Input : strdate1,strdate2 : days to compare
 * Example :
  * Copyright:    Copyright (c) 2001
 * Company:
 * @author : from Internet
 * @version 1.0
 */
/********************************************************/
function compdate(strdate1,strdate2)
{

	var m1,d1,y1,m2,d2,y2;

	var s, pos1,pos2;
	var s = strdate1,s1=strdate2;
	if (s.length==0 || s1.length==0) return 1;
	pos1=s.indexOf("/",0);
	pos2=s.indexOf("/",pos1+1);
	d1=parseInt(s.substr(0,pos1),10);
	m1=parseInt(s.substr(pos1+1,pos2-pos1-1),10);
	y1=parseInt(s.substr(pos2+1,s.length-pos2),10);

	pos1=s1.indexOf("/",0);
	pos2=s1.indexOf("/",pos1+1);
	d2=parseInt(s1.substr(0,pos1),10);
	m2=parseInt(s1.substr(pos1+1,pos2-pos1-1),10);
	y2=parseInt(s1.substr(pos2+1,s1.length-pos2),10);
	var d1= new Date(y1,m1,d1);
	var d2= new Date(y2,m2,d2);
	if (d1>=d2)
		return 1;
	else
		return 0;
}
/**************************************************************/
/*
 * Description:
 *		Check if a date is valid or not
 * Input:
 *	objName:
 *		Name of object must be check
 *	strStyle:
 *		'US' : United States date style
 *		'EU';  //European date style
 * Output:
 *	return false is date is invalid and true if date is valid
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author : from Internet
 * @version 1.0
 */
/********************************************************/
function checkdate(objName,strStyle) {
	var datefield = objName;
	if (chkdate(objName,strStyle) == false) {
		datefield.select();
		alert("Date invalide.Vueillez-vous retaper");
		datefield.focus();
		return false;
	} else {
		return true;
	   }
}
/********************************************************/
function checkddmmyyyy(objName,strStyle) {
	var datefield = objName;
	var strValue = datefield.value;
	if(strValue.length < 10) {
		alert("That date is invalid.  Please try again.");
		   datefield.focus();
		   return false;
	} else if (chkdate(objName,strStyle) == false) {
		datefield.select();
		alert("Date est invalide.Veuillez vous re-saisir.");
		datefield.focus();
		return false;
	} else {
		return true;
	}
}

/********************************************************/
function chkdate(objName,strStyle) {
var strDatestyle = "US"; //United States date style
//var strDatestyle = "EU";  //European date style
if(strStyle==null){strDatestyle = "US";}
else{strDatestyle = strStyle;}
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
var err = 0;
var strMonthArray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
strDate = datefield.value;

if (strDate.length < 6) {
	return false;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
	if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
		strDateArray = strDate.split(strSeparatorArray[intElementNr]);
		if (strDateArray.length != 3) {
			   err = 1;
			   return false;
		} else {
			   strDay = strDateArray[0];
			   strMonth = strDateArray[1];
			   strYear = strDateArray[2];
		}
		booFound = true;
	  }
  }

if (booFound == false) {
	if (strDate.length>5) {
		   strDay = strDate.substr(0, 2);
		   strMonth = strDate.substr(2, 2);
		   strYear = strDate.substr(4);
	   }
}
if (strYear.length == 2) {
	strYear = '20' + strYear;
}
// US style
if (strDatestyle == "US") {
	strTemp = strDay;
	strDay = strMonth;
	strMonth = strTemp;
}
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
	err = 2;
	return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
	for (i = 0;i<12;i++) {
		if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
			intMonth = i+1;
			strMonth = strMonthArray[i];
			i = 12;
		   }
	}
	if (isNaN(intMonth)) {
		err = 3;
		return false;
	   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
	err = 4;
	return false;
}
if (intMonth>12 || intMonth<1) {
	err = 5;
	return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
	err = 6;
	return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
	err = 7;
	return false;
}
if (intMonth == 2) {
	if (intday < 1) {
		err = 8;
		return false;
	}
	if (LeapYear(intYear) == true) {
		if (intday > 29) {
		err = 9;
		return false;
	}
} else {
	if (intday > 28) {
		err = 10;
		return false;
	}
}
}
/*
if (strDatestyle == "US") {
datefield.value = strMonthArray[intMonth-1] + " " + intday+" " + strYear;
}
else {
datefield.value = intday + " " + strMonthArray[intMonth-1] + " " + strYear;
}*/
return true;
}
//Check if a year is leap or not
function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}
/**************************************************************/
/*
 * Description:
 *		compare 2 dates (include checking these dates are valid or not)
 * Input:
 *	from,to:
 *		dates to compare
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author : from Internet
 * @version 1.0
 */
/********************************************************/
function doDateCheck(from, to) {
	if (Date.parse(from.value) <= Date.parse(to.value)) {
		alert("The dates are valid.");
	}
	else {
		if (from.value == "" || to.value == "")
			alert("Both dates must be entered.");
		else
			alert("To date must occur after the from date.");
   }
}
/********************************************************/
function isSpecialCharater(s)
{
	var i;
	var c="'";
	if (s.indexOf(c) == -1) return false;
	return true;
}
function StrToNum(pstrControl) {
	var num_out="";
	var i;
	var str_in=escape(pstrControl.value);
	for(i=0;i<str_in.length;i++)num_out+=str_in.charCodeAt(i)-23;
	pstrControl.value=num_out;
}

function StrToNum1(pstr) {
	var str_in=escape(pstr);
	var num_out="";
	for(var i=0;i<str_in.length;i++) num_out+=str_in.charCodeAt(i)-23;
	return num_out;
}

function NumToStr(pstrControl)
{
	var str_out="";
	var num_out="";
	var num_in="";
	var i,flag;
	str_out="";var flag=0;
	num_out=pstrControl.value;
	for(i=0;i<num_out.length;i++)
		{
		if((num_out.charAt(i)>=0)||(num_out.charAt(i)<=9))flag=0;
		else{flag=1;break}
	}
	if(flag)alert("You may only enter numbers here");
	else
		{
		num_out=pstrControl.value;
		for(i=0;i<num_out.length;i+=2)
			{
			num_in=parseInt(num_out.substr(i,[2]))+23;
			num_in=unescape('%'+num_in.toString(16));
			str_out+=num_in;
		}
		pstrControl.value=unescape(str_out);
	}
}


function CheckSpecChar(theField)
{
	var i;
	for (i=0;i < theField.length;i++)
	{
		if (theField.charAt(i) == "'")
			return true;
	}
	return false;

	return theField ;
}
/*
	 Display : frech format number
	 Obj 	: string to format
	char1   : char to separate   integal number and   odd number
	char2  : char to seperate digits of  integal number
 */
 function formatNumberFrench(obj, char1, char2)
 {
	// check empty string
	if ( obj.length == 0 ) return;
	var i  = obj.length -1 ;
	while (i >=0 )
	{
			if ( obj.charAt(i) == char1)
					break;
			i = i -1;
	}
	//obj = integal number +   odd number
	obj = obj.substr(0, i).replace(char2, char1) + obj.substr(i, obj.length).replace(char1 ,char2);
	return obj;
 }

/*------------------------------------------
// Site http://www.merlyn.demon.co.uk/index.htm
	YWDToYMD = Year Week Day -> Year Month Day
	 Function : return date of week of year
	year   : year
	 weeknr 	: week of year
	begin : 1 first day of week, 2: second day of week, so on ..
	Example:
		ofweeknr(7, 2004, 1) =>  09/02/2004
		ofweeknr(7, 2004, 7) =>  15/02/2004
*/

function YWDToYMD(yyyy, weeknr, day) {
	OD = new Date( yyyy, 0, 4);
	OD.setDate(OD.getDate() - (OD.getDay()+6)%7 + (weeknr-1)*7 + day-1 );

	  return (OD.getDate() < 10 ? '0' : '') + OD.getDate() +"/"+
				(OD.getMonth() < 9 ? '0' : '') + (OD.getMonth() +1)+"/"+OD.getYear();
}

function week2days(yyyyww, objDate1, objDate2, labelDate1, labelDate2 ) {
	objDate1.value = '';
	objDate2.value = '';
	if ( yyyyww.length != 6 ) {
		labelDate1.innerHTML = '??/??/????';
		labelDate2.innerHTML = '??/??/????';
		return false;
	}
	var yyyy = yyyyww.substring(0,4);
	var ww = yyyyww.substring(4,6);
	labelDate1.innerHTML = YWDToYMD( yyyy, ww, 1);
	labelDate2.innerHTML = YWDToYMD( yyyy, ww, 7);
	objDate1.value = labelDate1.innerHTML;
	objDate2.value = labelDate2.innerHTML;
	return true;
}


/* ---------------------------------------------
Focus next element
------------------------------------------------*/
function isValidTag(obj) {
	if ( ( ( obj.tagName == 'INPUT' && obj.type != 'hidden' && ( obj.type != 'text' ||
																(obj.type == 'text' && obj.name.indexOf('_Label_') != 0 ))) ||
		   ( obj.tagName == 'SELECT' ) ) )
		   return true;
	 return false;
}

/*var focusableError = false;
function myErrorHandler() {
	focusableError = true;
	alert('Error Hai');
	return true;
}*/

function focusable( obj ) {
/*	if ( !obj ) return false;
	var event = window.onerror;
	focusableError = false;
	window.onerror = myErrorHandler;*/
	el = document.activeElement;
	var focusableE = true;
	try {
		obj.focus();
	} catch(er) {
		focusableE = false;
	}
	try {
		el.focus();
	} catch(er) {}

	return focusableE;
/*	window.onerror = event;
	return !focusableError;*/
}
/*
	focus control if possible
	if no, do nothing
*/
function focusControl( obj ) {
	el = document.activeElement;
	var focusableE = true;
	try {
		obj.focus();
	} catch(er) {
		focusableE = false;
		try {
			el.focus();
		} catch(er1) {}
	}

	return focusableE;
}

function setDisplayStyle(obj, styleValue) {
	if (!obj) return;
	if ( !obj.length ) {
		if (!obj.style || obj.style.display == null ) return;
		obj.style.display= styleValue;
	} else {
		//alert(obj.length);
		for(var j = 0; j < obj.length; j++) {
			//alert(obj[j].style.display==null);
			if (!obj[j].style || obj[j].style.display == null ) continue;
			obj[j].style.display=styleValue;
		}	
	}
}	

function getNextElement(i) {
	 for (j = (document.all.length == i+1)?0:i+1; j < document.all.length; j++)
		   if( isValidTag(document.all[j]) && focusable(document.all[j]) )
			 return document.all[j];
	for (j = (document.all.length == i+1)?i+1:0; j < i; j++)
		   if( isValidTag(document.all[j]) && focusable(document.all[j]) )
			 return document.all[j];
	return null;
}

function getCurrentElement() {
	el = document.activeElement;
	var i = 0;
	for (i = 0; i < document.all.length && document.all[i].uniqueID != el.uniqueID; i++ );
	return i < document.all.length ? i : -1;
}

/*
Enter => Tab
*/

var controlTabs = new Array(0);


function keyDown(DnEvents) { // handles keypress
var src= window.event.srcElement; // document.activeElement;
//alert("hai: " + src.name);


k = window.event.keyCode;

	if (k == 13) { // enter key pressed
		if ( src.type == "textarea" )
			return 0;

		var myform = src.form;
		if ( myform != null ) { // FORME
			if ( src.name == 'FILTER_VALUE' || src.name == 'Filtrer'  ) {
				document.body.style.cursor = "wait";   
				myform.submit();
				return 0;
			}
			if (  src.name == 'Ajouter' || src.name ==  'Modifier' ||
				src.name == 'Supprimer' || src.name == 'Logon' ) {
				   document.onkeyup = null;
				document.body.style.cursor = "wait";   
				src.disabled = true;
				formUpdate(src);
				return 0;
			}
		}

		var obj_index = getCurrentElement();
		if ( obj_index == - 1 || obj_index == document.all.length - 1 ) {
			window.event.keyCode = 9;
			return 0;
		}

//		alert("Testing..." + obj_index);
		if ( controlTabs.length > 0 ) {
			var i = 0, j;
			 for ( i = 0;  i < controlTabs.length && document.all[obj_index] != controlTabs[i]; i++) ;
//		alert("Testing1..." + i);
			if ( i == controlTabs.length ) {
				for(j = obj_index+1; j < document.all.length; j++) {
					for ( i = 0;  i < controlTabs.length && document.all[j] != controlTabs[i]; i++) ;
					if ( i < controlTabs.length ) break;
				}
			} else i++;
//		alert("Testing2..." + i);
			j = i - 1;
			for( ; i < controlTabs.length; i++ )
				try {
					controlTabs[i].focus();
					return 0;
				} 	catch(er) { }
			for( i=0; i < j; i++ )
				try {
					controlTabs[i].focus();
					return 0;
				} 	catch(er) { }

		}

		 for ( obj_index++;  obj_index < document.all.length; obj_index++)
			   if( isValidTag( document.all[obj_index] ) )
				try {
					document.all[obj_index].focus();
					return 0;
				} catch(er) { }

		window.event.keyCode = 9;
		return 0;
	}
//	alert(k);
}
document.onkeyup = keyDown; // work together to analyze keystrokes


function formPrint(){
	// Hide all div
	var div = new Array("idPrint", "idDelete", "idButton", "idPage", "idFilter", "idForm");
	for(var i = 0; i < div.length; i++) {
		var obj = document.getElementsByName(div[i]);
		if (obj==null) continue;
		if (!obj.length) {
			if (obj.style!=null) {
				obj.style.display="none";
			}
		} else {
			for(var j = 0; j < obj.length; j++){
				obj[j].style.display="none";
//				if ( div[i] == "idDelete" && obj[j].parentNode )
//					obj[j].parentNode.style.display="none";
			}
		}
	}

	var idTableGrid = document.getElementById("idTableGrid");
	if ( idTableGrid ) {
		idTableGrid.border = "1";
		//alert( idTableGrid.style.borderCollapse );
		idTableGrid.style.borderCollapse = "collapse";
		for (var i=0; i < idTableGrid.rows.length; i++)  {
			var r = idTableGrid.rows[i].cells; // row --
			for (var c=0; c < r.length; c++){ // each cell
				if ( r[c].className == 'grid_footer' ) 
					r[c].style.display = "none";
        		else r[c].style.borderColor = '#111111';
    		}
		}
		idTableGrid.style.borderTopWidth = 1;
		idTableGrid.style.borderRightWidth = 1;
		idTableGrid.style.borderBottomWidth = 1;
		idTableGrid.style.borderRightWidth = 1;
		idTableGrid.style.borderColor = '#111111';
		//alert(idTableGrid.style.borderColor);
	}
	window.print();

	// Show all div
	for(var i = 0; i < div.length; i++) {
		var obj = document.getElementsByName(div[i]);
		if (!obj.length) {
			if (obj.style!=null) {
				obj.style.display="";
			}
		} else {
			for(var j = 0; j < obj.length; j++){
				obj[j].style.display="";
			}
		}
	}

	if ( idTableGrid ) {
		idTableGrid.border = "0";
		for (var i=0; i < idTableGrid.rows.length; i++)  {
			var r = idTableGrid.rows[i].cells; // row --
			for (var c=0; c < r.length; c++){ // each cell
        		r[c].style.borderColor = '';
				if ( r[c].className == 'grid_footer' ) 
					r[c].style.display = "";
    		}
		}
	}
}

/*
Function for tag <select> <option></select>
*/

function comboRemoveAll(combo){
	if (combo){
		while (combo.options.length>0){combo.options.remove(0);}
	}
}

function comboAdd(combo,value,text){
	if (combo){
		if (document.createElement){
			var item = document.createElement("OPTION");
			item.value=value;
			item.text=text;
			combo.options.add(item);
		}else{
			combo.options[combo.options.length+1] = new Option(text,value,false,false);
			history.go(0);
		}
	}
}

// choisir une valeur dans la liste en tappant la valeur
var valueSelectedText = '';

function setSelectedIndexOfObjDual( obj ) {
/*	if ( document.all[ obj.name ][0] &&  document.all[ obj.name ][1] &&
		 document.all[ obj.name ][0].name &&  document.all[ obj.name ][1].name &&
		 document.all[ obj.name ][0].name == document.all[ obj.name ][1].name ) { // >= 2 liste
		var i = (document.all[ obj.name ][0] == obj ) ? 1 : 0;
		document.all[ obj.name ][ i ].value =  obj.value;
	}*/
	var objArray = document.all.item( obj.name );
	if ( objArray.length && objArray.length >= 2 && objArray[1].name && objArray[1].name == obj.name ) {
		var i = (objArray[0] == obj ) ? 1 : 0;
		objArray[ i ].value = obj.value;
	}
	valueSelectedText = '';
//	alert('on change');
}

function setSelectedIndex( obj ) {
	var key = window.event.keyCode;
	if ( key == 27 || key == 13 ) {
		valueSelectedText = '';
/*		if ( obj.onchange ) {
			alert("execute " + obj.onchange);
			alert(eval( obj.onchange ));
		}*/
		return;
	}
	var temp = valueSelectedText;
	if ((key==46) || (key>47 && key<59)||(key>62 && key<127) ||(key==32) || key >= 32 ) {
		temp += String.fromCharCode(key).toUpperCase();
		var i = getSelectedIndex( obj, temp);
		if ( i >= 0 ) {
			var objArray = document.all.item( obj.name );
			if ( objArray.length && objArray.length >= 2 && objArray[1].name && objArray[1].name == obj.name ) { // >= 2 liste
				objArray[ 0 ].options.selectedIndex = i;
				objArray[ 1 ].options.selectedIndex = i;
			} else // 1 liste
				obj.options.selectedIndex = i;
			valueSelectedText = temp;
		}
		window.event.returnValue = false ;
	}
}

function getSelectedIndex( combo, valueStr ) {
	if ( !combo )
		return -1;
	//valueStr = valueStr.toUpperCase();
	for(var i = 0; i < combo.options.length; i ++) {
		var valueText = combo.options[i].text.toUpperCase();
		if ( valueText.indexOf( valueStr ) == 0 )
			return i;
	}
	return -1;
}

/* ---- end tag Select */

/* input checkBox */
/* return: ncheck */
function setCheckAll( objCheckAll, CheckboxName ) {
	if ( !objCheckAll ) return 0;
	var obj = document.all.item( CheckboxName );
	if ( !obj ) return 0;
	if ( !obj.length ) {
		if ( obj.disabled == false )
			obj.checked = objCheckAll.checked;
		return obj.checked ? 1 : 0;
	}
	
	var nchecked = 0;
	
	for (var i=0;i< obj.length;i++){
		if ( obj[i].disabled == false )
			obj[i].checked = objCheckAll.checked;
			nchecked += ( obj[i].checked ) ? 1 : 0;
	}
	return nchecked;
}
/* ---- end input checkBox */

/* ----- cookie functions 
	use : setCookie('??? name', '???', '', '/', '', '' );
		  getCookie('??? name');
*/
function setCookie( name, value, expires, path, domain, secure )  {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );

	/*
	if the expires variable is set, make the correct 
	expires time, the current script below will set 
	it for x number of days, to make it for hours, 
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1){
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }else{
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1){
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/* ----- end cookie functions ---- */


/* ----- begin ajax functions ---- */

function postProcess() { // waiting overwite
	//alert('postProcess(responseText):' + responseText);
}

function AJAXInteraction(url) {
    this.url = url;
	var fpostProcess = null;
	var xlm = false; 
	var para = AJAXInteraction.arguments;
	//alert("para:" + para);
	//alert(AJAXInteraction.arguments.length);
	for(var ip = 1; ip < AJAXInteraction.arguments.length; ip++) 
 		if (typeof AJAXInteraction.arguments[ip] == "function") 
			fpostProcess=AJAXInteraction.arguments[ip];
		else if (typeof AJAXInteraction.arguments[ip] == "boolean") 
			xlm=AJAXInteraction.arguments[ip];
	//alert(fpostProcess + " : " + xlm);
	//alert(fpostProcess + " : " + xlm);
	if (fpostProcess == null)
		fpostProcess = postProcess; // default

    var req = init();
    req.onreadystatechange = processRequest;
        
    function init() {
      	if (window.XMLHttpRequest) {
        	return new XMLHttpRequest();
      	} else if (window.ActiveXObject) {
        	isIE = true;
        	return new ActiveXObject("Microsoft.XMLHTTP");
      	}
    }
    
    function processRequest () {
      	if (req.readyState == 4) {
        	if (req.status == 200 && fpostProcess) {
          		//fpostProcess(req.responseXML);
				//alert('in processRequest .... ' + para);
				fpostProcess(xlm ? req.responseXML : req.responseText, para);
        	}
      	}
    }

    this.send = function() {
        req.open("GET", url, true);
        req.send(null);
    }
}
/* ----- end ajax functions ---- */

/*-- SelectBox Editable */
function calculate_absolute_X( theElement ) {
	var xPosition = 0;
	while ( ( theElement != null ) && ( theElement.id != this.id ) ) {
		xPosition += theElement.offsetLeft;
		theElement = theElement.offsetParent;
	}
	return xPosition;
}

function calculate_absolute_Y( theElement ) {
	var yPosition = 0;
	while ( ( theElement != null ) && ( theElement.id != this.id ) ) {
		yPosition += theElement.offsetTop;
		theElement = theElement.offsetParent;
	}
	return yPosition;
}

var uniqueID="a_";
var uniqueNID = 0;
	
function getActualWidth(e){
    if (! e.currentStyle)   e.currentStyle = e.style;
    return  e.clientWidth - parseInt(e.currentStyle.paddingLeft) - parseInt(e.currentStyle.paddingRight);
}
	
/* 	minWidth : min Width in pixel
	maxWidth : max Width in pixel
*/	
function initSelectBoxEditable(oTextBox, oSelectBox, minWidth, maxWidth) {
	if (!oTextBox || !oSelectBox) return false;
	//var oSpan = children( 0 );
	//alert(oTextBox.id);
	if ( minWidth && getActualWidth(oSelectBox) < minWidth)
		oSelectBox.style.width = minWidth + 'px';
	if ( maxWidth && getActualWidth(oSelectBox) > maxWidth)
		oSelectBox.style.width = maxWidth + 'px';
		
		
	oTextBox.id = uniqueID + (uniqueNID) + "_text";
	oTextBox.className = "input_editable";
	//oTextBox.name = name + "_text";
	//alert("uniqueNID:"+uniqueNID);

	oSelectBox.id	= uniqueID + (uniqueNID++) + "_select";
	//oSelectBox.name = name + "_select";
	oTextBox.className = "select_editable";
	oSelectBox.tabIndex = -1;
	

	oSelectBox.calculate_absolute_X=calculate_absolute_X;
	oSelectBox.calculate_absolute_Y=calculate_absolute_Y;

	oSelectBox.style.position	=	"absolute";
	oSelectBox.style.setExpression("pixelLeft", "calculate_absolute_X(" + oTextBox.id + ")");
	oSelectBox.style.setExpression("pixelTop", "calculate_absolute_Y(" + oTextBox.id + ")");
	
	var iBrowserVersion = 6;
	if ( iBrowserVersion == 6 ) {
		oSelectBox.style.setExpression("clip","'rect(auto auto auto '+(offsetWidth - 18)+')'");
	}
	else {
		oSelectBox.style.setExpression("clip","'rect(auto auto auto '+(offsetWidth - 20)+')'");
	}

	var iWidth = oSelectBox.getAttribute( "width" );
	/*alert("iWidth of oSelectBox:"+iWidth);
	if (iWidth == null) 
		oSelectBox.style.pixelWidth = oSelectBox.offsetWidth - 18;*/
	//iWidth = 100;	
	if ( ( iWidth != null ) && ( iWidth != "" ) ) {
		oSelectBox.style.pixelWidth = iWidth;
	}
	oTextBox.style.setExpression("pixelWidth", oSelectBox.id + ".offsetWidth - 18" );
	
	//oSelectBox.attachEvent("onchange", onChangeListSelection);
	oTextBox.style.display = "";
	oSelectBox.style.display = "";
}

function onChangeListSelection()
{
}

/*-- END SelectBox Editable */
