﻿$(document).ready(function() {
    /* Customer service */
    if ($("#policy div.menu div.selected") && $("#policy div.menu div.selected").attr('id')) {
        document.getElementById($("#policy div.menu div.selected").attr('id').replace(/dv_/, 'pl')).style.display = '';
        $("#policy div.menu div").each(function(i) {
            if ($(this).parent().attr('class') == 'menu') {
                $(this).click(function(e) {
                    if (this.className != 'selected') {
                        var selItem = $("#policy div.menu div.selected").attr('id');
                        document.getElementById(selItem.replace(/dv_/, 'pl')).style.display = 'none';
                        document.getElementById(this.id.replace(/dv_/, 'pl')).style.display = '';
                        $("#policy div.menu div.selected").attr('class', '');
                        this.className = 'selected';
                    }
                });
            }
        });
    }

    var btSearch = "";
    var btSearchBool = true;

    $("#mainSearch #li1").click(function() {
        activeSearchBt("#mainSearch #li1 a");
        if ($("#searchEntries").is(":hidden")) {
            btSearch = "quickSearch";
            openSearchEntriesContent();
        } else if ($(".quickSearchEntries").is(":hidden")) {
            transitionSearchEntriesContent("quickSearch");
        }
    });

    $("#mainSearch #li2").click(function() {
        activeSearchBt("#mainSearch #li2 a");
        if ($("#searchEntries").is(":hidden")) {
            btSearch = "advSearch";
            openSearchEntriesContent();
        } else if ($(".advSearchEntries").is(":hidden")) {
            transitionSearchEntriesContent("advSearch");
        }
    });

    $("#mainSearch #li3").click(function() {
        activeSearchBt("#mainSearch #li3 a");
        if ($("#searchEntries").is(":hidden")) {
            btSearch = "searchParts";
            openSearchEntriesContent();
        } else if ($(".searchPartsEntries").is(":hidden")) {
            transitionSearchEntriesContent("searchParts");
        }
    });

    $(".btClose").click(function() {
        $("#searchEntries").slideUp("slow");
        activeSearchBt();
    });

    function openSearchEntriesContent() {
        $(".quickSearchEntries").hide();
        $(".advSearchEntries").hide();
        $(".searchPartsEntries").hide();
        if (btSearch == "quickSearch") {
            $(".quickSearchEntries").show();
        }
        else if (btSearch == "advSearch") {
            $(".advSearchEntries").show();
        } else {
            $(".searchPartsEntries").show();
        }
        $("#searchEntries").slideDown("slow");
    }

    function transitionSearchEntriesContent(actBt) {
        btSearch = actBt;
        $("#searchEntries").slideUp("slow", openSearchEntriesContent);
    }

    function activeSearchBt(actBt) {
        if (actBt != "#mainSearch #li1 a") {
            $("#mainSearch #li1 a").css({ 'background-position': '0' });
        }
        if (actBt != "#mainSearch #li2 a") {
            $("#mainSearch #li2 a").css({ 'background-position': '0' });
        }
        if (actBt != "#mainSearch #li3 a") {
            $("#mainSearch #li3 a").css({ 'background-position': '0' });
        }

        $("#mainSearch #li1 a").hover(
                function() {
                    $(this).css({ 'background-position': '-139px 0' });
                },
                function() {
                    $(this).css({ 'background-position': '0' });
                }
             );
        $("#mainSearch #li2 a").hover(
                function() {
                    $(this).css({ 'background-position': '-139px 0' });
                },
                function() {
                    $(this).css({ 'background-position': '0' });
                }
             );
        $("#mainSearch #li3 a").hover(
                function() {
                    $(this).css({ 'background-position': '-139px 0' });
                },
                function() {
                    $(this).css({ 'background-position': '0' });
                }
             );
        if (actBt != null) {
            $(actBt).hover(
                    function() {
                        $(this).css({ 'background-position': '-139px 0' });
                    },
                    function() {
                        $(this).css({ 'background-position': '-139px 0' });
                    }
                 );
        }

    }
    /* *************************************** jCarousel **************************************************** */

    var popkit = false;
    var mover = 4;

    if ($('.popkitMenu').length) {
        popkit = true;
        mover = 3;
    }



    $(".carrousel").each(function(index) {

        $(this).parent().css("overflow", "hidden");

        // Calcule de la longeur du .carrousel
        var Reference = $(this).children("li");
        originalCarrouselWidth = 0;
        for (var i = 0; i < Reference.length; i++) {
            originalCarrouselWidth += Reference[i].clientWidth;
        }

        var eightFirstItemsText = "";
        $(this).children("li:lt(7)").each(function(i) {
            eightFirstItemsText += "<li>" + this.innerHTML + "</li>";
        });
        $(this).append(eightFirstItemsText);


        // Calcule de la longeur du .carrousel
        Reference = $(this).children("li");
        var TotalWidth = 0;
        for (var i = 0; i < Reference.length; i++) {
            TotalWidth += Reference[i].clientWidth;
        }
        // Application d'une largeur à la bande de diapositive afin de conserver une structrure horizontale
        $(this).css("width", TotalWidth);



    });

    // Actions de navigation 

    // Initialisation du compteur 
    Cpt = 0;
    // Clic sur le lien "Suivant"
    $(".carrousel-next").click(function() {

        var Reference = $(this).parent().find(".carrousel").children("li");


        if ((Cpt + 7) >= Reference.length) {
            Cpt = 7 - (Reference.length - Cpt);

            Calcul = 0;
            for (var i = 0; i < Cpt; i++) {
                Calcul += Reference[i].clientWidth;
            }

            // Mouvement du carrousel en arrière-plan
            $(this).parent().find(".carrousel").css({
                marginLeft: -(Calcul)
            });
        }

        // Ajout +1 au compteur (nous allons sur la diapositive suivante)

        Cpt += mover;



        // Calcule
        Calcul = 0;
        for (var i = 0; i < Cpt; i++) {
            Calcul += Reference[i].clientWidth;
        }

        // Mouvement du carrousel en arrière-plan
        $(this).parent().find(".carrousel").animate({
            marginLeft: -(Calcul)
        }, 1000);

        // Blocage du lien 
        return false;

    });



    // Clic sur le lien "Précédent"
    $(".carrousel-prev").click(function() {

        var Reference = $(this).parent().find(".carrousel").children("li");

        // Si le compteur est supérieur à zéro

        if (Cpt < mover) {
            Cpt = Reference.length + Cpt - 7;


            Calcul = 0;
            for (var i = 0; i < Cpt; i++) {
                Calcul += Reference[i].clientWidth;
            }

            // Mouvement du carrousel en arrière-plan
            $(this).parent().find(".carrousel").css({
                marginLeft: -(Calcul)
            });
        }

        // Soustraction -1 au compteur (nous allons sur la diapositive précédente)
        Cpt -= mover;

        // Calcule
        Calcul = 0;
        for (var i = 0; i < Cpt; i++) {
            Calcul += Reference[i].clientWidth;
        }

        // Mouvement du carrousel en arrière-plan
        $(this).parent().find(".carrousel").animate({
            marginLeft: -(Calcul)
        }, 1000);

        // Blocage du lien 
        return false;

    });



    /*
    $(".carrousel").parent().css("overflow", "hidden");

    // Calcule de la longeur du .carrousel
    var Reference = $(".carrousel li");
    originalCarrouselWidth = 0;
    for (var i = 0; i < Reference.length; i++) {
    originalCarrouselWidth += Reference[i].clientWidth;
    }

    var eightFirstItemsText = "";
    $(".carrousel li:lt(7)").each(function(i) {
    eightFirstItemsText += "<li>" + this.innerHTML + "</li>";
    });
    $(".carrousel").append(eightFirstItemsText);


    // Calcule de la longeur du .carrousel
    Reference = $(".carrousel li");
    var TotalWidth = 0;
    for (var i = 0; i < Reference.length; i++) {
    TotalWidth += Reference[i].clientWidth;
    }
    // Application d'une largeur à la bande de diapositive afin de conserver une structrure horizontale
    $(".carrousel").css("width", TotalWidth);

    // Actions de navigation 

    // Initialisation du compteur 
    Cpt = 0;

    // Clic sur le lien "Suivant"
    $(".carrousel-next").click(function() {

        if ((Cpt + 7) >= Reference.length) {
    Cpt = 7 - (Reference.length - Cpt);

            Calcul = 0;
    for (var i = 0; i < Cpt; i++) {
    Calcul += Reference[i].clientWidth;
    }

            // Mouvement du carrousel en arrière-plan
    $(this).parent().find(".carrousel").css({
    marginLeft: -(Calcul)
    });
    }

        // Ajout +1 au compteur (nous allons sur la diapositive suivante) 
    Cpt += 4;

        // Calcule
    Calcul = 0;
    for (var i = 0; i < Cpt; i++) {
    Calcul += Reference[i].clientWidth;
    }

        // Mouvement du carrousel en arrière-plan
    $(this).parent().find(".carrousel").animate({
    marginLeft: -(Calcul)
    }, 1000);

        // Blocage du lien 
    return false;

    });

    // Clic sur le lien "Précédent" 
    $(".carrousel-prev").click(function() {

        // Si le compteur est supérieur à zéro
    if (Cpt < 4) {
    Cpt = Reference.length + Cpt - 7;

            Calcul = 0;
    for (var i = 0; i < Cpt; i++) {
    Calcul += Reference[i].clientWidth;
    }

            // Mouvement du carrousel en arrière-plan
    $(this).parent().find(".carrousel").css({
    marginLeft: -(Calcul)
    });
    }

        // Soustraction -1 au compteur (nous allons sur la diapositive précédente)
    Cpt -= 4;

        // Calcule
    Calcul = 0;
    for (var i = 0; i < Cpt; i++) {
    Calcul += Reference[i].clientWidth;
    }

        // Mouvement du carrousel en arrière-plan
    $(this).parent().find(".carrousel").animate({
    marginLeft: -(Calcul)
    }, 1000);

        // Blocage du lien 
    return false;

    });
    
    */

    // Au changement d'option dans la collection il place les options dans Frame et donne la meme chose dans l'autres boite de recherche.
    $(".quickSearchEntries .right li:first select").change(function() {
        dynamicSelecte("#CollectionSelectList", ".frameSelect", this);
    });

    $(".searchPartsEntries .right li:first select").change(function() {
        dynamicSelecte("#CollectionSelectList", ".frameSelect", this);
    });

    $(".frameSelect").change(function() {
        var page = ($(this).attr("value")).toString();
        var currentId = $(this).attr("id");
        //If we're looking for part
        if (currentId == "partselect") {
            page = page.replace("p-", "part-");
        }
        window.location = page + ".aspx";
    });


    //Recherche de piece
    $(".searchPartsEntries .center .submitSearch").click(function() {
        dynamicBasicSearchPart(".searchPartsEntries .center input.SmallSquareText");
    });

    //Recherche simple
    $(".quickSearchEntries .center .submitSearch").click(function() {
        dynamicBasicSearch(".quickSearchEntries input#smallSquareText");
    });


    // Slider pour le roleover du bouton Cart
    CartContentPaddingtop = $("#wishCartContent").css("padding-top");
    if (CartContentPaddingtop) {
        $("#wishCartContent").css("margin-top", -$("#wishCartContent").height() - CartContentPaddingtop.replace("px", ""));
    }
    $("#cartSliderButton").hover(function() {
        slider("#wishCartContent");
    });
    $("#cartSlider").parent().hover(function() {
    },
    function() {
        $("#wishCartContent").animate({
            marginTop: -$("#wishCartContent").height() - CartContentPaddingtop.replace("px", "")
        });
    });

    // click sur le bouton chose view
    var bt1ChoseViewSelected = false;
    $(".choseView .li0 a").click(function() {
        bt1ChoseViewSelected = choseview(bt1ChoseViewSelected, ".choseView .li0 a");
    });

    $(".choseView .li1 a").click(function() {
        bt1ChoseViewSelected = choseview(bt1ChoseViewSelected, ".choseView .li1 a");
    });


    $("#accountInfo .li5 a").click(function() {
        ChangeHidePrice();
    });

    $("#Color").change(function() {
        var color = $("#Color option:selected").attr("value");
        LoadImageAfterColorChange(color);
    });



    $('.toolTip').hover(
      function() {
          $('#searchEntries .content .info').css("visibility", "visible");
      },
      function() {
          $('#searchEntries .content .info').css("visibility", "hidden");
      }
    );
    // Patient/Tray Number on the shopping cart page.
    if ($('input.patientBox')) {
        // Find all text box
        $('input.patientBox').each(function(i, box) {
            // Find the anchor next to this text box
            var anchor = $(this).parent().find('a.textLinkWithArrow')[0];

            // Set the click event
            $(anchor).click(function() {
                var boxVal = $(this).parent().find('input.patientBox')[0].value;
                if (boxVal != '') {
                    $.ajax({
                        type: "GET",
                        url: "queries/AddRemovePatientNumber.aspx",
                        dataType: "text",
                        data: "ShoppingCartRecId=" + this.id.replace(/add_/, '') + "&PatientNumber=" + boxVal + "&Action=add",
                        success: function(msg) {
                            var recId = msg.substr(msg.lastIndexOf(':') + 1);
                            var iList = msg.substr(0, msg.lastIndexOf(':')).split(",");
                            var disp = 'none';
                            if (iList.length > 0 && !(iList.length == 1 && iList[0] == ''))
                                disp = '';
                            document.getElementById('patienList_' + recId).innerHTML = GenerateTrayNumberList(iList, recId);
                            document.getElementById('patienList_' + recId).style.display = disp;
                            document.getElementById('patient_' + recId).value = '';
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {
                            alert("Error: \nstatus: " + textStatus + "\nerreur: " + errorThrown);
                        }
                    });
                }
            });

            $(box).keydown(function() {

                if (trim(box.value) == '') {
                    anchor.style.visibility = 'hidden';
                }
                else {
                    anchor.style.visibility = 'visible';
                }

            });
        });
    }

    $("#emailInfo").hide();
    $("#accountTInfo").hide();

    $('#redistrationContent #left .li3 .toolTip').mousemove(

      function(e) {

          $("#emailInfo").css("display", "block");
          $("#emailInfo").css("left", e.clientX + "px");
          $("#emailInfo").css("right", e.clientY + "px");

      });


    $("#redistrationContent #left .li3 .toolTip").mouseout(
    function(e) {
        $("#emailInfo").css("display", "none");
    });


    $('#redistrationContent #left .li2 .toolTip').mousemove(

      function(e) {

          $("#accountTInfo").css("display", "block");
          $("#accountTInfo").css("left", e.clientX + "px");
          $("#accountTInfo").css("right", e.clientY + "px");

      });


    $("#redistrationContent #left .li2 .toolTip").mouseout(
    function(e) {
        $("#accountTInfo").css("display", "none");
    });


    $(".username[title]").tooltip({ showURL: false, positionLeft: true });





    $(".popkitMenu .carrousel a").click(function(e) {
        e.preventDefault();
        $(this).next('.modalWindow').modal({ close: 'True', closeHTML: null, modal: 'True', opacity: '5' }); return false;
    });

    $("a.aChangePassword").click(function(e) {
    e.preventDefault();
    /*$('.modalWindow').modal({ close: 'True', closeHTML: null, modal: 'False', opacity: '.5' }); return false;*/
    /*$('.modalWindow').modal(); return false;*/

    window.open('ChangeAccountPassword.aspx', 'change_password', config = 'height=200, width=400, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no')
    });




    SelectAllAdvancedSearchOnLoad();
});

function trim(myString) {
    return myString.replace(/^\s+/g, '').replace(/\s+$/g, '')
}

// ************************** function *************************

function dynamicSelecte(thisSelectBox, target, selected) {
    var selectedValue = $(selected).attr("value");
    $(thisSelectBox + ' option[value="' + selectedValue + '"]').attr("selected", "selected");
    var str = "";
    $.getJSON(
        "queries/getFramesbymanufacturer.aspx?collection=" + selectedValue + "&customerid=" + window.ThisCustomerID,
        function(data) {
            $.each(data.results, function(i, results) {
                str += "<option value=" + results.url + ">" + results.text + "</option>";
            });
            $(target).html(str);
        }
    );
}


function dynamicBasicSearch(thisInputBox) {
    var value = $(thisInputBox).val();
    
    var errorMessage = $('#errorMessageProductNotFound').attr("value");
    var errorMessageBoxEmpty = $('#errorMessageBoxEmpty').attr("value");

    if ( (value == "") || (value == undefined)) {
        alert(errorMessageBoxEmpty);
        return;
    }

    $.getJSON(
        "queries/GetFrameById.aspx?name=" + value, "",
        function(data) {
            $.each(data.results, function(i, results) {
                if (results != "404") {
                    if (results == "multiple") {
                        // There are multiple results. Submit the advanced search with the keyword used.
                        document.forms['frmAdvSearch'].elements['framename'].value = value;
                        document.forms['frmAdvSearch'].submit();
                    }
                    else {
                        window.location = results + ".aspx";
                    }
                }
                else {
                    alert(errorMessage);
                }
            });
        }
    );
}

function dynamicBasicSearchPart(thisInputBox) {
    var value = $(thisInputBox).val();

    var errorMessage = $('#errorMessageProductNotFound').attr("value");
    var errorMessageBoxEmpty = $('#errorMessageBoxEmpty').attr("value");

    if ((value == "") || (value == undefined)) {
        alert(errorMessageBoxEmpty);
        return;
    }

    $.getJSON(
        "queries/GetFrameById.aspx?name=" + value, "",
        function(data) {
            $.each(data.results, function(i, results) {
                if (results != "404") {
                    if (results == "multiple") {
                        // There are multiple results. Submit the advanced search with the keyword used.
                        document.forms['frmAdvSearch'].elements['framename'].value = value;
                        document.forms['frmAdvSearch'].elements['musthaveparts'].value = '1';
                        document.forms['frmAdvSearch'].submit();
                    }
                    else {
                        window.location = results.toString().replace("p-", "part-") + ".aspx";
                    }
                }
                else {
                    alert(errorMessage);
                }
            });
        }
    );
}



function slider(slideElement) {
    $(slideElement).animate({
        marginTop: 0
    });
}

function GotoPreviousProduct() {
    if (window.AspexPreviousProductName && window.AspexPreviousProductName != '') {
        window.location = 'p-' + window.AspexPreviousProductName + ".aspx";
    }
}

function GotoNextProduct() {
    if (window.AspexNextProductName && window.AspexNextProductName != '') {
        window.location = 'p-' + window.AspexNextProductName + ".aspx";
    }
}

function EnableAdvSearch(active) {
    var els = document.getElementById('advSearchEnable').getElementsByTagName('SELECT');
    for (var x = 0; x < els.length; x++) {
        els[x].disabled = active;
    }
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}


function ChangeHidePrice() {
    $.ajax({
        type: "GET",
        url: "queries/SetHidePrice.aspx",
        dataType: "text",
        data: "",
        success: function(msg) {

            var showPriceText = $('#HiddenShowPriceMessage').val().toString();
            var hidePriceText = $('#HiddenHidePriceMessage').val().toString();

            var hidePrice = readCookie("HidePrice");
            if (hidePrice.toString().toLowerCase() == "true") {
                $('#accountInfo .li5 a').text(showPriceText);
                /*$('#accountInfo .li5 a').attr("title",showPriceText);*/

                //Cachons le prix sur la page des produits
                $('#price').css("display", "none");
                $('div.price').css("display", "none");
                //Cachons le prix sur la page de recherche        
                $('div div.content.price').css("display", "none");
                //Cachons le prix sur la page des categories
                $('td div.grayCadre div div.content').css("display", "none");
                //Cachons le prix sur la liste de souhait
                $('.wishlistContent td.colPrice div').css("display", "none");
                //Cachons le prix dans le panneau en haut à droite
                $('#thumbnailItem .itemInfos .price').css("display", "none");
            }
            else {
                $('#accountInfo .li5 a').text(hidePriceText);
                /*$('#accountInfo .li5 a').attr("title",hidePriceText);*/

                $('#price').css("display", "block");
                $('div.price').css("display", "block");
                $('div div.content.price').css("display", "block");
                $('td div.grayCadre div div.content').css("display", "block");
                $('.wishlistContent td.colPrice div').css("display", "block");
                $('#thumbnailItem .itemInfos .price').css("display", "block");

            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Erreur: \nstatus: " + textStatus + "\nerreur: " + errorThrown);
        }

    });

}

// ************ chose your view bouton *********************

function choseview(bt1Selected, clickedBt) {
    if (!bt1Selected && clickedBt == ".choseView .li0 a") {
        changeCssChoseView(clickedBt);
        choseViewBt(true);
        return true;
    } else if (bt1Selected && clickedBt == ".choseView .li1 a") {
        changeCssChoseView(clickedBt);
        choseViewBt(false);
        return false;
    }
    return bt1Selected;
}

function changeCssChoseView(clickedBt) {
    if (clickedBt == ".choseView .li0 a") {
        var unclickedBt = ".choseView .li1 a";
        var clickedBtBackgroundPosition = -73;
        var unclickedBtBackgroundPosition = -36;
        var unclickedBtHover = -109;
    } else {
        var unclickedBt = ".choseView .li0 a";
        var clickedBtBackgroundPosition = -109;
        var unclickedBtBackgroundPosition = 0;
        var unclickedBtHover = -73;
    };
    $(clickedBt).css({
        'cursor': 'default',
        'background-position': clickedBtBackgroundPosition + "px"
    });
    $(clickedBt).hover(function() {
        $(this).css('background-position', clickedBtBackgroundPosition + "px");
    }, function() {
        $(this).css('background-position', clickedBtBackgroundPosition + "px");
    });
    $(unclickedBt).css({
        'cursor': 'pointer',
        'background-position': unclickedBtBackgroundPosition + "px"
    });
    $(unclickedBt).hover(function() {
        $(this).css('background-position', unclickedBtHover + "px");
    }, function() {
        $(this).css('background-position', unclickedBtBackgroundPosition + "px");
    });
}

function choseViewBt(isTemple) {
    var target = "#accueilContent div#mainGlasses div.menu div.items ul li a";

    $(target).attr("onclick", "return false;");

    $(target + " div").each(function(i, results) {
        $(results).css('display', 'none');
    });

    var str = '<div class=spiner><img border="0" alt="Loading..." src="skins/skin_1/images/spinner.gif"/></div>';

    $(target).each(function(i, results) {
        $(results).append(str);
    });

    var imType = 't';
    if (!isTemple)
        imType = '';


    $(target + " div.image img").each(function(i, results) {
        var str = $(this).attr("src");

        var ceci = $(this);

        //AJAX!
        var posDot = str.indexOf(".");
        var posLastSlash = str.lastIndexOf("/");
        posLastSlash++;
        var sku = $(this).parent().attr('id').split('_')[1];
        var customerid = window.ThisCustomerID;

        var param = "addtag=false&sku=" + sku + "&size=icon&customerid=" + customerid + "&firstimageonly=true&type=" + imType;

        $.ajax({
            type: "GET",
            datatype: "text",
            url: "Queries/GetImages.aspx",
            data: param,
            success: function(content) {
                ceci.attr("src", content);
                ceci.bind("load", function() {
                    ceci.parent().parent().removeAttr("onclick");
                    ceci.parent().parent().children().css('display', 'block');
                })
            }
               ,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                // typically only one of textStatus or errorThrown 
                // will have info
                //this; // the options for this ajax request                  
                alert("Erreur: \nstatus: " + textStatus + "\nerreur: " + errorThrown);
            }
        });
    });
}

function FindColorId(oColor) {
    var posDelColor = oColor.indexOf(",");
    var posDelDot = oColor.indexOf(".");
    var posDelDot2 = oColor.indexOf(".", posDelDot + 1);

    if (posDelColor <= 0) {
        posDelColor = oColor.toString().length;
    }

    if (posDelDot == 0) {
        posDelDot = 1;
    }

    if (posDelDot2 <= 0) {
        posDelDot2 = posDelColor;
    }

    if (posDelDot < posDelColor) {
        posDelDot = oColor.indexOf(".", posDelColor + 1) + 1;
        posDelDot2 = oColor.indexOf(".", posDelDot + 1);
        /*alert("oColor: " + oColor + "\nposDelDot: " + posDelDot + "\nposDelDot2: " + posDelDot2);*/
    }

    var color = "";
    if (posDelColor > 0) {
        color = oColor.substring(posDelDot, posDelDot2);
        if (color.charAt("0")) {
            color = color.substr(1, 2);
        }
    }
    else {
        color = parseInt(0);
    }

    return color;
}

var selectedTab = 0;

function switchMoreView(type) {

    var largeImage = $(".MagicZoom");
    var mediumImage = $("#ProductPic4");

    var oColor = "";
    var color = -1;
    if ($('#Color option:selected').length) {
        oColor = ($('#Color option:selected').attr("value")).toString();
        color = parseInt(FindColorId(oColor));
    }


    var sku = $('#txtSKU').attr("value");
    var imageName = "";

    var skuColor = sku;
    if (color > 0) {
        skuColor = sku + "." + color.toString();
    }

    if (type != "") {
        imageName = skuColor + "." + type;
    }
    else {
        imageName = skuColor;
    }

    var largeImageSrc = "images/product/large/" + type; //imageName + ".jpg";
    var mediumImageSrc = "images/Product/medium/" + type; //imageName + ".jpg";

    var selector = '.thumbnails img:eq(' + selectedTab + ')';
    $(selector).removeAttr('class');

    selector = '.thumbnails img:eq(' + type + ')';
    $(selector).addClass('selected');

    selectedTab = type;

    var dList = $('.thumbnails div');
    var found1 = false;
    for (var x = 0; x < dList.length; x++) {
        if (dList[x]) {
            if (found1) {
                $('.thumbnails').removeChild(dList[x]);
            }
            else {
                found1 = true;
            }
        }
    }

    selector = '.thumbnails img:eq(' + type + ')';
    var selSrc = $(selector).attr("src");
    $('.MagicZoom').attr("href", largeImageSrc);
    $('.MagicZoom img:eq(0)').attr("src", mediumImageSrc);
    MagicZoom.refresh();
}


function LoadImageAfterColorChange(oColor) {

    var sku = $('#txtSKU').attr("value");
    var color = FindColorId(oColor);

    var customerid = window.ThisCustomerID;
    var param = "addtag=" + false.toString() + "&sku=" + sku + "&size=gallery&color=" + color + "&customerid=" + customerid + "&firstimageonly=" + false.toString();


    $.ajax({
        type: "GET",
        datatype: "text",
        url: "Queries/GetImages.aspx",
        data: param,
        success: function(content) {

            if (content.toString().length > 0) {
                MagicZoom.refresh();
                $('.thumbnails').html(content);

                var imageName = "";

                var cStr = content.toString();

                var posEndLine = cStr.indexOf("\n");
                var lineImg = cStr.substring(0, posEndLine).toString();
                var posLastSlash = lineImg.indexOf("/", lineImg.indexOf("thumbs"));
                var posDoubleQuote = lineImg.indexOf("\"", posLastSlash);
                var longueur = posDoubleQuote - posLastSlash;

                imageName = lineImg.substr(posLastSlash + 1, longueur - 1);

                $('.MagicZoom').attr("href", "images/product/large/" + imageName);
                $('.MagicZoom').attr("alt", imageName);
                $('.MagicZoom img:eq(0)').attr("src", "images/product/medium/" + imageName);
                $('.MagicZoom img:eq(0)').attr("alt", imageName);

                MagicZoom.refresh();
            }

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            // typically only one of textStatus or errorThrown 
            // will have info
            //this; // the options for this ajax request
            alert("Error: \nstatus: " + textStatus + "\nerreur: " + errorThrown);
        }

    });
}

//Add part to the shopping cart
function AjaxAddPartToCart() {
    var inputs = [];
    var nbItem = 0;

    var colorSelected = true;

    for (var i in document.forms) {
        if (document.forms[i].id != null) {
            if (document.forms[i].id.toString().indexOf('AddToCartForm_') > -1) {
                if (document.forms[i].Quantity.value != '0') {
                    if (document.forms[i].Color.selectedIndex == 0) {
                        colorSelected = false;
                    }
                    else {

                    }
                }
            }
        }
    }

    if (!colorSelected) {
        alert($('#HiddenPleaseChooseAColor').val().toString());
    }
    else {
        for (var i in document.forms) {
            if (document.forms[i].id != null) {
                if (document.forms[i].id.toString().indexOf('AddToCartForm_') > -1) {
                    if (document.forms[i].Quantity.value != '0') {
                        if (document.forms[i].Color.selectedIndex > 0) {
                            nbItem++;
                            //AjaxAddToCart(document.forms[i].id);
                            var ele = document.forms[i].elements;
                            for (var x = 0; x < ele.length; x++) {
                                inputs.push(ele[x].name + '_' + nbItem + '=' + escape(ele[x].value));
                            }
                        }
                        else {
                            alert($('#HiddenPleaseChooseAColor').val().toString());
                        }
                    }
                }
            }
        }
    }

    if (nbItem > 0) {
        inputs.push('nbItem=' + nbItem);

        jQuery.ajax({
            data: inputs.join('&'),
            url: "addToCartAjax.aspx",
            timeout: 2000,
            error: function() {
                console.log("Error sending request to addToCartAjax.aspx");
            },
            success: function(r) {
                document.getElementById('cartSlider').innerHTML = r;
                UpdateCartCount();
            }
        });
    }
}

//Efface un produit du shopping cart
function DeleteCartItem(Id) {
    var selectName = "Quantity_" + Id;
    var trName = "#cart_item_" + Id;

    document.getElementById(selectName).selectedIndex = 0;
    $(trName + " td").css("display", "none");
    $(".UpdateCartButton").click();
}

//Efface un produit du shopping cart
function DeleteWishItem(Id) {
    var selectName = "Quantity_" + Id;
    var trName = "#cart_item_" + Id;

    document.getElementById(selectName).value = 0;
    $(trName + " td").css("display", "none");
    //window.location = "shoppingcart.aspx?delid=" + Id;
    $(".UpdateWishButton").click();
}

//Simule un click sur le bouton de confirmation de commande
function ConfirmOrder() {
    $('.ReviewPageContinueCheckoutButton').click();
}

function CustomInputSelect(obj, btnValue) {
    var radioName = obj.firstChild.id;
    var radId = radioName.substr(radioName.indexOf('_') + 1);
    radioName = radioName.substr(0, radioName.indexOf('_') + 1);
    obj.firstChild.src = obj.firstChild.src.replace(/off\.gif/, 'on.gif');
    for (var x = 0; x < 100; x++) {
        if (document.getElementById(radioName + x)) {
            if (x == radId)
                document.getElementById(radioName + "value").value = btnValue;
            else
                document.getElementById(radioName + x).src = document.getElementById(radioName + x).src.replace(/on\.gif/, 'off.gif');
        }
        else {
            break;
        }
    }
}

function RemoveTrayNumber(val, shopRecId) {
    $.ajax({
        type: "GET",
        url: "queries/AddRemovePatientNumber.aspx",
        dataType: "text",
        data: "ShoppingCartRecId=" + shopRecId + "&PatientNumber=" + val + "&Action=remove",
        success: function(msg) {
            var htmlStr = "";
            var iList = msg.substr(0, msg.lastIndexOf(':')).split(",");
            var recId = msg.substr(msg.lastIndexOf(':') + 1);
            var disp = 'none';
            if (iList.length > 0 && !(iList.length == 1 && iList[0] == ''))
                disp = '';
            document.getElementById('patienList_' + recId).innerHTML = GenerateTrayNumberList(iList, recId);
            document.getElementById('patienList_' + recId).style.display = disp;
            document.getElementById('patient_' + recId).value = '';
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Error: \nstatus: " + textStatus + "\nerreur: " + errorThrown);
        }
    });
}

function GenerateTrayNumberList(valArr, shopRecId) {
    var htmlStr = "";
    for (var x = 0; x < valArr.length; x++) {
        htmlStr += valArr[x] + '<a href="#" onclick="RemoveTrayNumber(\'' + valArr[x] + '\', ' + shopRecId + ');return false;">x</a><br/>';
    }
    return htmlStr;
}

function submitenterQuick(e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13) {
        dynamicBasicSearch(".quickSearchEntries input#smallSquareText");
        return false;
    }
    else
        return true;
}

