/*  BOUTIQUES BAYARD / BAYARD PRESSE */
/* Created by Atos Worldline - 06/2009 */

// Loading all scripts ...

    
    var ie6 = (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion) == 4 && navigator.appVersion.indexOf("MSIE 6.0") != -1);

window.onload = function(e) {
    
    // Print
    $(function(){
        $("a.print").click (function(){
            window.print();
            return false;
        });
      });
    
    
    // Dropdown behaviour for IE6
    if (ie6) {dropdown();}
    
    // Facets accordion
    if(document.getElementById("transversalNav")) {
        $(function(){
            $("li.allItems ul.allProducts").hide();
            $("li.allItems strong").click (function(){
                $(this).parents("li.allItems").siblings("li.mainProducts").slideUp("slow");
                $(this).siblings("ul.allProducts").slideToggle("slow").siblings("ul.allProducts:visible").slideUp("slow");
                $(this).toggleClass("active");
            });
      });
    }
    
    // Basket page
    if(document.getElementById("inBasket")) {dynamicForm();}
    if(document.getElementById("payChoice")) {JT_init();}
    if(document.getElementById("inBasket")) {
        $("h2.open:last").addClass("active");
        $("div.purchaseData div.dataBox").hide();
        $("h2.open:last").next("div.dataBox").show();
        if($("h2.open:last").attr('id') != "confOrd"){
      $("div.purchaseData h2").click (function(){           

          Expression = new RegExp("^open.*","")
                    if(Expression.test(this.className)){
                        $(this).next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");
                        $(this).toggleClass("active");
                    }
                    
          if($(this).attr("id") == "h2_delivery"){
            var payment = document.getElementById("h2_payment");
            if(Expression.test($(payment).attr("class"))){
              $(payment).next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");
            }
            $(payment).attr("class", "");
          
          }
            });
        }else{
            $("h2.open").removeAttr('title');
        }
        $('.qttyInput').numeric('0');
        $("#codePromo").click(function(){
            $("#frInBasket").attr('action','promotions/manageForm');
            $("#frInBasket").submit();
            return false;
        });
        $("#recalculer").click(function(){
            $("#frInBasket").submit();
            return false;
        });
        //var vDeliveryData = document.getElementById("inBasketfrTradeData");
        //$(vDeliveryData).submit( function() { 
        //  var vCadeau = document.getElementById("cadeau");
        //  if(vCadeau && $(vCadeau).attr("checked") == true){
        //      if($("#delivery_ipCadoEmail").attr("value") == ""){
        //          $("#cadeauError").html("le champ email est vide");
        //          return false;
        //      }else{
        //          Expression = new RegExp("^.*@.*\..*","")
        //          if(!Expression.test($("#delivery_ipCadoEmail").attr("value"))){
        //              $("#cadeauError").html("le champ email est invalide");
        //              return false;
        //          }
        //      }
        //  }
        //  return true; 
        //});
        $("a.viewCart").click(function(){
            if($("#h2_cart").attr('class') != "open active"){
                $("#h2_cart").next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");
                $("#h2_cart").attr('class','open active');
            }
        });
        
    }
    


    
    
    // Create account
    if(document.getElementById("myInfo")) {
		$('#modalModifCoord').css("display","none");
        $("div.myDataBox:first h2").addClass("active");
        $("div.myDataBox:first h2").attr("title","");
        $("div.myDataBox div.dataBox:not(:first)").hide();
        //$("div.myDataBox:first h2").click (function(){
        //  $(this).next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");
        //  $(this).toggleClass("active");
        //});
        //$("div.myDataBoxUserIdentified:first h2").hide();
        $("div.myDataBoxUserIdentified div.dataBox:first").hide();
        $("div.myDataBoxUserIdentified div.dataBox:not(:first)").addClass("active");
        $("div.myDataBoxUserIdentified h2").click (function(){
            $(this).next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");
            $(this).toggleClass("active");
        });
    }
    // Account
    if(document.getElementById("myMags")) {
        $("div.accountBox h2").addClass("active");
        $("div.accountBox h2").click (function(){
            $(this).next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");
            $(this).toggleClass("active");
        });
    }


    if(document.getElementById("productPerAge")) {$(function() {$('#productPerAge').tabs({remote: true});});}
    if(document.getElementById("catalogPerAge")) {$(function() {$('#catalogPerAge').tabs({remote: true});});}
    if(document.getElementById("specifications")) {$(function() {$('#specifications').tabs();});}
    if(document.getElementById("productSheet")) {JT_init();}
    if(document.getElementById("frPayment")) {JT_init();}
    // if(document.getElementById("severalGifts")) {JT_init();}
    if(document.getElementById("idRecall")) {idForm("modify","idRecall","frIdentification");}
    if(document.getElementById("coordsRecall")) {idForm("modify","coordsRecall","frUserData");}
    if(document.getElementById("coordsCreate")) {idForm("modifyCreate","coordsCreate","coordsCreateModify");}
    if(document.getElementById("coordsUpdate")) {idForm("modifyUpdate","coordsUpdate","coordsUpdateModify");}
    if(document.getElementById("address_ipTelF") || document.getElementById("coordonnees_ipTelF")) {$('.numTel').numeric();}
    
    // Date picker calendar
    if (document.getElementById("ipDateFrom")) {
        $.datepicker.regional['fr'] = {
            closeText: 'Fermer',
            prevText: '&#x3c;Préc',
            nextText: 'Suiv&#x3e;',
            currentText: 'Courant',
            monthNames: ['Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre'],
            monthNamesShort: ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Jun', 'Jul', 'Aoû', 'Sep', 'Oct', 'Nov', 'Déc'],
            dayNames: ['Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi'],
            dayNamesShort: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
            dayNamesMin: ['Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa'],
            dateFormat: 'dd/mm/yy',
            firstDay: 1,
            isRTL: false
        };
        $.datepicker.setDefaults($.datepicker.regional['fr']);
        $("#ipDateFrom").datepicker({
            showOn: 'button',
            buttonImage: 'imgs/pic_calendar.gif',
            buttonImageOnly: true
        });
        $("#ipDateTo").datepicker({
            showOn: 'button',
            buttonImage: 'imgs/pic_calendar.gif',
            buttonImageOnly: true
        });
    }
    
    //MODAL WINDOWS :
    // tarif modal window
    if (document.getElementById("productSheet")) {
        $('.ppLayer').hide();
        $("span.viewerTarif").click (
            function(){
                var vModalName = '#modal'+$(this).attr("id");
                $(vModalName).dialog({
                    autoOpen: false,
                    width: 350
                });
                $(vModalName).dialog('open');
                //var ppPrime = document.getElementById("ppTarif");
                //var id = this.id;
                //jQuery.ajax({type:'GET',dataType:'html',success:function(data, textStatus){jQuery('#ppTarif').html(data);},beforeSend:function(XMLHttpRequest){ppPrime.innerHTML="<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >"},complete:function(XMLHttpRequest, textStatus){},url:'/products/popupTarif/id/'+encodeURIComponent(encodeURIComponent(id))});
                return false;
        });
    }

    /* Alert prelevement modal window */
    if (document.getElementById("modalAlertePrelevement")) {
        $('#modalAlertePrelevement').css("display","none");
        $('#modalAlertePrelevement').dialog({
            autoOpen: true,
            width: 710 
        }); 
    }

    // prime modal window
    if (document.getElementById("modalPrime")) {
        $('#modalPrime').css("display","none");
        $('#modalPrime').dialog({
            autoOpen: false,
            width: 500
        });
        $("span.viewerPrime").click (
            function(){
                $('#modalPrime').dialog('open');
                var ppPrime = document.getElementById("ppPrime");
                var id = this.id;
                jQuery.ajax({type:'GET',dataType:'html',success:function(data, textStatus){jQuery('#ppPrime').html(data);},beforeSend:function(XMLHttpRequest){ppPrime.innerHTML="<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >"},complete:function(XMLHttpRequest, textStatus){},url:'/products/popupPrime/id/'+encodeURIComponent(encodeURIComponent(id))});
                return false;
        });
        $("dd.viewerPrime").click (
            function(){
                $('#modalPrime').dialog('open');
                var ppPrime = document.getElementById("ppPrime");
                var id = this.id;
                jQuery.ajax({type:'GET',dataType:'html',success:function(data, textStatus){jQuery('#ppPrime').html(data);},beforeSend:function(XMLHttpRequest){ppPrime.innerHTML="<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >"},complete:function(XMLHttpRequest, textStatus){},url:'/products/popupPrime/id/'+encodeURIComponent(encodeURIComponent(id))});
                return false;
        });
    }
    // pitch modal window
    if (document.getElementById("modalPitch")) {
        $('#modalPitch').css("display","none");
        $('#modalPitch').dialog({
            autoOpen: false,
            width: 810
        });
        $("p.thumbnail").click (
            function(){
                $('#modalPitch').dialog('open');
                var ppPitch = document.getElementById("ppPitch");
                var id = this.id;
                jQuery.ajax({type:'GET',dataType:'html',success:function(data, textStatus){jQuery('#ppPitch').html(data);},beforeSend:function(XMLHttpRequest){ppPitch.innerHTML="<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >"},complete:function(XMLHttpRequest, textStatus){},url:'/products/popupPitch/id/'+encodeURIComponent(encodeURIComponent(id))});
                return false;
        });
        $("a.calc").click (
            function(){
                $('#modalPitch').dialog('open');
                var ppPitch = document.getElementById("ppPitch");
                var id = this.id;
                jQuery.ajax({type:'GET',dataType:'html',success:function(data, textStatus){jQuery('#ppPitch').html(data);},beforeSend:function(XMLHttpRequest){ppPitch.innerHTML="<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >"},complete:function(XMLHttpRequest, textStatus){},url:'/products/popupPitch/id/'+encodeURIComponent(encodeURIComponent(id))});
                return false;
        });
    }
    // Feuilletage modal window
    if (document.getElementById("modalFeuille")) {
        $('#modalFeuille').css("display","none");
        $('#modalFeuille').dialog({
            autoOpen: false,
            width: 710
        });
        $("dd.viewer").click (
            function(){
                $('#modalFeuille').dialog('open');
                var ppFeuille = document.getElementById("ppFeuille");
                var id = this.id;
                jQuery.ajax({type:'GET',dataType:'html',success:function(data, textStatus){jQuery('#ppFeuille').html(data);},beforeSend:function(XMLHttpRequest){ppFeuille.innerHTML="<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >"},complete:function(XMLHttpRequest, textStatus){},url:'/products/popupFeuilletage/id/'+encodeURIComponent(encodeURIComponent(id))});
                return false;
        });
    }
    // Login modal window
    if (document.getElementById("modalLogin")) {
        $('#modalLogin').css("display","none");
        if (document.getElementById("erreurLogin")) {
            $('#modalLogin').dialog({
                autoOpen: true,
                width: 810
            });
        } else {
            $('#modalLogin').dialog({
                autoOpen: false,
                width: 810
            });
        }
        $('.accountLk').click(
            function(){
                $('#modalLogin').dialog('open');
				if (document.getElementById("ipSort") && ie6) {
					$('#ipSort').css("display","none");
				}
                //var ppLogin = document.getElementById("ppLogin");
                //jQuery.ajax({type:'GET',dataType:'html',success:function(data, textStatus){jQuery('#ppLogin').html(data);},beforeSend:function(XMLHttpRequest){ppLogin.innerHTML="<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >"},complete:function(XMLHttpRequest, textStatus){},url:'subscribers/login'});
                return false;
        });
		//if close button is clicked   
		$('.ui-dialog-titlebar-close').click(function (e) {   
			if (document.getElementById("ipSort") && ie6) {
				$('#ipSort').css("display","inline");
			}
		});        

    }

    // auto launch login window ?
    if ("login"==self.document.location.hash.substring(1))
        $('.accountLk').click();

    // Create account modal
    if (document.getElementById("modalCreate")) {
        $('#modalCreate').css("display","none");
        $('#modalCreate').dialog({
            autoOpen: false,
            width: 810
        });
        $('#createLk').click(
            function(){
                $('#modalCreate').dialog('open');
				if (document.getElementById("ipSort") && ie6) {
					$('#ipSort').css("display","none");
				}
                return false;
        });
		//if close button is clicked   
		$('.ui-dialog-titlebar-close').click(function (e) {   
			if (document.getElementById("ipSort") && ie6) {
				$('#ipSort').css("display","inline");
			}
		});        
    }
    // Change delivery address modal
    if (document.getElementById("changeAdd")) {
            $(function(){
                if(document.getElementById("show")){
                    $('#show').parent().dialog({
                        autoOpen: false,
                        width: 820,
                        zIndex: 20
                    });
                    $('#show').parent().dialog('open');
                }
                $("a.modify").click (
                    function(){
                        var box = $("#changeAdd_"+$(this).attr("href"));
                        box.dialog({
                            autoOpen: false,
                            width: 820,
                            zIndex: 20
                        });
                        box.dialog('open');
                        return false;
                });
            });
    }
    
    // ADD TO BASKET
        var vBuyPP = document.getElementById("modalBuy");
        if(!document.getElementById("inBasket") && vBuyPP) {
            $('#modalBuy').css("display","none");
            $(function(){
                $('#modalBuy').dialog({
                    autoOpen: false,
                    width: 820,
                    zIndex: 20
                });
                $("p.buy").click (
                    function(){
                        var ppBuy = document.getElementById("ppBuy");
                        var itemNumber = this.id;
                        if(itemNumber){
                            $('#modalBuy').dialog('open');
                            jQuery.ajax({type:'GET',dataType:'html',success:function(data, textStatus){jQuery('#ppBuy').html(data);},beforeSend:function(XMLHttpRequest){ppBuy.innerHTML="<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >"},complete:function(XMLHttpRequest, textStatus){},url:'/shoppingcarts/addProducts/id/'+encodeURIComponent(encodeURIComponent(itemNumber))+'/quantity/1/rdm/'+Math.floor(Math.random()*1001)});
                            return false;
                        }
                });
                $("p.buyTarif").click (
                    function(){
                        var ppBuy = document.getElementById("ppBuy");
                        var itemNumber = this.id;
                        var vRadioCheck = false;
                        var vRadio = document.getElementsByName("rateCode");
                        for (i = 0; i < vRadio.length; i++) {
                            if(vRadio[i].checked) {
                                itemNumber = itemNumber + "_" + vRadio[i].value;
                                vRadioCheck = true;
                            }
                        }
                        if (!vRadioCheck) {
                            // aucune zone selectionnee
                            $('#ppTarifError_'+itemNumber).css("display","block");
                            return false;
                        } else {
                            if(itemNumber){
                                $('#modalBuy').dialog('open');
                                jQuery.ajax({type:'GET',dataType:'html',success:function(data, textStatus){jQuery('#ppBuy').html(data);},beforeSend:function(XMLHttpRequest){ppBuy.innerHTML="<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >"},complete:function(XMLHttpRequest, textStatus){},url:'/shoppingcarts/addProducts/id/'+encodeURIComponent(encodeURIComponent(itemNumber))+'/quantity/1'});
                                return false;
                            }
                        }
                });
            });
        }
    
    //WALK through Basket
    var vCart = document.getElementById("vCart");
    if(vCart){
        $(vCart).click(function(){
            var ipAccept = document.getElementById("ipAccept");
            if(ipAccept.checked){
                var delivery = document.getElementById("h2_delivery");
                var cart = document.getElementById("h2_cart");
                if(delivery.className!="open active"){
                    delivery.className="open";
                    $(delivery).next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");
                    $(delivery).toggleClass("active");
                }
                $(cart).next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");
                $(cart).toggleClass("active");
                $('span.error').hide();
                return false;
            }else{
                $('span.cgv').show();
                return false;
            }
        });
        //Control CGV validation
        var vCgv = document.getElementById("ipAccept");
        if(vCgv){
            $(vCgv).click(function(){
                if($(vCgv).attr('checked') == false){
                    var delivery = document.getElementById("h2_delivery");
                    var payment = document.getElementById("h2_payment");
                    if($(delivery).attr('class') == "open active"){
                        $(delivery).next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");                        
                    }                   
                    if($(payment).attr('class') == "open active"){
                        $(payment).next("div.dataBox").slideToggle("slow").next("div.dataBox:visible").slideUp("slow");                     
                    }
                    $(payment).attr('class','');
                    $(delivery).attr('class','');
                }
            });
        }
    }
    
    // ADD/Remove Quantity
        var vAdd = document.getElementsByTagName("a");
        for (i = 0; i < vAdd.length; i++) {
            if (vAdd[i].className == "plus") {
            $(vAdd[i]).click(function(){
                var inputQuantity = document.getElementById('qt_'+this.id);
                if (inputQuantity.value < 999) {
                    inputQuantity.value ++;
                }
                $("#frInBasket").submit();
                return false;
            });
            }
            if (vAdd[i].className == "moins") {
            $(vAdd[i]).click(function(){
                var inputQuantity = document.getElementById('qt_'+this.id);
                if(inputQuantity.value > 0) {
                    inputQuantity.value --;
                }
                $("#frInBasket").submit();
                return false;
            });
            }           
        }
        
    // Change Quantity
    vBasket = document.getElementById("frInBasket");
    if (vBasket) {
        var vInputBasket = vBasket.getElementsByTagName("input");
        for (i = 0; i < vInputBasket.length; i++) {
            if (vInputBasket[i].className == "qttyInput") {
            $(vInputBasket[i]).blur(function(){
                $("#frInBasket").submit();
                return false;
            });
            }           
        }
    }
        
    // Clear ipSearch text
    var vBuyPP = document.getElementById("ipSearch");
    if(vBuyPP) {
        $(vBuyPP).focus(function(){
            this.value="";
            return false;
        });
    }
    
    // charCounter - envoyer ami
    var vToFriend = document.getElementById("frToFriend");
    if(vToFriend) {
        $("#tofriend_message").charCounter(800, {
            container: "#counterToFriend",
            classname: "counterToFriend",
            format: "<p>%1 caractère(s) restant(s)</p>"
        });
    }
    
    // add to calculator
    vCalc = document.getElementById("frCalculette");
    if (vCalc) {
        jQuery.ajax({type:'GET',cache:false,dataType:'html',success:function(data, textStatus){jQuery('#selection').html(data);},beforeSend:function(XMLHttpRequest){jQuery('#selection').html("<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >")},complete:function(XMLHttpRequest, textStatus){},url:'/calculator/addToCalc/id/0'});
        
        $("form input:checkbox").click (function(){
            var vInput = vCalc.getElementsByTagName("input");
            var vListProducts = '';
            var compteur = 0;
            for (i = 0; i < vInput.length; i++) {
                if(vInput[i].checked) {
                    if (compteur == 0) {
                        vListProducts = vInput[i].id;
                    } else {
                        vListProducts = vListProducts+"|"+vInput[i].id;
                    }
                    compteur++;
                }
            }
            if (compteur > 0) {
                jQuery.ajax({type:'GET',cache:false,dataType:'html',success:function(data, textStatus){jQuery('#selection').html(data);},beforeSend:function(XMLHttpRequest){jQuery('#selection').html("<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >")},complete:function(XMLHttpRequest, textStatus){},url:'/calculator/addToCalc/id/'+encodeURIComponent(encodeURIComponent(vListProducts))});
            } else {
                jQuery.ajax({type:'GET',cache:false,dataType:'html',success:function(data, textStatus){jQuery('#selection').html(data);},beforeSend:function(XMLHttpRequest){jQuery('#selection').html("<img class=\"ppLoad\" src=\"/imgs/pp_ajax_loader.gif\" >")},complete:function(XMLHttpRequest, textStatus){},url:'/calculator/addToCalc/id/0'});
            }
        });
    }
    
    // viewProduct
    vEncadre = document.getElementById("id_encadre");
    if(vEncadre){
    $(vEncadre).mouseover(function(){
      Expression = new RegExp("^thumbnail.*","")
      if(Expression.test(this.className)){
          this.className = "encadre";
        }
    });
    $(vEncadre).mouseout(function(){
      Expression = new RegExp("^encadre.*","")
      if(Expression.test(this.className)){
          this.className = "thumbnail";
        } 
    });
  }
  
    if (document.getElementById("coordsRecallModify")) {
        $('#modalModifCoord').css("display","none");
    }

	if (document.getElementById("myInvoicesList")) {
        $('#modalModifCoord').css("display","none");
    }
	
	if (document.getElementById("invoiceView")) {
        $('#modalModifCoord').css("display","none");
    }
	
	if (document.getElementById("mdpBody")) {
        $('#modalModifCoord').css("display","none");
    }
	  
    if (document.getElementById("flagErreurCreate")) {
        $('#coordsCreate').css("display","none");
        $('#coordsCreateModify').css("display","block");
        $('#modifyCreate').css("display","none");
    }
	
	if (document.getElementById("flagErreurUpdate")) {
        $('#coordsUpdate').css("display","none");
        $('#coordsUpdateModify').css("display","block");
        $('#modifyUpdate').css("display","none");
    }
    
    if (document.getElementById("myInvoiceAdd")) {
        var vLink = document.getElementById("myInvoiceAddModify");
        var vValidModifCoord = document.getElementById("validModifCoord");
        var vResetModifCoord = document.getElementById("resetModifCoord");
        $('#modalModifCoord').css("display","none");
        $('#modalModifCoord').dialog({
            autoOpen: false,
            width: 710
        });

        vLink.onclick = function(){
            $('#modalModifCoord').dialog('open');
            return false;
        }
        
        vValidModifCoord.onclick = function(){
                $('#modalModifCoord').dialog('close');
                document.location.href="/subscribers/editAddress?modify=true";
        }
        
        vResetModifCoord.onclick = function(){
                $('#modalModifCoord').dialog('close');
        }   
    }

}
