//-----------------------------------------------------------------------------
// Verification de donnees
//-----------------------------------------------------------------------------
// Librairie Javascript pour validation de formulaires avant envoi
//
// Version               : 2.67
// Derniere modification : 21/12/06 - VerifyInteger
// Par                   : HJ
//
// Mode d'emploi :
// Dans la page du formulaire :
//	<FORM name="FormName" action="..." method="get" onsubmit="return CheckDatas(document.FormName);">
//
// Optionnel : donner des noms plus explicites aux champs :
//	NomChamp=new Array(2);
//	NomChamp["OS_LeNomDuChamp"]="Le Nom Du Champ";

// A mixer : /MacPro Datas/Labo/Javascript/VŽrification de donnŽes/RegExpValidate.js

/*
Principe : le nom des champs defini le type de donnees attendu et l'optionalite.
"OM_..."     -> mail
"OW_..."     -> web
"OL_n_..."   -> longueur mini
"OS_..."     -> pas d'espaces
"ON_..."     -> numerique
"OC_m_M_..." -> n cases cochees mini/Maxi
"OR_..."     -> boutons radio coche
"OD_..."     -> date valide [HJ 08/09/04]

"OX_..."     -> Optionnel
"RX_..."     -> Requis. Si cˆc ou boutons radio => au moins 1 sel

MTI01_RC_2_5]Nom du champ  ou  RC_2_5_Nom du champ
=====-==-=-=-============
|  |  |  | | |_ Nom du champ en clair
|  |  |  | |___ Nb cases maxi
|  |  |  |_____ Nb cases mini
|  |  |________ Optionalite (R ou O) et type (M, W,...)
|  |___________ Si MTI, 2 chiffres obligatoires, utilises pour le tri dans le retour form
|______________ Si MTI, le champs est traite, sinon, on l'ignore

*/
var NS4 = (document.layers) ? true : false;
var debut = 1;

function CheckDatas(theForm) {
	theTest=true;
	for (var i=0; i< theForm.elements.length; i++) {
		// Tester si numero d'ordre avant : ex: "MTI01_RM]Nom champ"
		debut=1;
		if (theForm.elements[i].name) { // prise en compte objets fieldset
			if (theForm.elements[i].name.substr(0,3)=="MTI") {
				debut=7;
			}		
//alert(theForm.elements[i].name)
			if (theForm.elements[i].value != "" && theTest) {	
				// On traite ou pas ?
				// Si champ debute par "MTI" ou si debute par "R" ou "O" et 3eme car = "_"
				if (theForm.elements[i].name.substr(0,3)=="MTI" || (theForm.elements[i].name.substr(2,1)=="_" && (theForm.elements[i].name.substr(0,1)=="R" || theForm.elements[i].name.substr(0,1)=="O"))) {
					// On traite
					switch (theForm.elements[i].name.substr(debut,2)) { // "switch" ne marche pas dans NS4 !!!
					case "I_" : // HJ 061221
						if (!VerifyInteger(theForm.elements[i])) { theTest=false; }
						break;
					case "N_" :
						if (!VerifyNumeric(theForm.elements[i])) { theTest=false; }
						break;
					case "D_" :
						if (!VerifyDate(theForm.elements[i])) { theTest=false; }
						break;
					case "Y_" :
						if (!VerifyYear(theForm.elements[i])) { theTest=false; }
						break;
					case "W_" :
						if (!VerifyWeb(theForm.elements[i])) { theTest=false; }
						break;
					case "M_" :
						if (!VerifyEmail(theForm.elements[i])) { theTest=false; }
						break;
					case "S_" :
						if (!VerifySpace(theForm.elements[i])) { theTest=false; }
						break;
					case "L_" :
						if (!VerifyLength(theForm.elements[i],theForm.elements[i].name.substring(debut+2,theForm.elements[i].name.indexOf('_',debut+2)))) { theTest=false; }
						break;
					case "R_" :
						if (!VerifyRadio(theForm,theForm.elements[i])) { theTest=false; }
						break;
					case "C_" :
						if (!VerifyCheckBox(theForm,theForm.elements[i])) { theTest=false; }
						break;
					case "P_" : // HJ 061120
						if (!VerifyPhone(theForm.elements[i])) { theTest=false; }
						break;
					case "T_" : // texte long - HJ 061120
						theTest=true;
						break;
					default :
						// Autres cas
					}
				}			
			} else {
				// Test champ obligatoire
				if (theForm.elements[i].name.substr(debut+1,1)=="_" && theForm.elements[i].name.substr(debut-1,1)=="R" && theTest) {
					alert(checkdata_TT["THE_FIELD"]+ GetNomChamp(theForm.elements[i].name) +checkdata_TT["IS_REQUIRED"]);
					ShowBadField(theForm.elements[i]);
					theTest=false
				}
			}
		}
	} // Fin boucle For
	return theTest;
}


