var tField = [];
var tFieldOblig = [];
var tFieldFunc = [];


/**
 * Vérifie un siret
 *
 */
function checkFormSiret(siret) {
    /* Vérification du SIRET */
    if (!(/[0-9]{14}$/).test(siret.value)) {
        alert("Le champ SIRET doit contenir 14 chiffres.");
        return false;
    }
    return true;
}

/**
 * Vérifie si le champ est non vide
 * @param champ Le nom du champ
 * @param str Une chaine contenant le nom du champ pour l'alerte
 * @return True si le champ est rempli, False sinon
 */
function checkEmpty(champ, str) {
    b = (champ.value != "");    
    if (!b) {
        alert("Le champ " + str + " est obligatoire.");
        champ.focus();
    }
        
    return b;
}
 
 
/**
 * Vérifie de l'email : on vérifie la présence du @ et du .
 * @param champ Le nom du champ
 * @return True si le champ est bien rempli, False sinon
 */
function checkEmail(champ) {
    if (!(/[A-Za-z0-9\-\.\_]+\@[A-Za-z0-9\-\.\_]+\.[a-z]{2,6}$/).test(champ.value)) {
        return false;
    }
    
    return true;
}
                    
 
/**
 * Vérifie le cp sous la forme "12345"
 * @param champ Le nom du champ
 * @return True si le champ est bien rempli, False sinon
 */
function checkCP(champ) {
    if (isNaN(champ.value) || (champ.value.length != 5) || (champ.value.indexOf('.') != -1)) {
        return(false);
    }
    return(true);
}
 
/**
 * Vérifie le cp sous la forme "12"
 * @param champ Le nom du champ
 * @return True si le champ est bien rempli, False sinon
 */
function checkCPShort(champ) {
    if (isNaN(champ.value) || (champ.value.length < 2 || champ.value.length > 5) || (champ.value.indexOf('.') != -1)) {
        return(false);
    }
    return(true);
}

/**
 * Vérifie la validité du champ : entier
 * @param champ Le nom du champ
 * @return True si le champ est bien rempli, False sinon
 */
function checkInt(champ) {    
    if (isNaN(champ.value) || (champ.value == "") || (champ.value.indexOf('.') != -1)) {
        alert("La valeur doit être un nombre entier.\nVeuillez la corriger.");
        champ.value = 0;

        if (champ.focus){
            champ.focus();
        }

        return(false);
    }
    return(true);
}


/**
 * Vérifie la validité du champ : décimal
 * @param champ Le nom du champ
 * @return True si le champ est bien rempli, False sinon
 */
function checkDecimal(champ) {    
    if (isNaN(champ.value) || (champ.value == "")) {
        alert("La valeur doit être une valeur décimale.\nVeuillez la corriger.");
        champ.value = 0.00;

        if (champ.focus) {
            champ.focus();
        }
            
        return(false);
    }
    return(true);
}


/**
 * Vérification d'un numéro de téléphone
 * @param champ Le nom du champ
 * @return True si le champ est bien rempli, False sinon
*/
function checkTel(champ) {
    ret = false;
    var verifPhoneFr = /^(01|02|03|04|05|06|08|09)[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}$/; 
    var verifPhoneInt = /^(\+[0-9]{2})[ \.\-]?[0-9][ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}$/;
    if ( (verifPhoneFr).test(champ.value) ){
        ret = true;
    }
    if ( (verifPhoneInt).test(champ.value) ){
        ret = ret | true;
    }
    return(ret);
}

/**
 * Vérification d'un numéro de téléphone
 * @param champ Le nom du champ
 * @return True si le champ est bien rempli, False sinon
*/
function checkCellular(champ) {
    ret = false;
    var verifPhoneFr = /^(06)[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}$/; 
    var verifPhoneInt = /^(\+[0-9]{2})[ \.\-]?[6][ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}[ \.\-]?[0-9]{2}$/;
    if ( (verifPhoneFr).test(champ.value) ){
        ret = true;
    }
    if ( (verifPhoneInt).test(champ.value) ){
        ret = ret | true;
    }
    return(ret);
}

/**
 * Vérifie la longueur du champ (pour les textaera où les maxlength ne fonctionnent pas)
 * @param champ Le nom du champ
 * @return True si la maxlength n'est pas atteinte
 */
function checkNotMaxLength(champ, maxlength) {
    if (champ.value.length >= maxlength) {
        alert("La taille maximale du champ de " + maxlength + " caractères est atteinte.\nVeuillez raccourcir le texte.");
        champ.focus();
        return(false);
    }
    return(true);
}

function disableTruefield(){
    if (document.getElementById('etranger').checked){
        tFieldOblig[7] = '';
        tFieldOblig[8] = '';
        document.getElementById("verif"+tField[7]).className='verif';
        document.getElementById("verif"+tField[8]).className='verif';
    } else {
        tFieldOblig[7] = '1';
        tFieldOblig[8] = '1';
        document.getElementById("verif"+tField[7]).className='verif';
        document.getElementById("verif"+tField[8]).className='verif';
    }
    return true;
}

