 var lim_champs_obligatoires=100;//nombre max de champs obligatoire
 var pasPlusDe=5;
 var lang="fr";
  
 function submit_form(formulaire,lng) 
 {
    var champs = lireChampsObligatoires(formulaire);
    lang=lng;
	if (champs.length > 0) {
        var ok = true;
        for (var i=0;i<champs.length;i++) ok &= champs[i].controler();
        if (ok) return true; 
        else {
            editerErreurs(champs,"");
            return false;
        }
    }
    else {
        alert("Aucun champ n'a été indiqué pour le contrôle de formulaire"); 
        return false;
    }
}

function click_form(formulaire) 
{
    var champs = lireChampsObligatoires(formulaire);
    var ok = true;
    if (champs.length > 0) {
        for (var i=0;i<champs.length;i++) ok &= champs[i].controler();
        if (ok) formulaire.submit();
        else editerErreurs(champs);
    }
    else alert("Aucun champ n'a été indiqué pour le contrôle de formulaire");
} 

// Va chercher les champs obligatoires
function lireChampsObligatoires(formulaire) 
{
    var champs = new Array();
	var champInput = formulaire.getElementsByTagName("input");
	var champTextarea = formulaire.getElementsByTagName("textarea");
	var dataTocheck = [ champInput,champTextarea ];
	
	for ( var j = 0 ; j < 2 ; j++ )
	{
		champ = dataTocheck[j];		
		for ( var i = 0 ; i < champ.length ; i++ )
		{
			NextHiddenField = champ[i];
			do
			{
				NextHiddenField = NextHiddenField.nextSibling;
				if ( NextHiddenField != null )
					if ( NextHiddenField.attributes != null ) break;
			}  while ( NextHiddenField != null )

			var fieldType = champ[i].tagName.toUpperCase();			
			if ( NextHiddenField != null && (
				fieldType == "TEXTAREA" || ( fieldType == "INPUT" &&
					champ[i].attributes["type"] != "hidden" &&
					champ[i].attributes["type"].value != "image" )))
			{
				name = champ[i].attributes["name"].value;
				strToParse = NextHiddenField.attributes["value"].value;
				arrayParsed = strToParse.split(";");
				lib = ( arrayParsed[0] ) ? arrayParsed[0] : null;
				ctl = ( arrayParsed[1] ) ? arrayParsed[1] : null;
				lim = ( arrayParsed[2] ) ? arrayParsed[2] : null;
				if( lib ) champs[champs.length] = new ChampForm(formulaire, name, lib, ctl, lim);				
			}
		}		
	}
	
    return champs;
}

function editerErreurs(champs) {
    var html = "Le formulaire n'a pu être envoyé pour la(es) raison(s) suivante(s):\n";
    if(lang=="en") html = "The form could not be sent for the following reason(s):\n";	
	for (var i=0;i<champs.length;i++) html += champs[i].editerErreurs();
    alert(html);
}

function ChampForm(formulaire, nom, lib, ctl, lim) {
    this.form = formulaire;
    this.nom = nom; 
    this.type = null; 
    this.lib = lib; 
    this.format = null; 
    this.args = null; 
    this.min = null; 
    this.max = null;
    this.erreurs = new Array();
    if (ctl) this._analyserFormat(ctl);
    if (lim) this._analyserLim(lim);
}

ChampForm.prototype.controler = function() {
	ok = true;
	if (this._champExiste()) {
        this._lireType();
        if (this._estVide()) ok = false;
        else {
            if (this.min || this.max) ok = this._controlerTaille();
            if (this.format) ok &= this._controlerFormat();
        }
    }
    else {
        this._ajouterErreur("champ_inconnu");
        ok = false;
    }
    return ok;
}

ChampForm.prototype.editerErreurs = function() {
    var texte = "";
    if (this.erreurs.length > 0) {
        for (var i=0;i<this.erreurs.length;i++) texte += "- " + this.erreurs[i] + "\n";
    }
    return texte;
}

