var delai_chrono;
var paramInit;
var estIE = (document.all) ? true : false;
var transparent;
var x = 0, y = 0;
var VRAI = true;
var FAUX = false;
var flottage;


// MAUDIT INTERNET EXPLORER -- ON NE PEUT PAS MODIFIER HTMLInputElement.prototype...
function element_distingue (el) {
    var cocheur, obj, motDePasseCache;

    if (el.type === 'button' || el.type === 'submit' || el.type === 'reset'
          || el.className === 'input_bouton') {
        el.onmousedown = function () {
            this.style.borderBottomColor = '#99CC66';
            this.style.borderLeftColor = '#336600';
            this.style.borderRightColor = '#99CC66';
            this.style.borderTopColor = '#336600';
        };
        el.onmouseout = function () {
            this.style.borderBottomColor = '#336600';
            this.style.borderLeftColor = '#99CC66';
            this.style.borderRightColor = '#336600';
            this.style.borderTopColor = '#99CC66';
        };
        el.onmouseup = function () {
            this.style.borderBottomColor = '#336600';
            this.style.borderLeftColor = '#99CC66';
            this.style.borderRightColor = '#336600';
            this.style.borderTopColor = '#99CC66';
        };
    } else if (el.type === 'password') {
        motDePasseCoche = nouveau_noeud(
            {tagName: 'div', className: 'champ_info',
            childNodes: [
                {tagName: 'input', type: 'checkbox', checked: 'true',
                onclick: function () {el.type = (this.checked) ? 'password' : 'text';}},
                {tagName: 'textNode', nodeValue: 'Offusquer la boîte ci-dessus'}]}
        );

        obj = el.nextSibling;
        while (obj && obj.nodeType === 3) obj = obj.nextSibling;

        if (!el.nextSibling) {
            el.parentNode.appendChild(motDePasseCoche);
        } else {
            el.parentNode.insertBefore(motDePasseCoche, el.nextSibling);
        }
    }
}


// PRÉPARE LES ÉLÉMENTS AFIN QU'ILS SE DIRIGENT VERS LE BOUTON DE SOUMISSION PRINCIPAL
function bouton_principal (formulaire) {
    var els;
    var bouton_principal = getElementsByClassName('_bouton_principal', formulaire);
    var el_names = ['input', 'select', 'textarea', 'button'];
    var expr = new RegExp('_bouton_principal');

    if (bouton_principal.length === 0) return;
    bouton_principal = bouton_principal[0];

    for (idx in el_names) {
        els = document.getElementsByTagName(el_names[idx]);

        for (i = 0; i < els.length; i++) {
            if (expr.test(els[i].className) || (els[i].tagName.toLowerCase() === 'input'
                && (els[i].tagName.toLowerCase() === 'submit'
                || els[i].tagName.toLowerCase() === 'reset'
                || els[i].tagName.toLowerCase() === 'image'
                || els[i].tagName.toLowerCase() === 'button'))
                || els[i].tagName.toLowerCase() === 'button') continue;

            els[i].onkeypress = function (e) {
                var cle;
                if (window.event) cle = window.event.keyCode;
                else if (e) cle = e.which;
                else return true;

                if (cle === 13) {
                    bouton_principal.click();
                    return false;
                } else {
                    return true;
                }
            };
        }
    }
}


// DONNE LA VERSION TEXTE D'UNE DATE
function date_texte (jour, mois, annee) {
    var expr = new RegExp('janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre'
        + '|novembre|décembre', 'g');
    var mois_char = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août',
        'septembre', 'octobre', 'novembre', 'décembre'];

    // Convertir d'une valeur indéfinie ou d'une chaîne de caractères vide à nulle
    jour = (jour === undefined || jour === '') ? null : jour;
    mois = (mois === undefined || mois === '') ? null : mois;
    annee = (annee === undefined || annee === '') ? null : annee;

    // Convertir d'une chaîne de caractères à un nombre entier
    jour = (typeof jour === 'string') ? parseInt(jour).toString() : jour;
    mois = (typeof mois === 'string') ? ((expr.test(mois)) ? mois : mois_char[parseInt(mois) - 1]) :
        mois_char[mois - 1];
    annee = (typeof annee === 'string') ? parseInt(annee).toString() : annee;

    // Sélectionner la bonne option pour les variables disponibles
    if (jour === null && mois === null && annee === null) return '';
    else if (jour === null && mois === null) return 'en ' + annee;
    else if (jour === null && annee === null) return 'au mois de ' + mois;
    else if (mois === null && annee === null) return 'au ' + jour + ' <sup>'
        + ((parseInt(jour) === 1) ? 'er' : 'e') + '</sup> jour du mois';
    else if (annee === null) return 'le ' + jour + ' ' + mois;
    else if (mois === null) return 'au ' + jour + ' <sup>'
        + ((parseInt(jour) === 1) ? 'er' : 'e') + '</sup> jour du mois en ' + annee;
    else if (jour === null) return 'en ' + mois + ' ' + annee;
    else return 'le ' + jour + ' ' + mois + ' ' + annee;
}