function checkMultiEmail(champ) {
    var tEmail = [];
    tEmail = champ.value.split(";");
    i=0;
    bRet = true;
    while (i<tEmail.length){
        bRetTmp = true;
        if (!(/[A-Za-z0-9\-\.\_]+\@[A-Za-z0-9\-\.\_]+\.[a-z]{2,6}$/).test(tEmail[i])) {
            bRetTmp = false;
        }
        bRet = bRet & bRetTmp;
        i++;
    }    
    return bRet;
}

/**
 * Vérification d'une date sous la forme jj/mm/aa
 * @param champ Le nom du champ
 * @return True si le champ est bien rempli, False sinon
 */
function checkDate(champ) {
    // Creation d'un tableau de valeurs
    // tabVal[0] : jour
    // tabVal[1] : mois
    // tabVal[2] : annee
    var i = 0;
    //var numSlashes = 0;
    var valBeforeSlash = "";
    var tabVals =[];
    var nbVals = 0;
    while (i < champ.value.length) {
        var car = champ.value.substring(i, i+1);
        if (car == "-") {
            tabVals[nbVals++] = parseInt(valBeforeSlash,10);
            valBeforeSlash = "";
        }
        else {
            valBeforeSlash += car;
        }
        i++;
    }

    /* Ajout du dernier élément du tableau (l'année)
     * Si l'année est < à 50, on suppose que c'est 20xx
     * Si l'année est > à 50, on suppose que c'est en 19xx
     */    
    tabVals[tabVals.length] = parseInt(valBeforeSlash,10);
    ajoutSiecleAnnee = ( parseInt(valBeforeSlash,10) < 50 ) ? 2000 : parseInt(valBeforeSlash,10)+1900;
            
    // Si le champ ne contient pas 2 caractères '/' ou si la date tappé par l'utilisateur fait plus de 8 caractères (jj/mm/aa):
    if (tabVals.length != 3 || champ.value.length > 10 || champ.value.length < 10) {
        champ.focus();
        return(false);
    }
    
    // Vérification de la validité des valeurs du tableau
    var j = 0;
    while (j < tabVals.length) {
        if (isNaN(tabVals[j])) {
            champ.focus();
            return(false);
        }
        j++;
    }
    
    // Verification que la date existe et est valable :
    var bissec = (((tabVals[2] % 4 === 0) && (tabVals[2] % 100 !== 0)) || (tabVals[2] % 1000 === 0));
    var tabMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    if (bissec){
        tabMonths[1]++;
    }
    
    if ((tabVals[1] < 1) || (tabVals[1] > 12) || (tabVals[0] < 1) || (tabVals[0] > tabMonths[tabVals[1]-1])) {
        alert("La date indiquée n'existe pas.\nVeuillez la corriger.");
        champ.focus();
        return(false);
    }

    return(true);
}
 
function checkPass(champ) {
    if (champ.value != document.getElementById('pass').value) {
        return(false);
    }
    return(true);
}

function verif_check(champ) {
    var radioLength = document.tx_hpoforms_form.elements['tx_hpoforms_pi1['+champ.id+']'].length;
    bRet = 0;
    for(var i = 0; i < radioLength; i++) {
        if(document.tx_hpoforms_form.elements['tx_hpoforms_pi1['+champ.id+']'].item(i).checked) {
            bRet = 1;
            document.getElementById("verif"+champ.id).className='verif ok';
            return true;
        }
    }
    if (!bRet)
        document.getElementById("verif"+champ.id).className='verif nok';    
    return false;
}


