function sendToActionScript(){
    var flash = document.getElementById("QUIZZ_2");
    flash.sendToActionScript();
}

function reloadQuizz()
{
    $('#reloadQuizz').click(function(){
        $( "#quizzContainer" ).empty();
        
        
        var url = window.location.pathname+'?reload=true'; 
        window.location  = url;
        
    });
}


$(function() {
    
    $("div#animation_poster").dialog({
        autoOpen: false,
        width: 800,
        height: 600,
        modal: true,
        disabled:true
    });

    $("a[href=/animation_poster/]").click(function() {
        animation_poster();
        return false;
    });
   
    $("#pdgVideo").live('click',function(){
        $( "#clo" ).css('background-color','#000');
        $( "#clo" ).parent().css('background','none');
        $( "#clo" ).dialog('open');
    });
    
    $( "#clo" ).dialog({
        autoOpen: false,
        width: 700,
        modal: true,
        disabled:true
    });

    $( "#dialogQuizz" ).dialog({
        autoOpen: false,
        width: 640,
        height: 600,
        modal: true,
        disabled:true
    });
    
    
    $( "#dp3Quizz" ).dialog({
        autoOpen: false,
        width: 640,
        height: 600,
        modal: true,
        disabled:true
    });
    $('#getQuizz').click(function(){
        f_quiz();
        $( "#dp3Quizz" ).dialog( "open" );
        return false; 
    });
    
    $('#idQuizzDp3').click(function(){
        var firstName   = $('#firstNameDp3').val();
        var lastName    = $('#lastNameDp3').val();
        var url         = '/ajaxDp3.php';
        
        if(firstName != "" && lastName != ""){
            $.ajax({
                url: url,
                data:{
                    action:'recordIdDp3',
                    firstName:firstName,
                    lastName:lastName
                }
            });
            $('#formQuizz').css('display','none');
            $('#quizzContainer').css('display','block'); 
        } else {
            $('#errorFormDp3').css('display','block');
        }
        return false;
    });
    

    function constructNewQuizzPopositions(type,data)
    {
        var html = '';
        switch(type){
		
            case('1'):
                html+='<tr>';
                html+='<td><input type="radio" name="choice" value="a" /></td>';
                html+='<td><label>'+data.qcm_a+'</label></td>';
                html+='</tr>';
                html+='<tr>';
                html+='<td><input type="radio" name="choice" value="b" /></td>';
                html+='<td><label>'+data.qcm_b+'</label></td>';
                html+='</tr>';
                html+='<tr>';
                html+='<td><input type="radio" name="choice" value="c" /></td>';
                html+='<td><label>'+data.qcm_c+'</label></td>';
                html+='</tr>';
                break;
			
            case('2'):
                html+='<tr>';
                html+='<td><input type="radio" name="choice" value="vrai" /></td>';
                html+='<td><label>Oui</label></td>';
                html+='</tr>';
                html+='<tr>';
                html+='<td><input type="radio" name="choice" value="faux" /></td>';
                html+='<td><label>Non</label></td>';
                html+='</tr>';
                break;
        }
        return html;
    }
    
    function validateQuizz(urlAjax)
    {
        var answer          = $('input[name=choice]:checked').val();
        var url             = urlAjax+'.php';
        var questionNumber  = parseInt($('#quizzQuestion').attr('rel')) - 1;
        
        
        
        if(typeof(answer)=='undefined'){
            $('p#errorQuizz').css('visibility','visible');
            return false;
        }else{
            $('p#errorQuizz').css('visibility','hidden');
        }
        
        $.ajax({
            url: url,
            data:{
                action:'nextStep',
                question:questionNumber
            },
            success: function(data){
                
                data = $.parseJSON(data);
                
                if(data.answer == answer)
                {
                    $('#titleAnswer').html('Bonne Réponse').css({
                        'color':'#00913D',
                        'font-size':'1.2em'
                    });
                    $('#imageAnswer').attr('src','/css/quizz/images/bonne_reponse.gif');
                    $('#goodAnswer').text('');

			
                    $.get(url, {
                        action:'getScore'
                    }, function(score) {
                        sendToActionScript();
                    });
                } else {
                    $('#titleAnswer').html('Mauvaise Réponse').css({
                        'color':'#D22127',
                        'font-size':'1.2em'
                    });
                    $('#imageAnswer').attr('src','/css/quizz/images/mauvaise_reponse.gif');
                    var goodAnswer = formatAnswer(data.answer);
                    $('#goodAnswer').text(goodAnswer);
                    
                }
                $('#quizzResponse').css('visibility','visible');
                $('#response').text(data.details);
                $('button#validateQuestions').css('visibility','hidden');
                
                if(urlAjax == "/ajaxDp3") {
                    $.ajax({
                        url: url,
                        data:{
                            action:'answerComparaison',
                            answerGiven:answer,
                            rightAnswer:data.answer,
                            question:questionNumber
                        }
                    //                        success: function(data){
                    //                            alert(data);
                    //                        }
                    });
                }
            }
        }); 
    }
	
    $('#validateQuestions').click(function(){
        var ajaxFile = $(this).attr('rel');
        if(ajaxFile=="ajaxDp3") {
            validateQuizz('/ajaxDp3');   
        }
        if(ajaxFile=="AjaxQuizz") {
            validateQuizz('/AjaxQuizz');
        }
        return false;
    });
    
    function formatAnswer (answer){
        switch(answer){
            case('a'):
                return 'La bonne réponse était la première proposition.';
                break;
            case('b'):
                return 'La bonne réponse était la deuxième proposition.';
                break;
            case('c'):
                return 'La bonne réponse était la troisième proposition.';
                break;
            case('vrai'):
                return 'La bonne reponse était oui.';
                break;
            case('faux'):
                return 'La bonne reponse était non.';
                break;
        }  
    }
			
    $('#nextQuestions').click(function(){
        var ajaxFile = $(this).attr('rel');
        if(ajaxFile=="ajaxDp3") {
            nextQuestion('/ajaxDp3');   

        }
        if(ajaxFile=="AjaxQuizz") {
            nextQuestion('/AjaxQuizz');
        }
        return false;
    });
    
    function nextQuestion(urlAjax)
    {
        $('button#validateQuestions').css('visibility','visible');
        var url                 = urlAjax+'.php';        
        var questionNumber	= parseInt($('#quizzQuestion').attr('rel'));
        var nbStep              = $('table#qcm tr td.imageQuizz img').length;
        var answer              = $('input[name=choice]:checked').val();
        if(typeof(answer)=='undefined')
        {
            $('p#errorQuizz').css('visibility','visible');
            return false;
        }
        else
        {
            $('p#errorQuizz').css('visibility','hidden');
        } 
        $.ajax({
            url: url,
            data:{
                action:'nextStep',
                question:questionNumber
            },
            success: function(data) 
            {
                data            = $.parseJSON(data);
                questionNumber 	= questionNumber + 1;

                $('table#qcm tr td.imageQuizz img').each(function(index){
			  			
                    index = index +1;
			  				
                    if(index == questionNumber)
                    {
                        $(this).attr('src','/css/quizz/images/question_on_'+index+'.gif');
                    }
                    else
                    {
                        $(this).attr('src','/css/quizz/images/question_off_'+index+'.gif');
                    }
                });
                var text = '';
                if (questionNumber > 10) {
                    $('#swfContainer').empty();
                    var html = '';
                    if(data==0){
                        
                        text = 'Vous pouvez recommencer!';
                    } else if (data> 0 && data<=5) {
                        text = 'Vous pouvez surement mieux faire!';
                    } else if(data> 5 && data<=8) {
                        text = 'Vous êtes dans la bonne moyenne!';
                    } else if (data> 8 && data<10) {
                        text = 'Vous avez presque atteint le score parfait!';
                    } else if (data==10) {
                        text = 'Bravo, votre score est parfait!';
                    }
                    html+='<div id="finalballon"><img src="/css/quizz/images/ballon_'+data+'.png" /></div>';
                    if (urlAjax == "AjaxQuizz") {
                        html+='<div id="finalResults"><p id="finalResponse">'+text+'</p><button id="reloadQuizz"></button></div>';
                        $('.bodyQuizz').html(html);
                        reloadQuizz(); 
                    }else{
                        html+='<div id="finalResults"><p id="finalResponse">'+text+'</p><p><span  id="getPdf">Imprimez vos résultats en cliquant sur l\'icône  </span><img id="getResultDp3" width=20 src="/css/quizz/images/pdf.png"/></p></div>';
                        $('.bodyQuizz').html(html);
                        
                        $("#getResultDp3").click(function(){
                            //var url    = window.location.pathname+'mod/sub_dp3.php?action=resultDp3Pdf'; 
                            var url    = '/mod/sub_dp3.php?action=resultDp3Pdf';
                             
                            //                             url        = url.replace('index.php','');
                            window.location  = url;
                            return false;
                        });
                    }
                    $('.bodyQuizz').append('<div style="clear:both;"></div>');
                }
                else
                {
                    var type = data.type;
                    var newPropositions = constructNewQuizzPopositions(type,data);
                    $('#tablePropositions').html(newPropositions);
                    $('#quizzQuestion').attr('rel',questionNumber).text(data.question);
                }
                $('#quizzResponse').css('visibility','hidden');

            }
        },'json');
    }
    
    var icons = {
        header: "ui-icon-triangle-1-e",
        headerSelected: "ui-icon-triangle-1-s"
    };
    var accentMap = {
        "à": "a",
        "ö": "o",
        "ô": "o",
        "ï": "i",
        "î": "i",
        "é": "e",
        "è": "e",
        "ê": "e",
        "ë": "e",
        "ù": "u",
        "û": "u",
        "ü": "u",
        "ç": "c"
    };
    var normalize = function( term ) {
        var ret = "";
        for ( var i = 0; i < term.length; i++ ) {
            ret += accentMap[ term.charAt(i) ] || term.charAt(i);
        }
        return ret;
    };
    $( "#tags" ).autocomplete({
        minLength: 3,
        source: function(request, response) {
            $.getJSON("/post/research.php?term="+request.term, function(data) {
                var items = [];
                var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" );
                $.each(data, function(key, val) {
                    var temp = [];
                    temp['id'] = val.id;
                    temp['url'] = val.url;
                    temp['value'] = $.grep( eval('["'+val.value+'"]'), function( value ) {
                        value = value.label || value.value || value;
                        return matcher.test( value ) || matcher.test( normalize( value ) );
                    }).toString();
                    items.push(temp);
                });
                response(items);
            });
        },
        select: function(event, ui){
            window.location.href = ui.item.url;
        },
        close : function(event, ui){
            $(this).val('');
            $(this).hide();
        }
    });
    $( "#accordion" ).accordion({
        header: 'h1',
        icons: icons,
        autoHeight: false,
        navigation: true,
        collapsible: true
    });
    $( "#formation" ).accordion({
        active: false,
        header: 'h1',
        icons: icons,
        autoHeight: false,
        navigation: true,
        collapsible: true
    });
    $("#formation").click(function() {
        if ($("#accordion h1 a[href=#section2]").parent().next('div').css('display') == 'none') {
            $("#accordion h1 a[href=#section2]").click();
        }
    })
    $("#gest1_bt_agenda_ml").datepicker({
        dayNamesMin:['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
        monthNames:['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Decembre'],
        minDate: 0,
        onSelect: function(dateText, inst) {
            $("#gest1_bt_agenda_ctn").val(dateText);
        }
    });
    $("#gest2_bt_agenda_ml").datepicker({
        dayNamesMin:['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
        monthNames:['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Decembre'],
        minDate: 0,
        onSelect: function(dateText, inst) {
            $("#gest2_bt_agenda_ctn").val(dateText);
        }
    });
	
    $("#taskspt").click(function() {
        $("#tasksp").slideToggle("slow");
    });
    $("#natspt").click(function() {
        $("#natsp").toggle();
    });
    $("#qualspt").click(function() {
        $("#qualsp").toggle();
    });
    $("#careerspt").click(function() {
        $("#careersp").toggle();
    });
    $("#associst").click(function() {
        $("#associs").toggle();
    });
    $("#6110-3espt").click(function() {
        $("#6110-3esp").toggle();
    });
    $("#6120-1espt").click(function() {
        $("#6120-1esp").toggle();
    });
    $("#6120-2espt").click(function() {
        $("#6120-2esp").toggle();
    });
    $("#6120-3espt").click(function() {
        $("#6120-3esp").toggle();
    });
    $("#6120-4espt").click(function() {
        $("#6120-4esp").toggle();
    });
    $("#6130-2espt").click(function() {
        $("#6130-2esp").toggle();
    });
    $("#menu_9").click(function() {
        $("#menu_9 a > input").css('display', 'block');
        $("#menu_9 a > input").focus();
    });


    // Toggle pages
    $(document).ready(function(){
        $('.acc_container').hide();
        //$('.acc_trigger:first').addClass('active').next().show();
		 
        //On Click
        $('.acc_trigger').click(function(){
            if( $(this).next().is(':hidden') ) {
                $('.acc_trigger').removeClass('active').next().slideUp();
                $(this).toggleClass('active').next().slideDown();
            }else{
                $(this).toggleClass('active').next().slideUp();
            }
            return false;
        });
    });


    $("#etape1 input").live('click', function() {
        var form = $(this).siblings('label').text();
        $.post("/mapselector.php", {
            form: form
        }, function (data) {
            if (data.length > 0) {
                $("#etape2 #content2").html(data);
            }
        });

        $.post("/map_breadcrumb.php", {
            step: 2
        }, function(datastep2) {
            $("#mapcrumb2").html(datastep2);
        });
    });

    $("#etape1 input.step").live('click', function() {
        var n = $("#etape1 input[type=radio]:checked").length;
        if (n > 0) {
            $("#etape1").toggle();
            $("#etape2").toggle();
        } else {
            alert('Veuillez séléctionner une formation pour pouvoir acceder à l\'étape suivante');
        }
    });

    $("#etape2 input").live('click',function() {
        var mode = $(this).siblings('label').text();
        $.post("/mapselector.php", {
            mode: mode
        });
        $.post("/map_breadcrumb.php", {
            step: 3
        }, function(datastep3) {
            $("#mapcrumb3").html(datastep3);
        });
    });

    $("#etape2 input.step").live('click', function() {
        var n = $("#etape2 input[type=radio]:checked").length;
        if (n > 0) {
            $("#etape2").toggle();
            $("#etape3").toggle();
        } else {
            alert('Veuillez séléctionner un mode de formation pour pouvoir acceder à l\'étape suivante');
        }
    });

    $("#mapfrance area").click(function() {

        var ref = $(this).attr('href');
        $.post("/mapselector.php", {
            href: ref
        }, function(data) {
            if (data == 'visible') {
                $(ref).css('visibility', 'visible');
                $(ref+'_info').css('display', 'block');
                $(ref+'_info').html('Chargement en cours');
                $.post("/map_step3.php", {
                    href: ref
                }, function(data3) {
                    $(ref+'_info').html(data3);
                });
            } else if (data == 'hidden') {
                $(ref).css('visibility', 'hidden');
                $(ref+'_info').css('display', 'none');
                $(ref+'_info').html('');
            }
        });
    });

    $("#etape3 input.step").click(function() {
        var n = $("#etape3 #etabl div ul").length;
        if (n > 0) {
            $.post("/map_breadcrumb.php", {
                step: 4
            }, function(datastep4) {
                $("#mapcrumb4").html(datastep4);
            });
            $("#etape3").toggle();
            $.post("/map_step4.php", {
                bs: 'bs'
            }, function(data4) {
                $("#etape4 #content4").html(data4);
            });
            $("#etape4").toggle();
        } else {
            alert('Veuillez séléctionner au moins une région pour pouvoir acceder à l\'étape suivante');
        }
    });

    $("#etape3 span.tout").click(function() {
        $("#mapfrance area").each(function() {
            if ($($(this).attr('href')).css('visibility') == 'hidden') {
                $(this).click();
            }
        });
        $("#etape3 span.tout").toggle();
        $("#etape3 span.rien").toggle();
    });

    $("#etape3 span.rien").click(function() {
        $("#mapfrance area").each(function() {
            if ($($(this).attr('href')).css('visibility') == 'visible') {
                $(this).click();
            }
        });
        $("#etape3 span.tout").toggle();
        $("#etape3 span.rien").toggle();
    });

    $("#show_parcours").click(function() {
        $( "#view_parcours" ).dialog({
            title: "Parcours complet",
            modal: true,
            width: 850,
            buttons: {
                Fermer: function() {
                    $(this).dialog( "close" );
                }
            }
        });
    });
    $("#video_prev").click(function() {
        $.post('/videos_slide.php', {
            previous: true
        }, function(data) {
            if (data) {
                $("#videos").html(data);
            }
        });
    });
    $("#video_next").click(function() {
        $.post('/videos_slide.php', {
            next: true
        }, function(data) {
            if (data) {
                $("#videos").html(data);
            }
        });
    });
    $('#videos img').live('mouseover mouseout', function(event) {
        if (event.type == 'mouseover') {
            var vign = $(this).attr('name');
            $.post('/videos_slide.php', {
                hover: vign
            }, function(data) {
                if (data) {
                    $("#vid_hover").html(data);
                }
            });
        } else {
            $("#vid_hover").html("");
        }
    });
    $('#videosp').live('click', function() {
        $.post('/videos_slide.php', {
            dialog: true
        }, function(data) {
            if (data) {
                $("#view_video").html(data);
                select('');
            //                $("#v_selected embeds").Stop();
            }
        });
        $( "#view_video" ).dialog({
            modal: true,
            width: 665,
            height: 460,
            resizable: false,
            dialogClass: 'allblack',
            buttons: {
                Fermer: function() {
                    $(this).dialog( "close" );
                }
            }
        });
    });
});

function supprime(ref) {

    $.post("/mapselector.php", {
        href: ref
    }, function(data) {

        if (data == 'visible') {
            $(ref).css('visibility', 'visible');
            $(ref+'_info').css('display', 'block');
            $(ref+'_info').html('Chargement en cours');
            $.post("/map_step3.php", {
                href: ref
            }, function(data3) {
                $(ref+'_info').html(data3);
            });
        } else if (data == 'hidden') {
            $(ref).css('visibility', 'hidden');
            $(ref+'_info').css('display', 'none');
            $(ref+'_info').html('');
        }
    });
}

function gotoStep(from, to) {
    if (from == 3 || (from == 4 && to != 3)) {
        $("#mapfrance area").each(function() {
            if ($($(this).attr('href')).css('visibility') == 'visible') {
                $(this).click();
            }
        });
        $("#etape3 span.tout").css('display', 'block');
        $("#etape3 span.rien").css('display', 'none');
    }
    $("#etape"+from).toggle();
    $("#etape"+to).toggle();
}

function select(v) {
    $.post('/videos_slide.php', {
        select: v
    }, function(data) {
        if (data) {
            $("#v_selected").html(data);
            $.post('/videos_slide.php', {
                refresh: true
            }, function(data) {
                if (data) {
                    $("#videos").html(data);
                }
            });
        }
    });
}

function actuDay(div,day){
    $.post('/post/agenda.php', {
        jour: day
    }, function(data) {
        if (data) {
            $("#"+div+"_bt_agenda_ctn").html(data);
        }
    });
}

function Affich_ActuDr(id_dr){
    $("#map_actu_reg").attr('src', '/img/img_home/actu_region_'+id_dr+'.gif');
    
    infos = '';
    $.getJSON(encodeURI('/info_regions.php?dr='+id_dr), function(data) {
        $.each(data, function(index, value) {
            infos += '>> '+value['title']+'<br /><br />';
        });
        $("div#infoRegions").html(infos);
    });
}

function Affich_ActuDrIn(id_dr){
    $("#map_actu_reg").attr('src', '/img/img_pages/actu_region_'+id_dr+'.gif');
    
    infos = '';
    $.getJSON(encodeURI('/info_regions.php?dr='+id_dr), function(data) {
        $.each(data, function(index, value) {
            infos += '>> '+value['title']+'<br /><br />';
        });
        $("div#infoRegions").html(infos);
    });
}

function verif_Ctt(frm){
    switch(frm) 
    {
        case 'frm_conseiller':
            var $msg = "";
		
            //Verification de la structure de l'adresse mail
            var adresse = document.forms[frm].adr_mail.value;
            var place = adresse.indexOf("@",1);
            var point = adresse.indexOf(".",place+1);
            if ((place > -1)&&(adresse.length >4)&&(point > 1)) {
            }
            else
            {
                $msg= " - Adresse e-mail non valide   \n";
            }
            if (document.forms[frm].message.value==''){
                $msg +=" - Veuillez saisir un message\n";
            }
            if ($msg==''){
                return true;
            }else{
                alert("Le formulaire est incomplet.\nMerci de vérifier les informations ci-dessous : \n\n"+$msg);
                return false;
            }

            break;
    }
}

function carte_france(id,libelle){
    // Gestion des cartes : Rechercher un lieu de formation
    var carte = document.getElementById("Map");
    var region = document.getElementById("region_nom");
	
    carte.src="/imgs/cartes/r_"+id+".gif";
    region.innerHTML = libelle;
}
function carte_france_reset(){
	
    var carte = document.getElementById("Map");
    var region = document.getElementById("region_nom");
    carte.src="/imgs/cartes/france.gif";
    region.innerHTML="&nbsp;";
}

function carte_departement(id_departement,id_region,libelle){
    // Gestion des cartes : Département
    var carte = document.getElementById("MapRegion");
    var departement = document.getElementById("departement_nom");
    carte.src="/imgs/cartes/regions/"+id_region+"/d_"+id_departement+".gif";
    departement.innerHTML = libelle;
    document.forms['frm_etape2'].id_departement.value = id_departement;
    document.forms['frm_etape2'].id_region.value = id_region;
    document.forms['frm_etape2'].submit();
}

function valid_formation_etape2(){
    if (document.forms['frm_etape2'].id_departement.value ==''){
        alert("Vous devez sélectionner un département sur la carte de la région");
    }else{
        document.forms['frm_etape2'].submit();
    }
}

function f_quiz()
{
    var flashvars = {};
    var params = {};
    var attributes = {};
    attributes.id = "QUIZZ_2";
    attributes.name = "QUIZZ_2";
    attributes.allowscriptaccess = "always";
    swfobject.embedSWF("/swf/QUIZZ_2.php", "embedballon", "120", "402", "9.0.0", false, flashvars, params, attributes);
    $( "#dialogQuizz" ).dialog( "open" );
    $('head').append('<link rel="stylesheet" type="text/css" href="/css/quizz/jquery-ui-1.8.9.custom.css" />');
}

function animation_poster() {
    var flashvars = {};
    var params = {};
    var attributes = {};
    attributes.id = "animation_poster";
    attributes.name = "animation_poster";
    swfobject.embedSWF("/swf/poster/poster_anfa_5.swf", "animation_poster_embed", "742", "526", "9.0.0", false, flashvars, params, attributes);
    $("div#animation_poster").dialog("open");
    $('head').append('<link rel="stylesheet" type="text/css" href="/css/quizz/jquery-ui-1.8.9.custom.css" />');
}

function f_video(name) {
    $.post('/videos_slide.php', {
        dialog: true,
        file: name
    }, function(data) {
        if (data) {
            $("#view_video").html(data);
            //$("#AutoPlay").lecture_js('play');
            select('');
        }
    });
    $( "#view_video" ).dialog({
        modal: true,
        width: 665,
        height: 460,
        dialogClass : 'allblack',
        resizable:false,
        buttons: {
            Fermer: function() {
                $(this).dialog( "close" );
                $(this).html('');
            }
        }
    });
    

  
    
}

