/*
  -------------------------------------------------------------------------
	Based on Web-MA JavaScript Form Validator Version 1.0.4
	Copyright 2006 www.web-ma.com. All rights reserved.
	You can freely use this script in your Web pages, providing these credits
	lines.
	You may please add a link to www.web-ma.com as reconoissance.
  	You may not reprint or redistribute this code without permission of the
  	Author.
  -------------------------------------------------------------------------

	Version history:

 	* 1.0.0 - 04/02/2006 - Initial release;
	* 1.0.1 - 04/04/2006 - Minor bug fix;
	* 1.0.2 - 04/08/2006 - Added new small function for validate input
				     fields;
	* 1.0.3 - 04/19/2006 - Added support for CSS ClassName property;
	* 1.0.4 - 05/05/2006 - Minor bug fix: while re-submitting form, if a
				     previous error has been generated and then
				     fixed, error message wasn't clear.
  -------------------------------------------------------------------------
	
	
*/

var validationResult;
var validationMessage='';
var validationMessageGlobal='';
var validationDivErreur='';
var validationAffichageGlobal='';
var currentSpan;

function Validator(frmName, classError)
{

  //Initialisation des propriétés
	this.MessageGlobal='';  //Message global du type : Les erreurs suivantes on été détectées.
	this.AffichageGlobal=2; //valeurs possibles : 0 - Auncun affichage global, 1 - Affichage d'un DIV, 2 - Affichage d'une alerte
	this.IncludeValidatorMessages=true;
	this.DivErreur='';		//Identifiant du DIV dans lequel afficher le message global
	this.AffichageSpan=false; //Active ou désactive l'affichage de span à côté des champs de saisie pour écrire le message d'erreur
	this.LabelAuto=true;			//Active ou désactive l'affichage des labels attachés aux champs en rouge
	this.ErrorClass=classError;				//Classe à utiliser pour les span et/ou les labels

	//this.frmObj = document.getElementById(frmName);
	this.frmObj=document.forms[frmName];

	if(!this.frmObj){
	  alert("Formulaire " + frmName + " introuvable." );
		return;
	}

	//Initialisation des affichages
	if (this.AffichageGlobal==1){
		 if(this.DivErreur=="" || this.DivErreur==null){
  		 alert('Aucun DIV n\'a été spécifié');
			 this.AffichageGlobal=0;
		 }else{
		   _DisplayErrorDiv(this.DivErreur, 'none');
		 }
	}
	
	if(this.LabelAuto){
  	this.cLabels=new Array();
  	
	}
	
	
	
	if(this.frmObj.onsubmit)
	{
	 this.frmObj.old_onsubmit = this.frmObj.onsubmit;
	 this.frmObj.onsubmit = null;
	}
	else
	{
	 this.frmObj.old_onsubmit = null;
	}

	this.frmObj.onsubmit = _SubmitEventHandler;
	this.AddValidator = AddValidator;
	this.ExtraValidatorFunction = _ExtraValidatorFunction;
	this.clearValidators = _clearValidators;
}

function _DisplayErrorDiv(ErrorDiv, sAttribute){

  if(ErrorDiv.type && (ErrorDiv.type=="GroupePopup" || ErrorDiv.type=="GroupeFormPopup")){
  	if(sAttribute=='none')
  		ErrorDiv.Hide();
		else
  		ErrorDiv.Show();
	}else if(document.getElementById(ErrorDiv)){
  	document.getElementById(ErrorDiv).style.display=sAttribute;
	}
}

function _SetDivErreurText(ErrorDiv, sText){
  if(ErrorDiv.type && (ErrorDiv.type=="GroupePopup" || ErrorDiv.type=="GroupeFormPopup")){
  	ErrorDiv.SetText(sText);
	}else if(document.getElementById(ErrorDiv)){
  	document.getElementById(ErrorDiv).innerHTML=sText;
	}
}

function _InitLabelClass(){
	if(document.getElementsByTagName){
  	cLabel=document.getElementsByTagName('label');
  	for(i=0;i<cLabel.length;i++){
			cLabel[i].className="inherit";													 
  	}
  }
}

