/* auteur: Bernard Martin-Rabaud */
/* Date de création: 18/12/2004 */

// CONTROLE DE FORMULAIRE VERSION 1

var lim_champs_obligatoires = 100;

function submit_form(formulaire) {
    var champs = lireChampsObligatoires(formulaire);
    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");
} 

function lireChampsObligatoires(formulaire) {
    var champs = new Array();
    for (var i=0;i<lim_champs_obligatoires;i++) {
        champ = document.getElementsByTagName("champ")[i];
        if (champ) {
            if (champ.attributes["lib"]) lib = champ.attributes["lib"].nodeValue;
            else lib = null;
            if (champ.attributes["ctl"]) ctl = champ.attributes["ctl"].nodeValue;
            else ctl = null;
            if (champ.attributes["lim"]) lim = champ.attributes["lim"].nodeValue;
            else lim = null;
            if (champ.attributes["double"]) {double = champ.attributes["double"].nodeValue;}
            else double = null;
            champs[champs.length] = new ChampForm(formulaire, champ.attributes["nom"].nodeValue, lib, ctl, double);
        }
        else break;
    }    
    return champs;
}

function editerErreurs(champs) {
    var html = "Le formulaire n'a pu être envoyé pour les raisons suivantes:\n";
    for (var i=0;i<champs.length;i++) html += champs[i].editerErreurs();
    alert(html);
}

function ChampForm(formulaire, nom, lib, ctl, lim, double) {
    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);
    if (double) this._analyserDouble(nom, double);
}

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 = true;
    }
    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 "pass" :        
                if (!(ok = controlerPass(valeur, this))) this._ajouterErreur("format_doublon"); 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) {
    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_doublon" :        
            this.erreurs.push("Le champ '" + this.lib + "' ne correspond pas au champ de confirmation"); 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 + "' est un nombre non valide"); 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 controlerPass(valeur, page) {
	champ = page.form.elements[page.nom].value;
	champ = page.form.elements[page.nom].name;
	champ_verif = 're' + champ;
	valeur = page.form.elements[page.nom].value;
	valeur_verif = page.form.elements[champ_verif].value;
	if (page.form.elements[champ_verif].value != page.form.elements[page.nom].value)
	{ return false;}
    else return true;
}
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) 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;
}









<!--
// bbCode control by
// subBlue design
// www.subBlue.com

// Startup variables
var imageTag = false;
var theSelection = false;

// Check for Browser & Platform for PC & IE specific bits
// More details from: http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html
var clientPC = navigator.userAgent.toLowerCase(); // Get client info
var clientVer = parseInt(navigator.appVersion); // Get browser version

var is_ie = ((clientPC.indexOf("msie") != -1) && (clientPC.indexOf("opera") == -1));
var is_nav = ((clientPC.indexOf('mozilla')!=-1) && (clientPC.indexOf('spoofer')==-1)
                && (clientPC.indexOf('compatible') == -1) && (clientPC.indexOf('opera')==-1)
                && (clientPC.indexOf('webtv')==-1) && (clientPC.indexOf('hotjava')==-1));
var is_moz = 0;

var is_win = ((clientPC.indexOf("win")!=-1) || (clientPC.indexOf("16bit") != -1));
var is_mac = (clientPC.indexOf("mac")!=-1);

// Helpline messages
b_help = "Texte gras: [b]texte[/b] (alt+b)";
i_help = "Texte italique: [i]texte[/i] (alt+i)";
u_help = "Texte souligné: [u]texte[/u] (alt+u)";
q_help = "Citation: [quote]texte cité[/quote] (alt+q)";
c_help = "Afficher du code: [code]code[/code] (alt+c)";
l_help = "Liste: [list]texte[/list] (alt+l)";
o_help = "Liste ordonnée: [list=]texte[/list] (alt+o)";
p_help = "Insérer une image: [img]http://image_url/[/img] (alt+p)";
w_help = "Insérer un lien: [url]http://url/[/url] ou [url=http://url/]Nom[/url] (alt+w)";
a_help = "Fermer toutes les balises BBCode ouvertes";
s_help = "Couleur du texte: [color=red]texte[/color] Astuce: #FF0000 fonctionne aussi";
f_help = "Taille du texte: [size=x-small]texte en petit[/size]";

// Define the bbCode tags
bbcode = new Array();
bbtags = new Array('[strong]','[/strong]','[em]','[/em]','[u]','[/u]','[quote]','[/quote]','[code]','[/code]','[list]','[/list]','[list=]','[/list]','[img]','[/img]','[url]','[/url]');
imageTag = false;

// Shows the help messages in the helpline window
function helpline(help) {
	document.formMessageForum.helpbox.value = eval(help + "_help");
}


// Replacement for arrayname.length property
function getarraysize(thearray) {
	for (i = 0; i < thearray.length; i++) {
		if ((thearray[i] == "undefined") || (thearray[i] == "") || (thearray[i] == null))
			return i;
		}
	return thearray.length;
}

// Replacement for arrayname.push(value) not implemented in IE until version 5.5
// Appends element to the array
function arraypush(thearray,value) {
	thearray[ getarraysize(thearray) ] = value;
}