function dans_mat (val, mat) {
    var i, lim = mat.length;

    for (i = 0; i < lim; i++) {
        if (mat[i] === val) return true;
    }

    return false;
}


function getElementsByClassName (nomClasse, obj) {
    var elements, expression, i, lim, res = [];

    if (obj === undefined || obj === null) obj = document;

    elements = obj.getElementsByTagName('*');
    expression = new RegExp('\\b' + nomClasse + '\\b', 'i');
    lim = elements.length;
    for (i = 0; i < elements.length; i++) {
        if (expression.test(elements[i].className)) res[res.length] = elements[i];
    }

    return res;
}


function nouveau_noeud (defNoeud) {
    var i, lim, noeud, param;

    if (defNoeud.tagName === 'textNode') {
        noeud = document.createTextNode(defNoeud.nodeValue);

        for (param in defNoeud) noeud[param] = defNoeud[param];
    } else {
        noeud = document.createElement(defNoeud.tagName);

        placerValeurs(noeud, defNoeud);

        if (defNoeud.childNodes) {
            lim = defNoeud.childNodes.length;
            for (i = 0; i < lim; i++) noeud.appendChild(nouveau_noeud(defNoeud.childNodes[i]));
        }
    }

    return noeud;
}


function placerValeurs (cible, obj) {
    var param, style;

    for (param in obj) {
        if (param === 'style') {
            for (style in obj.style) {
                if (style === 'cssFloat') {
                    cible.style[flottage] = obj.style[style];
                } else {
                    cible.style[style] = obj.style[style];
                }
            }
        } else if (param !== 'tagName' && param !== 'childNodes') {
            cible[param] = (typeof obj[param] !== 'object') ? obj[param]
                : placerValeurs(cible[param], obj[param]);
        }
    }

    return cible;
}


function posSouris (e) {
    e = e || event;

    if (e.pageX || e.pageY) {
        x = e.pageX;
        y = e.pageY;
    } else if (e.clientX || e.clientY) {
        x = e.clientX + document.body.scrollLeft;
        y = e.clientY + document.body.scrollTop;
    } else {
        x = -1;
        y = -1;
    }
}


function prepareSouris () {
    document.onmousemove = posSouris;
}


function getXMLNode (currNode, path, getData) {
    getData = getData || FAUX;
    els = [currNode];

    for (var branch in path) {
        new_els = [];

        for (var node in els) {
            var tmp_els = els[node].getElementsByTagName(path[branch]);

            for (var new_node in tmp_els) {
                if (tmp_els[new_node].parentNode === els[node])
                    new_els[new_els.length] = tmp_els[new_node];
            }
        }

        els = new_els;
    }

    return (els.length === 0) ? null
        : ((els.length === 1 && getData) ? getXMLData(els[0]) : els);
}


function getXMLData (node) {
    return node.textContent;
}


// OBTAIN THE DATA FROM SECURUS ARCIS VIA XML HTTP REQUEST
// google search: request xmlhttprequest
// http://www.phpbuilder.com/columns/adam_delves20060224_2.php3
function dataRequest (adresse, actionSucces, actionFaillite) {
    var request = null;
    var paramStr = '';
    var ua = navigator.userAgent.toLowerCase();

    // New request
    if (!window.ActiveXObject) request = new XMLHttpRequest();
    else if (ua.indexOf('msie 5') === -1) request = new ActiveXObject("Msxml2.XMLHTTP");
    else request = new ActiveXObject("Microsoft.XMLHTTP");

    // Prepare the request
    request.open('GET', adresse, VRAI);

    // Set the resulting function
    request.onreadystatechange = function () {
        if (request.readyState === 4) {
            if (request.status === 200) actionSucces(request.responseXML, adresse);
            else actionFaillite(adresse);
        }
    }

    // Send the request
    request.send(null);
}


function supprimeNoeuds (noeud) {
    while (noeud.childNodes.length > 0)
        noeud.removeChild(noeud.childNodes[noeud.childNodes.length - 1]);
}
 
 
function verifie_temoins () {
    var cookiesActives, element, h2, message;

    document.cookie = 'test=test';
    cookiesActives = (document.cookie.indexOf('test') !== -1) ? true : false;

    if (!cookiesActives) {
        element = nouveau_noeud({
            tagName: 'div', className: 'alerte',
            childNodes: [
                {tagName: 'h2',
                childNodes: [{tagName: 'textNode', nodeValue: 'Erreur'}]},
                {tagName: 'p',
                childNodes: [{tagName: 'textNode', nodeValue: 'Vous devez accepter les témoins '
                    + 'afin d\'utiliser ce site web efficacement! Afin d\'éliminer ce message, '
                    + 'veuillez indiquer à votre navigateur Internet d\'accepter les témoins et '
                    + 'rafraîchissez la page.'}]}]}
        );

        if (document.getElementById('contenu')) {
            document.getElementById('contenu').insertBefore(element,
                document.getElementById('contenu').firstChild);
        } else {
            element.style.position = 'fixed';
            element.style.left = '0px';
            element.style.right = '0px';
            element.style.top = '82px';
            document.body.insertBefore(element, document.body.firstChild);
        }
    }
}