function hpo_forms_verif(obj,obligatory,funcVerif){
    ret = false;
    if (obligatory==1){
        //RTE
        if(obj.id.indexOf('RTEarea')!=-1){
            valId = obj.id.substring(7);
            //objValue = RTEarea[valId]['editor'].getHTML();
            objValue = RTEarea[valId].editor.getHTML();
        } else {//Common
            objValue = obj.value;
        }
            
        if (objValue!=''){
            document.getElementById("verif"+obj.id).className='verif ok';
            ret = true;
        } else {
            document.getElementById("verif"+obj.id).className='verif nok';
        }
    } else {
        ret = true;
    }
        
    if (funcVerif){
        ret = false;
        if (obj.value!=''){
            if (funcVerif=="email"){
                if (checkEmail(obj)){
                    document.getElementById("verif"+obj.id).className='verif ok';
                    ret = true;
                } else {
                    document.getElementById("verif"+obj.id).className='verif nok';
                }
            } else if (funcVerif=="phone"){
                if (checkTel(obj)){
                    ret = true;
                    document.getElementById("verif"+obj.id).className='verif ok';
                } else {
                    document.getElementById("verif"+obj.id).className='verif nok';
                }
            } else if (funcVerif=="cellular"){
                if (checkCellular(obj)){
                    ret = true;
                    document.getElementById("verif"+obj.id).className='verif ok';
                } else {
                    document.getElementById("verif"+obj.id).className='verif nok';
                }
            } else if (funcVerif=="cp"){
                if (checkCP(obj)){
                    ret = true;
                    document.getElementById("verif"+obj.id).className='verif ok';
                } else {
                    document.getElementById("verif"+obj.id).className='verif nok';
                }
            } else if (funcVerif=="cpshort"){
                if (checkCPShort(obj)){
                    ret = true;
                    document.getElementById("verif"+obj.id).className='verif ok';
                } else {
                    document.getElementById("verif"+obj.id).className='verif nok';
                }
            } else if (funcVerif=="multiEmail"){
                if (checkMultiEmail(obj)){
                    ret = true;
                    document.getElementById("verif"+obj.id).className='verif ok';
                } else {
                    document.getElementById("verif"+obj.id).className='verif nok';
                }
            } else if (funcVerif=="date"){
                if (checkDate(obj)){
                    ret = true;
                    document.getElementById("verif"+obj.id).className='verif ok';
                } else {
                    document.getElementById("verif"+obj.id).className='verif nok';
                }
            } else if (funcVerif=="enableField"){
                ret = true;
            } else if (funcVerif=="disableTruefield"){
                if (disableTruefield()){
                    ret = true;
                }
            } else if (funcVerif=="password"){
                if (checkPass(obj)){
                    ret = true;
                    document.getElementById("verif"+obj.id).className='verif ok';
                } else {
                    document.getElementById("verif"+obj.id).className='verif nok';
                }
            } else if (funcVerif=="checkCategorie"){
                ret = true;
                //alert(obj.selectedIndex+"--"+obj.options[obj.selectedIndex].value);
                document.getElementById("item_categorieprev").style.display='none';
                document.getElementById("item_division").style.display='block';
                    document.getElementById("item_formation").style.display='none';
                if (obj.options[obj.selectedIndex].value == 6){
                    document.getElementById("item_categorieprev").style.display='block';
                } else if (obj.options[obj.selectedIndex].value > 6 && obj.options[obj.selectedIndex].value < 10){
                    document.getElementById("item_division").style.display='none';
                    document.getElementById("item_formation").style.display='block';
                }
            } else if (funcVerif=="verif_check"){
                if (verif_check(obj)){
                    ret = true;
                }
            }
        } else if (funcVerif=="disableTruefield"){
            if (disableTruefield()){
                ret = true;
            }
        } else if (!obligatory){
            ret = true;
            document.getElementById("verif"+obj.id).className='verif';
        }
    }
    return ret;
}

function hpo_forms_verifFields(form, nextpart, control){
    var i=0;
    bRet = true;
    
    document.getElementById('tcForm').value=nextpart;
    if (control){
        while (i<tField.length){
            obj = document.getElementById(tField[i]);
            bRet = bRet & hpo_forms_verif(obj, tFieldOblig[i], tFieldFunc[i]);
            i++;
        }
    }
    if (bRet){
        if (window.onSubmitRTE){
            onSubmitRTE();
        }
        form.submit();
    } else {
        alert("Veuillez renseigner les champs incorrects");
    }
}

