$(document).ready(function(){

    $("button", $("#searchForm")).click(function(){
        window.location.href = "/fr/index/recherche/q/" + Url.encode($("#key", $("#searchForm")).val());
    });

    $("#searchForm").submit(function(){
        window.location = $(this).attr("action") + "/q/" + $("#key").val();
        return false;
    });	
	
    if($(".news-slide").length){
        $(".news-slide").lofJSidernews({
            direction:"opacity",
            easing:"easeInOutSine"
        }
        );
    }
	
    if($("#slides").length){
        // Set starting slide to 1
        var startSlide = 1;
        // Get slide number if it exists
        if (window.location.hash) {
            startSlide = window.location.hash.replace('#','');
        }
        // Initialize Slides
        $('#slides').slides({
            preload: true,
            generatePagination: true,
            play: 5000,
            pause: 2500,
            hoverPause: true,
            // Get the starting slide
            start: startSlide,
            /*animationComplete: function(current){
                // Set the slide number as a hash
                window.location.hash = '#' + current;
            }*/
        });
    }
			
	
    if($(".show-description").length){
        $(".show-description").click(function(){
            //$(".slide-description").toggle();
            $(this).parent().parent().prev().toggle();
            return false;
        })
    }

    if($("#accordion-hp").length){
        $("#accordion-hp h3").click(function() {
            if ($(this).hasClass("disable")){
                $(this).removeClass("disable").addClass("enable");
            } else {
                $(this).removeClass("enable").addClass("disable")
            }
            $(this).next().toggle();
            return false;
        });
    }

    if($("#close-banner").length){
        $("#close-banner").click(function(){
            $(".banner-container").toggle();
        });
    }

    $(".log-tabs a").click(function(){
        $(".log-block > div", $(this).parent().parent()).hide();
        $(".content-" + $(this).attr("rel"), $(this).parent().parent()).show();
        $("a", $(this).parent()).removeClass("active");
        $(this).addClass("active");
    });

    if( $("#tabs").length ){
        $("#tabs").tabs();
    }
    if( $("#accordion").length ){
        $("#accordion").accordion({
            autoHeight: false
        });
    }

    if($("#ville_pharmacie").length > 0){
        $("#ville_pharmacie").change(function(){
            $.ajax({
                url: $("#pharmacieUrl").val(),
                type: "POST",
                data: "format=json&ville=" + $(this).val(),
                success : function( response ){
                    var options = '<option value="">--Quartiers--</option>';
                    for( var i in response.quartiers ){
                        options += '<option value="' + response.quartiers[i].id_quartier + '">' + response.quartiers[i].nom_quartier + '</option>';
                    }
                    $("#quartier_pharmacie").html(options);
                }
            });
        });
    }

    /* Pascal :: Menu du jour */
    if( $("#zoneProgramme").length ){
        $("ul#menuProgramme > li > a").click(function(){
            $("#dateChoisie").html($(this).attr("datecourante"));
            $.blockUI({
                message:"<div><h2>Merci de patienter ...</h2></div>",
                css: {
                    backgroundColor: "#f00",
                    color: "#fff"
                }
            });
            $.ajax({
                url: $("#baseUrl").val() + "/fr/ajax/grilledesprogrammes",
                type: "POST",
                dataType: "xhtml",
                data: $(this).next().val(),
                success: function(response) {

                    $("#zoneProgramme").html(response);
                    $.unblockUI();
                }
            });
        })
    }
    /* End Pascal */

    /* Carousel Communauté */
    if( $("#myController").length ){
        $("#myController").jFlow({
            slides: "#slides",
            controller: ".jFlowControl", // must be class, use . sign
            slideWrapper : "#jFlowSlide", // must be id, use # sign
            selectedWrapper: "jFlowSelected",  // just pure text, no sign
            auto: true,		//auto change slide, default true
            width: "224px",
            height: "170px",
            duration: 400,
            prev: ".jFlowPrev", // must be class, use . sign
            next: ".jFlowNext" // must be class, use . sign
        });
    }

    /* Fin Carousel Communaute */
    $("#searchParmacie").click(function(){
        var ville =  $("#ville_pharmacie").val();
        var quartier = $("#quartier_pharmacie").val();
        var baseUrl = $("#baseUrl").val();
        window.location = Url.encode( baseUrl + "/fr/loisirs/pharmacies/pharmaciesdegarde/ville/" + ville + "/quartier/" + quartier);
    });

    /*
     * Pooling Module
     * @auth Hassan Qorchi <hqorchi@extensys.ma>
     */
    $("#search_pooling_module").click(function(){
        $.ajax({
            type : "POST",
            url :  $("#poolingForm").attr("action"),
            data : $("#poolingForm").serialize(),

            success : function(response){
                var html = "";

                for( var i in response ){
                    html += '<div class="rating"><label>' + response[i].reponse + ' </label><div class="graph" style="width:285px;"><strong class="bar" style="width:' + response[i].pourcentage + '%;">' + response[i].pourcentage + '%</strong></div></div><div class="clear"></div>';
                }

                $("#pooling_reponse").html(html);
                $("#pooling_button").hide();
            }
        });
    });

    /*
     * Pooling Content
     * @auth Hassan Qorchi <hqorchi@extensys.ma>
     */
    $("#voter_pooling_content").click(function(){

        var data = $("#poolingForm").serialize();
        var seed = data.split("=");
        id_question = seed[2];

        setCookie("POOLING-" + id_question, 1, 10);

        $.ajax({
            type : "POST",
            url :  $("#poolingForm").attr("action"),
            data : $("#poolingForm").serialize(),

            success : function(response){
                var html = "";

                for( var i in response ){
                    html += '<div class="rating"><label>' + response[i].reponse + ' </label><div class="graph" style="width:290px;"><strong class="bar" style="width:' + response[i].pourcentage + '%;">' + response[i].pourcentage + '%</strong></div></div><div class="clear"></div>';
                }

                $("#pooling_content").html(html);
            }
        });
    });

    if( $("#voirResultat").length > 0 ){
        $("#voirResultat").click(function() {
            $("#pooling_reponses").hide();
            $("#resultat_pooling_content").show("slow");
        });
    }

    if( $("#retourResultat").length > 0 ){
        $("#retourResultat").click(function() {
            $("#pooling_reponses").show("slow");
            $("#resultat_pooling_content").hide();
        });
    }

    window.essaies = 2;
    var btn = $("#search_gaming");

    btn.click(function(){
        var data = $("#gamingForm").serialize();
        var seed = data.split("&");
        var seed1 = seed[1].split("=");
        var id_question = seed1[1];

        setCookie("GAMING-" + id_question, 1, 10);

        $.ajax({
            type : "POST",
            url :  $("#gamingForm").attr("action"),
            data : $("#gamingForm").serialize(),

            success : function(response){

                var seed = response.split(";");
                if( seed[0] == "SUCCES"){
                    $("#gaming_form").attr("style" , "display:none");

                    html = "<div><strong>Bravo! bonne réponse</strong></div>";
                    $("#resultatgaming").html( html );
                    $("#resultatgaming").fadeIn('1600');

                    btn.attr("class", "novote");
                    btn.attr("disabled", "disabled");

                }else{
                    window.essaies = window.essaies - 1;
                    if(window.essaies == 0) {
                        $("#gaming_form").hide();
                        html = "<div><strong>La bonne réponse est : </strong><strong>" + seed[1] + "</strong></div>";
                        $("#resultatgaming").html( html );
                        $("#resultatgaming").fadeIn("1600");
                        btn.attr("class","novote");
                        btn.attr("disabled","disabled");
                    }else{
                        $("#gaming_form").attr("style" , "display:none");
                        html = "<div><strong>Malhereusement ce n'est pas la bonne réponse, Réessayez encore une fois</strong></div>";
                        $("#resultatgaming").html( html );
                        $("#resultatgaming").fadeIn().delay(1600).fadeOut(1600);
                        $("#gaming_form").fadeOut().delay(2100).fadeIn(1600);
                    }
                }
            }
        });
    })


    $("#id_pays").change(function(){
        $.ajax({
            url : $("#villeAction").val(),
            type : "POST",
            data : "format=json&id_pays=" + $(this).val(),
            success : function(response){
                dispatchVilles(response);
            }
        });
    });

    $("#allcomments").click(function(){
        var idContent = $("#id").val();
        var action = $("#commentAction").val();
        var pageNumber = $("#pageNumber").val();

        $.ajax({
            url : action,
            type : "POST",
            data : "format=json&idContent=" + idContent + "&pageNumber=" + pageNumber,
            success : function(response){
                var html = "";
                for( var i in response ){
                    html +=  '<div class="comment" id="comment-' + response[i].id_commentaire + '">'+
                    '<img src="/data/images/users/avatar.png">'+
                    '<strong>' + response[i].utilisateur + '</strong>'+
                    '<p>' + response[i].contenu_commentaire + '</p>'+
                    '<div class="clear"></div>'+
                    '</div>';
                }

                $("#comments").prepend( html );
                $("#pageNumber").val( parseInt( pageNumber ) + 1 );
            }
        });
    });

    // Newslatter
    if( $("#newsletterForm").length ){
        $("#newsletterForm").submit(function(){
            $.blockUI({
                message:"<div><h2>Merci de patientez ...</h2></div>",
                css: {
                    backgroundColor: "#f00",
                    color: "#fff"
                }
            });

            $.ajax({
                url : $("#newsletterForm").attr("action"),
                type : "POST",
                data : $("#newsletterForm").serialize(),
                success : function(response){
                    if( response == 'EXISTS' ){
                        $("#resultatnewsletter").addClass("error").html("Vous êtes déjà inscript!");
                    } else if( response == 'SUCCESS' ){
                        $("#resultatnewsletter").removeClass("error").addClass("success").html("Félicitations ! Votre abonnement a bien été pris en compte.<br />Un e-mail de confirmation vient de vous être transmis.");
                    } else if ( response == 'ERROR_FORMAT' ){
                        $("#resultatnewsletter").addClass("error").html("L'adresse mail est incorrecte!");
                    }
                },
                error: function() {
                    $("#resultatnewsletter").addClass("error").html("Erreur lors de l'inscription! Vueillez réessayer")
                }
            });
            $.unblockUI();
            return false;
        });
        $("#newsletterValidate").click(function(){
            $.blockUI({
                message:"<div><h2>Merci de patientez ...</h2></div>",
                css: {
                    backgroundColor: "#f00",
                    color: "#fff"
                }
            });

            $.ajax({
                url : $("#newsletterForm").attr("action"),
                type : "POST",
                data : $("#newsletterForm").serialize(),
                success : function(response){
                    if( response == 'EXISTS' ){
                        $("#resultatnewsletter").addClass("error").html("Vous êtes déjà inscript!");
                    } else if( response == 'SUCCESS' ){
                        $("#resultatnewsletter").removeClass("error").addClass("success").html("Félicitations ! Votre abonnement a bien été pris en compte.<br />Un e-mail de confirmation vient de vous être transmis.");
                    } else if ( response == 'ERROR_FORMAT' ){
                        $("#resultatnewsletter").addClass("error").html("L'adresse mail est incorrecte!");
                    }
                },
                error: function() {
                    $("#resultatnewsletter").addClass("error").html("Erreur lors de l'inscription! Vueillez réessayer")
                }
            });
            $.unblockUI();
        });
    }
    // Fin Newslatter

    // horaires de prière
    if( $("#horairepriereForm").length ){
        $("#switchform").change(function(){
            $.ajax({
                url : $("#horairepriereForm").attr("action"),
                type : "POST",
                data : $("#horairepriereForm").serialize(),
                success : function(response){
                    var responseContent = '';
                    if( response ) {
                        responseContent = '<ul class="menuHorairePriere" id="menuHorairePriere"><li><span class="heurePriere">'+ response.assoubh +'</span> As-Sobh </li>'+
                        '<li><span class="heurePriere">'+ response.addouhr +'</span> Ad-Dohr </li>'+
                        '<li><span class="heurePriere">'+ response.alasr +'</span> Al-Asr</li>'+
                        '<li><span class="heurePriere">'+ response.almaghrib +'</span> Al-Maghrib</li>'+
                        '<li><span class="heurePriere">'+ response.alichaa +'</span> Al-Ichae</li></ul>';
                    } else {
                        responseContent = '<div style="color: red;">Pas de données disponibles !</div>';
                    }
                    $("#contentPriere").html( responseContent );
                }
            });
        });
    }
    //Fin  horaires de prière

    // meteo
    if($("#meteoForm").length > 0 ){
        $("#villeMeteo").change(function(){
            $.ajax({
                url : $("#meteoForm").attr("action"),
                type : "POST",
                data : $("#meteoForm").serialize(),
                success : function(response){
                    
                    if( response == "ERROR" ){
                        $("#resultPrevMeteoAjourdhui").html( '<div style="color:red;font-size:10px;">Le service est momentanément indisponible! Veuillez réessayer ultérieurement.</div>' );
                        $("#resultatMeteo").html( "" );
                    } else {
                        var responseImgPrevi = '';
                        var responseInfosPrevi = '';
                        var tabPictos =  new Array( "", // ligne 0
                                "soleil.png", // ligne 1
                                "belles-eclaircies.png", // ligne 2
                                "quelques-eclaircies.png", // ligne 3
                                "nuages-eleves.png", // ligne 4
                                "soleil-voile-avec-orage.png", // ligne 5
                                "couvert.png", // ligne 6
                                "orage-ou-risque-d-orage.png", // ligne 7
                                "orage-fort.png", // ligne 8
                                "pluies-eparses.png", // ligne 9
                                "pluie.png", // ligne 10
                                "pluies-et-neige-melees.png", // ligne 11
                                "averses-de-grele.png", // ligne 12
                                "gelee.png", // ligne 13
                                "chasse-sable.png", // ligne 14
                                "brume-matinale.png", // ligne 15
                                "brouillard.png" // ligne 16
                            );
                                
                        responseImgPrevi +='<img src="http://www.aswat.ma/data/images/meteo/'+ tabPictos[response.imgPicto[0]] +'" alt="'+ response.prevMatinAujourdHui +'" class="bellesEclaircies"/>'+
                        '<div class="contentBellesEclr">'+
                        '<span class="ville">'+ response.actualTmp[0]+'°C ' + response.ville[0]  + ', Maroc</span><br/>'+
                        '<span class="climat">'+ response.prevision[0] +'</span>'+
                        '</div>';


                        responseInfosPrevi +='<table>'+
                        '<thead>'+
                        '<tr>'+
                        '<td class="titreClimat" align="center">Aujourd\'hui aprés-midi</td>'+
                        '<td class="titreClimat" align="center">Demain<br/>matin</td>'+
                        '<td class="titreClimat" align="center">Demain<br/>aprés-midi</td>'+
                        '</tr>'+
                        '</thead>'+
                        '<tbody>'+
                        '<tr id="resultInfosPrevis" class="resultInfosPrevis">'+
                        '<td align="center" class="imgResultatMeteo"><img src="http://www.aswat.ma/data/images/meteo/'+ tabPictos[response.picto_PM_aujourdhui[0]] +'" alt="Aujourd\'hui Aprés Midi" class="correctPNG"/></td>'+
                        '<td align="center" class="imgResultatMeteo"><img src="http://www.aswat.ma/data/images/meteo/'+ tabPictos[response.picto_AM_demain[0]] +'" alt="demain matin" class="correctPNG"/></td>'+
                        '<td align="center" class="imgResultatMeteo"><img src="http://www.aswat.ma/data/images/meteo/'+ tabPictos[response.picto_PM_demain[0]] +'" alt="Demain Aprés-Midi" class="correctPNG"/></td>'+
                        '</tr>'+
                        '</tbody>'+
                        '</table>';
                        $("#resultPrevMeteoAjourdhui").html( responseImgPrevi );
                        $("#resultatMeteo").html( responseInfosPrevi );
                    }
                }
            });
        });
    }
    // fin meteo

    // Journal parle
    if( $("#jp-fr").length ){
        $("#jp-fr").click(function(){
            $.ajax({
                url : $("#jp-url").val(),
                type : "POST",
                data : "langue=" + $(this).val(),
                success : function(response){
                    if( response ){
                        $("#contentJournalParle").html(response);
                    }
                }
            });
        });
    }
    if( $("#jp-ar").length ){
        $("#jp-ar").click(function(){
            $.ajax({
                url : $("#jp-url").val(),
                type : "POST",
                data : "langue=" + $(this).val(),
                success : function(response){
                    if( response ){
                        $("#contentJournalParle").html(response);
                    }
                }
            });
        });
    }
    
    /*
 * Nyro Modal Envoyer Actualité a un ami
 * Appel la fonction addValidator qui a son tour appel la fonction d'envoi de mail doSendEmail
 * @author Hassan QORCHI
 * 14/12/2010
 */

    if ( $("a[rel^='prettyPhoto-gv']").length ){
        $("a[rel^='prettyPhoto-gv']").prettyPhoto({
            default_width: 600,
            allow_resize: false
        });
    }
    if( $("a[rel^='prettyPopin']").length ){
        $("a[rel^='prettyPopin']").prettyPopin({
            loader_path : "/recette/style/js/prettyPhoto/images/prettyPopin/loader.gif",
            onload : function(){
                attachEventConnexionForm();
            }
        });
    }

    /*if( $("ul#ticker01").length ){
        $(function(){
            $("ul#ticker01").liScroll();
        });
    }*/
    if( $("#jqscroller").length ){
        $("#jqscroller").SetScroller({
            velocity: 	 60,
            direction: 	 "horizontal",
            startfrom: 	 "right",
            loop:        "infinite",
            movetype: 	 "linear",
            onmouseover: "pause",
            onmouseout:  "play",
            onstartup: 	 "play"
        });
    }

    if( $("#grilleControl").length ){
        $("#grilleControl").click(function(){
            $(this).hide();
            $(this).next().animate({
                opacity: 1,
                height: 362
            }, 500);
        });
    }
});