onload = function () {
    // Variables
    var i, j, lim, lim2, ensembleChamps, legende, listeOptions, listeSelect, entrees, legende,
        formulaires, els, div, lien;

    // Flottage : Internet Explorer veut être différent!
    div = document.createElement('div'),
    div.style.display = 'none';
    div.innerHTML = '<a href="./SecurusArcis.php" style="float:left;">SA</a>';
    lien = div.getElementsByTagName('a')[0];
    flottage = (!!lien.style.cssFloat) ? 'cssFloat' : 'styleFloat';

    // Éxécuter les paramètres initiaux
    if (paramInit !== undefined) paramInit();

    // Vérifier si l'on est dans un cadre
    if (self !== top) top.location = './SecurusArcis.php';

    // Vérification des témoins
    verifie_temoins();

    // MAUDIT INTERNET EXPLORER -- ON NE PEUT PAS MODIFIER Node.prototype...
    els = document.getElementsByTagName('*');
    lim = els.length;
    for (i = 0; i < lim; i++) {
        els[i].chgTransparence = function (val) {
            if (this.style !== undefined) {
                this.style.opacity = val;
                this.style.filter = 'alpha(opacity=' + (val * 100) + ')';
                this.style.KHTMLOpacity = val;
                this.style.MozOpacity = val;
            }
        };
    }

    // Boutons dynamiques
    entrees = document.getElementsByTagName('input');
    for (i = 0; i < entrees.length; i++) element_distingue(entrees[i]);
    entrees = document.getElementsByClassName('input_bouton');
    for (i = 0; i < entrees.length; i++) element_distingue(entrees[i]);

    // Boutons de soumission principals
    formulaires = document.getElementsByTagName('form');
    for (i = 0; i < formulaires.length; i++) bouton_principal(formulaires[i]);

    // Champs de formulaire supplémentaires
    ensembleChamps = getElementsByClassName('supp');
    lim = ensembleChamps.length;
    for (i = 0; i < lim; i++) {
        ensembleChamps[i].courrant = 'plein';
        legende = ensembleChamps[i].getElementsByTagName('legend')[0];
        legende.style.backgroundPosition = '3px 3px';
        legende.style.backgroundRepeat = 'no-repeat';
        legende.style.cursor = 'pointer';
        legende.style.paddingLeft = '17px';
        legende.onclick = function () {
            var i, listeInput;

            if (this.parentNode.courrant === 'plein') {
                this.parentNode.courrant = 'vide';
                this.style.backgroundImage = 'url("./Images/Mini/Plus.png")';
                for (i = 0; i < this.parentNode.childNodes.length; i++) {
                    if (this.parentNode.childNodes[i].style !== undefined
                        && this.parentNode.childNodes[i].nodeName.toLowerCase() !== 'legend')
                        this.parentNode.childNodes[i].style.display = 'none';
                }
            } else {
                this.parentNode.courrant = 'plein';
                this.style.backgroundImage = 'url("./Images/Mini/Moins.png")';
                for (i = 0; i < this.parentNode.childNodes.length; i++) {
                    if (this.parentNode.childNodes[i].style
                          && this.parentNode.childNodes[i].nodeName.toLowerCase() !== 'legend') {
                        listeInput = this.parentNode.childNodes[i].getElementsByTagName('input');
                        if (listeInput.length === 1 && listeInput[0].type === 'text'
                              && listeInput[0].id.substring(listeInput[0].id.length - 3) === 'Alt'
                              && document.getElementById(listeInput[0].id.substring(0,
                              listeInput[0].id.length - 3))) {
                            if (document.getElementById(
                                this.parentNode.childNodes[i].childNodes[1].id.substring(0,
                                this.parentNode.childNodes[i].childNodes[1].id.length - 3)).value
                                === 'alt_ernatif')
                                this.parentNode.childNodes[i].style.display = 'block';
                            else this.parentNode.childNodes[i].style.display = 'none';
                        } else {
                            this.parentNode.childNodes[i].style.display = 'block';
                        }
                    }
                }
            }
        };
        legende.onclick();
    }

    listeSelect = document.getElementsByTagName('select');
    lim = listeSelect.length;
    for (i = 0; i < lim; i++) {
        listeOptions = listeSelect[i].options;
        lim2 = listeOptions.length;

        for (j = 0; j < lim2; j++) {
            if (listeOptions[j].value === 'alt_ernatif') {
                if (document.getElementById(listeSelect[i].id + 'Alt')) {
                    document.getElementById(listeSelect[i].id + 'Alt').parentNode.style.display
                        = (listeSelect[i].value === 'alt_ernatif') ? 'block' : 'none';
                    listeSelect[i].onclick = function () {
                        if (document.getElementById(this.id + 'Alt')) {
                            if (this.value === 'alt_ernatif') document.getElementById(this.id
                                + 'Alt').parentNode.style.display = 'block';
                            else document.getElementById(this.id
                                + 'Alt').parentNode.style.display = 'none';
                        }
                    };
                    break;
                }
            }
        }
    }
};