ChampForm.prototype._analyserFormat = function(format) {
    var args = format.split(/,\s?/);
    if (args) {
        this.format = args.shift();
        if (args.length == 1) this.args = args[0];
        else this.args = args;
    }
}

ChampForm.prototype._analyserLim = function(lim) {
    var min_max = lim.match(/(\d+)(,\s?)?(\d+)?/);
    if (min_max) {
        if (!isNaN(min_max[1])) this.min = min_max[1];
        if (min_max[2]) {
            if (min_max[3] && !isNaN(min_max[3])) this.max = min_max[3];
            else this.max = 0;
        }
        else this.max = -1;
    }
}
    
ChampForm.prototype._champExiste = function() {
    if (this.form.elements[this.nom]) return true;
    else return false;
}

ChampForm.prototype._estVide = function() {
    if (this.type == null) return null;
    var vide = true;
    with (this.form) {
        if ((this.type == "checkbox") || (this.type == "radio")) {
            if (elements[this.nom].checked) vide = false;
            else this._ajouterErreur("case_non_cochee");
        }
        else if ((this.type == "radio-set") || (this.type == "checkbox-set")) {
            var i = 0;
            while (i<elements[this.nom].length) {
                if (elements[this.nom][i].checked) break;
                else i++;
            }
            if (i == elements[this.nom].length) this._ajouterErreur("case_non_cochee");
            else vide = false;
        }
        else if (this.type == "select-multiple") {
            var i = 0;
            while (i<elements[this.nom].options.length) {
                if (elements[this.nom].options[i].selected) break;
                else i++;
            }
            if (i == elements[this.nom].options.length) this._ajouterErreur("option_non_selec");
            else vide = false;
        }
        else if (this.type.estChampTexte() || (this.type == "select-one")) {
            if ((elements[this.nom].value.trim()) || (elements[this.nom].value.trim() != "")) vide = false
            else this._ajouterErreur("champ_non_rempli");
        }
        else vide = undefined;
    }
    return vide;
}

ChampForm.prototype._lireType = function() {
    with (this.form) {
        if (elements[this.nom]) {
            if (elements[this.nom].type == undefined) {
                if ((elements[this.nom].length != undefined) && (elements[this.nom].length > 1))
                    this.type = elements[this.nom][0].type + "-set";
                else this._ajouterErreur("type_inconnu");
            }
            else this.type = elements[this.nom].type;
        }
        else this._ajouterErreur("champ_inconnu");
    }
}

ChampForm.prototype._controlerTaille = function() {
	if (this.type.estChampTexte()) {
        var taille = this.form.elements[this.nom].value.length;
        var ok = false;
        if (this.max == -1) {
            if (taille == this.min) ok = true; 
            else this._ajouterErreur("champ_longueur", this.min);
        }
        else if (taille >= this.min) {
            if (this.max) {
                if (taille <= this.max) ok = true; 
                else this._ajouterErreur("champ_trop_long", this.max);
            }
            else ok = true;
        }
        else this._ajouterErreur("champ_trop_court", this.min);
    }
    return ok;
}

ChampForm.prototype._controlerFormat = function() {
    if (this.type.estChampTexte()) {
        var valeur = this.form.elements[this.nom].value;
        var ok = false;
        switch (this.format) {
            case "date" :        
                if (!(ok = controlerDate(valeur))) this._ajouterErreur("format_date"); break;
            case "heure" :        
                if (!(ok = controlerHeure(valeur))) this._ajouterErreur("format_heure"); break;
            case "date-heure" :    
            case "dateheure" :    
            case "date_heure" :    
                if (!(ok = controlerDateHeure(valeur))) this._ajouterErreur("format_date_heure"); break;
            case "email" :        
                if (!(ok = controlerEmail(valeur))) this._ajouterErreur("format_email"); break;
            case "url" :        
                if (!(ok = controlerUrl(valeur))) this._ajouterErreur("format_url"); break;
            case "cp" :            
                if (!(ok = controlerCP(valeur))) this._ajouterErreur("format_cp"); break;
            case "tel" :        
                if (!(ok = controlerTel(valeur))) this._ajouterErreur("format_tel"); break;
            case "nombre" :        
                if (!(ok = controlerNombre(valeur, this.args))) this._ajouterErreur("format_nombre"); break;
            case "html" :        
                if (!(ok = controlerBalisesHTML(valeur))) this._ajouterErreur("format_html"); break;
            case "propre" :    
                this.form.elements[this.nom].value = controlerPropre(valeur); ok = true; break;
            default    :            
                var erreur = controlerFonction(this.format, valeur, this.args); 
                if (erreur) this._ajouterErreur("format_fonction", erreur);
                else ok = true;
        }
    }
    else this._ajouterErreur("controle_non_texte");
    return ok;
}