/* ****************************************************************** */
/*                              AJAX                                  */
/* ****************************************************************** */
    
    
    // gestion des formulaires dans un calques
    var HpoBoxObj;
    var HpoBox = new Class({
        border: 0,

        initialize: function(boxWidth, boxHeight, masque, content) 
        {
            HpoBoxObj = this;
            
            this.boxWidth = boxWidth;
            this.boxHeight = boxHeight;
            
            this.win = $$("#"+masque);
            this.winContent = $$("#"+ content);
            this.closeLink = $$("#"+ content + ' .close');
            
            this.setPositions();
        },
        
        setPositions: function() 
        {
            
            // $$('select').setStyle('display', 'none');
            $$('#MAIN select').setStyle('display', 'none');
            
            // masque
            this.win.setStyle('height', window.getSize().size.y + window.getSize().scroll.y);
            this.win.setStyle('display', 'block');
            
            // forms
            this.boxTop  = ((window.getSize().size.y - this.boxHeight) / 2);
            this.winContent.setStyle('top', (window.getSize().scroll.y + this.boxTop));
            this.winContent.setStyle('margin-left', '-'+(this.boxWidth/2)+"px");
            //this.winContent.setStyle('height', this.boxHeight);
            this.winContent.setStyle('width', this.boxWidth);
            this.winContent.setStyle('display', 'block');
            
            
            this.win.addEvent('click', function()
            {
                HpoBoxObj.close();
            });
            this.closeLink.addEvent('click', function()
            {
                HpoBoxObj.close();
            });
            window.addEvent('keydown', function(e)
            {
                e = new Event(e);
                if ( e.key == 'esc' ){
                    HpoBoxObj.close();
                }
            });
            window.addEvent('scroll', function()
            {
                HpoBoxObj.onScroll();
            });
        },
        
        onScroll: function()
        {
            this.win.setStyle('height', window.getSize().size.y+window.getSize().scroll.y);
            this.winContent.setStyle('top', (window.getSize().scroll.y + this.boxTop));
        },
        
        close: function()
        {
             if (document.getElementById('refreshParent')){
                if (document.getElementById('refreshParent').value){
                    eval(document.getElementById('refreshParent').value);
                }
             }
                
            $$('select').setStyle('display', 'block');
            this.win.setStyle('display', 'none');
            this.winContent.setStyle('display', 'none');
            
        }

    });
    
    
    var globalUrl = null;
    var myBox = null;
    var myBigBox = null;
    function showAjaxPage(url){
        
        document.getElementById('hpo_masquecontent').className = '';
        document.getElementById('hpo_masquecontent').innerHTML = '';
        
        new Ajax(url, {
            method: 'get',
            onComplete: function()
            {
                var contentHTML = '<a href="#" class="calque_fermer" onclick="if(myBox) myBox.close(); return false;">X Fermer</a>' + this.response.text;
                $$('#hpo_masquecontent').setHTML(contentHTML);
                myBox = new HpoBox(500, 500, 'hpo_masque', 'hpo_masquecontent');
                myBox.boxHeight = document.getElementById('hpo_masquecontent').offsetHeight;
                myBox.setPositions(); 
                globalUrl = url;
            }
        }).request();
    }
    function showAjaxPageBigForm(url){
        document.getElementById('hpo_masquecontent').innerHTML = '';
        
        new Ajax(url, {
            method: 'get',
            onComplete: function()
            {
                var contentHTML = '<a href="#" class="calque_fermer" onclick="if(myBigBox) myBigBox.close(); return false;">X Fermer</a>' + this.response.text;
                $$('#hpo_masquecontent_big_form').setHTML(contentHTML);
                myBigBox = new HpoBox(650, 400, 'hpo_masque_big_form', 'hpo_masquecontent_big_form');
                globalUrl = url;
            }
        }).request();
    }
    
    function hpo_forms_ajaxSubmit(form, nextpart, control){        
        eval(document.getElementById('ajaxVerif').value);
        
        var i=0;
        bRet = true;
        
        document.getElementById('tcForm').value=nextpart;
        
        if (control){
            while (i<tField.length){
                obj = document.getElementById(tField[i]);
                bRet = bRet & hpo_forms_verif(obj, tFieldOblig[i], tFieldFunc[i]);
                i++;
            }
        }
        if (bRet){
            
            new Ajax(globalUrl, {
                postBody: form, 
                onComplete: function()
                {
                    var contentHTML = '<a href="#" class="calque_fermer" onclick="if(myBox) myBox.close(); return false;">Fermer X</a>' + this.response.text;
                    //form.getParent().getParent().setHTML(contentHTML);
                    if ( $$('#hpo_masquecontent').getStyle('display') == 'block' ){
                        $$('#hpo_masquecontent').setHTML(contentHTML);
                    } else if ( $$('#hpo_masquecontent_big_form').getStyle('display') == 'block' ){
                        $$('#hpo_masquecontent_big_form').setHTML(contentHTML);
                    }
                }
            }).request();
            
            /* marche pas sous ie6
            form.send({
                onComplete: function()
                {
                    form.parentNode.parentNode.innerHTML = this.response.text;
                }
            });*/
        } else {
            alert("Veuillez renseigner les champs incorrects");
        }
    }
    
    
var hpoform_curBulle = null;

function hideInfoBulle(obj)
{
    $(hpoform_curBulle).getParent().removeClass('info_bulle_actif');
    
    hpoform_curBulle.setStyle('display', 'none');

}

function showInfoBulle(obj){
    
    var test = $(obj).getParent().getElement('.info_bulle_content');
    
    if($(obj).getParent().getElement('.info_bulle')) {
        $(obj).getParent().getElement('.info_bulle').addClass('info_bulle_actif');
    } else {
        $(obj).getParent().addClass('info_bulle_actif');
    }
    
    
    // $(obj).getParent().getElement('.info_bulle').addClass('info_bulle_actif');
    
    if(hpoform_curBulle){
        hpoform_curBulle.setStyle('display', 'none');
        $(hpoform_curBulle).getParent().removeClass('info_bulle_actif');
    }
    
    test.setStyle('display', 'block');
    hpoform_curBulle=test;

    return true;
    
}