function VerifyEmail(theField) { // [HJ 21/06/06]
	email=theField.value;
	theReM=/^[\-\._0-9a-zA-Z]+@[\-\._0-9a-zA-Z]+\.[a-zA-Z]+$/;
	resArrM = theReM.exec(email);
	if (resArrM==null) { 
		alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["BAD_MAIL"] + email + checkdata_TT["VLD_MAIL"]);
		ShowBadField(theField);
		return false;
	} else { return true; }
}

function VerifyWeb(theField) {
	web=theField.value;
	theReW=/^(http:\/\/|https:\/\/)?[\-\._0-9a-zA-Z]+\.[a-zA-Z]+([#=&\?\/\-\._0-9a-zA-Z]*)?$/i;
	resArrW = theReW.exec(web);
	if (resArrW==null) { 
		alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["BAD_WEB"] + web + checkdata_TT["VLD_WEB"]);
		ShowBadField(theField);
		return false;
	} else {
		if (web.substr(0,7) != "http://" && web.substr(0,8) != "https://") {
			theField.value="http://" + web;
		}
		return true;
	}
}

function VerifySpace(theField) {
	text=theField.value;
	if (text.indexOf(' ',0) != -1) {
		alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["VLD_CHR"]);
		ShowBadField(theField);
		return false;
	} else { return true; }
}

function VerifyLength(theField,nbcarmin) {
	text=theField.value;
	if (text.length < nbcarmin) {
		alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["ENTER"] + nbcarmin + checkdata_TT["CHARS"]);
		ShowBadField(theField);
		return false;
	} else { return true; }
}

function VerifyNumeric(theField) { // [HJ 21/12/06]
	// Autoriser - . , e E
	theVal=theField.value.replace(/,/,".");
	var regExpDouble=/^[-+]?[0-9]+(\.[0-9]+)?$/; // Accepte une chaine de type 'double'
	var regExpFloat =/^[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$/; // Accepte une chaine de type 'float'	
	if (!regExpFloat.test(theVal)) {
		alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["VLD_NUM"]);
		ShowBadField(theField);
		return false;
	}
	return true;
}

function VerifyInteger(theField) { // [HJ 21/12/06]
	// Nombres entiers seulement + ou - : autoriser -
	theVal=theField.value;
	var regExpInt=/^[0-9]+$/g; // Accepte une chaine de type 'int'
	if (!regExpInt.test(theVal)) {
        alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["VLD_INT"]);
		ShowBadField(theField);
		return false;
	}
	return true;
}

function VerifyPhone(theField) { // [HJ 15/11/06]
// [Ref] On vous rappelle ds UMP
	// Autoriser chiffres, + . ( ) et espaces
	theVal=theField.value; // .replace(/,/,".")
	var tDigits = theVal.match(/\d/g);
	var nbDigits = 0;
	if (tDigits!=null) { nbDigits = tDigits.length; }
	theReT=/^(\+)?[ ()0-9]+/gi;
	//theReT=/^(\+[0-9]{2})[ \.\-]?[0-9][ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}$/g;
	resArrT = theReT.test(theVal);
	if (!resArrT || nbDigits<10) { 
		alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["VLD_TEL"]);
		ShowBadField(theField);
		return false;
	} else { return true; }
}