ChampForm.prototype._ajouterErreur = function(erreur) {    
	if(lang=="en"){
	   switch (erreur) {
        case "champ_mal_ecrit" :        
            this.erreurs.push(this.lib + " : syntax error in the field at form creation"); break;
        case "champ_inconnu" :        
            this.erreurs.push("Unknown field: '" + this.lib); break;
        case "champ_vide" :        
            this.erreurs.push("The field '" + this.lib + "' is empty or unselected"); break;
        case "champ_non_rempli" :        
            this.erreurs.push("The field '" + this.lib + "' is empty"); break;
        case "case_non_cochee" :    
            this.erreurs.push("La checkbox '" + this.lib + "' is unchecked"); break;
        case "option_non_selec" :    
            this.erreurs.push("There is no option selected in the list '" + this.lib); break;
        case "type_inconnu" :        
            this.erreurs.push("The field '" + this.lib + "''s type is unknown"); break;
        case "champ_index_types_diff" :        
            this.erreurs.push("The fields '" + this.lib + "' must have the same type"); break;
        case "champ_longueur" :    
            this.erreurs.push("The field '" + this.lib + "' must have " + arguments[1] + " characters"); break;
        case "champ_trop_long" :    
            this.erreurs.push("The field '" + this.lib + "''s length mustn't exceed " + arguments[1] + " characters"); break;
        case "champ_trop_court" :    
            this.erreurs.push("The field '" + this.lib + "' must have at least " + arguments[1] + " characters"); break;

        case "format_date" :        
            this.erreurs.push("The field '" + this.lib + "' is not a correct date"); break;
        case "format_heure" :        
            this.erreurs.push("The field '" + this.lib + "' is not a correct hour"); break;
        case "format_date_heure" :    
            this.erreurs.push("The field '" + this.lib + "' is not a correct date/hour"); break;
        case "format_email" :        
            this.erreurs.push("The field '" + this.lib + "' is not a correct e-mail adress"); break;
        case "format_url" :        
            this.erreurs.push("The field '" + this.lib + "' is not a correct url (internet adress)"); break;
        case "format_cp" :            
            this.erreurs.push("The field '" + this.lib + "' is not a correct postal code"); break;
        case "format_tel" :        
            this.erreurs.push("The field '" + this.lib + "' is not a correct phone number"); break;
        case "format_nombre" :        
            this.erreurs.push("The field '" + this.lib + "' is not a valid number"); break;
        case "format_html" :        
            this.erreurs.push("The field '" + this.lib + "' doesn't contain HTML markups"); break;
        case "format_fonction" :    
            this.erreurs.push("The field '" + this.lib + "' has the following error: " + arguments[1]); break;
        case "controle_non_texte" : 
            this.erreurs.push("The field '" + this.lib + "' is not a text field"); break;
       }
	}
	else{
	   switch (erreur) {
           case "champ_mal_ecrit" :        
               this.erreurs.push(this.lib + " : erreur dans la syntaxe du champ à la création du formulaire"); break;
           case "champ_inconnu" :        
               this.erreurs.push("Le champ '" + this.lib + "' est inconnu"); break;
           case "champ_vide" :        
               this.erreurs.push("Le champ '" + this.lib + "' n'a pas été rempli ou sélectionné"); break;
           case "champ_non_rempli" :        
               this.erreurs.push("Le champ '" + this.lib + "' n'a pas été rempli"); break;
           case "case_non_cochee" :    
               this.erreurs.push("La case '" + this.lib + "' n'a pas été cochée"); break;
           case "option_non_selec" :    
               this.erreurs.push("Aucune option n'a été sélectionnée dans la liste '" + this.lib); break;
           case "type_inconnu" :        
               this.erreurs.push("Le type du champ '" + this.lib + "' est inconnu"); break;
           case "champ_index_types_diff" :        
               this.erreurs.push("Les champs '" + this.lib + "' doivent être de type identique"); break;
           case "champ_longueur" :    
               this.erreurs.push("Le champ '" + this.lib + "' doit avoir " + arguments[1] + " caractères"); break;
           case "champ_trop_long" :    
               this.erreurs.push("Le champ '" + this.lib + "' ne doit pas excèder " + arguments[1] + " caractères"); break;
           case "champ_trop_court" :    
               this.erreurs.push("Le champ '" + this.lib + "' doit avoir au minimum " + arguments[1] + " caractères"); break;
           case "format_date" :        
               this.erreurs.push("Le champ '" + this.lib + "' n'est pas une date conforme"); break;
           case "format_heure" :        
               this.erreurs.push("Le champ '" + this.lib + "' n'est pas une heure conforme"); break;
           case "format_date_heure" :    
               this.erreurs.push("Le champ '" + this.lib + "' n'est pas une date/heure conforme"); break;
           case "format_email" :        
               this.erreurs.push("Le champ '" + this.lib + "' n'est pas une adresse e-mail conforme"); break;
           case "format_url" :        
               this.erreurs.push("Le champ '" + this.lib + "' n'est pas une url (adresse internet) conforme"); break;
           case "format_cp" :            
               this.erreurs.push("Le champ '" + this.lib + "' n'est pas un code postal conforme"); break;
           case "format_tel" :        
               this.erreurs.push("Le champ '" + this.lib + "' n'est pas un numéro de téléphone conforme"); break;
           case "format_nombre" :        
               this.erreurs.push("Le champ '" + this.lib + "' n'est pas un nombre"); break;
           case "format_html" :        
               this.erreurs.push("Le champ '" + this.lib + "' ne contient pas de balises HTML"); break;
           case "format_fonction" :    
               this.erreurs.push("Le champ '" + this.lib + "' a l'erreur suivante: " + arguments[1]); break;
           case "controle_non_texte" : 
               this.erreurs.push("Le champ '" + this.lib + "' n'est pas un champ de type texte"); break;
    }
	}
}