function openMenu(i) {
    $.fx.speeds._default = 600;
    var ligne = i;
    $( "#dialog_"+ligne ).dialog({
        autoOpen: false,
        show: "scale",
        hide: "explode"
    });

    $( "#dialog_"+ligne ).dialog( "open" );
    return false;
}

function openAccessPlan() {
    $.fx.speeds._default = 600;
    $( "#dialog_plan" ).dialog({
        autoOpen: false,
        show: "scale",
        hide: "explode"
    });

    $( "#dialog_plan" ).dialog( "open" );
    return false;
}


function openPlayer( param ){
    switch( param ){
        case 2:
            window.open ("/fr/index/player/param/podcasts", "Player aswat", config="width=600, height=580, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no");
            break;
        case 3:
            window.open ("/fr/index/player/param/musique", "Player aswat", config="width=600, height=580, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no");
            break;
        case 4:
            $("#direct_video").show("slow");
            $("#hide_video").click(function(){
                $("#direct_video").hide("slow");
            });
            break;
        case 1:
        default:
            window.open ("/fr/index/player/param/direct", "Player aswat", config="width=600, height=580, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no");
            break;
    }
}
function dispatchVilles(response){

    var options = "";

    for( var i in response.villes ){
        options += '<option value="' + response.villes[i].key + '">' + response.villes[i].value + '</option>';
    }

    $("#id_ville").html(options);
}