function _ExtraValidatorFunction(functionname)
{
  this.frmObj.ExtraValidatorFunction = functionname;
}

function _clearValidators()
{
	for(var i=0;i < this.frmObj.elements.length;i++)
	{
		this[this.elements[i].name].ValidatorCollection = null;
	}
}

function _SubmitEventHandler()
{
  
	validationMessage='';
	_InitLabelClass();
	for(var i = 0; i < this.elements.length; i++)
	{

  	
  	if(this[this.elements[i].name] && this[this.elements[i].name].ValidatorCollection)
  	  		this[this.elements[i].name].ValidatorCollection.validate();
  	}
  
  	if(validationResult && this.ExtraValidatorFunction)
  	{
       	validationResult = eval(this.ExtraValidatorFunction + "()");
  	}
  
  	if(!validationResult){
  	 if(validationAffichageGlobal==1){
		    _SetDivErreurText(validationDivErreur, validationMessageGlobal+validationMessage);
  			_DisplayErrorDiv(validationDivErreur, 'block');
  		}else if(validationAffichageGlobal==2){
  		  alert(ReplaceVals(validationMessageGlobal,"<br>","\n")+ReplaceVals(validationMessage,"<br>","\n"));
  		} 
	}
	
	return validationResult;
}

function ReplaceVals(textValue, regex, replacement) {
  var re = new RegExp(regex, "g");
  return textValue.replace(re, replacement);
	
}

function AddValidator(sitem, validatorFunction, validateParam, errorMsg)
{

  validationDivErreur=this.DivErreur;
	validationAffichageGlobal=this.AffichageGlobal;
	if (validationMessageGlobal=='') validationMessageGlobal=this.MessageGlobal+"<br>";
  	if(!this.frmObj)
	{
	     alert("The form object is not set properly");
	     return;
	}

	var frmField = this.frmObj[sitem];

 	if(!frmField)
	{
	     alert("Could not get the " + sitem + " object.");
	     return;
	}

	if(!frmField.ValidatorCollection)
	{
		frmField.ValidatorCollection = new ValidatorCollection(frmField, this.MessageGlobal, this.AffichageGlobal, this.IncludeValidatorMessages, this.DivErreur, this.AffichageSpan, this.LabelAuto, this.ErrorClass);
	}

	frmField.ValidatorCollection.add(validatorFunction, validateParam, errorMsg);
	
}

function ValidatorCollection(inputitem, MessageGlobal, AffichageGlobal, IncludeValidatorMessages, DivErreur, AffichageSpan, LabelAuto, ErrorClass)
{

	this.MessageGlobal=MessageGlobal;
	this.AffichageGlobal=AffichageGlobal;
	this.IncludeValidatorMessages=IncludeValidatorMessages;
	this.DivErreur=DivErreur;
	this.AffichageSpan=AffichageSpan;
	this.LabelAuto=LabelAuto;
	this.ErrorClass=ErrorClass;
	
  this.ValidArray = new Array();
	this.add = _AddValidator;
	this.validate = Validate;
	this.frmField = inputitem;

}

function _AddValidator(validatorFunction, validateParam, errorMsg)
{
	this.ValidArray[this.ValidArray.length] =
		new AddValidationControl(this.frmField, validatorFunction, validateParam, errorMsg, this.AffichageSpan);
}

function AddValidationControl(sitem, validatorFunction, validateParam, errorMsg, AffichageSpan)
{

	this.AffichageSpan=AffichageSpan;

	this.errorMsg = errorMsg;
	this.sitem = sitem;
	this.validator = validatorFunction;
	this.validateParam = validateParam;
	this.validate = _Validate;

}