// Replacement for arrayname.pop() not implemented in IE until version 5.5
// Removes and returns the last element of an array
function arraypop(thearray) {
	thearraysize = getarraysize(thearray);
	retval = thearray[thearraysize - 1];
	delete thearray[thearraysize - 1];
	return retval;
}


function checkForm() {

	formErrors = false;

	if (document.formMessageForum.message.value.length < 2) {
		formErrors = "Vous devez entrer un message avant de poster.";
	}

	if (formErrors) {
		alert(formErrors);
		return false;
	} else {
		bbstyle(-1);
		//formObj.preview.disabled = true;
		//formObj.submit.disabled = true;
		return true;
	}
}

function emoticon(text) {
	var txtarea = document.formMessageForum.message;
	text = ' ' + text + ' ';
	if (txtarea.createTextRange && txtarea.caretPos) {
		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}

function bbfontstyle(bbopen, bbclose) {
	var txtarea = document.formMessageForum.message;

	if ((clientVer >= 4) && is_ie && is_win) {
		theSelection = document.selection.createRange().text;
		if (!theSelection) {
			txtarea.value += bbopen + bbclose;
			txtarea.focus();
			return;
		}
		document.selection.createRange().text = bbopen + theSelection + bbclose;
		txtarea.focus();
		return;
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbopen, bbclose);
		return;
	}
	else
	{
		txtarea.value += bbopen + bbclose;
		txtarea.focus();
	}
	storeCaret(txtarea);
}


function bbstyle(bbnumber) {
	var txtarea = document.formMessageForum.message;

	txtarea.focus();
	donotinsert = false;
	theSelection = false;
	bblast = 0;

	if (bbnumber == -1) { // Close all open tags & default button names
		while (bbcode[0]) {
			butnumber = arraypop(bbcode) - 1;
			txtarea.value += bbtags[butnumber + 1];
			buttext = eval('document.formMessageForum.addbbcode' + butnumber + '.value');
			eval('document.formMessageForum.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
		}
		imageTag = false; // All tags are closed including image tags :D
		txtarea.focus();
		return;
	}

	if ((clientVer >= 4) && is_ie && is_win)
	{
		theSelection = document.selection.createRange().text; // Get text selection
		if (theSelection) {
			// Add tags around selection
			document.selection.createRange().text = bbtags[bbnumber] + theSelection + bbtags[bbnumber+1];
			txtarea.focus();
			theSelection = '';
			return;
		}
	}
	else if (txtarea.selectionEnd && (txtarea.selectionEnd - txtarea.selectionStart > 0))
	{
		mozWrap(txtarea, bbtags[bbnumber], bbtags[bbnumber+1]);
		return;
	}

	// Find last occurance of an open tag the same as the one just clicked
	for (i = 0; i < bbcode.length; i++) {
		if (bbcode[i] == bbnumber+1) {
			bblast = i;
			donotinsert = true;
		}
	}

	if (donotinsert) {		// Close all open tags up to the one just clicked & default button names
		while (bbcode[bblast]) {
				butnumber = arraypop(bbcode) - 1;
				txtarea.value += bbtags[butnumber + 1];
				buttext = eval('document.formMessageForum.addbbcode' + butnumber + '.value');
				eval('document.formMessageForum.addbbcode' + butnumber + '.value ="' + buttext.substr(0,(buttext.length - 1)) + '"');
				imageTag = false;
			}
			txtarea.focus();
			return;
	} else { // Open tags

		if (imageTag && (bbnumber != 14)) {		// Close image tag before adding another
			txtarea.value += bbtags[15];
			lastValue = arraypop(bbcode) - 1;	// Remove the close image tag from the list
			document.formMessageForum.addbbcode14.value = "Img";	// Return button back to normal state
			imageTag = false;
		}

		// Open tag
		txtarea.value += bbtags[bbnumber];
		if ((bbnumber == 14) && (imageTag == false)) imageTag = 1; // Check to stop additional tags after an unclosed image tag
		arraypush(bbcode,bbnumber+1);
		eval('document.formMessageForum.addbbcode'+bbnumber+'.value += "*"');
		txtarea.focus();
		return;
	}
	storeCaret(txtarea);
}

// From http://www.massless.org/mozedit/
function mozWrap(txtarea, open, close)
{
	var selLength = txtarea.textLength;
	var selStart = txtarea.selectionStart;
	var selEnd = txtarea.selectionEnd;
	if (selEnd == 1 || selEnd == 2)
		selEnd = selLength;

	var s1 = (txtarea.value).substring(0,selStart);
	var s2 = (txtarea.value).substring(selStart, selEnd)
	var s3 = (txtarea.value).substring(selEnd, selLength);
	txtarea.value = s1 + open + s2 + close + s3;
	return;
}

// Insert at Claret position. Code from
// http://www.faqts.com/knowledge_base/view.phtml/aid/1052/fid/130
function storeCaret(textEl) {
	if (textEl.createTextRange) textEl.caretPos = document.selection.createRange().duplicate();
}

//-->




