﻿var IntNbFmt = 0;

//Récupère les formations et les options sélectionnées
function GetSelectFormations(designation) {
    var i;
    var checked = true;
    var chkname = document.getElementsByTagName("input");
    var n = chkname.length
    var value = '';
    var libelle1 = '';
    var libelle2 ='';
    var len=0    
    //Initialiser les champs
    document.getElementById('F_Fmt').value = designation;
    document.getElementById('F_FmtHidden').value = ''

    // Boucle sur les champs de type checkbox contenu dans la page
    for (i = 0; i < n; i++) {
        var control = chkname[i];
        var name = control.id;
        var j = name.indexOf('F_CheckFmt');

        //
        if ((control.type == "checkbox" && (j != -1))) {
            if (control.checked) {                
                //Retrouve la valeur du label du checkbox selectionné
                value = $('#F_FmtHidden').val() + control.title + '; ';
                $('#F_FmtHidden').attr('value', value);
                var children = control.id.replace('CheckBox', '').replace('n', 't');
                // Seulement les formations
                var title = $('#' + children).attr('title');
                if (title.indexOf("!") < 0) {
                    libelle1 += '<li>' + $('#' + children).html() + '</li>';
                }
                else {
                    libelle1 += '<li class="opt">' + $('#' + children).html() + '</li>';
                }
            }
        }
    }

    $('#CtrFmt_F_Fmt').show()
    $('.FmtSelected').empty();
    if ($('#F_FmtHidden').val() != '') {
        // Ajoute les formations sélectionnées  //
        $('.FmtSelected').append('<fieldset><legend>Formation(s) sélectionnée(s)</legend><div><ul>' + libelle1 + '</ul></div></fieldset>');
        $('#F_Fmt').attr('value', 'Cliquer ici pour modifier votre choix')
        // Controle la page
        Page_ClientValidate();
    }
        
}

// Afficher ou masque la liste des formations
function DisplayDiv(id, SelectSitPro, SelectDip, SelectMed,SelectMotCon) {
    //---  Position combo situation professionnelle
    var pos = $('#F_SitPro').offset()
    var width = $('#F_Fmt').width()
    //---  definit la position de la liste des formations
    $(id).css({ "top": pos.top, "left": ((pos.left-35) - (width / 2)) }) 
    // --- Cache ou affiche la liste
    $(id).toggle();
    // --- suivant     
    if ($(id).css("display") == "none") {
        $(SelectSitPro).css("visibility", "visible"); $(SelectDip).css("visibility", "visible"); $(SelectMed).css("visibility", "visible");
        //$(SelectMotCon).css("visibility", "visible")
    }
    else {
        $(SelectSitPro).css("visibility", "hidden"); $(SelectDip).css("visibility", "hidden"); $(SelectMed).css("visibility", "hidden");
        //$(SelectMotCon).css("visibility", "hidden")
        }

}

// Calendrier
function calendarShown(sender, e) { sender._switchMode("years");}

// Affiche le support
function loadSupport(value) {
    var FirstPassage = true;
    var InfosMedia;
    
    
    if (value != -1) {
        $('#RowSup').show();
        // Initialise le support
        $('#F_CloneSup').children().each(function() { $(this).clone().appendTo('#F_Sup'); })
        // récupère seulement le média
        InfosMedia = value.split("|")
        // Supprime les zone
        $('#F_Sup').children().each(function() {
        if (this.value.substring(0, InfosMedia[0].length) != InfosMedia[0] && !FirstPassage) {
                $(this).remove();
            }
            else { if (this.value == -1) { FirstPassage = false; } }
        })
    }
    else $('#RowSup').hide();
}

// Controle la saisie du télephone
var ValidatePhone = function(source, args) {
    var Tel;

    if ($('#F_Tel1').val() == '' && $('#F_Tel2').val() == '') { args.IsValid = false; return; }
    // Par défaut c'est Ok
    $('#F_Tel1').removeClass("Err");
    $('#F_Tel2').removeClass("Err");

    // Pays
    var pays = $('#F_Pay').val();
    var codPos = $('#F_CodPos').val();
    // Appliquer le format numérique //
    if (args.Value != '') {
        Tel = args.Value.replace(/[\/ .]/g, "");
        // Numérique
        if (isNaN(Tel)) { args.IsValid = false; return false };
        // Longueur France
        if (pays == 'FRA' && Tel.length < 10) {
            // COntrole DOM TOM
            if (!isNaN(codPos) && codPos.length>1) {
                if (codPos.substring(0,2) > 96 && Tel.length > 5) { args.IsValid = true;return true } 
            }
            args.IsValid = false; return false
        };
        //$('#' + source.controltovalidate).removeClass("Err");
    }
    args.IsValid = true;
}

// Controle saisie voie
var ValidateVoie = function(source, args) {  
    // Travail avec des variables locales 
    var NumVoi = trim($('#F_NumVoi').val());
    var Voi = trim($('#F_Voi').val());

    // Supprimer la chaine par defaut
    if (Voi.indexOf('Merci') == 0) { Voi = '' }

    // controle
    if (NumVoi != '' && Voi == '') { args.IsValid = false; return false; }
    
    // controle OK
    args.IsValid = true;
    
    // Retirer la classe erreur
    $('#F_Voi').removeClass("Err");
    return true;
} 