String.prototype.lastChar = function() {
    return this.substr(-1, 1);
}

String.prototype.trim = function() {
    chaine = unescape(this);
    return chaine.replace(/(^\s*)|(\s*$)/g, "");
}

String.prototype.estChampTexte = function() {
    return ((this == "text") || (this == "password") || (this == "textarea") || (this == "hidden"));
}

function is_array(valeur) {
    var source = valeur.toSource();
    return (source.search(/^\[([^,]*,)+[^,]*\]/) != -1);
}

function controlerDate(valeur) {
    var ok = false;
    ctl = /^(\d\d?)[\/\-\.](\d\d?)[\/\-\.](\d{4,})$/;
    var tab = valeur.match(ctl);
    if (tab) {
          var unedate = new Date(tab[3], parseInt(tab[2])-1, tab[1]);
          if ((unedate.getFullYear() == tab[3]) && (unedate.getMonth() == tab[2]-1) && (unedate.getDate() == tab[1])) ok = true;
    }    
    return ok;
}

function controlerHeure(valeur) {
    ctl = /^([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?$/;
    if (valeur.search(ctl) != -1) return true;
    else return false;
}

function controlerDateHeure(valeur) {
    var date_heure = valeur.split(/\s+/);
    return (controlerDate(date_heure[0]) && controlerHeure(date_heure[1]));
}
        
function controlerEmail(valeur) {
    ctl = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+([\.][a-z0-9-]+)+$/;
    if (valeur.search(ctl) != -1) return true;
    else return false;
}

function controlerUrl(valeur) {
    ctl = /^((http(s?)|ftp):\/\/)?([\w\-]+\.)+([\w\-]+)(\/[\w\-\s]+)*(\/(([\w\-]+)(\.[\w]+)*)?(#\w+)?(\?.+)?)?$/;
    if (valeur.search(ctl) != -1) return true;
    else {
        ctl = /^mailto:[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+([\.][a-z0-9-]+)+$/;
        if (valeur.search(ctl) != -1) return true;
        else return false;
    }
}

function controlerCP(valeur) {
    ctl = /^([A-Z]+\-)?[\d]{5}$/;
    if (valeur.search(ctl) != -1) return true;
    else return false;
}

function controlerTel(valeur) {
    ctl = /^(\(\d+\))?([\s\.\-]?\d{2,})+$/;
    if ((valeur.search(ctl) != -1) && (valeur.length ==10) && (valeur.charAt(0)==0)) return true;
    else return false;
}

function controlerNombre(valeur, limites) {
    valeur = valeur.replace(" ", "");
    if (isNaN(valeur)) var ok = false;
    else {
        if (limites != "") {
            if (typeof limites == "string") 
                eval("ok = (" + valeur + " " + limites + ");");
            else if (limites.length == 2)    
                eval("ok = ((" + valeur + " " + limites[0] + ") && (" + valeur + " " + limites[1] + "));");
        }
        else var ok = true;
    }
    return ok;
}

function controlerBalisesHTML(valeur) {
    if (valeur.search(/<\/?(\w+)(\s[^>]+)?>/) != -1) return true;
    else return false;
}

function controlerPropre(valeur) {
    valeur = valeur.replace(/<(\w+)(\s[^>]+)?>/g, "&lt;$1$2&gt;");
    valeur = valeur.replace(/<\/(\w+)>/g, "&lt;/$1&gt;");
    valeur = valeur.replace(/<([\?%])(\w*)/, "&lt;$1$2");
    valeur = valeur.replace(/([\?%])>/, "$1&gt;");
    return valeur;
}

function controlerFonction(fonction, valeur, args) {
    if (isNaN(valeur)) var ch_eval = fonction + "(\"" + valeur.replace(/\"/, '\\"') + "\"";
    else var ch_eval = fonction + "(" + valeur;
    if (args) {
        if (is_array(args)) {
            for (i=0;i<args.length;i++) ch_eval += "," + variable_selon_type(args[i]);
        }
        else ch_eval += "," + variable_selon_type(args);
    }
    ch_eval += ");";
    return eval(ch_eval);
}

function variable_selon_type(valeur) {
    var variable = "";
    if (isNaN(valeur)) {
        if (valeur.search(/^'([^'])+'$/) != -1) valeur = valeur.slice(1, -1);
        if (valeur.indexOf("var ") == 0) variable = valeur.substring(4);
        else variable = "\"" + valeur.replace(/\"/, '\\"') + "\"";
    }
    else variable = valeur;
    return variable;
}

function carClavier(e){
    if(window.event)
       //pour internet explorer
       return String.fromCharCode(window.event.keyCode);
    else
        //pour Netscape
       return String.fromCharCode(e.which);
 }

 function estCeNum(e){
   caractere=carClavier(e);
   if(caractere <"0" || caractere >"9")
     return false;
   else
     return true;
 }

 function Compter(Target, max, nomchamp)
 {

   StrLen = Target.value.length ;
   if (StrLen > max )
   {
      Target.value = Target.value.substring(0,max);
      CharsLeft = max;
   }
    else
        {
           CharsLeft = StrLen;

        }

 }
