/*##############################################################################
 
    Fonctions appelées dès la fin du chargement de la page

##############################################################################*/


$(document).ready(function() {

    // si le champ 'portOu' est présent dans la page...
    if ($('#portOu'))
    {
        $('#portOui').click(function()
        {
            $('#portOu').parent('div').slideDown(300);
        });

        $('#portNon').click(function()
        {
            $('#portOu').parent('div').slideUp(300);
        });
    }
    
    isMsgErr();
});




/*##############################################################################

    Classes et Fonctions liées aux formulaires

##############################################################################*/


/**
 *  Fonction appelée par le bouton 'Valider'
 */
function verifForm(idForm)
{
    var oFormulaire = new Formulaire(idForm);
    oFormulaire.verifChamps();
}


/**
 *  Fonction appelée par le bouton 'Effacer'
 */
function resetForm(idForm, laisseChamps)
{
    var oFormulaire = new Formulaire(idForm);

    if (laisseChamps == null)
    {
        oFormulaire.resetChampsTotal();
    }
    else
    {
        oFormulaire.resetChamps();
    }
}


/**
 *  CLASSE : 'Formulaire' permettant le traitement d'un formulaire HTML
 */
function Formulaire(idForm)
{
    /* propriétés privées */
    var oForm = $('#'+idForm);
    var blocErr = oForm.children('.msgErr:first');
    var msgErr = '';
    var mailOk = '';
    var textLabel = '';


    var aMsgErr = new Array();
    aMsgErr['login']     = 'Veuillez entrer votre login';
    aMsgErr['civ']       = 'Veuillez s&eacute;lectionner une civilit&eacute;';
    aMsgErr['nom']       = 'Veuillez entrer votre nom';
    aMsgErr['prenom']    = 'Veuillez entrer votre pr&eacute;nom';
    aMsgErr['password']  = 'Veuillez entrer votre mot de passe';
    aMsgErr['passconf']  = 'Veuillez entrer la confirmation de votre mot de passe';
    aMsgErr['pass_diff'] = 'Votre mot de passe ne correspond pas &agrave; sa confirmation';
    aMsgErr['mail']      = 'Veuillez entrer votre e-mail';
    aMsgErr['mailconf']  = 'Veuillez entrer la confirmation de votre e-mail';
    aMsgErr['mail_ko']   = 'Votre e-mail n\'est pas valide';
    aMsgErr['mail_diff'] = 'Votre e-mail ne correspond pas &agrave; sa confirmation';
    aMsgErr['adresse']   = 'Veuillez entrer votre adresse';
    aMsgErr['cp']        = 'Veuillez entrer votre code postal';
    aMsgErr['ville']     = 'Veuillez entrer votre ville';
    aMsgErr['tel']       = 'Veuillez entrer votre t&eacute;l&eacute;phone';
    aMsgErr['teldom']    = 'Veuillez entrer votre t&eacute;l&eacute;phone de domicile';
    aMsgErr['mobile']    = 'Veuillez entrer votre t&eacute;l&eacute;phone mobile';
    aMsgErr['port']      = 'Veuillez pr&eacute;ciser si OUI ou NON vous avez d&eacute;j&agrave; un portefeuille';
    aMsgErr['condition'] = 'Vous devez lire et accepter les conditions avant de continuer';
    aMsgErr['numCompte'] = 'Veuillez entrer votre num&eacute;ro de compte';
    aMsgErr['more']      = 'Veuillez préciser l\'objet de votre demande';
    aMsgErr['question']  = 'Veuillez poser votre question';
    aMsgErr['numFormation'] = 'Veuillez entrer au moins un num&eacute;ro de formation';
    aMsgErr['no_action'] = 'Veuillez préciser votre demande';
    aMsgErr['connu']     = 'Veuillez préciser comment vous avez connu Bourse Direct';
    aMsgErr['agence']    = 'Veuillez sélectionner une agence';
    aMsgErr['dateJouNaisTitu']  =   'Veuillez s&eacute;lectionner le jour de naissance';
    aMsgErr['dateMoiNaisTitu']  =   'Veuillez s&eacute;lectionner le mois de naissance';
    aMsgErr['dateAnnNaisTitu']  =   'Veuillez s&eacute;lectionner l\'année de naissance';
    aMsgErr['sitFam']    =  'Veuillez s&eacute;lectionner votre situation de famille';
    aMsgErr['captcha']    =  'Le code de s&eacute;curit&eacute; ne correspond pas &agrave; celui de l\'image';
    aMsgErr['theme']       = 'Veuillez s&eacute;lectionner un th&egrave;me';
    aMsgErr['date']       = 'Veuillez s&eacute;lectionner une date';
    aMsgErr['horaire']       = 'Veuillez s&eacute;lectionner une horaire';
    aMsgErr['client']      = 'Veuillez pr&eacute;ciser si OUI ou NON vous &ecirc;tes client Bourse Direct';
    aMsgErr['clientOnly']      = 'La formation que vous avez s&eacute;lectionn&eacute;e est r&eacute;serv&eacute;e aux clients, nous vous invitons &agrave; vous inscrire &agrave; une formation ouverte &agrave; tous. Cordialement, L\'&eacute;quipe Bourse Direct';
    /* propriétés publiques */
    this.id     = idForm;
    this.name   = oForm.name;
    this.action = oForm.action;
    this.method = oForm.method;

    /**
     *     Méthode PRIVEE : Affiche le message d'erreur
     */
    var showMsgErr = function()
    {
        if (msgErr == '' || !msgErr)
        {
            if (textLabel != '')
            {
                msgErr = 'Le champ "'+textLabel+'" est obligatoire';
            }
            else
            {
                msgErr = 'Ce champ (en rouge) est obligatoire';
            }
        }

        $('span', blocErr).html(msgErr);
        var Ht = $('span', blocErr).height();
        blocErr.slideDown();
    }

    /**
     *     Méthode PUBLIC : Vérifie tous les champs du formulaire
     */
    this.verifChamps = function()
    {
        
        captchaCookie=lit_cook('captchaCookie');
        
      
        //EcrireCookie('captchaCookieJs', 'oui');
        
        var aChamps = oForm.children("div[class^='champ']");

        for (var i=0; i<aChamps.length; i++)
        {
            var oChamp = new Champ(aChamps[i]);

            if ( ((!oChamp.isOblig()) || (!oChamp.visible)) && (oChamp.name != 'action') && (oChamp.name != 'connu'))
            {
                continue; // ne rien faire si le champ n'est pas obligatoire ou s'il est caché
            }
            else
            {
                textLabel = oChamp.textLabel;
                
                if (oChamp.value == '')
                {
                    msgErr = aMsgErr[oChamp.name];
                    showMsgErr();
                    oChamp.focusOn();
                    return false;
                }
                else if (oChamp.name == 'mail')
                {
                    if (!oChamp.checkMail())
                    {
                        msgErr = aMsgErr['mail_ko'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                    else {
                        mailOk = oChamp.value;
                    }
                }
                else if (oChamp.name == 'mailconf')
                {
                    if (oChamp.value != mailOk)
                    {
                        msgErr = aMsgErr['mail_diff'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'password')
                {
                    passOk = oChamp.value;
                }
                else if (oChamp.name == 'passconf')
                {
                    if (oChamp.value != passOk)
                    {
                        msgErr = aMsgErr['pass_diff'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'action')
                {
                    champAction = oChamp.value;
                    if (oChamp.value == 0)
                    {
                        msgErr = aMsgErr['no_action'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'connu')
                {
                    
                    if (oChamp.value == 0 && champAction!=2 && champAction!=3)
                    {
                        msgErr = aMsgErr['connu'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'connu2')
                {
                    if (oChamp.value == 0)
                    {
                        msgErr = aMsgErr['connu'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'agence')
                {
                    if (oChamp.value == 0)
                    {
                        msgErr = aMsgErr['agence'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'question')
                {
                    if (oChamp.value == 0)
                    {
                        msgErr = aMsgErr['question'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'captcha')
                {
                    if (MD5(oChamp.value.toUpperCase()) != captchaCookie)
                    {
                        msgErr = aMsgErr['captcha'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'theme')
                {
                    if (oChamp.value == 0)
                    {
                        msgErr = aMsgErr['theme'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                    else if (oChamp.value == 2 && $('#clientNon').attr('checked'))
                    {
                        msgErr = aMsgErr['clientOnly'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'date')
                {
                    if (oChamp.value == 0)
                    {
                        msgErr = aMsgErr['date'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
                else if (oChamp.name == 'horaire')
                {
                    if (oChamp.value == 0)
                    {
                        msgErr = aMsgErr['horaire'];
                        showMsgErr();
                        oChamp.focusOn();
                        return false;
                    }
                }
            }
        }
        oForm[0].submit();
        return true;
    }


    /**
     *     Méthode PUBLIC : Efface tous les champs du formulaire, cache la boite
     *                      de message uniquement.
     */
    this.resetChamps = function()
    {
        $('label', this.form).css('color', '#555')
        $(':input:not(:radio,:checkbox,:submit,:reset,:image,:button,:hidden)', this.form).css({'background-color':'white','border-color':'#24a'});

        $('form .msgErr').slideUp();
    }

    /**
     *     Méthode PUBLIC : Efface tous les champs du formulaire, cache la boite
     *                      de message et remet l'aspect par défaut de tous les
     *                      champs du formulaire.
     */
    this.resetChampsTotal = function()
    {
        $('label', this.form).css('color', '#555')
        $(':input:not(:radio,:checkbox,:submit,:reset,:image,:button,:hidden)', this.form).css({'background-color':'white','border-color':'#24a'});

        $('form .msgErr').slideUp();
        oForm[0].reset();
    }

}


/**
 *  CLASSE : 'Champ' permettant le traitement d'un formulaire HTML
 */
function Champ(champ){
    champ = $(champ);
    if (champ.children('input').length > 0)
    {
        this.input = champ.children('input:first');
        this.id    = champ.children('input:first').attr('id');
        this.name  = champ.children('input:first').attr('name');
        this.type  = champ.children('input:first').attr('type');
        this.textLabel  = champ.children('label:first').text();
        this.textLabel = this.textLabel.replace(/ \*+/g, "");

        if (this.type == 'radio')
        {
            var aRadios = $('input', champ);
            var check = false;

            for (var i=0; i<aRadios.length; i++)
            {
                if (aRadios[i].checked == true) { check = true; }
            }

            if (check == false)
            {
                this.value = '';
            }
            else
            {
                this.value = 'checked';
            }
        }
        else if (this.type == 'checkbox')
        {
            if ($('input', champ).is(':checked'))
            {
                this.value = 'checked';
            }
            else
            {
                this.value = '';
            }
        }
        else
        {
            this.value = champ.children('input:first').val();
        }
    }
    else if (champ.children('select').length > 0)
    {
        this.input = champ.children('select:first');
        this.id    = champ.children('select:first').attr('id');
        this.name  = champ.children('select:first').attr('name');
        this.type  = 'select';
        this.value = champ.children('select:first').val();
    }
    else if (champ.children('textarea').length > 0)
    {
        this.input = champ.children('textarea:first');
        this.id    = champ.children('textarea:first').attr('id');
        this.name  = champ.children('textarea:first').attr('name');
        this.type  = 'textarea';
        this.value = champ.children('textarea:first').val();
    }
    this.form  = champ.parent('form:first');
    this.label = champ.children('label:first');

    this.visible = true;
    if (champ.is(':hidden')) { this.visible = false; }


    /**
     *  Méthode PUBLIC : détermine si le champ est obligatoire ou pas
     *
     *  @return : (Boolean) VRAI si obligatoire sinon FAUX
     */
    this.isOblig = function()
    {
        if (this.label)
        {
            var texte = this.label.html().toLowerCase() + '';

            if (texte.search(/<b>\*<\/b>/) > -1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }


    /**
     *  Méthode PUBLIC : met le focus, avec surbrillance, sur le champ erroné
     */
    this.focusOn = function ()
    {
        // remet l'aspect par défaut de tous les champs du formulaire
        $('label', this.form).css('color', '#555')
        $(':input:not(:radio,:checkbox,:submit,:reset,:image,:button,:hidden)', this.form).css({'background-color':'white','border-color':'#24a'});
        if (this.label) { this.label.css('color', '#EB3E3E'); }

        if (this.type != 'radio')
        {
            var oInput = this.input;

            if (isIE6() || isIE7())
            {
                oInput.css('border', '1px red solid');
            }
            else
            {
                oInput.animate({
                    backgroundColor: '#ff8',
                    border: '3px red solid'
                    }, 300, 'linear',
                    function()
                    {
                        oInput.animate({
                            backgroundColor: '#fff',
                            border: '1px red solid'
                            }, 300);
                    }
                );
            }

            oInput.focus();
        }
    }

    /**
     *  Méthode PUBLIC : met le focus, avec surbrillance, sur le champ erroné
     *
     *  @return : (Boolean) VRAI si obligatoire sinon FAUX
     */
    this.checkMail = function()
    {
        if (this.value.indexOf('@',0) == -1 || this.value.indexOf('.',0) == -1)
        {
            return false;
        }
        else
        {
            return true;
        }
    }


}





/*##############################################################################

    Fonctions autonomes liées aux formulaires

##############################################################################*/


/**
 *  fait apparaitre le bloc de message d'erreur s'il est prérempli
 *  (message provenant du PHP)
 *
 *  @author : Denis THEVENOT
 *  @return: VOID
 */
function isMsgErr()
{
    $('form .msgErr').each(function(i)
    {
        if ($(this).children('span:first').html() != '')
        {
            $(this).slideDown();
        }
    });
}


function focusOn(oElement)
{
    aInputs = $('input');

    for(i=0; i<aInputs.length; i++)
    {
        if (aInputs[i].type == "submit" || aInputs[i].type == "reset" || aInputs[i].type == "radio") { continue; }
        aInputs[i].css('background-color', 'white');
        aInputs[i].css('border-color', '#a0a0a0');
    }

    if (oElement.type != 'radio')
    {
/*
        new Fx.Morph(oElement, {duration: 300, wait:false, onComplete: function () {
            new Fx.Morph(oElement, {duration: 300, wait:false}).start({});
        }}).start({});
*/
        oElement.animate({'background-color':'#ff8', 'border-width':'3px'}, 300, 'swing',
            function()
            {
                oElement.animate({'background-color':'#fff', 'border-color':'#f00', 'border-width':'1px'}, 300);
            }
        );
    }
    oElement.focus();
}


function checkMail(sMail)
{
    if (sMail.indexOf('@',0) == -1 || sMail.indexOf('.',0) == -1)
    {
        return false;
    } else {
        return true;
    }
}


function showMsgErr(sId, sTexte)
{
    var oBloc = $(sId);
    oBloc.children('p:first').html(sTexte);
    var Ht = oBloc.children('p:first').offsetHeight;
    toggleBloc(oBloc, Ht+20);
}

function EcrireCookie(nom, valeur)
{
    var argv=EcrireCookie.arguments;
    var argc=EcrireCookie.arguments.length;
    var expires=(argc > 2) ? argv[2] : null;
    var path=(argc > 3) ? argv[3] : null;
    var domain=(argc > 4) ? argv[4] : null;
    var secure=(argc > 5) ? argv[5] : false;
    document.cookie=nom+"="+escape(valeur)+
    ((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
    ((path==null) ? "" : ("; path="+path))+
    ((domain==null) ? "" : ("; domain="+domain))+
    ((secure==true) ? "; secure" : "");
}

function lit_cook(nom) {
      var deb,fin
      deb = document.cookie.indexOf(nom + "=")
      if (deb >= 0) {
         deb += nom.length + 1
         fin = document.cookie.indexOf(";",deb)
         if (fin < 0) fin = document.cookie.length
         return unescape(document.cookie.substring(deb,fin))
         }
      return ""
}
 
function refresh()
{
    var c_currentTime = new Date();
    c_miliseconds = c_currentTime.getTime(); 
    document.getElementById('imageCaptcha').src = '/streaming/captcha.php?x='+ c_miliseconds;
}
