$(document).ready(function() {
    initAll();
});

//Spécial layout2
function initAll()
{
    MenuAccordeon();

    $("#header #logo").bind("click", function(event)
    {
        document.location='/';
    });

    // liens internes au panier
    $('.lightbox2').hide();
    $('.lightbox2 #close').click( function (){
        $('.lightbox2').hide();
    });

	
	
    $('#commandeTable a').click( function (){

        //alert($(this).attr('href'));

        //url: 'panier/ajoute?quantite=5&id=1&addon=1',
        $.ajax(
        {
            dataType:'html',
            cache:false,
            url: $(this).attr('href'),
            success: function(data)
            {
                $('#lightbox2').css("margin-left", (-40+$(window).width()-$('#lightbox2').width())/2);
                $('#lightbox2 #contenu').html(data);
            },
            complete:function(XMLHttpRequest,textStatus,errorThrows){
                $('.lightbox2').fadeIn("slow");
                presenteArticles();
                $('.vignettes').hide();
            },
            error:function(XMLHttpRequest,textStatus,errorThrows){
            }
        });
        return false;
    });
    $('#uploadTable a').click( function (){

        //alert($(this).attr('href'));
        //url: 'panier/ajoute?quantite=5&id=1&addon=1',
        $.ajax(
        {
            dataType:'html',
            cache:false,
            url: $(this).attr('href'),
            success: function(data)
            {
                $('#lightbox2').css("margin-left", (-40+$(window).width()-$('#lightbox2').width())/2);
                $('#lightbox2 #contenu').html(data);
            },
            complete:function(XMLHttpRequest,textStatus,errorThrows){
                $('.lightbox2').fadeIn("slow");
                presenteArticles();
                $('.vignettes').hide();
            },
            error:function(XMLHttpRequest,textStatus,errorThrows){
            }
        });
        return false;
    });

    //**************** Traitement des commandes client adherents/votre compte
    $("#vosCommandes .commande .contenuCommande").hide();
    $('#vosCommandes .commande h2 .bouton').click(function(){
        openCommande($(this));
    });
    $('#vosCommandes .commande h2 .titre').click(function(){
        openCommande($(this));
    });
    function openCommande(theDiv){
        $("#vosCommandes .commande .contenuCommande").hide(130);
        if(theDiv.parent().children('.bouton').hasClass("ouvert")){
            $('#vosCommandes .commande h2 .bouton').removeClass('ouvert');
        }else{
            $('#vosCommandes .commande h2 .bouton').removeClass('ouvert');
            theDiv.parent().children('.bouton').addClass("ouvert");
            //$(this).prev().prev().addClass("ouvert");
            theDiv.parent().next().slideDown("slow");

        }
    }
    //*************FIN Traitement des commandes client adherents/votre compte


    //** Boite de recherche

    if($("#query").val()==""){
        $("#query").val($("#recherche").text());
        $("#query").bind("focus", function(event)
        {
            $("#query").val('');
        });
    }
    //*** Panier
    $('#panier').click( function (){
        document.location.href ='/panier';
    });
    $('.ajaxAjoutPanier').click( function (){
        //alert($('#cdeLigne').attr('action'));#
        var form = $(this).parents('form:first');
        var id = $("input[name='id']",form).val();
        //alert($(form).find('#id').val());

        //var id = $(form).find("[name='id']").val()
        // var quantite = $("input[name='quantite']",form).val();
        var quantite = $("select[name='quantite']",form).val();
        var addon = $("input[name='addon']",form);
        addonV = 0;
        if(addon.is(':checked')){
            addonV = 1;
        }
        //alert($(form).attr('action'));
        $.ajax(
        {
            type:'POST',
            dataType:'html',
            url: $(form).attr('action')+'?quantite='+quantite+'&id='+id+'&addon='+addonV,
            beforeSend: function() {
                $('#panier').animate({
                    opacity: 0.10
                })
                },
            complete: function() {
                $('#panier').animate({
                    opacity: 1
                })
                },
            success: function(data)
            {
                $('#panier').html(data);
            }
        });


        return false;
    });


    presenteArticles();
    presenteSitemap();
    ajusteLiensDomaines();

    //** validation #adherentsPassword
    $("#clientPassword").validate({
        rules: {
            'clientPassword[password]': {
                required: true,
                minlength: 4,
                equalTo: "#clientPassword_passwordV"
            },
            'clientPassword[passwordV]': {
                required: true,
                minlength: 4
            }
        },
        messages: {
            'clientPassword[password]': {
                required: "Mandatory / Obligatoire",
                minlength: jQuery.format("Mini {0}"),
                equalTo: "Please Confirm / confirmez"
            },
            'clientPassword[passwordV]': {
                required: "Mandatory / Obligatoire",
                minlength: jQuery.format("Mini {0}")
            }
        },


        // set this class to error-labels to indicate valid fields
        success: function(label) {
            // set   as text for IE
            label.html(" ").addClass("checked");
        }
    });



    $("#modifClient").validate({
        rules: {

            'modifClient[nom]': {
                required: true,
                minlength: 2
            },
            'modifClient[prenom]': {
                required: true,
                minlength: 2
            },
            'modifClient[email]': {
                required: true,
                email: true,
                minlength: 4
            }


        },
        messages: {
            'modifClient[nom]': {
                required: "Mandatory / Obligatoire",
                minlength: jQuery.format("Mini {0}")
            },
            'modifClient[prenom]': {
                required: "Mandatory / Obligatoire",
                minlength: jQuery.format("Mini {0}")
            },
            'modifClient[email]': {
                required: "Obligatoire",
                email: "Email Incorrect",
                minlength: jQuery.format("Mini {0}")
            }
        },
        // specifying a submitHandler prevents the default submit, good for the demo
        /**
        submitHandler: function() {
            alert("submitted!");
        }, **/

        // set this class to error-labels to indicate valid fields
        success: function(label) {
            // set   as text for IE
            label.html(" ").addClass("checked");
        }
    });

    $("#loginF").validate({
        rules: {
            'loginF[login]': {
                required: true,
                minlength: 4,
                remote: "users4jqvalidate"
            },
            'loginF[nom]': {
                required: true,
                minlength: 2
            },
            'loginF[prenom]': {
                required: true,
                minlength: 2
            },
            'loginF[password]': {
                required: true,
                minlength: 4,
                equalTo: "#loginF_passwordV"
            },
            'loginF[passwordV]': {
                required: true,
                minlength: 4
            },
            'loginF[email]': {
                required: true,
                email: true,
                minlength: 4,
                remote: "users4jqvalidatemail"
            }


        },
        messages: {
            'loginF[login]': {
                required: "Mandatory / Obligatoire",
                minlength: jQuery.format("Nb caractères Mini {0}"),
                remote: jQuery.format("{0} est déjà utilisé")
            },
            'loginF[nom]': {
                required: "Mandatory / Obligatoire",
                minlength: jQuery.format("Mini {0}")
            },
            'loginF[prenom]': {
                required: "Mandatory / Obligatoire",
                minlength: jQuery.format("Mini {0}")
            },
            'loginF[password]': {
                required: "Mandatory / Obligatoire",
                minlength: jQuery.format("Mini {0}"),
                equalTo: "Please Confirm / confirmez"
            },
            'loginF[passwordV]': {
                required: "Mandatory / Obligatoire",
                minlength: jQuery.format("Mini {0}")
            },
            'loginF[email]': {
                required: "Mandatory / Obligatoire",
                email: "Email Incorrect",
                minlength: jQuery.format("Mini {0}"),
                remote: jQuery.format("{0} est déjà utilisé")
            }
        },
        // specifying a submitHandler prevents the default submit, good for the demo
        /**
        submitHandler: function() {
            alert("submitted!");
        }, **/

        // set this class to error-labels to indicate valid fields
        success: function(label) {
            // set   as text for IE
            label.html(" ").addClass("checked");
        }
    });



}
function initLayout2()
{
    $(window).resize(function() {
        $('#flecheGauche').unbind('click');
        $('#flecheDroite').unbind('click');
        initFleches();
    });



    initFleches();
    $('#flecheGauche').show();

}
function initFleches(){
    var deplacementSlide = ($('#global').position().left+ $('#global').width())-60;

    $('#flecheGauche').click(function(){
        $('#slide').animate({
            left: '+='+deplacementSlide
        }, 500, function() {
            afficheFleches(deplacementSlide);
        });
    });





    $('#flecheDroite').click(function(){
        //alert( "left: " + position.left + ", top: " + position.top );
        $('#slide').animate({
            left: '-='+deplacementSlide
        }, 500, function() {
            afficheFleches(deplacementSlide);
        });
    });



    afficheFleches(deplacementSlide);
}
function afficheFleches(deplacementSlide){
    if($('#slide').position().left+$('#global').position().left>=30){
        $('#flecheGauche').hide();
    }else{
        $('#flecheGauche').show();
    }
    //$fenetreUtile = $(window).width() - 280 - 60 ;
    if( (-$('#slide').position().left-$('#global').position().left) >= $('#slide').width() - 2*deplacementSlide   ){
        $('#flecheDroite').hide();
    }else{
        $('#flecheDroite').show();
    }

//$('#info').append(' '+ $('#global').position().left+' '+ $('#global').width() ) ;
//$('#info').append('->'+ ($('#slide').position().left+$('#global').position().left)+' '+ $('#slide').width() ) ;
//$('#info').append('->'+ ($('#slide').position().left+$('#global').position().left)+' '+ $('#slide').width()+' '+ deplacementSlide ) ;
//$('#info').append($('#slide').position().left+$('#global').position().left);
//$('#info').append((-$('#slide').position().left-$('#global').position().left) - $('#slide').width() - 2*deplacementSlide);
//alert($(window).width());   // returns width of browser viewport
//$(document).width();
}