function Validate()
{
//ValidatorCollection Validate
	// this routine validate all controls in the form
	var someFails = false;

	for(var i = 0; i < this.ValidArray.length; i++)
	{
		if(!someFails)
		{
	           if (this.AffichageSpan && this.ValidArray[i].errorMsg != null && this.ValidArray[i].errorMsg != "")
	                 currentSpan = _CreateSpanError(this.ValidArray[i], this.ErrorClass);
						 
						 
						 		
	           if(!this.ValidArray[i].validate())
	           {
  						 if(this.LabelAuto){
							   if(_IsCollection(this.frmField) && this.frmField[0]){
   							   cLabel=_GetLabelFor(this.frmField[0].id)
  								 if(!cLabel) cLabel=_GetLabelFor(this.frmField[0].name)
								 }else{
  							   cLabel=_GetLabelFor(this.frmField.id)
  								 if(!cLabel) cLabel=_GetLabelFor(this.frmField.name)
								 }
								 if(cLabel){
								  cLabel.className=this.ErrorClass;
								}
							 }
							 
							 if(this.AffichageGlobal>0 && this.IncludeValidatorMessages && this.ValidArray[i].errorMsg!=null && this.ValidArray[i].errorMsg!=""){
  							 if(_IsCollection(this.frmField)){
								  validationMessage=validationMessage.replace("<br>"+this.ValidArray[i].errorMsg,'');
								  validationMessage+="<br>"+this.ValidArray[i].errorMsg;
								 }else{
    							 validationMessage+="<br>"+this.ValidArray[i].errorMsg;
								 }
							 }
							 someFails = true;
	           }
	      }
	}

	if (someFails)
	{
	  
		validationResult = false;
		return false;
	}
	else
	{
		if(currentSpan) currentSpan.style.visibility = "hidden";
		return true;
	}
}
function _GetLabelFor(sInputId){
		if(document.getElementsByTagName){
			cLabel=document.getElementsByTagName('label');
			
			for(iLabel=0;iLabel<cLabel.length;iLabel++){
				if(cLabel[iLabel].htmlFor==sInputId){return cLabel[iLabel];}
			}
			return null;
		}
}

function _Validate()
{
//AddValidationControl Validate

	if(!this.validator(this.sitem, this.validateParam))
	{
	  if(this.AffichageSpan){
				currentSpan.innerHTML = this.errorMsg;
				currentSpan.style.visibility = "visible";
		}

		return false;
	}

	return true;
}

function _CreateSpanError(sitem, className)
{
	var errorSpan = eval("document.getElementById('" + sitem.sitem.id + "Val')");

	if (errorSpan == null)
	{
		var errorSpan = document.createElement("span");
		errorSpan.id = sitem.sitem.id + 'Val';

		var curEl = document.getElementById(sitem.sitem.id);
		var parent = curEl.parentNode;

		//if (sitem.errorDisplayMode == 'right')
			parent.insertBefore(errorSpan, curEl.nextSibling);
		//else
		//	parent.insertBefore(errorSpan, curEl);

		// Manage the style;
		//var styles = sitem.style.split(";");
		//var styleEl = "";
		//var i = 0;
		//while (i < styles.length - 1)
		//{
		//	styleEl = styles[i].split(":");
		//
		//	if (styleEl[0] == "className")
		//	{
		//		eval("errorSpan." + styleEl[0] + "= '" + styleEl[1] + "';");
		//		break;
		//	}
		//
		//	else
		//		eval("errorSpan.style." + styleEl[0] + "= '" + styleEl[1] + "';");
		//	i += 1;
		//}
		errorSpan.className=className;
	}

	return errorSpan;
}


function _IsCollection(sitem){
  return (!sitem.type && sitem.length>0);
}

//***********************************************************************//
// Validators: you can modify the name as well as the functionality of   //
// single validators according to your exigencies.								 //
// Remember to change the name of the called function into html page.	 //
//***********************************************************************//
function Requis(sitem, param)
{

  if(sitem.type=='checkbox' || sitem.type=='radio'){
		return EstCoche(sitem, param);
	}else if(_IsCollection(sitem)){
	  if(param==null || param==''){param=1;}
		iCoches=0;
		for(iRequis=0;iRequis<sitem.length;iRequis++){
		 if(sitem[iRequis].checked) iCoches++;
		}
		if(iCoches<param) return false; 
	}else{
  	if(param==null || param==''){
  		return !(sitem.value.length == 0);
  	}else{
    	if(sitem.value.length <= param)
    	{
    		return false;
    	}
  	}
	}
	return true;
	
}