var Url = {
    // public method for url encoding
    encode : function (string) {
        return escape(this._utf8_encode(string));
    },
    // public method for url decoding
    decode : function (string) {
        return this._utf8_decode(unescape(string));
    },
    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }
        }
        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }
        }
        return string;
    }
}

function setCookie(nom,valeur,jours) {
    var expDate = new Date()
    expDate.setTime(expDate.getTime() + (jours * 24 * 3600 * 1000))
    document.cookie = nom + "=" + escape(valeur) + "; path=/; expires=" + expDate.toGMTString()
}

/*
* Nyro Modal Envoyer Actualité a un ami
* Appel la fonction addValidator qui a son tour appel la fonction d'envoi de mail doSendEmail
* @author Hassan QORCHI
* 14/12/2010
*/

function addValidator(){
    $("#sendToFriend").validate({
        submitHandler: function(form) {
            doSendEmail();
            return false;
        }
    });

    $("#sendToFriend").submit(function(){
        return false;
    });
}


/*
* doSendEmail
* Nyro Modal Envoyer Actualité a un ami
*
* @author Hassan QORCHI
* 14/12/2010
*/

function doSendEmail(){
    $("#loading").fadeIn("slow");
    $.ajax({
        url  : $("#sendToFriend").attr("action"),
        type : "POST",
        data : $("#sendToFriend").serialize(),
        success : function(response){
            if( response == "SUCCESS" ){
                $("#response").html("Votre email a été envoyé avec succès! Merci");
            } else {
                $("#response").html("Erreur lors de l'envoie de votre email! Merci de réessayer a nouveau. <span><a title=\"Fermer\" href=\"#\" onclick=\"javascript:closePopin();\">Fermer</a></span>");
            }

            $("#loading").fadeOut("slow");
            $("#response").fadeIn("slow");

            setTimeout ( "closePopin()", 3000 );
        }
    });
}

