﻿//L'Oréal
var Loreal = Loreal || {};
$.extend(Loreal, {
    loadState: false,
    conteneur_tampon: '',
    refresh_one_more_time: true,
    Trace: function(message) {
        if (loc.debug) {
            alert(message);
        }
    },
    toInt: function(value) {
        return parseInt(value.replace(" ", ""));
    },
    toPrice: function(price) {
        return parseFloat(price.replace(" ", "").replace(loc.currency, "").replace(",", "."));
    },
    menuOnMouseOver: function() {
        var $li = $(this).parent();
        $li.addClass("navbar_item_on").removeClass("navbar_item_off");
        $li.find("div:last").addClass("header_catalogue_navbar_item_on").removeClass("header_catalogue_navbar_item_off");
        $li.prev().children().css('visibility', 'visible');
        $li.next().children().css('visibility', 'visible');
        $li.find("div:first").show();
		cacherSelectSousDiv($li.find("div:first").eq(0));
    },
    menuOnMouseOut: function() {
        var $li = $(this).parent();
        $li.addClass("navbar_item_off").removeClass("navbar_item_on");
        $li.find("div:last").addClass("header_catalogue_navbar_item_off").removeClass("header_catalogue_navbar_item_on");
        $li.prev().children().css("visibility", "hidden");
        $li.next().children().css("visibility", "hidden");
		montrerSelectSousDiv($li.find("div:first").eq(0));
        $li.find("div:first").hide();
    },
    search: function() {
        var code = encodeURIComponent($("#header_input_search").val());
        var searchpage = $("#launch_search").attr("href");
        var url = $.format(loc.url.search, searchpage, code);
        $(location).attr("href", url); //Redirect to search page
        return false;
    },
    search2: function() {
        var code = encodeURIComponent($("#header_input_search2").val());
        var searchpage = $("#launch_search2").attr("href");
        var url = $.format(loc.url.search, searchpage, code);
        $(location).attr("href", url); //Redirect to search page
        return false;
    },
    startLoading: function() {
        $(this).dialog('open');
    },
    stopLoading: function() {
        $(this).dialog('close');
    },
    errorRedirect: function() {
        $(location).attr("href", loc.url.error500);
    },
    print: function() {
        $(this).blur();
        window.print();
        return false;
    },
    viewOrderDetails: function() {
        var id = $(this).attr("href").split('#')[1];
        var url = $.format(loc.url.orderdetails, id);
        $("#orderdetails").load(url, Loreal.afterLoadOrderDetails);
        return false;
    },
    firstviewdetails: true,
    afterLoadOrderDetails: function() {
        if (!Loreal.firstviewdetails) {
            $("#orderdetails").scroll();
        }
        Loreal.firstviewdetails = false;
    },
    loadPopinSendWishlist: function() {
        var url = '/ajax/send_wishlist.aspx';
        $("#popin_send_wishlist").load(url, Loreal.openPopinSendWishlist);
        return false;
    },
    openPopinSendWishlist: function() {
        $('#popin_send_wishlist').dialog('open');
        $('#popin_send_wishlist').find('.close_button').click(Loreal.closePopinSendWishlist).blur();
        return false;
    },
    closePopinSendWishlist: function() {
        $('#popin_send_wishlist').dialog('close');
        return false;
    },
   loadPopinSendProduct: function() {
        var url = '/ajax/send_product.aspx?prdcode={0}&categorycode={1}';
		var prdcode = $('#prdcode').val();
		var catcode = $('.catpath').val();
		url = $.format(url, prdcode, catcode);
        //$("#popin_send_product").load(url, Loreal.openPopinSendProduct);
        $.get(url, Loreal.getTellAfFriend);
        return false;
    },
    openPopinSendProduct: function() {
        // Recuperation produit
        var product_name = $('#product_info h1').html();
        var product_image_src = $('#product_photo img').attr('src');
        $('#popin_send_product h2 span').html(product_name);
        $('#popin_send_product .product_image').attr('src', product_image_src.replace('236x443.png', '93x105.png'));
        $('#popin_send_product').dialog('open');
        $('#popin_send_product').find('.close_button').click(Loreal.closePopinSendProduct).blur();
        return false;
    },
    closePopinSendProduct: function() {
        $('#popin_send_product').dialog('close');
        return false;
    },
    getTellAfFriend: function(data) {
        $("#popin_send_product").html("").append($(data).filter("FORM").children());

        var product_name = $('#product_info h1').html();
        var product_image_src = $('#product_photo img').attr('src');
        $('#popin_send_product h2 span').html(product_name);
        $('#popin_send_product .product_image').attr('src', product_image_src.replace('236x443.png', '93x105.png'));
        $('#popin_send_product').dialog('open');
        $('#popin_send_product').find('.close_button').click(Loreal.closePopinSendProduct).blur();

        $('#popin_send_product').find("#submittellafriend").click(Loreal.submitTellaFriend);
    },
    submitTellaFriend: function() {
        var url = '/ajax/send_product.aspx?prdcode={0}&categorycode={1}';
		var prdcode = $('#prdcode').val();
		var catcode = $('.catpath').val();
		url = $.format(url, prdcode, catcode);
        var dataForm = $("#popin_send_product").serializeElement();
        $.post(url, dataForm, Loreal.postTellaFriend, "html");
        return false;
    },
    postTellaFriend: function(data) {
        var $tellafriendinsert = $("#popin_send_product");
        $tellafriendinsert.children().remove();
        $tellafriendinsert.append($(data).filter("FORM").children());
        var succes = ($("#opcsuccesstellafriend").length > 0);
        $('#popin_send_product').find('.close_button').click(Loreal.closePopinSendProduct).blur();

        $('#popin_send_product').find("#submittellafriend").click(Loreal.submitTellaFriend);
        if (succes) {
            $('#popin_send_product').dialog('close');
        }
        else if (!succes) {
            alert("Merci de vérifier votre saisie.");
            //$("#global_error_msg_container").scroll();
        }
    },
    ///
    LoadPopinProductNotification: function() {

        //var url = '/ajax/productnotification.aspx?prdcode=' + $("#prdcode").val();

        //$("#popin_send_product").load(url, Loreal.openPopinSendProduct);
        //$.get(url, Loreal.getProductNotification);

        return false;
    },
    closePopinProductNotification: function() {
        $('#nostock_popin').dialog('close');
        return false;
    },
    getProductNotification: function(data) {
        $("#nostock_popin").dialog({
            autoOpen: false,
            //height: "auto",
            width: "290px",
            bgiframe: true,
            modal: true
        });
        $("#nostock_popin").html("").append($(data).filter("FORM").children());

        $('#nostock_popin').dialog('open');
        $('#nostock_popin').find('.close_button').click(Loreal.closePopinProductNotification).blur();

        $('#nostock_popin').find("#submitproductnotification").click(Loreal.submitProductNotification);
    },
    submitProductNotification: function() {
        var url = '/ajax/productnotification.aspx?prdcode=' + $("#prdcode").val();
        var dataForm = $("#nostock_popin").serializeElement();
        $.post(url, dataForm, Loreal.postProductNotification, "html");
        return false;
    },
    postProductNotification: function(data) {
        var $stockpopininsert = $("#nostock_popin");
        $stockpopininsert.children().remove();
        $stockpopininsert.html("").append($(data).filter("FORM").children());
        var succes = ($("#successproductnotification").length > 0);
        $('#nostock_popin').find('.close_button').click(Loreal.closePopinProductNotification).blur();

        $('#nostock_popin').find("#submitproductnotifiction").click(Loreal.submitProductNotification);
        if (succes) {
            $('#nostock_popin').dialog('close');
        }
        else if (!succes) {
            alert("erreur");
            //$("#global_error_msg_container").scroll();
        }
    },
    loadQuickShop: function() {
        var $this = $(this).blur();
        var href;
        if ($this.attr("nodeName").toLowerCase() == "a") {
            href = $this.attr("href");
        }
        else {
            href = $this.val();
        }
        var val = href.split("#");
        $.data($("INPUT[id$=save_state]").get(0), "quickshop", href);
        var $this = $(this).blur();
        var href;
        if ($this.attr("nodeName").toLowerCase() == "a") {
            href = $this.attr("href");
        }
        else {
            href = $this.val();
        }
        var val = href.split("#");
        $.data($("INPUT[id$=save_state]").get(0), "quickshop", href);
        var catcode = val[1];
        var prdcode = val[2];
        var url = $.format(loc.url.quickshop, catcode, prdcode);
        $("#productlayout").hide().load(url, Loreal.openQuickShop);
        return false;
    },
    openQuickShop: function() {
        $("#qtylist option:first,#varlist option:first", this).attr("selected", "selected");
        var $varlist = $("#varlist", this).change(Loreal.selectedList);
        if ($varlist.length) {
            Loreal.selectedList.apply($varlist); //Set the first selected shade
        }
        $(".shade_item", this).click(Loreal.selectedShade);
        $("#addtobag", this).click(Loreal.addToBag);
        $("#addtofavorite", this).click(Loreal.addToFavorite);
        //$("IMG.imgtog", this).ToggleImage();
        $(this).dialog({
            width: 280,
            resizable: false,
            bgiframe: true,
            modal: true,
            //show: "slide",
            hide: "slide",
            dialogClass: "popin_product_layer",
            position: "center"
        });

        $("#productlayout_aligntitle A").blur();
        $(".popin_close_button").click(Loreal.closeQuickShop).blur();
        if (Loreal.loadState) {
            Loreal.loadState = false;
            $("#addtofavorite", this).click();
        }
        PngFixImg();
        return false;
    },
    closeQuickShop: function() {
        $("#productlayout").dialog("close").dialog("destroy");
        return false;
    },
    addToFavorite: function() {
        $(this).blur();
        if (Loreal.Customer.Signed) {
            var $selected = $("#varlist option:selected");
            var sku = $selected.val().split("#")[0];
            var url = $.format(loc.url.favorite, "add", sku);
            $("#favoriteresult").hide().load(url, Loreal.refreshFavorite);
        }
        else {
            var $state = $("INPUT[id$=save_state]");
            if ($state.length) {
                var state = $.data($("INPUT[id$=save_state]").get(0), "quickshop");
                $("INPUT[id$=save_state]").val(state); //Save state
            }
            $("#popin_login").dialog("open");
        }
        return false;
    },
	addBasketToBag: function () {
		retour = 0;
		if (Loreal.Customer.Signed) {
            var sku = $("#saveBasket input.prdcode");
		//alert(sku);
			sku.each( function () {
				var url = $.format(loc.url.favorite, "add", $(this).val());
		//alert(url);
				$('#favoriteresult').load(url, {async: false}, function () {
					retour++;
					if (retour == sku.length) {
						document.location.href = loc.sitename + "/myspace/members/myspace.aspx";
					}
				});
			});
        }
		
	},
    refreshFavorite: function() {
        var $favoriteresult = $("#favoriteresult");
        if ($("#favoritesuccess").length) {
            $("#popin").dialog("open");
        }
        else {
            $favoriteresult.show();
        }
    },
    deleteFavorite: function() {
        var $this = $(this).blur();
        var ligne = $this.parent().parent();
        var sku = $("INPUT", ligne).val();
        var url = $.format(loc.url.favorite, "delete", sku);
        ligne.find(".addtobagresult").hide();
        ligne.find(".addtobagfavoriteresult").hide().load(url, function() {
            var $favoriteresult = ligne.find(".addtobagfavoriteresult");
            if (ligne.find("#favoritesuccess").length) {
                ligne.remove();
            }
            else {
                $favoriteresult.show();
            }
        });
        return false;
    },
    addToBagFavorite: function() {
        var $this = $(this).blur();
        var ligne = $this.parent();
        var varcode = ligne.find('.varlist').val().split('#')[0];
        var qty = ligne.find('.qtylist').val();
        var url = $.format(loc.url.addtobag, varcode, qty);
        ligne.find(".favoriteresult").hide();
        ligne.find(".addtobagfavoriteresult").hide().load(url, function() { Loreal.refreshBagFavorite(ligne); });
        return false;
    },
    addAllFavoriteToBag: function() {
        var $this = $(this).blur();
        var ligne = $this.parent();
        var prdList = "";
        var qtyList = "";

        $("#page_onglet_1").find('.varlist').each(function(i) {
            var varcode = $(this).val().split('#')[0];
            if (i == 0)
                prdList = varcode;
            else
                prdList = prdList + ":" + varcode;
        });


        $("#page_onglet_1").find('.qtylist').each(function(j) {
            var qty = $(this).val();
            if (j == 0)
                qtyList = qty;
            else
                qtyList = qtyList + ":" + qty;
        });
        var url = $.format(loc.url.addtobag, prdList, qtyList);
        ligne.find(".favoriteresult").hide();
        ligne.find("#addallfavoritetobagresult").hide().load(url, function() { Loreal.refreshBagAllFavorite(ligne); });
        return false;
    },

    refreshBagAllFavorite: function(ligne) {
        var $addtobagresult = ligne.find(".addallfavoritetobagresult");
        if ($("#addtobagsuccess").length) {
            $("#header_bag_container").load(loc.url.refreshbag, Loreal.afterRefreshBag);
        }
        else {
            $addtobagresult.show();
        }
    },

    refreshBagFavorite: function(ligne) {
        var $addtobagresult = ligne.find(".addtobagfavoriteresult");
        if ($("#addtobagsuccess").length) {
            $("#header_bag_container").load(loc.url.refreshbag, Loreal.afterRefreshBag);
        }
        else {
            $addtobagresult.show();
        }
    },
    addToBagOrderDetail: function() {
        var $this = $(this).blur();
        var varcode = $this.parent().parent().find('input').val();
        var qty = $this.parent().parent().find('.qtylist').val();
        var url = $.format(loc.url.addtobag, varcode, qty);
        $("#favoriteresult").hide();
        $("#addtobagorderdetailresult"+varcode).hide().load(url, function () {
			Loreal.refreshBagOrderHistory(varcode);
		});
        return false;
    },
    refreshBagOrderHistory: function(varcode) {
        var $addtobagresult = $("#addtobagorderdetailresult"+varcode);
        if ($("#addtobagsuccess").length) {
            $("#header_bag_container").load(loc.url.refreshbag, Loreal.afterRefreshBag);
        }
        else {
            $addtobagresult.show();
        }
    },
    addToBag: function() {
        // Pour déterminer d'ou vient l'action dans la page product (plusieurs boutons ajouter au panier)
        Loreal.conteneur_tampon = '';
        if ($(this).parents('#productlayout').size()) {
            Loreal.conteneur_tampon = '#productlayout ';
        }

        $(this).blur();
        var varcode = $(Loreal.conteneur_tampon + "select[id=varlist] option:selected").val().split('#')[0];
        var qty = $(Loreal.conteneur_tampon + "select[id=qtylist] option:selected").val();
        var url = $.format(loc.url.addtobag, varcode, qty);
        $(Loreal.conteneur_tampon + "div[id=addtobagresult]").hide().load(url, Loreal.refreshBag);
        return false;
    },
    refreshBag: function() {
        var $addtobagresult = $(Loreal.conteneur_tampon + "div[id=addtobagresult]");
        if ($(Loreal.conteneur_tampon + "div[id=addtobagsuccess]").length) {
            $("#header_bag_container").load(loc.url.refreshbag, Loreal.afterRefreshBag);
        }
        else {
            $addtobagresult.show();
        }
    },
    afterRefreshBag: function() {
        if (Loreal.refresh_one_more_time) {
            Loreal.refresh_one_more_time = false;
            $("#header_bag_container").load(loc.url.refreshbag, Loreal.afterRefreshBag);
        } else if (Loreal.Page.Name != 'basket') {
            $("#header_bag_title").click(Loreal.openBag);
            $("#header_bag_open_basket_layer").click(Loreal.openBag);
            //$("IMG.imgtog", this).ToggleImage();
            Loreal.closeQuickShop();
            $("BODY").scroll(); //Scroll Top
            Loreal.openBag();
            window.setTimeout('Loreal.CloseBagWithTimer();', 5000);
            // On repasse le marqueur à true au cas ou ajout d'un autre panier
            Loreal.refresh_one_more_time = true;
        } else {
            Loreal.CloseBagWithTimer();
            // On repasse le marqueur à true au cas ou ajout d'un autre panier
            Loreal.refresh_one_more_time = true;
        }

    },
    CloseBagWithTimer: function() {
        Loreal.closeBag();
        $("#header_bag_title").mouseover(function() {
            timerBag = window.setTimeout("Loreal.openBag()", 1000);
            $("#header_bag_title").mouseout(function() {
                window.clearTimeout(timerBag)
            });
        });
        $("#header_bag_title").mouseleave(function() {
            Loreal.closeBag();
        });
		PngFixImg();
		// On repasse le marqueur à true au cas ou ajout d'un autre panier
        Loreal.refresh_one_more_time = true;
    },
    openBag: function() {
        $("#headerbasket:hidden").slideDown();
    },
    closeBag: function() {
        $("#headerbasket").slideUp();
    },
    handleTabSelect: function handleTabSelect(event, tabs) {
        $(this).find(".tab_img_lt_on").addClass("tab_img_lt_off").removeClass("tab_img_lt_on");
        $(this).find(".tab_img_rt_on").addClass("tab_img_rt_off").removeClass("tab_img_rt_on");
        var $li = $(tabs.tab).blur().parent();
        $li.prev().addClass("tab_img_lt_on").removeClass("tab_img_lt_off");
        $li.next().addClass("tab_img_rt_on").removeClass("tab_img_rt_off");
    },
    sortByPriceAsc: function() {
        Loreal.sortPaging(this, Loreal.sortPriceAsc);
        return false;
    },
    sortByPriceDesc: function() {
        Loreal.sortPaging(this, Loreal.sortPriceDesc);
        return false;
    },
    sortByNameAsc: function() {
        Loreal.sortPaging(this, Loreal.sortNameAsc);
        return false;
    },
    sortByNameDesc: function() {
        Loreal.sortPaging(this, Loreal.sortNameDesc);
        return false;
    },
    sortPaging: function(element, sortfunc) {
        var $pageselect = $("a[class^='pagingpage'].selected_sort_page_link");
        $(".body_sort_paging a").removeClass("selected_sort_page_link");
        $(element).blur().addClass("selected_sort_page_link");
        var mylist = $("#body_content_item_container");
        var listitems = mylist.find(".body_content_item").removeClass(loc.paging.spacerclass);
        listitems.sort(sortfunc); //Sort table
        $.each(listitems, function(index, item) { mylist.append(item); }); //Append new sort
        listitems.filter(":nth-child(" + loc.paging.spacernth + ")").addClass(loc.paging.spacerclass);
        if ($("#pagingseeall:visible").length) {
            $pageselect.click();
        }
    },
    sortPriceAsc: function(a, b) {
        var compA = Loreal.getPrice(a);
        var compB = Loreal.getPrice(b);
        return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    },
    sortPriceDesc: function(a, b) {
        var compA = Loreal.getPrice(a);
        var compB = Loreal.getPrice(b);
        return (compA < compB) ? 1 : (compA > compB) ? -1 : 0;
    },
    sortNameAsc: function(a, b) {
        var compA = Loreal.getName(a);
        var compB = Loreal.getName(b);
        return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
    },
    sortNameDesc: function(a, b) {
        var compA = Loreal.getName(a);
        var compB = Loreal.getName(b);
        return (compA < compB) ? 1 : (compA > compB) ? -1 : 0;
    },
    getPrice: function(element) {
        var $element = $(element);
        var $price = $element.find(".product_amount_new");
        if ($price.length == 0) {
            $price = $element.find(".product_amount");
        }
        return parseFloat($price.text().replace(loc.currency, "").replace(" ", "").replace(",", "."));
    },
    getName: function(element) {
        return $(element).find("H2.product_name").text().toLowerCase().replace('"', "");
    },
    selectedShade: function() {
        var sku = this.id.split("_")[1];
        var $selected = $("#varlist option[value^=" + sku + "]").attr("selected", "selected");
        Loreal.setProductData($selected);
        $(this).blur();
        return false;
    },
    selectedList: function() {
        $(this).blur();
        var $selected = $(this).find("option:selected");
        Loreal.setProductData($selected);
    },
    setProductData: function($selected) {
        // Pour déterminer d'ou vient l'action dans la page product (plusieurs boutons ajouter au panier)
        Loreal.conteneur_tampon = '';
        if ($selected.parents('#productlayout').size()) {
            Loreal.conteneur_tampon = '#productlayout ';
        }

        var shade = $selected.text();
        var values = $selected.val().split("#");
        var sku = values[0];
        var price = values[1];
        var stock = parseInt(values[2]);
        var newprice = values[3];
        var reference_unit = values[4];
        var reference_quantity = values[5];
        var quantity = values[6];
        var parsedPrice = strrev(strrev(newprice).substring(2)).replace(",", ".");
        var reference_price = parseFloat(parseFloat(parsedPrice) / parseFloat(quantity) * parseFloat(reference_quantity));

        if (reference_price.toString() != 'NaN') {
            $(Loreal.conteneur_tampon + "#product_reference_price").text(round(reference_price, 2) + '€ / ');
        }

        if (reference_quantity != '') {
            //alert('reference_unit='+reference_unit);
            $(Loreal.conteneur_tampon + "#product_reference_quantity_and_unit").text(reference_quantity + " " + reference_unit);
        }

        var $shades = $(".shade_item");
        if ($shades.length > 0) {
            $shades.removeClass("selected_shade_item");
            $(Loreal.conteneur_tampon + "#shade_" + sku).addClass("selected_shade_item").blur();
            $(Loreal.conteneur_tampon + "#product_shade_preview_text").text(shade);
            //$("#img_product_shade").attr("alt", shade).attr("title", shade).attr("src", $.format(loc.packshot.variants, sku));
            //$("#img_preview_shade").attr("alt", shade).attr("title", shade).attr("src", $.format(loc.packshot.shades, sku));
            $(Loreal.conteneur_tampon + "#img_title_shade").attr("alt", shade).attr("title", shade).attr("src", $.format(loc.packshot.shadestitle, sku));
        }

        if (stock <= 5) {
            $(Loreal.conteneur_tampon + "a[id=addtobag]").show();
            $(Loreal.conteneur_tampon + "div[id=out_of_stock]").hide();
            $(Loreal.conteneur_tampon + "div[id=nostock_popin]").hide();
            $('#addtobag').click(function() {
                var url = '/ajax/productnotification.aspx?prdcode=' + $("#prdcode").val();
                $.get(url, Loreal.getProductNotification);

                /*$('#nostock_popin').show().find('.close_popin').click( function () {
                $('#nostock_popin').hide();
                return false;
                });*/
                return false;
            });
        }
        else {
            $(Loreal.conteneur_tampon + "a[id=addtobag]").show();
            $(Loreal.conteneur_tampon + "div[id=out_of_stock]").hide();
        }
		/* 	Modification du 25-02-2011 : Le changement de variant dans la popin Quick shop ne modifiait pas le champ prix. 
		 	Récupération du if/else de Khiel's FR et mise en commentaire de celui qui ne marchait pas */
		if (newprice == price) {
			$("#prd_price").removeClass("price_old").addClass("price").text(price).show();
			$("#prd_newprice").text("").show();
		}
		else {
			$("#prd_price").removeClass("price").addClass("price_old").text(price).show();
			$("#prd_newprice").text(newprice).show();
		} 
		/*
        if (newprice == price) {
            $(Loreal.conteneur_tampon + "p[id=prd_price]").removeClass("price_old").addClass("price").text(price).show();
            $(Loreal.conteneur_tampon + "p[id=prd_newprice]").text("").show();
        }
        else {
            $(Loreal.conteneur_tampon + "p[id=prd_price]").removeClass("price").addClass("price_old").text(price).show();
            $(Loreal.conteneur_tampon + "p[id=prd_newprice]").text(newprice).show();
        }*/
    },
    setLogin: function() {
        $("INPUT[id$=hidden_login]").val($(this).val());
    },
    toggleLoginLayer: function() {
		if ( $("#login_layer").dialog('isOpen') ) {
			$("#login_layer").dialog('close');
		} else {
			$("#login_layer").dialog('open');
		}
    },
    toggleNostockPopin: function() {
        $(this).blur();
        $("#nostock_popin").toggle();
    },

    showPopinForgotPassword: function() {
        $('#popin_forgot_password').dialog('open');
        return false;
    },
    oneZoom: function() {
        Loreal.startLoading.apply($("#popin_loading"));
        var prdcode = $(this).attr("href").split("#")[1];
        var src = $.format(loc.packshot.zoom, prdcode);
        $(Loreal.zoomImg).attr("src", src);
        return false;
    },
    loadZoom: function() {
        $(this).hide();
        $("#productlayout_content").append(this);
        $(this).css("width", "500px").fadeIn();
        $("#productZoom").dialog({
            width: 523,
            bgiframe: true,
            modal: true,
            draggable: false,
            resizable: false,
            position: "center",
            autoOpen: true,
            dialogClass: "popin_zoom",
            hide: "slide",
            show: "slide"
        }).find(".popin_close_button").click(Loreal.closeZoom).blur();
        $("#zoom").click(Loreal.openZoom);
        Loreal.stopLoading.apply($("#popin_loading"));
    },
    openZoom: function() {
        $("#productZoom").dialog("open");
        return false;
    },
    closeZoom: function() {
        $("#productZoom").dialog("close");
        return false;
    },
    errorZoom: function() {
        Loreal.stopLoading.apply($("#popin_loading"));
        $("#zoom").click(Loreal.alertZoom);
        Loreal.alertZoom();
        return false;
    },
    alertZoom: function() {
        alert(loc.zoom.error);
        return false;
    },
    storeLocator: function() {
        var address = $("#loc-address").val();
        var city = $("#loc-city").val();
        var postcode = $("#loc-postcode").val();
        var country = $("#loc-country option:selected").val();
        address = encodeURIComponent($.format(loc.storelocator.addressformat, address, city, postcode, country));
        var url = $.format(loc.url.storelocator, address);
        $(location).attr("href", url);
        return false;
    },
    createGiftWrapping: function() {
        var $gift = $("#giftwrappinglayout");
        $gift.dialog({
            width: 280,
            resizable: false,
            bgiframe: true,
            modal: true,
            autoOpen: false,
            position: "center",
            dialogClass: 'popin_product_layer'
        }).find(".popin_close_button").click(Loreal.closeGiftWrapping).blur();
        $("#addgiftwrapping").click(Loreal.addGiftWrapping);
        $("#removegiftwrapping").click(Loreal.removeGiftWrapping);
        $("#giftwrapmessage").keyup(Loreal.maxLength);
        Loreal.maxLength.apply($("#giftwrapmessage"));
    },
    maxLength: function() {
        if ($(this).val()) {
            var $this = $(this);
            var max = loc.giftwrapping.maxlength;
            var originalVal = $this.val();
            var val = originalVal.replace(/\^+/g, ""); //Remove ' ^ ' character.
            if (val.length > max) {
                val = val.substr(0, max);
            }
            if (originalVal != val) {
                var scrollTop = $this.attr("scrollTop"); //Save scroll bar position
                var selectionStart = $this.attr("selectionStart"); //Save selection start
                var selectionEnd = $this.attr("selectionEnd"); //Save selection end
                $this.val(val);
                $this.attr("scrollTop", scrollTop);  //Set old scroll bar position
                $this.attr("selectionStart", selectionStart);  //Set old selection start
                $this.attr("selectionEnd", selectionEnd);  //Set old selection end
            }
            var text = $.format(loc.giftwrapping.remaining, max - $this.val().length);
            $("#length_left").html(text);
        }
    },
    addGiftWrapping: function() {
        $("#giftwrappingerror").hide();
        $("#giftwrappingload").hide();
        var $giftwrap = $("INPUT[type=radio][name=giftwrap]:checked");
        var from = encodeURIComponent($("#giftwrapfrom").val());
        var to = encodeURIComponent($("#giftwrapto").val());
        var message = encodeURIComponent($("#giftwrapmessage").val());
        if ($giftwrap.length && from != "" && to != "" && message != "") {
            var code = encodeURIComponent($giftwrap.val());
            var url = $.format(loc.url.addgiftwrapping, code, from, to, message);
            $("#giftwrappingload").load(url, Loreal.addGiftWrappingOK);
        }
        else {
            $("#giftwrappingerror").show();
        }
        return false;
    },
    removeGiftWrapping: function() {
        $.get(loc.url.removegiftwrapping, Loreal.removeGiftWrappingOK);
        return false;
    },
    addGiftWrappingOK: function() {
        if ($("#addgiftwrapsuccess").length) {
            $(location).attr("href", $(location).attr("href"));
        }
        else {
            $("#giftwrappingload").show();
        }
    },
    removeGiftWrappingOK: function() {
        $(location).attr("href", $(location).attr("href"));
    },
    openGiftWrapping: function() {
        $("#giftwrappinglayout").dialog("open");
        $("#mycarousel_gift").show().jcarousel();
        return false;
    },
    closeGiftWrapping: function() {
        $("#mycarousel_gift").hide();
        $("#giftwrappinglayout").dialog("close");
        return false;
    },
    labelLink: function() {
        //Prevent checkbox check when clicking on link inside label
        $("A.labellink").click(function() {
            window.open($(this).attr("href"), "_blank");
            return false;
        });
    },
    showSpecialOffers: function() {
        var image = $('#header_static_navbar_rightmost_option img').eq(0);
        image.attr("src", image.attr("src").replace("_OFF.", "_ON."));
        $('#promotion_layer').show();
    },
    hideSpecialOffers: function() {
        var image = $('#header_static_navbar_rightmost_option img').eq(0);
        image.attr("src", image.attr("src").replace("_ON.", "_OFF."));
        $('#promotion_layer').hide();
    },
    remplirCatpath: function(menu, ligne, input) {
        $(menu).each(function() {
            if ($(this).find('input' + input).size()) {
                var catpath = $(this).find('input' + input).val();
                $(this).find(ligne).each(function() {
                    $(this).attr('href', $(this).attr('href') + catpath);
                });
            }
        });
    },
    onReady: function() {
        /* Switch Site Homme/Femme - Begin */
        /* Ce traitement permet de basculer entre le site homme et femme de Biotherm FR 
        * Pour basculer sur le site homme il faut mettre le paramètre "site_men=true" dans l'URL et recharger le navigateur
        * Pour revenir au site femme il suffit de supprimer ce paramètre
        */
        var locSiteMen = window.location;
        var pathNameParam = locSiteMen.search.substring(locSiteMen.search.length - 5, locSiteMen.search.length - 13);
        var pathNameParamValue = locSiteMen.search.substring(locSiteMen.search.length, locSiteMen.search.length - 4);
        var success = ($("#nostock_popin").length > 0);
        if (success)
            Loreal.LoadPopinProductNotification();
        if (pathNameParam == 'site_men' && pathNameParamValue == 'true') {
            /* Changement du background body dans la CSS */
            //var BodyBackground = $("body").css("background-image");
            //var NewBodyBackground = BodyBackground.replace("/img/","/men/img/");
            //$("body").css("background-image", NewBodyBackground);
            /* Changement du background des DIV dans la CSS */
            $("*").each(function() {
                var DivBackground = $(this).css("background-image");
                var NewDivBackground = DivBackground.replace("/img/", "/men/img/");
                $(this).css("background-image", NewDivBackground);
            });

            $("link[href^='/css/']").each(function() {
                /* Changement de l'inclusion des feuilles de styles */
                this.href = this.href.replace("/css/", "/men/css/");
            });
            $("link[href^='/img/']").each(function() {
                /* Changement de l'inclusion de l'icone du site */
                this.href = this.href.replace("/img/", "/men/img/");
            });
            $("img[src^='/img/']").each(function() {
                /* Changement de l'inclusion des images */
                this.src = this.src.replace("/img/", "/men/img/");
            });
            //alert('Bienvenue sur le site homme de Biotherm FR ...');
        }
        /* Test permettant de vider le champ code postal s'il contient des valeurs alphabétiques */
        function testIsNumeric(element) {
            var valid = "0123456789-";
            var hyphencount = 0;
            field = element.value;
            for (var i = 0; i < field.length; i++) {
                temp = "" + field.substring(i, i + 1);
                if (temp == "-") hyphencount++;
                if (valid.indexOf(temp) == "-1") {
                    element.value = "";
                    return false;
                }
            }
        }

        /* Switch Site Homme/Femme - End */
        // Fermer le popin out of stock 
        if ($("#test_SuccessTemplate").val() == 'OK') {
            Loreal.toggleNostockPopin();
        }

        if (Loreal.Page == null)
            return;
        Loreal.Page.Name = Loreal.Page.Name.toLowerCase().replace(".aspx", "");
        var IsPage = function(pages) {
            var pageName = Loreal.Page.Name;
            var list = pages.split(",");
            var isPage = false;
            $.each(list, function() {
                if (this == pageName) {
                    isPage = true;
                }
                return !isPage;
            });
            return isPage;
        }

        /*var couleur = '#F00';
        var conteneur_select;
        $('select').each(function () {
        $(this).wrap('<div class="conteneur_select"></div>');
        conteneur_select = $(this).parent();
        conteneur_select.css('width', ($(this).innerWidth() + 2) + 'px');
        conteneur_select.css('height', ($(this).innerHeight() + 2) + 'px');
        conteneur_select.css('border', '1px solid ' + couleur);
        conteneur_select.css('position', 'relatif');
        conteneur_select.css('margin', '-1px 0 0 -1px');
        });*/


        // First tab dynmenu
        $('.header_catalogue_navbar_item_common').eq(0).addClass('first_header_catalogue_navbar');
        //Fix Url rewriting
        $("form").attr("action", Loreal.Page.Url);
        //All : Set image toggle
        //$("IMG.imgtog").ToggleImage();
        //All : Reset password field
        $(".input_container input[id$=password]").val("");
        //Header : Set Menu
        $("#header_catalogue_navbar").find(".navbar_item_off div").mouseover(Loreal.menuOnMouseOver).mouseout(Loreal.menuOnMouseOut); //Init Main Menu
        //Header : Set search text and keypress
        $("#header_input_search").DefaultValue(loc.search.value).keyPressEnter("#launch_search");
        //Footer : Set mailing text and keypress
        $("#footer_input_search INPUT").DefaultValue(loc.newsletter.email).keyPressEnter("A[id$=submitNL]");
        //Header : Set search feature
        $("#launch_search").click(Loreal.search);
        // Page recherche
        $("#launch_search2").click(Loreal.search2);
        // Le body rail n'est pas cliquable
        //$('#body_rail a').click(function () {return false;});
        //Product & Receipt : Set print
        $("#print").click(Loreal.print);
        // Catpath dans les liens
        /*retour a la normal */
	Loreal.remplirCatpath('#header_catalogue_navbar li[class^=navbar_item_]', '.colonne a', '.catpath');
        Loreal.remplirCatpath('#body_rail', 'a', '.catpath');
        Loreal.remplirCatpath('#menu', '#ul_all li a, #ul_need li li a, #ul_gamme li a', '.catpath');
        Loreal.remplirCatpath('#navigation_sitemap_women', 'li a', '.catpathWomen');
        Loreal.remplirCatpath('#navigation_sitemap_men', 'li a', '.catpathMen');
        //Header : Set Basket action
        var timerBag = 0;
        $("#header_bag_title").mouseover(function() {
            timerBag = window.setTimeout('Loreal.openBag()', 1000);
            $("#header_bag_title").mouseout(function() { window.clearTimeout(timerBag) });
        }); //mouseover
        $("#header_bag_title").mouseleave(function() { Loreal.closeBag(); });
        //All : Set Ajax Loading
        $("#popin_loading").ajaxStart(Loreal.startLoading).ajaxStop(Loreal.stopLoading).dialog({
            width: 201,
            bgiframe: true,
            modal: true,
            draggable: false,
            resizable: false,
            position: "center",
            autoOpen: false,
            dialogClass: "popin_loading"
        });
        $("#popin_login").dialog({
            width: 327,
            bgiframe: true,
            modal: true,
            draggable: true,
            resizable: false,
            position: "center",
            //show: 'slide',
            //hide: 'slide',
            autoOpen: false,
            dialogClass: "popin_login"
        }).find("#close_popin_login").click(function() {
            $("#popin_login").dialog("close");
            return false;
        }).blur();
        $("A[id$=submitpopinlogin]").click(function() {
            //Need to be in form
            $("/html/body/form[0]").append($("#popin_login").parent());
        });
        $("#popin_forgot_password").dialog({
            width: 324,
            bgiframe: true,
            modal: true,
            draggable: true,
            resizable: false,
            position: "center",
            //show: 'slide',
            //hide: 'slide',
            autoOpen: false,
            dialogClass: "popin_forgot_password"
        }).find("#close_forgot_password_layer").click(function() {
            $("#popin_forgot_password").dialog("close");
            return false;
        }).blur();
        $("A[id$=submitforgotpassword]").click(function() {
            //Need to be in form
            $("/html/body/form[0]").append($("#popin_forgot_password").parent());
        });
		
		$("#login_layer").dialog({
			width: 328,
			bgiframe: false,
			modal: true,
			draggable: false,
			resizable: false,
			position: ["center", "top"],
			autoOpen: false,
			dialogClass: "login_layer"
		}).blur();
		$("A[id$=submitheaderlogin]").click(function() {
			//Need to be in form
			$("/html/body/form[0]").append($("#login_layer").parent());
		});

        $("#popin").dialog({
            width: 320,
            bgiframe: true,
            modal: true,
            draggable: true,
            resizable: false,
            position: "center",
            //show: 'slide',
            //hide: 'slide',
            autoOpen: false,
            dialogClass: "popin_favorite"
        }).find(".close_popin_favorite").click(function() {
            if ($("#successpopinlogin").length) {
                $(location).attr("href", $(location).attr("href"));
            }
            else {
                $("#popin").dialog("close");
            }
            return false;
        }).blur();
        // Popins checkout
        $("#popin_colissimo").css({ 'position': 'absolute', 'display': 'none' });
        $("#popin_territory").css({ 'position': 'absolute', 'display': 'none' }).find(".close_popin").click(function() {
            $("#popin_territory").hide();
            return false;
        }).blur();
        $('#shipping_type').mouseover(function() { $("#popin_colissimo").show(); });
        $('#shipping_type').mouseout(function() { $("#popin_colissimo").hide(); });
        $('#shipping_list').click(function() { $("#popin_territory").show(); });
        // Popin send wishlist
        $("#popin_send_wishlist").dialog({
            width: 720,
            bgiframe: true,
            modal: true,
            draggable: false,
            resizable: false,
            position: "center",
            autoOpen: false,
            dialogClass: "popin_send_wishlist"
        });
        $("#popin_send_product").dialog({
            width: 720,
            bgiframe: true,
            modal: true,
            draggable: false,
            resizable: false,
            position: "center",
            autoOpen: false,
            dialogClass: "popin_send_product"
        });
        //All : Set Ajax Error
        $(location).ajaxError(Loreal.errorRedirect);
        //Header : Set login menu
        $("#header_login_button_sign_in, #header_login_button_order, #close_login_layer").click(Loreal.toggleLoginLayer);
        // Fermer out of stock 
        $("#close_nostock_popin").click(Loreal.toggleNostockPopin);

        $(".forgot_password").click(Loreal.showPopinForgotPassword);
        //Headet : Set keypress, login and password text
        $("#login_layer INPUT[id$=login]").DefaultValue(loc.login.email).keyPressEnter("A[id$=submitheaderlogin]");
        $("#login_layer INPUT[id$=password]").DefaultValue(loc.login.password).keyPressEnter("A[id$=submitheaderlogin]");
        if ($("#login_layer .messagekoerror").length || $(location).attr("href").indexOf("ReturnUrl=") > 0) {
            Loreal.toggleLoginLayer();
        }
		if ($("#popin_login .messagekoerror").length) {
            $("#popin_login").dialog("open");
        }
        if ($("#popin_forgot_password .messagekoerror").length) {
            $("#popin_forgot_password").dialog('open');
        }

        //Some pages : Set Carousel if exist
        if ($.fn.jcarousel) {
            $("#mycarousel").show().jcarousel();
            $("#mycarousel2").show().jcarousel();
            $("#mycarousel3").show().jcarousel();
            if ($.browser.safari) {
                $(".jcarousel-prev, .jcarousel-next").css("top", "53px");
            }
        }

        // Remplacement des nombres dans le footer
        // texte_livraison défini dans default/generalcall
        $(function() {
            var div_echantillons = 'id=banner1_text_1';
            var div_livraison = 'id=banner2_text_1';

            if ($('#footer *[' + div_livraison + ']').size()) {
                $('#footer *[' + div_livraison + ']').html($('#footer *[' + div_livraison + ']').html().replace('{PROMO_FREE_SHIP}', texte_livraison_footer));
            }
            if ($('#footer *[' + div_echantillons + ']').size()) {
                $('#footer *[' + div_echantillons + ']').html($('#footer *[' + div_echantillons + ']').html().replace('{PROMO_SAMPLE}', texte_echantillon_footer));
            }
        });


        // Offre spéciale
        if (IsPage("index")) {
            Loreal.showSpecialOffers();
            setTimeout('Loreal.hideSpecialOffers();', 4000);
        }
        $('#header_static_navbar_rightmost_option').mouseenter(Loreal.showSpecialOffers);
        $('#header_static_navbar_rightmost_option').mouseleave(Loreal.hideSpecialOffers);

        // Affichage quickshop
        if (IsPage("subcategory,search,gift,product")) {
            $('.body_content_item .product_photo').each(function() {
                $(this).mouseover(function() {
                    $($(this).children()[1]).show();
                });
                $(this).mouseout(function() {
                    $($(this).children()[1]).hide();
                });
            });

        }
        // Action du quickshop
        if (IsPage("subcategory,search,content,staticpage,category,gift,product")) {
            $("a[id^=quickshop]").click(Loreal.loadQuickShop);
        }

        // Product - for daily routine and perfect partners
        if (IsPage("product")) {
            //Product : Set Tab if exist
            var $li = $("#tabs").tabs({ select: Loreal.handleTabSelect }).show().find("li a:first").parent();
            $li.prev().addClass("tab_img_lt_on").removeClass("tab_img_lt_off");
            $li.next().addClass("tab_img_rt_on").removeClass("tab_img_rt_off");

            Loreal.zoomImg = new Image();
            $(Loreal.zoomImg).load(Loreal.loadZoom).error(Loreal.errorZoom);
            $("#zoom").one("click", Loreal.oneZoom);


            if ($('.daily_routine_item')) {
                for (var i = 0; i < $('.daily_routine_item').length; i++) {
                    if (i < $('.daily_routine_item').length - 1) {
                        //on insert le +					
                        $('<img src="/img/Product/plus.gif" class="compo_pack" />').insertAfter($('.daily_routine_item')[i]);
                    } else {
                        //sinon on insert le =
                        $('<img src="/img/Product/egal.gif" class="compo_pack" />').insertAfter($('.daily_routine_item')[i]);
                    }
                }
            }
            if ($('.perfect_partners_item')) {
                for (var i = 0; i < $('.perfect_partners_item').length - 1; i++) {
                    //on insert la séparation				
                    $('<img src="/img/Product/separation_produit.jpg" class="separation_compo_pack" />').insertAfter($('.perfect_partners_item')[i]);
                }
            }

            // Last viewed
            $(".last_product_viewed").mouseover(function() {
                timerView = window.setTimeout('$("#last_view_list").slideDown();', 1000);
                $(".last_product_viewed").mouseout(function() { window.clearTimeout(timerView) });
            });
            $(".last_product_viewed").mouseleave(function() { $('#last_view_list').slideUp(); });


            // Prix de référence
            $("*[class=product_reference_price_container]").each(function() {

                var price = $("input[id=price_" + this.id + "]")[0].value;
                var reference_quantity = $("input[id=reference_quantity_" + this.id + "]")[0].value;
                var quantity = $("input[id=quantity_" + this.id + "]")[0].value;

                price = strrev(strrev(price).substring(2)).replace(",", ".");
                var reference_price = parseFloat(parseFloat(price) / parseFloat(quantity) * parseFloat(reference_quantity));
                if (reference_price.toString() != 'NaN') {
                    $("#product_reference_price_" + this.id).text(round(reference_price, 2));
                }
            });
            Loreal.remplirCatpath('.category_div', 'a', '.catpath');

            // Produits complémentaires
            var prdList = "";
            $("input[id*='var_']").each(function(i) {

                if (i == 0) {
                    prdList = $(this).val();
                }
                else {
                    prdList = prdList + ":" + $(this).val();
                }
            });

            $("#addToBasket").click(function() {
                var dataForm = $("#insertdata");
                $.get("TpShoppingCartAddUrl.aspx?productstoadd=" + prdList, dataForm, function(data) {
                    $("#insertdata").children().remove();
                    $("#insertdata").append($(data).filter(".ShoppingCart").children());
                    if ($("#insertdata").find('span[id$=Addes]').size()) {
                        $("#header_bag_container").load(loc.url.refreshbag, function() {
                            $("#header_bag_container").load(loc.url.refreshbag, function() {
                                $("BODY").scroll(); //Scroll Top
                                Loreal.openBag();
                                window.setTimeout('Loreal.CloseBagWithTimer();', 5000);
                            });
                        });
                    }
                });
            });
        }

        if (IsPage("receipt-failed")) {
			$("#btn_ajouter_panier_aux_favoris").click(Loreal.addBasketToBag);
		}

        //Product & Product Layout & Search
        if (IsPage("subcategory,search,product,content,staticpage")) {
            //Set addToBag action
            $("#body #addtobag").click(Loreal.addToBag);
            //Set addToFavorite action
            $("#body #addtofavorite").click(Loreal.addToFavorite);
            //Set product select
            $("#body select[id=qtylist] option:first,#body select[id=varlist] option:first").attr("selected", "selected");
            var $varlist = $("#body select[id=varlist]").change(Loreal.selectedList);
            if ($varlist.length) {
                Loreal.selectedList.apply($varlist); //Set the first selected shade
            }
            $("#body .shade_item").click(Loreal.selectedShade);
        }

        if (IsPage("sitemap")) {
            $(".column").filter(":odd").filter(":odd").after('<div class="column_spacer"></div>');
        }

        // Checkout delivery
        if (IsPage("checkout-delivery")) {
            // Le faux bouton doit prendre le href du vrai qui doit rester dans le bodytemplate
            $('.button_proceed').attr('href', $('a[id$=submitcheckoutregister]').attr('href'));
        }

        // Paging
        if (IsPage("subcategory,search,gift")) {
            var $quickpage = $(".body_content_item, .body_category_subtitle");
			if ( IsPage("gift") ) {
				loc.paging.lineperpage = 7;
			}
            //Set Quick Paginate
            $quickpage.quickpaginate({ pager: $(".body_paging"), perpage: loc.paging.perpage, seealltext: loc.paging.seeall, countertext: loc.paging.counter, spacernth: loc.paging.spacernth, spacerclass: loc.paging.spacerclass, lineperpage: loc.paging.lineperpage });
            if ($quickpage.length == 1) {
                $(".body_sort_paging").hide();
            }
            else {
                //Set name sorting
                $(".paging_name_desc").click(Loreal.sortByNameDesc);
                $(".paging_name_asc").click(Loreal.sortByNameAsc);
                //Set price sorting
                $(".paging_price_desc").click(Loreal.sortByPriceDesc);
                $(".paging_price_asc").click(Loreal.sortByPriceAsc);
            }
        }

        // A trier apres
        $("a[id$=btn_send_wishlist]").click(Loreal.loadPopinSendWishlist);
        $("#btn_send_product").click(Loreal.loadPopinSendProduct);

        // Homepage (bottomcol picture)
        var images = $('#homepage_bottomcol .image');
        if (images.length > 0) {
            var tampon_top = 0;
            var nb_images = 0;

            while (images[nb_images]) {
                if (tampon_top != images[nb_images].offsetTop) {
                    $(images[nb_images]).addClass('first_image');
                    tampon_top = images[nb_images].offsetTop;
                }
                nb_images++;
            }
        }

        //Open QuickShop if login error
        if ($("#popin_login .messagekoerror").length) {
            var $state = $("INPUT[id$=save_state]");
            if ($state.length) {
                Loreal.loadState = true;
                Loreal.loadQuickShop.apply($state.get(0));
            }
            else {
                $("#addtofavorite").click();
            }
        }

        //Open QuickShop if login success
        if ($("#successpopinlogin").length) {
            Loreal.Customer.Signed = true;
            var $state = $("INPUT[id$=save_state]");
            if ($state.length) {
                Loreal.loadState = true;
                Loreal.loadQuickShop.apply($state.get(0));
            }
            else {
                $("#addtofavorite").click();
            }
        }

        //Favorites

        if (IsPage("myspace")) {
            //Set "delete" and "add to bag"
            $("A[class=addtobagfavorite]").click(Loreal.addToBagFavorite);
            $("A[class=addallfavoritetobag]").click(Loreal.addAllFavoriteToBag);
            $("A[class=deletefavorite]").click(Loreal.deleteFavorite);

            var onglets = new Onglets('onglets_dynamiques', 1);

            // Chargement dynamique de l'historique de commande
            var nombre_commandes = $('.orderid_history').size();
            $('.orderid_history').each(function(numero_commande) {
                var id_order = $(this).val();
                var url = $.format(loc.url.orderdetails, id_order);
                $(this).next().load(url, function() {
                    if (nombre_commandes == (numero_commande + 1)) {
                        $("A[id$=addtobagorderdetail]").click(Loreal.addToBagOrderDetail);
                    }
					PngFixImg();
                });
            });
            $('.orderid_status').each(function() {
                var id_order = $(this).val();
                var url = $.format(loc.url.orderstatus, id_order);
                $(this).parent().find('.description_order').load(url);
            });
			
			$("#body select[class=varlist]").change(function () {
			
				var $selected = $(this).find("option:selected");
				var shade = $selected.text();
				var values = $selected.val().split("#");
				var sku = values[0];
				var price = values[1];
				var stock = parseInt(values[2]);
				var newprice = values[3]; 
				
				
				if (newprice == price) {
					$(this).parent().parent().find('.prd_price').removeClass("price_old").addClass("price").text(price).show();
					$(this).parent().parent().find('.price_old_container').hide();
					$(this).parent().parent().find('.price_old').text("");
				}
				else {
					$(this).parent().parent().find('.prd_price').removeClass("price").addClass("price_new").text(newprice).show();
					$(this).parent().parent().find('.price_old_container').show();
					$(this).parent().parent().find('.price_old').text(price);
				}
			});
        }

        //Login&Register checkout
        if (IsPage("login-register")) {
            //Set Key Press Enter on inputs
            $("#checkout_register INPUT").keyPressEnter("A[id$=submitcheckoutregister]");
            $("#checkout_login INPUT").keyPressEnter("A[id$=submitcheckoutlogin]");
            //Set hidden login
            $("#checkout_register INPUT[id$=email]").blur(Loreal.setLogin);
            // Bouton interrogation
            $('#btn_interrogation').click(function() {
                $('#popin_newpassword').show().find('.close_popin').click(function() {
                    $('#popin_newpassword').hide();
                    return false;
                });
                return false;
            });
        }

        //Register
        if (IsPage("register")) {
            //Set Key Press Enter on inputs
            $("#register INPUT").keyPressEnter("A[id$=submitregister]");
            $("#othersubmitregister").click(function() { $("A[id$=submitregister]").clickServer(); return false; });
            //Set hidden login
            $("#register INPUT[id$=email]").blur(Loreal.setLogin);
            if (!Loreal.Page.IsPostBack) {
                $("INPUT[id$=ep0cbPrimaryDeliveryAddress]").attr("checked", "checked");
            }
        }

        //Edit profil
        if (IsPage("edit-profile")) {
            //Set Key Press Enter on inputs
            $("#editprofil INPUT").keyPressEnter("A[id$=submitedit]");
            $("#othersubmitedit").click(function() { $("A[id$=submitedit]").clickServer(); return false; });
            //Set hidden login
            $("#editprofil INPUT[id$=email]").blur(Loreal.setLogin);
        }

        //Register, edit-profil
        if (IsPage("register,edit-profile")) {
            Loreal.labelLink();
        }

        //Forgot Password
        if (IsPage("forgot-password")) {
            //Set password key press
            $("#forgotpassword INPUT").keyPressEnter("A[id$=submitforgotpassword]");
        }

        //Basket
        if (IsPage("basket")) {
            $("#header_bag_container").load(loc.url.refreshbag, Loreal.afterRefreshBag);
            //Remove
            $("A[id$=updatebutton]").each(function() {
                var $select = $(this).parent().parent().find("SELECT");
                if ($select.length == 0) {
                    $(this).remove();
                }
            });
            //Update buttons
            $("A[id$=updatebutton]").click(function() { $("A[id$=refreshbutton]").clickServer(); return false; });
            //Keycode
            $("INPUT[id$=keycode]").keyPressEnter("A[id$=submitkc]");
            Loreal.createGiftWrapping();
            $("#load_gift_popin,#updategiftwrap").click(Loreal.openGiftWrapping);
            //afficheContenuDiv($('#divDisplyOrNot'));

            // Valeur par defaut coupon code
            $(".input_coupon_code").each(function() {
                $(this).DefaultValue(loc.couponcode.value);
            });
			
			// Selection automatique coupon sur women
			$('#keywomen').attr('checked', 'cheched');
        }

        //Order History
        if (IsPage("order-history")) {
            //Set view order details
            $(".vieworderdetails").click(Loreal.viewOrderDetails);
            $(".vieworderdetails").eq(0).click();
        }

        //Order History
        if (IsPage("storelocator-search")) {
            $("#loc-search").click(Loreal.storeLocator);
            $("DIV.margin_bloc INPUT").keyPressEnter("#loc-search");
        }
		
		// Header checkout
		if (IsPage("login-register,checkout-delivery,one-page-checkout,check-payment")) {
			$('#mybag').addClass('etape_cliquable');
			$('#mybag').click(function () {
				document.location.href = loc.sitename + '/checkout/basket.aspx';
			});
		}
		if (IsPage("one-page-checkout,check-payment")) {
			$('#delivery').addClass('etape_cliquable');
			$('#delivery').click(function () {
				document.location.href = loc.sitenamessl + '/checkout/checkout-delivery.aspx';
			});
		}
		
		// Renommer les sitenames
		if (IsPage("one-page-checkout,check-payment,checkout-delivery,login-register,check_payment,receipt,receipt-failed")) {
			$('.lien_sitename').each( function () {
				$(this).attr( 'href', loc.sitename + $(this).attr('href') );
			});
		}

        //All page focus
        $(".setfocus").find("INPUT,SELECT").eq(0).focus();
    }
});

//On DOM Ready Let's Go
$(Loreal.onReady);