function VerifyYear(theField) {
// HJ 16/10/06
// [Ref] Annee naissance ds UMP
	theVal=parseInt(theField.value);
	var now = new Date();
	thisYear = now.getFullYear();
	if (theVal<1900||theVal>thisYear || isNaN(theVal)) {
		alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["VLD_ANN"]);
		ShowBadField(theField);
		return false;
	} else { return true; }
}

function VerifyDate(theField) {
	if (!isDateValid(theField.value)) {
		alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["VLD_DAT"]);
		ShowBadField(theField);
		return false;
	} else { return true; }
}

function isDateValid(theDate) {
// HJ 06/09/06
// http://www.webmaster-hub.com/publication/article18.html
   if (theDate == "") return true
   if (theDate.lastIndexOf(" ")>0) theDate=theDate.substring(0,theDate.lastIndexOf(" "))
   var tabDate = theDate.split("/");
   if ((tabDate.length != 3) || isNaN(parseInt(tabDate[0])) || isNaN(parseInt(tabDate[1])) || isNaN(parseInt(tabDate[2]))) return false
   var theDateObj = new Date(eval(tabDate[2]),eval(tabDate[1])-1,eval(tabDate[0]))
   var annee = theDateObj.getYear()
   if ((Math.abs(annee)+"").length < 4) annee = annee + 1900
   var anneeK = eval(tabDate[2])
   if ((Math.abs(anneeK)+"").length < 4) anneeK = anneeK + 1900
   return ((theDateObj.getDate() == eval(tabDate[0])) && (theDateObj.getMonth() == eval(tabDate[1])-1) && (annee == anneeK))
}

function VerifyRadio(theForm,theField) {
	isChecked=false;
	for (var i=0; i< theForm.elements.length; i++) {
		if (theForm.elements[i].type == "radio" && theForm.elements[i].name == theField.name) {
			if (theForm.elements[i].checked) {
				isChecked=true;
			}
		}
	}
	if (isChecked==false) {
       	alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["CHECK_OPTION"]);
		ShowBadField(theField);
		return false;
    } 
	return true;
}

function VerifyCheckBox(theForm,theField) {
	nbChecked=CountCheckedBox(theForm,theField.name);
	temp=theField.name.substring(debut+2,theField.name.lastIndexOf('_',theField.name.length));
	var tmpTab=temp.split("_")
	nbMin=tmpTab[0] //parseInt(temp.substring(0,theField.name.indexOf('_',0)-1));
	nbMax=tmpTab[1] //parseInt(temp.substring(temp.indexOf('_',0),temp.length));

	if (nbChecked<nbMin) {
		if (nbMin != nbMax) {
	   	    alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["CHECK_FROM"] + nbMin + checkdata_TT["TO"] + nbMax + checkdata_TT["OPTIONS"]);
		} else {
	   	    alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + checkdata_TT["CHECK"] + nbMin + checkdata_TT["OPTION_S"]);
		}
		ShowBadField(theField);
		return false;
    } else {
		if (nbChecked>nbMax) {
   	    	alert(checkdata_TT["FIELD"] + GetNomChamp(theField.name) + "' :\n" + nbMax + checkdata_TT["MAX_NB"]);
			ShowBadField(theField);
			return false;
   		}
    }
	return true;
}


function VerifySameFields(theField1,theField2) {
// Test si 2 champs sont bien identiques (ex: confirmation de mot de passe)
	text1=theField1.value;
	text2=theField2.value;
	if (text1 != text2) {
		alert(checkdata_TT["FIELD"] + GetNomChamp(theField1.name) + "' :\n" + checkdata_TT["NOT_SAME"]);
		ShowBadField(theField1);
		return false;
	} else { return true; }
}