function Compare(sitem, param)
{
	// Supply an input field name in the param value

	var param = eval("document.getElementById(param)");
  if(!param){
  	alert("ERREUR: L\'élément " + param + " n\'a pas été trouvé.");
		return false;
	}
	if(sitem.value != param.value)
	{
		return false;
	}

	return true;
}

function LongueurMax(sitem, param)
{
	// Supply the max length that control should not override

	if(sitem.value.length > param)
	{
		return false;
	}

	return true;
}

function LongueurMin(sitem, param)
{
	// Supply the max length that control should not override

	if(sitem.value.length < param)
	{
		return false;
	}

	return true;
}

function EstCoche(sitem, param)
{
	// Param isn't used;

	if(sitem.checked == true)
	{
		return true;
	}

	return false;
}

function EstEntier(sitem, param){
	// Supply a valid regular expression param
	if (param == null)
		param = "[^0-9]";

	if (sitem.value.length > 0 && (!parseInt(sitem.value) || sitem.value.search(param) >= 0))
		return false;
	return true;

}


function EstNumerique(sitem, param)
{
	// Supply a valid regular expression param
	if (param == null)
		param = "[^0-9\.,]";

	if (sitem.value.length > 0 && sitem.value.search(param) >= 0)
		return false;

	return true;
}

function EstAlpha(sitem, param)
{
	// Supply a valid regular expression param
	if (param == null)
		param = "[^A-Za-z]";

	if (sitem.value.length > 0 && sitem.value.search(param) >= 0)
		return false;

	return true;
}

function EstAlphaNumerique(sitem, param)
{
	// Supply a valid regular expression param

	if (param == null)
		param = "[^A-Za-z0-9]";

	if (sitem.value.length > 0 && sitem.value.search(param) >= 0)
		return false;

	return true;
}

function UnIndexSelectionne(sitem, param)
{
	// Param isn't used;

	if (sitem.selectedIndex == -1)
		return false;

	return true;
}

function EstPlusPetit(sitem, param){
  if(isNaN(sitem.value)){
    alert(sitem.name+" n'est pas un nombre");
    return false;
  }
  if(eval(sitem.value) >=  eval(param)) {
    return false;
  }
  return true;
}

function EstPlusGrand(sitem, param){
  if(isNaN(sitem.value)){
    alert(sitem.name+" n'est pas un nombre");
    return false;
  }
  if(eval(sitem.value) <=  eval(param)) {
    return false;
  }
  return true;
}

function EstDate(sitem, param){
  // regex for date in yyyy/mm/dd format
  var thisRegEx = "^([0-9]{1,2})-([0-9]{1,2})-([0-9]{4})$";

  if (sitem.value.length>0){
    if(!sitem.value.match(thisRegEx)){
      return false;
    }//if
  }
}

function EstEmail(sitem, param)
{
    var splitted = sitem.value.match("^(.+)@(.+)$");
    if(splitted == null) return false;
    if(splitted[1] != null )
    {
      var regexp_user=/^\"?[\w-_\.]*\"?$/;
      if(splitted[1].match(regexp_user) == null) return false;
    }
    if(splitted[2] != null)
    {
      var regexp_domain=/^[\w-\.]*\.[A-Za-z]{2,4}$/;
      if(splitted[2].match(regexp_domain) == null)
      {
	    var regexp_ip =/^\[\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\]$/;
	    if(splitted[2].match(regexp_ip) == null) return false;
      }// if
      return true;
    }
    return false;
	
}

function ExclureValeur(sitem, param)
{
	if (param == null)
		param = 0;

	if (sitem.selectedIndex == param)
		return false;

	return true;
}

function ExpressionReguliere(sitem, param){
  if(!sitem.value.match(param)){
    return false;
  }
	return true;
}
/*
	Copyright 2006 www.web-ma.com. All rights reserved.
*/