// JavaScript Document

//Vérifie la validité d'une adresse mail par expression régulière :
// Version V2
function validateEmail(email)
      {
      // a very simple email validation checking.
      // you can add more complex email checking if it helps
          var splitted = email.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;
      }

//---------------------------------------------------
// Description: Appelle la page passée en paramètre
// avec la querystring spécifiée
// oCalling:		 L'objet qui a déclenché la fonction
// pageUrl:		 L'url de la page à lancer
// additionalParams: Les paramètres supplémentaires à passer à l'url
function CallPage(oCalling,pageUrl,additionalParams){
		if(oCalling && oCalling.value!='')
			window.location.href=pageUrl+'?'+oCalling.name+'='+oCalling.value+additionalParams;
}
		 
//Surligne en rouge le texte des balise <label></label> en cas d'erreur de saisie de formulaire
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;
      		}
      }
//Réinitialise la classe par défaut de toutes les balise <label></label> du formulaire   
function InitLabelClass(){
	if(document.getElementsByTagName){
  	cLabel=document.getElementsByTagName('label');
  	for(i=0;i<cLabel.length;i++){
			cLabel[i].className="inherit";													 
  	}
  }
}

function BuildErrorMessage(oInput, sMessage, sControl){
		var m_sError='';
		var bMessageDone=false;

		if (!oInput) return '';
		
		if(!oInput.type){
			//Il s'agit d'un tableau d'inputs
  		for(i=0; i<oInput.length;i++){
  			if(!ControlValueOk(oInput[i].value, sControl)){
  				if (!bMessageDone){
  					 m_sError=sMessage;
  					 bMessageDone=true;
  				}// end - if (!bMessageDone)
  				cLabels[cLabels.length]=GetLabelFor(oInput[i].id);
  			}// end - if(oInput[i].value=="")
  		}// end - for(i=0; i<oInput.length;i++)
			
		}else{
			//il s'agit d'un input isolé
			if(!ControlValueOk(oInput.value, sControl)){
    		m_sError=sMessage;
    		cLabels[cLabels.length]=GetLabelFor(oInput.id);
    	}
		}// end - if(oInput.length)
		
		
		return m_sError;
}

function ControlValueOk(sValue, sControl){
  
	switch (sControl){
		case 'isInt':
    		 var re = /^[0-9]+$/
				 return sValue.match(re) && parseInt(sValue)>0;
				 //return parseInt(sValue);
				 break;
		case 'telFR':
				 var re = /^(0[12345689])[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}$/	// Accepte un numero de téléphone de type 'national' y compris numéros en '08'.
				 return sValue.match(re);
				 break;
		case 'tel':
				 var re = /^[0-9\(\)\+\.\/\-\s]+$/	// Accepte un numero de téléphone de type 'international'. Ex : (+33) 1 34 12 52 30
				 return sValue.match(re);
				 break;
		case 'cpFR':
				 var re = /^([A-Z]+[A-Z]?\-)?[0-9]{1,2} ?[0-9]{3}$/	// Accepte une chaine de type 'code postal'. Ex : F-33370 ou 33 370 ou 33370 ou F-1 370				 
				 return sValue.match(re);
				 break;
		case 'cp':
				 var re = /^([a-zA-Z0-9-\/ ().]{4,8})$/	// Accepte une chaine de type 'code postal' autre que la France. Ex : NH- 5JT				 
				 return sValue.match(re);
				 break;
		case 'email':
				 return validateEmailv2(sValue)
				 break;
		case 'jjmmaaaa':
				 return !(sValue=='jj/mm/aaaa')
		case 'date':
				 return  estUneDate(sValue)
		default :
				 return sValue!="";
				 break;
	}// end - switch
	
}  
     function validateEmailv2(email)
      {
      // a very simple email validation checking.
      // you can add more complex email checking if it helps
          var splitted = email.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;
      }


			
//Vérifie la validité d'une adresse mail par expression régulière : 
//N'importe quel caractère et/ou chiffre + "@" + au moins 2 caractères et/ou chiffres + "." + 2 ou 4 caractères
//Paramètre "champ" >>> chemin du champ contenant l'email (Exemple d'appel: EstUnMail(document.form.email))
function estUnEmail(champ)
	{
    var strValeur;
    strValeur = champ.value;	
    var verif     = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9_.-]{2,}[.][a-zA-Z]{2,4}$/
		if (verif.exec(strValeur) == null)
		{
		return false;
		}
		if (strValeur.length > 50)
		{
		alert("Votre e-mail ne doit pas depasser 50 caracteres");
		champ.focus();
		champ.select();
		return false;
		}
return true;
}
//Affiche une alerte pour un champ obligatoire d'un formulaire
//Paramètre "champ"= nom du champ à contrôler
function erreur(champ) {
      alert('Le champ ' + champ + ' est obligatoire.\nVeuillez le compléter.');
      return false;
}

// Verifie si le champ est un entier
function estUnEntier(champ, nom_champ)
{
    var j;
    var strVal;
    var bErr;
    
    bErr = 0;
    strVal = champ.value;

    for (j = 0; j < strVal.length; j++)
    {
        if (strVal.charAt(j) < "0" || strVal.charAt(j) > "9")
            bErr = 1;
    }

    if (bErr == 1)
    {
        alert("Veuillez saisir un numérique dans le champ \"" + nom_champ + "\"");
        champ.focus();
        champ.select();
        return false;
    }
    
    return true;
}