//Fonction du menu déroulant (accordéon) des pages
function MenuAccordeon() {

    // alert('MenuDeroulant');
    // On cache les sous-menus :
    $(".listMenu01 ul.listMenu02").hide();

    $(".listMenu02 .actif").each( function ()
    {
        $(this).parent().addClass("listMenu01Open");
        $(this).parent().slideDown("slow");
    } ) ;
    $(".listMenu01 li.togglelistMenu02.listMenu01Open").each( function ()
    {
        $(".listMenu01 li.togglelistMenu02.listMenu01Open ul.listMenu02").slideDown("normal");
    } ) ;

    // On sélectionne tous les items de liste portant la classe "toggleSubMenu"
    // et on remplace l'élément span qu'ils contiennent par un lien :
    $(".listMenu01 li.togglelistMenu02 span").each( function ()
    {
        // On stocke le contenu du span :
        var TexteSpan = $(this).text();
        $(this).replaceWith('<a href="" title="' + TexteSpan + '">' + TexteSpan + '<\/a>') ;
    } ) ;

    // On modifie l'évènement "click" sur les liens dans les items de liste
    // qui portent la classe "togglelistMenu02" :
    $(".listMenu01 li.togglelistMenu02 > a").click( function () {
        // Si le sous-menu était déjà ouvert, on le referme :
        if ($(this).next("ul.listMenu02:visible").length != 0)
        {
            $(this).next("ul.listMenu02").slideUp("normal");
            $(this).parent().removeClass("listMenu01Open");
        }
        // Si le sous-menu est caché, on ferme les autres et on l'affiche :
        else
        {
            $(".listMenu01 ul.listMenu02").slideUp("normal");
            $('li.togglelistMenu02').removeClass("listMenu01Open");
            $(this).next("ul.listMenu02").slideDown("normal");
            $(this).parent().addClass("listMenu01Open");
        }
        // On empêche le navigateur de suivre le lien :
        return false;
    });
}
function videPanier(){

    //alert('vide Panier...');
    $.ajax(
    {
        type:'POST',
        dataType:'html',
        url: '/panier/vide',
        success: function(data)
        {
            $('#panier').html(data);
        }
    });
}
function videLignePanier(ligne){

    //alert('supprime Panier'+ligne);
    $.ajax(
    {
        type:'POST',
        dataType:'html',
        url: '/panier?sup='+ligne,
        success: function(data)
        {
            $('#colonneCentre #panier').html(data);
            $.ajax(
            {
                type:'POST',
                dataType:'html',
                url: '/panier/affiche',
                beforeSend: function() {
                    $('#panier').animate({
                        opacity: 0.10
                    })
                    },
                complete: function() {
                    $('#panier').animate({
                        opacity: 1
                    })
                    },
                success: function(data)
                {
                    $('#panier').html(data);
                }
            });
        }
    });
}
function modifAdresseLivraison(adrElement){
    //alert('lllllll'+adrElement.name);
    $.ajax(
    {
        type:'POST',
        dataType:'html',
        url: '/panier?'+adrElement.name+'='+adrElement.value,
        beforeSend: function() {
            $('#colonneCentre #panier').animate({
                opacity: 0.10
            })
        },
        complete: function() {
            $('#colonneCentre #panier').animate({
                opacity: 1
            })
        },
        success: function(data)
        {
            $('#colonneCentre #panier').html(data);
        }
    });
}
function modifAdresseLivraison_ss_maj(adrElement){
    $.ajax(
    {
        type:'POST',
        dataType:'html',
        url: '/panier?'+adrElement.name+'='+adrElement.value
    });
}
function modifLignePanier(ligne,qte){

    //alert('supprime Panier'+ligne);
    $.ajax(
    {
        type:'POST',
        dataType:'html',
        url: '/panier?mod='+ligne+'&qte='+qte,
        success: function(data)
        {
            $('#colonneCentre #panier').html(data);
            $.ajax(
            {
                type:'POST',
                dataType:'html',
                url: '/panier/affiche',
                beforeSend: function() {
                    $('#panier').animate({
                        opacity: 0.10
                    })
                    },
                complete: function() {
                    $('#panier').animate({
                        opacity: 1
                    })
                    },
                success: function(data)
                {
                    $('#panier').html(data);
                }
            });
        }
    });
}
function ajusteLiensDomaines(){
    //* ajuste le positionnement des liens vers les autres domaines.
    compteur = 0 ;
    $("#autresSites a img:visible").each(function(){
        compteur ++ ;
        if(compteur!=3 && compteur!=6){
            $(this).parent().css("margin-right", 8);
        }
    });
//alert (compteur) ;
}
function presenteSitemap(){
    compteur = 0 ;
    nbcolonnes = 6 ;
    var pdiv ;
    var mod_ =    $("#sitemap a").length / nbcolonnes  ;
    $("#sitemap a").each(function(){
        if(compteur % (parseInt(mod_+1)) == 0){
            pdiv = $("<ul/>", {
                "class": "colonne"
            }).appendTo("#sitemap");
        }
        $(this).appendTo(pdiv);
        $(this).wrap('<li/>');
        compteur ++ ;
    });

      $("#sitemap").append($('<div style="clear:both;">&nbsp;</div>'));
}
function presenteArticles(){
    //*** gestion des images des articles

    compteur = 0 ;
    $(".article div").each(function(){
        if($(this).hasClass('accessoire') || $(this).hasClass('produitInner')){
        compteur ++ ;



        $(".texte img", this).each(function(){
            if($(this).height()>70 && $(this).height()>70){
                // on ne traite pas les puces
                width = 62 ;
                height = $(this).height()/$(this).width()*width;
                $(this).css("width", width);
                $(this).css("height", height);
                $(this).css("margin", 0);
                $(this).css("margin-top", 2);
                $(this).css("margin-right", 2);
                //alert($(this).attr('src'));
                //alert(compteur);
                $(this).wrap('<a class="lightBox_'+compteur+'" href="'+$(this).attr('src')+'"></a>');
            }
        });




        var theDiv = $(document.createElement("div")).addClass('vignettes');
        var theVignette = $(this).children(".vignette");
        $(".lightBox_"+compteur).each(function(){
            $(this).appendTo(theDiv);
        //$(this).hide();
        });
        theDiv.insertAfter(theVignette);


        //* on wrappe la vignette principale
        $(".vignette img",this).each(function(){
            //alert($(this).attr('src'));
            $(this).wrap('<a class="lightBox_'+compteur+'" href="'+$(this).attr('src')+'"></a>')
        });
        //* on reprend les class lightbox




        $('a.lightBox_'+compteur).lightBox({
            overlayBgColor: '#FFF'
        });

   }
});

 
        $(".articleInner img").each(function(){

                width = 520 ;
            if($(this).width()> width ){
                // on ne traite pas les puces
                height = $(this).height()/$(this).width()*width;
                $(this).css("width", width);
                $(this).css("height", height);

            $(this).wrap('<a class="lightboxInner" href="'+$(this).attr('src')+'"></a>');
            /**$(this).parent().lightBox({
                overlayBgColor: '#FFF'
            });*/
            }
        });
            $(".lightboxInner").lightBox({
                overlayBgColor: '#FFF'
            });
    /**
    $(".articleInner .texte").truncatable({
        limit: 300,
        more: '...',
        less: true,
        hideText: '[-]'
    });
**/
    $('.articleInner .texte').truncate({
        max_length: 1000,
        more:'...',
        less:'[-]'
    });
    $('.produitInner .texte').truncate({
        max_length: 500,
        more:'...',
        less:'[-]'
    });
}
function enregistreCommande(){
    $.ajax(
    {
        type:'POST',
        dataType:'html',
        url: '/panier/enregistreCommande',
        success: function(data)
        {
            $('#colonneCentre #enregistreCommande').html(data);

        },
        complete: function() {
            $('#colonneCentre #enregistreCommande #form1').submit();
        }
    });
}