function ShowBadField(theField) {
	if (!NS4) {	theField.style.backgroundColor="#fa8072"; }
	theField.focus();
	// theField.blur();
	if (theField.type != "radio" && theField.type != "checkbox" && theField.type != "select-one") { theField.select(); }
}


function CountCheckedBox(theForm,theFieldName) {
// Renvoie le nb de cases cochees
	nbchecked=0;
	for( var i=0; i< theForm.elements.length; i++) {
		if (theForm.elements[i].type == "checkbox" && theForm.elements[i].name == theFieldName) {
			if (theForm.elements[i].checked) {
				nbchecked=nbchecked+1;
			}
		} else {
			// [HJ 03/01/03]
			if (theForm.elements[i].type == "radio" && theForm.elements[i].name == theFieldName) {
				if (theForm.elements[i].checked) {
					nbchecked=nbchecked+1;
				}
			}
		}
	}
	return nbchecked;
}


function CheckAll(theForm,theFieldName,theMode) {
// Coche, decoche ou inverse une serie de cases a cocher
// 0 : uncheck ; 1 : check ; 2 : swap
	for( var i=0; i< theForm.elements.length; i++) {
		if (theForm.elements[i].type == "checkbox" && theForm.elements[i].name == theFieldName) {
			if (theMode == 0) {
				theForm.elements[i].checked=false;
			} else {
				if (theMode == 1) {
					theForm.elements[i].checked=true;
				} else {
					if (theForm.elements[i].checked ) {
						theForm.elements[i].checked=false;
					} else {
						theForm.elements[i].checked=true;
					}
				}
			}
		}
	}
	return false;
}