// Verifie si le champ est un reel
function estUnReel(champ, nom_champ)
{
    var dblChamp;
    var i;
    var ch;
    var strChamp;

    strChamp = champ.value;
    for (i = 0; i < strChamp.length; i++) {
        ch = strChamp.charAt(i);
        if ((ch < "0" || "9" < ch) && ch != '.' && ch != ',') {
            alert(nom_champ + " contient des caracteres non numeriques");
            champ.focus();
            return false;
        }
        if (ch == '.') {
            alert(nom_champ + " contient un '.' au lieu d'une ','");
            champ.focus();
            return false;
        }
 	}
}

function AnneeBisextile(intAnnee)
{
    if (intAnnee % 100 == 0) {
        if (intAnnee % 400 == 0)
            return true;
    } else
    if (intAnnee % 4 == 0)
        return true;
    return false;
}

// Verifie si le champ saisi est une date valide
//
function estUneDate(champ, nom_champ)
{
	var bErr;
	var strValeur;
	var strJour, strMois, strAnnee;
    var intJour, intMois, intAnnee;
	var strSeparateur1, strSeparateur2;

	bErr = 0;
	strValeur = champ.value;
    
    // Verification de la longueur
	if (strValeur.length != 10)
	    bErr = 1;

    // Separation des chaines j/m/a
	strJour = strValeur.substring(0, 2);        // jour
	strSeparateur1 = strValeur.substring(2, 3); // '/'
	strMois = strValeur.substring(3, 5);        // mois
	strSeparateur2 = strValeur.substring(5, 6); // '/'
	strAnnee = strValeur.substring(6);          // année

    // Conversion des chaines en entier
    intJour = parseInt(strJour, 10);
    if (isNaN(intJour))
        bErr = 1;
    intMois = parseInt(strMois, 10);
    if (isNaN(intMois))
        bErr = 1;
    intAnnee = parseInt(strAnnee, 10);
    if (isNaN(intAnnee))
        bErr = 1;
	if (intAnnee < 1900 || intAnnee > 2099)
        bErr = 1;

	// Erreurs de base
	//

        if (intJour < 1 || intJour > 31)
            bErr = 1;
        if (strSeparateur1 != '/')
            bErr = 1;
        if (intMois < 1 || intMois > 12)
            bErr = 1;
        if (strSeparateur2 != '/')
            bErr = 1;


	// Erreurs avancées

	// Mois comportant 30 jours
	if (intMois == 4 || intMois == 6 || intMois == 9 || intMois == 11)
	{
		if (intJour == 31)
		    bErr = 1;
	}

	// Février, année bisextile
	if (intMois == 2)
	{
        if (intJour > 29)
		    bErr = 1;
        if ((intJour == 29) && (!AnneeBisextile(intAnnee)))
            bErr = 1;
	}

    if (bErr == 1)
    {
        alert("Date non valide (champ \"" + nom_champ + "\")");
        champ.focus();
        champ.select();
        return false;
    }

    return true;
}

//***************************************************************************************************
//*****Compteur de charactères qui décompte les charactères restant dans un champ de formulaire
//*****Le départ est fixé à 250 charactères. Chaque charactères tapé le compteur baisse .. 249, 248 ,etc ... jusqu'à 0
//*****Appel de la procédure avec displaylimit(nom du champ, id du champ, nombre de caractère)
//****************************************************************************************************
var ns6=document.getElementById&&!document.all

function restrictinput(maxlength,e,placeholder){
if (window.event&&event.srcElement.value.length>=maxlength)
return false
else if (e.target&&e.target==eval(placeholder)&&e.target.value.length>=maxlength){
var pressedkey=/[a-zA-Z0-9\.\,\/]/ 
if (pressedkey.test(String.fromCharCode(e.which)))
e.stopPropagation()
}
}

function countlimit(maxlength,e,placeholder){
var theform=eval(placeholder)
var lengthleft=maxlength-theform.value.length
var placeholderobj=document.all? document.all[placeholder] : document.getElementById(placeholder)
if (window.event||e.target&&e.target==eval(placeholder)){
if (lengthleft<0)
theform.value=theform.value.substring(0,maxlength)
placeholderobj.innerHTML=lengthleft
}
}
//trouvé sur: www.portugal-tchat.com//

function displaylimit(thename, theid, thelimit){
var theform=theid!=""? document.getElementById(theid) : thename
var limit_text='<span id="'+theform.toString()+'">'+thelimit+'</span> caractères Max.'
if (document.all||ns6)
document.write(limit_text)
if (document.all){
eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
}
else if (ns6){
document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true); 
document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true); 
}
}

//***************************************************************************************************
//*****Suprimer les carriage return d'un textarea
//*****Param : textarea : objet textarea
//*****Param : repalceWith = valeur de remplacement du carriage return
//*****Return : chaine de caractère avec les retours chariot remplacé
//****************************************************************************************************

function escapeVal(sValue,replaceWith){
//textarea is reference to that object, replaceWith is string that will replace the encoded return
strTextarea = escape(sValue) //encode textarea string's carriage returns
	for(i=0; i<strTextarea.length; i++){
		if(strTextarea.indexOf("%20") > -1){
		//Traitement des espace
		strTextarea=strTextarea.replace("%20",replaceWith)
		}
		//loop through string, replacing carriage return encoding with HTML break tag
		if(strTextarea.indexOf("%0D%0A") > -1){
		//Windows encodes returns as \r\n hex
		strTextarea=strTextarea.replace("%0D%0A",replaceWith)
		}
		else if(strTextarea.indexOf("%0A") > -1){
		//Unix encodes returns as \n hex
		strTextarea=strTextarea.replace("%0A",replaceWith)
		}
		else if(strTextarea.indexOf("%0D") > -1){
		//Macintosh encodes returns as \r hex
		strTextarea=strTextarea.replace("%0D",replaceWith)
		}
	
	}
strTextarea=unescape(strTextarea) //unescape all other encoded characters
return strTextarea
}