// Calculer la longueur de l'observation
function CalObsCon() {
  var iLongueur, iLongueurRestante;
  iLongueur = document.getElementById('F_ObsCon').value.length;
  if (iLongueur > 1000) {
    document.getElementById('F_ObsCon').value = document.getElementById('F_ObsCon').value.substring(0, 1000);
    iLongueurRestante = 0;
  }
  else {
    iLongueurRestante = 1000 - iLongueur;
  }
    document.getElementById('F_ObsConInd').innerHTML = '(' + iLongueurRestante + ' caractères restants)';
}

// Controler le nombre de formations choisies
function CheckFmt() {
    IntNbFmt = 0;
    $('#F_Mes').html(' (3 formations max.)')
    $('#F_ValFmt').show();
    // Affiche les options sur le clik de la formation
    $('#F_PanelContainer :checkbox').each(function() {
        var title = $(this).attr('title');
        if (title.indexOf("!") < 0) {
            if ($(this).attr('checked')) {
                IntNbFmt = IntNbFmt + 1;
            }
        }
    })

    //Message
    if (IntNbFmt > 3) { $('#F_ValFmt').hide(); $('#F_Mes').html('Vous ne pouvez pas choisir plus de 3 formations') }
    
}

// Declenchement au démarrage
$(document).ready(function() {
    // Mettre en majuscule les zones Nom, Prenom, Ville
    $('#F_Nom').blur(function() { var value = $(this).val(); $('#F_Nom').attr('value', value.toUpperCase()) })
    $('#F_Pre').blur(function() { var value = $(this).val(); $('#F_Pre').attr('value', value.toUpperCase()) })
    $('#F_Vil').blur(function() { var value = $(this).val(); $('#F_Vil').attr('value', value.toUpperCase()) })

    // Zone NUméro de voie
    $('#F_NumVoi').blur(function() { $('#F_Voi').focus(); })

    // Mettre en forme le texte
    $('.PanCooAid').focus(function() {
        var value = $(this).val();
        if (value.indexOf("Merci") == 0) {
            $(this).toggleClass('PanCooAidFoc');
            $(this).attr('value', '');
        }
    })

    // Mettre en forme le texte
    $('.PanCooAid').blur(function() {
        var value = $(this).val();
        if (value.length == 0) {
            $(this).toggleClass('PanCooAidFoc');
            $(this).attr('value', $(this).attr('title'));
        }
    })


    // Affiche les options sur le clik de la formation 
    $('#F_PanelContainer :checkbox').each(function() {
        var title = $(this).attr('title');
        if (title.indexOf("!") < 0) {
            var Nodes = $(this).attr("id").replace('CheckBox', 'Nodes')
            $(this).click(function() {
                $('#' + Nodes).show();
                //Controler nombre de formations
                CheckFmt();

                if (!$(this).attr('checked')) {
                    // Rechercher les enfants de la node sélectionné  
                    $('#F_PanelContainer :checkbox').each(function() {
                        if (title == $(this).attr('title').substring(0, title.length)) {
                            $(this).attr('checked', false)
                            return;
                        }
                    })
                }
            })
        }
    })

    // Coche automatiquement la formation si on clique sur une option
    $('#F_PanelContainer :checkbox').each(function() {
        var title = $(this).attr('title');
        // Rechercher les nodes
        if (title.indexOf("!") > 0) {
            var Fmt = $(this).attr("title").split("!")[0]
            $(this).click(function() {
                if ($(this).attr('checked')) {
                    // Rechercher le parent de la node sélectionné  
                    $('#F_PanelContainer :checkbox').each(function() {
                        if (Fmt == $(this).attr('title')) {
                            $(this).attr('checked', 'checked')
                            return;
                        }
                    })
                }

                //Controler nombre de formations
                CheckFmt();
            })
        }
    })

    // Tracker
    $("form").submit(function() {
        if (!Page_IsValid) {
            TrackerPage('EnvoyerClickNonValide')
        }
        else {
            // Eviter la multi validation
            $('.BtnVal').attr("disabled", "disabled");   
            TrackerPage('EnvoyerClickValide')
       }     
    })
   // tracker Load
    TrackerPage('LoadedFormBas');
});


// Tracker
function TrackerPage(command) {
       var xhr_object = null; 
     
       if(window.XMLHttpRequest) // Firefox 
          xhr_object = new XMLHttpRequest(); 
       else if(window.ActiveXObject) // Internet Explorer 
          xhr_object = new ActiveXObject("Microsoft.XMLHTTP");

      // Envoie la trace
      try
      {
          xhr_object.open("GET", 'service/Tracking/' + command, true);
          xhr_object.send(null);
      }
      catch (e) { }       
}

function trim(myString) {
    return myString.replace(/^\s+/g, '').replace(/\s+$/g, '')
}

        
           