function getRadioValue(radioObj) {
// HJ 061012
// Renvoie la valeur du bouton radio coche
	for (var i=0; i<radioObj.length;i++) {
		if (radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
}


function GetNomChamp(theFieldName) {
// Renvoie le texte apres le "_" ou nom du tableau 'NomChamp'
	theName="";
	if (typeof NomChamp != 'undefined') {
		theName=NomChamp[theFieldName];
	}
	if (typeof theName=="undefined" || theName=="") {
		// Test si ], sinon, lastIndexOf('_'
		theName=theFieldName.substr(theFieldName.lastIndexOf('_',theFieldName.length)+1,theFieldName.length);
	}
	theName=unescape(theName); // HJ 051222
	return theName;
}


//-----------------------------------------------------------------------------
// Menus popups
//-----------------------------------------------------------------------------

function UpdatePopup(thePopName,theValue) {
//Positionner un menu popup selon valeur d'un champ
	//Test si theValue existe dans thePopName
	Found=false;
	i=0;
	while ((i < thePopName.length) && !Found) {
		if (thePopName.options[i].value==theValue) {
			Found=true;
			theIndex=i;
		}
		i++;
	}
	
	if (Found) {
		// Oui : positionner index
		thePopName.selectedIndex=theIndex;
	} else {
		// Non : creer ligne et positionner
		thePopName.length++;
		thePopName.options[thePopName.length-1].value=theValue;
		thePopName.options[thePopName.length-1].text=theValue;
		thePopName.selectedIndex=thePopName.length-1;
	}
}


// ---------- Menus popups linked [HJ 14/04/04]
// -- Objet PopUps (Collection de tous les menus popups)
function PopUps(ID) {
  this.ID = ID;
  this.popupLines = new Array(); // Collection
  this.addLine     = PopUpsAddLine; // Methode
  this.index = PopUps.length; // Ajout liste
  PopUps[this.index] = this;
}

// -- Methodes de PopUps
function PopUpsAddLine(theLine) {
	this.popupLines[this.popupLines.length] = theLine;
}

// -- Objet PopUpLine (= une ligne du menu popup)
function PopUpLine(Label,IDVal,IDLink) {
  this.Label = Label;
  this.IDVal = IDVal;
  this.IDLink = IDLink;
}

// -- Initialisation et traitement
function BuildMainPopUp(theLinkedID) {
	var i,np;
	
	// [AF] Generaliser si plusieurs listes liees : collection de popup01, 02... ?
	var Found=false;
	theIndex=-1;
	if (theLinkedID>0) {
	// Chercher ID parent
		i=0;
		while ((i < popup02.popupLines.length) && !Found) {
			if (popup02.popupLines[i].IDVal==theLinkedID) {
				Found=true;
				theIndex=popup02.popupLines[i].IDLink;
			}
			i++;
		}
	}
	
	if (Found) {
		for (np = 0; np < popupsL1.length; np++) {
			thePopUp=eval("document." + formName + ".elements['" + popupsL1[np] + "']");
		for (i = 0; i < popup01.popupLines.length; i++) {
			thePopUp.length=i+1;
			if (returnType==1) {
				thePopUp.options[i].value=popup01.popupLines[i].Label;
			} else {
				thePopUp.options[i].value=popup01.popupLines[i].IDVal;
			}
			thePopUp.options[i].text=popup01.popupLines[i].Label;
			if (popup01.popupLines[i].IDVal == theIndex) {
				thePopUp.selectedIndex=i;
			}	
		}
		//thePopUp.selectedIndex=0;
		BuildLinkedPopUp(thePopUp,theLinkedID);
	}
	} else { // Effacer sous-menu
		thePopUp=eval("document." + formName + ".elements['" + popupsL2[0] + "']"); // [AF]
		thePopUp.length=0;
	}
}

function BuildLinkedPopUp(thePopUp,theLinkedID) {
	var i, np;
	
	for (np = 0; np < popupsL1.length; np++) {
		if (popupsL1[np]==thePopUp.name) {
			theLinkedPopUp=eval("document." + formName + ".elements['" + popupsL2[np] + "']"); // [HJ 22/11/05]
		}
	}	
	theLen=0;
	theLinkedPopUp.length=theLen;
	for (i = 0; i < popup02.popupLines.length; i++) {
		if (returnType==1) {
			for (j = 0; j < popup01.popupLines.length; j++) {
				if (thePopUp.options[thePopUp.selectedIndex].value == popup01.popupLines[j].Label) {
					theID=popup01.popupLines[j].IDVal;
				}
			}
		} else {
			theID=thePopUp.options[thePopUp.selectedIndex].value;
		}
		
		if (theID == popup02.popupLines[i].IDLink) {
			theLen=theLen+1;
			theLinkedPopUp.length=theLen;
			if (returnType==1) {
				theLinkedPopUp.options[theLen-1].text=popup02.popupLines[i].Label;
			} else {
				theLinkedPopUp.options[theLen-1].value=popup02.popupLines[i].IDVal;
			}
			theLinkedPopUp.options[theLen-1].text=popup02.popupLines[i].Label;
			if (popup02.popupLines[i].IDVal == theLinkedID ) {
				theLinkedPopUp.selectedIndex=theLen-1;
			}
		}
	}
}


//-----------------------------------------------------------------------------
// Validation OUI/NON
//-----------------------------------------------------------------------------
function validerSuppr(nbElts) {
	theMsg="";
	if (nbElts > 1) {
		theMsg=checkdata_TT["OK_DEL"]+ nbElts +checkdata_TT["ITEMS"];
	} else {
		if (nbElts != 0) {
			theMsg=checkdata_TT["OK_DEL1"];
		} else {
			alert(checkdata_TT["NO_SEL"]);
			theMsg="";
		}
	}
	if (theMsg != "") {
		if (confirm(theMsg)) {
			return true;
		} else {
			return false;
		}
	}
	return false;
}

function validerCopy(nbElts) { // [HJ 08/07/02]
	theMsg="";
	if (nbElts > 1) {
		theMsg=checkdata_TT["OK_CPY"]+ nbElts +checkdata_TT["ITEMS"];
	} else {
		if (nbElts != 0) {
			theMsg=checkdata_TT["OK_CPY1"];
		} else {
			alert(checkdata_TT["NO_SEL"]);
			theMsg="";
		}
	}
	if (theMsg != "") {
		if (confirm(theMsg)) {
			return true;
		} else {
			return false;
		}
	}
	return false;
}

function validerSelect() { //EB011029 HJ011129
	valtrouve=CountCheckedBox(FormName,"selElts");	

	if (valtrouve==0) {
		alert(checkdata_TT["SEL_LINE"]);
		return false;	
	} else {
		return true;	
	}
}

function validerNewFold(fname) { // [HJ 23/06/06]
	if (fname != "") {
		theMsg=checkdata_TT["NEW_FOLD"];
	} else {
		alert(checkdata_TT["NO_NAME"]);
		theMsg="";
	}
	if (theMsg != "") {
		if (confirm(theMsg)) {
			return true;
		} else {
			return false;
		}
	}
	return false;
}


//-----------------------------------------------------------------------------
// Detection modifications
//-----------------------------------------------------------------------------
var CRCIn = ""; // [HJ 030116] Pour detection modifications
var CRCOut = ""; // + onload="CRCIn=CalcCRC(document.FormName);" dans body

function CheckModified(theForm) {
	CRCOut=CalcCRC(theForm);
	if (CRCIn != CRCOut) {
		//alert("ModifiŽ !");
		return WarnNotSaved();
	} else {
		//alert("Pas modifiŽ !");
		return true;
	}
}

function WarnNotSaved() { // HJ 030103
	if (confirm(checkdata_TT["WARN_SAVE"])) {
		return true;
	} else {
		return false;
	}
}

function crcTable() {
    this.table = new Array(256);
   
    var c=0;
    var i=0, k=0;
    
    for(i=0;i<256;i++) {
	c=i;
	for(k=0; k < 8; k++) {
	    if (c & 1) { c = 0xEDB88320 ^ (c >> 1); }
	    else
		c = c >> 1;
	}
    this.table[i] = c;
    }
}

function nextCRC(preCrc,inStr) {
    var sL = inStr.length;
    var c = preCrc ^ 0xFFFFFFFF;
    var n = 0;
    var crcT = new crcTable();
    for(n=0; n < sL; n++) { c = crcT.table[(c ^ inStr.charCodeAt(n)) & 0xff] ^ (c >> 8); }
    return c ^ 0xffffffff;
}

function countCRC(str) {
    return nextCRC(0,str);
}

function crc32(str) {
    var c = countCRC(str);
    var cB = new dWordInBytes(c);    
    return cB.toString;
}

function dWordInBytes(dW) {
  this.rB = new Array(4);
  this.rB[0] = dW & 0x000000FF;
  this.rB[1] = (dW & 0x0000FF00) >>> 8;
  this.rB[2] = (dW & 0x00FF0000) >>> 16;
  this.rB[3] = (dW & 0xFF000000) >>> 24;
  this.toString = bytes2String(this.rB); // returns hex representation of the object
}

function bytes2String(aB) {
  var tA = new Array(4);
  var rS = new String;

  for(i=3;i>=0;i--) {
    if (aB[i] == 0)
       tA[i] = "00";
    else if (aB[i] < 16)
           tA[i] = "0" + aB[i].toString(16);
         else
           tA[i] = aB[i].toString(16);
    rS = rS + tA[i];
  }
  return rS;
}

function CalcCRC(theForm) {
	var theStr="";
	var theCRC="";
	for (var i=0; i< theForm.elements.length; i++) {
		if (theForm.elements[i].type == "checkbox" || theForm.elements[i].type == "radio") {
			if (theForm.elements[i].checked) {
				theStr+=theForm.elements[i].value;
			}
		} else {
			theStr+=theForm.elements[i].value;
		}
	}
	theCRC=crc32(theStr);
	return theCRC;
}