function closePopin(){
    $.nyroModalRemove();
}

function closeGrille(){
    $("#grilleControl").next().animate({
        opacity : 0.15,
        height: 40
    }, 500, function(){
        $("#grilleControl").show();
        $("#grilleControl").next().css({
            "display":"none"
        });
    });
}

function attachEventConnexionForm(){
    $("button", $("#connexionForm")).click(function(){
        $.ajax({
            url: $("#connexionForm").attr("action"),
            type: "POST",
            data: $("#connexionForm").serialize(),
            success: function(response){
                if( typeof(response) == "object" ){
                    if( response.status == "SUCCESS" ){
                        $("#connexionMessage").removeClass("error").addClass("success").css("font-size", "12px").html("Connexion réussie! Redirection dans quelqules instants").show();
                        $(".prettyPopin").animate({
                            height: 330
                        }, 300);
                        setTimeout(function(){
                            window.location.reload(true);
                        }, 3000);
                    } else if( response.status == "ERROR" ){
                        $(".error").remove();
                        $("#connexionMessage").addClass("error").css("font-size", "12px").html("Email ou mot de passe incorrecte! Veuillez Ré-essayer a nouveau").show();
                        $(".prettyPopin").animate({
                            height: 330
                        }, 300);
                    }
                } else {
                    response = jQuery.parseJSON(response);
                    $(".error").remove();
                    $("input", $("#connexionForm")).each(function(){
                        if( response[$(this).attr("id")] != undefined ){
                            if( response[$(this).attr("id")].isEmpty ){
                                $(this).after($("<div></div>").addClass("error").html(response[$(this).attr("id")].isEmpty));
                            }
                            if( response[$(this).attr("id")].emailAddressInvalidFormat ){
                                $(this).after($("<div></div>").addClass("error").html(response[$(this).attr("id")].emailAddressInvalidFormat));
                            }
                        }
                    });
                    $(".prettyPopin").animate({
                        height: 340
                    }, 300);
                }
            }
        });
    });
    
    FB.XFBML.parse();
}