function submitenterPart(e) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13) {
        dynamicBasicSearchPart(".searchPartsEntries .center input.SmallSquareText");
        return false;
    }
    else
        return true;
}

function GetOrderItemStatus(webOrderNumber, lineNumber) {
    $.ajax({
        type: "GET",
        url: "queries/GetOrderItemStatus.aspx",
        dataType: "text",
        data: "OrderNumber=" + webOrderNumber + "&LineNumber=" + lineNumber,
        success: function(msg) {
            $('#item' + webOrderNumber + '_' + lineNumber).html(msg);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("Error: \nstatus: " + textStatus + "\nerreur: " + errorThrown);
        }
    });
}

function SwitchSizeSearch(typeSearch) {
    if (typeSearch == 'small') {
        /*
        v.EyeSize BETWEEN 30 and 47
        OR v.Bridge BETWEEN 30 and 47
        OR v.Temple BETWEEN 30 and 47
        OR v.A BETWEEN 30 and 47
        OR v.B BETWEEN 30 and 47
        OR v.ED BETWEEN 30 and 47
        */
        //$("#EyeSizeFrom").val("39");  
        $("#EyeSizeFrom").val($("#EyeSizeFrom option:first").val());
        $("#EyeSizeTo").val("47");

        //$('#BridgeFrom').val("39");
        $("#BridgeFrom").val($("#BridgeFrom option:first").val());
        $("#BridgeTo").val("47");

        //$('#TempleFrom').val("39");
        $("#TempleFrom").val($("#TempleFrom option:first").val());
        $('#TempleTo').val("47");

        //$('#AFrom').val("39");
        $("#AFrom").val($("#AFrom option:first").val());
        $('#ATo').val("47");

        //$('#BFrom').val("39");
        $("#BFrom").val($("#BFrom option:first").val());
        $('#BTo').val("47");

        //$('#EDFrom').val("39");
        $("#EDFrom").val($("#EDFrom option:first").val());
        $('#EDTo').val("47");
    }
    else if (typeSearch == 'large') {
        $('#EyeSizeFrom').val("48");
        //$('#EyeSizeTo').val("65");
        $("#EyeSizeTo").val($("#EyeSizeTo option:last").val());

        $('#BridgeFrom').val("48");
        //$('#BridgeTo').val("65");
        $("#BridgeTo").val($("#BridgeTo option:last").val());

        $('#TempleFrom').val("48");
        //$('#TempleTo').val("65");
        $("#TempleTo").val($("#TempleTo option:last").val());

        $('#AFrom').val("48");
        //$('#ATo').val("65");
        $("#ATo").val($("#ATo option:last").val());

        $('#BFrom').val("48");
        $("#BTo").val($("#BTo option:last").val());
        //$('#BTo').val("65");

        $('#EDFrom').val("48");
        //$('#EDTo').val("65");
        $("#EDTo").val($("#EDTo option:last").val());
    }
    else if ((typeSearch == 'all') || (typeSearch == 'custom')) {
        $("#EyeSizeFrom").val($("#EyeSizeFrom option:first").val());
        $("#EyeSizeTo").val($("#EyeSizeTo option:last").val());

        $("#BridgeFrom").val($("#BridgeFrom option:first").val());
        $("#BridgeTo").val($("#BridgeTo option:last").val());

        $("#TempleFrom").val($("#TempleFrom option:first").val());
        $("#TempleTo").val($("#TempleTo option:last").val());

        $("#AFrom").val($("#AFrom option:first").val());
        $("#ATo").val($("#ATo option:last").val());

        $("#BFrom").val($("#BFrom option:first").val());
        $("#BTo").val($("#BTo option:last").val());

        $("#EDFrom").val($("#EDFrom option:first").val());
        $("#EDTo").val($("#EDTo option:last").val());

    }
}

//Select the All search on load
function SelectAllAdvancedSearchOnLoad() {
    if (window.location.search.length == 0) {
        SwitchSizeSearch("all");
    }
}

//Activate search field
function ActivateSearchField() {
    if ($('#advSearchEnable select').attr('disabled') != undefined) {
        $('#advSearchEnable select').removeAttr('disabled');
    }
}
