$(document).ready(function(){

    //store locator - submit the city and state search
    $("input.storesrchtxt, div.locatorState select[name='STORE_SEARCH<>state']").bind("keypress", function(e){
        var keyCode = e.charCode || e.keyCode;
        if (keyCode == 13) {
            $("div.locatorState input[name='us_city_state_search']").click();
            return false;
        }
    });
    //store locator - submit the zip search
    $("input.storezip").bind("keypress", function(e){
        var keyCode = e.charCode || e.keyCode;
        if (keyCode == 13) {
            $("div.locatorZip input[name='us_zip_search']").click();
            return false;
        }
    });

    //submit the search form when enter key is pressed
    $("form[name='basic_search']").bind("keypress", function(e){
        var keyCode = e.charCode || e.keyCode;
        if (keyCode == 13) {
            $("div#submitsearch input[type='submit']").click();
            return false;
        }
    });
    //submit the email signup form when enter key is pressed
    $("form[name='email_sign_up']").bind("keypress", function(e){
        var keyCode = e.charCode || e.keyCode;
        if (keyCode == 13) {
            $("div#emailsubmit input[type='submit']").click();
            return false;
        }
    });

    //
    //this function clears all the input fields in all sections except from the section where the 'add to cart' button was clicked
    $("input[name='add_to_cart'], input[name='submit_notify']").bind("click", function(){
        var splitStrings = $(this).attr("id").split("_");
        var positionSubmitted = splitStrings[1];
        $("input#positionSubmitted").val(positionSubmitted);

        //go over all input fields and disable all of them, unless the positionSubmitted matches the class
        $(this).parents("form").find("input.chk, select.chk").each(function(){
            if ($(this).attr("class").indexOf(positionSubmitted) == -1) {
                $(this).val("");
            } else {
                //
                // these elements are for the section which was submitted
                //this is add to cart, disable share with fried
                if ($(this).attr("name").indexOf("SHARE_WITH_FRIEND") > -1) {
                    $(this).val("");
                }
            }
        });
        return true;
    });
    //this function clears all the input fields in all sections except from the section where the 'Share with friend' button was clicked
    $("input[name='submit_share']").bind("click", function(){
        var splitStrings = $(this).attr("id").split("_");
        var positionSubmitted = splitStrings[1];
        $("input#positionSubmitted").val(positionSubmitted);

        //go over all input fields and disable all of them, unless the positionSubmitted matches the class
        $(this).parents("form").find("input.chk, select.chk").each(function(){
            if ($(this).attr("class").indexOf(positionSubmitted) == -1) {
                $(this).val("");
            } else {
                //
                // these elements are for the section which was submitted
                //this is add to cart, disable share with fried
                var name = $(this).attr("name");
                if (name.indexOf("ADD_CART_ITEM_ARRAY") > -1 || name.indexOf("CH_EMAIL_SUBSCRIPTION") > -1) {
                    $(this).val("");
                }
            }
        });
        return true;
    });

    //this method will open the share with a friend box if there are errors on the input fields
    // for the fields that don;t have errors, set the default value
    $("div.sharewf input[type='text']").each(function(){
        if ($(this).prev("span.errorElement").length > 0) {
            //set the block as visible
            $(this).parents("div.sharewf").parent().css("display", "block");
        } else {
            //set the default value
            if ($(this).attr("name").indexOf("emailFrom") > -1) {
                $(this).val("Enter Your Email");
            } else {
                $(this).val("Your Friend's Email");
            }
        }
    });

    //this method updates the price of a product after selecting SKU from drop down
    $("div.pdmainrightlast select[name='ADD_CART_ITEM_ARRAY<>sku_id']").bind("change", function(){
        // update the sale price
        // $("div.pdmainrightbottom select[name='ADD_CART_ITEM_ARRAY<>sku_id']").parents('div.pdmainright').find('span.saletxt').text();
        var tempStr = $(this).children("option:selected").attr("rel");
        var splitStrings = tempStr.split(":");
        if (splitStrings.length >= 1) {
            $("div.pdmainrightlast").find(".pdmainrighttopbodyprice span.saletxt").text(splitStrings[0]);
            if (splitStrings[0].length > 0) {
                $("div.pdmainrightlast").find(".pdmainrighttopbodyprice span.priceFront").show();
            } else {
                $("div.pdmainrightlast").find(".pdmainrighttopbodyprice span.priceFront").hide();
            }
            //set the available date text on the span and the hidden field
            $("div.forminputs").find("input.availableDate").val(splitStrings[1]);
            $("div.pdmainrighttopbody").find("div.specialcare").text(splitStrings[1]);
        }
        return false;
    });
    //this method creates the second drop down after size has been selected
    $("div.pdmainrightlast select[name='ADD_CART_ITEM_ARRAY<>firstDropDown']").bind("change", function(){
        // build the second drop down
        var tempStr = $(this).children("option:selected").attr("rel");
        var splitStrings = tempStr.split("|");

        var secondSelect = $(this).parents("div.forminputs").find("select.secondDropDown");
        var options = "<option value=\"\" rel=\"\">" + $(secondSelect).children("option:first").text() + "</option>";

        if (splitStrings.length > 2) {
            for (var i = 0; i < splitStrings.length; i = i + 3) {
                options += "\n<option value=\"" + splitStrings[i] + "\" rel=\"" + splitStrings[i + 1] + "\">"  + splitStrings[i + 2] + "</option>";
            }
        }

        $(secondSelect).empty();
        $(secondSelect).append(options);

        return false;
    });

    //this method updates the price of a product after selecting SKU from drop down in cart cross sells
    $("div#youmaylikecomp div.youmaylikecompbottom select[name='ADD_CART_ITEM_ARRAY<>sku_id']").bind("change", function(){
        var tempStr = $(this).children("option:selected").attr("rel");
        var splitStrings = tempStr.split(":");
        if (splitStrings.length >= 1) {
            //update the sale price
            $(this).parents("div.youmaylikeitemsout").find("div.youmaylikecomptop div.youmaylikeitemtextred").text(splitStrings[0]);
            //set the available date text on the span and the hidden field
            $(this).parents("div.youmaylikeitemform").find("input.availableDate").val(splitStrings[1]);
        }
        return false;
    });
    //this method creates the second dropdown after size has been selected (for Product 1 - Cart Cross Sells)
    $("#firstDropDown1").bind("change", function(){
        // build the second drop down
        var tempStr = $(this).children("option:selected").attr("rel");
        var splitStrings = tempStr.split("|");

        var secondSelect = $("#secondDropDown1");
        var options = "<option value=\"\" rel=\"\">" + $(secondSelect).children("option:first").text() + "</option>";

        if (splitStrings.length > 2) {
            for (var i = 0; i < splitStrings.length; i = i + 3) {
                options += "\n<option value=\"" + splitStrings[i] + "\" rel=\"" + splitStrings[i + 1] + "\">"  + splitStrings[i + 2] + "</option>";
            }
        }

        $(secondSelect).empty();
        $(secondSelect).append(options);

        return false;
    });
     //this method creates the second dropdown after size has been selected (for Product 2 - Cart Cross Sells)
    $("#firstDropDown2").bind("change", function(){
        // build the second drop down
        var tempStr = $(this).children("option:selected").attr("rel");
        var splitStrings = tempStr.split("|");

        var secondSelect = $("#secondDropDown2");
        var options = "<option value=\"\" rel=\"\">" + $(secondSelect).children("option:first").text() + "</option>";

        if (splitStrings.length > 2) {
            for (var i = 0; i < splitStrings.length; i = i + 3) {
                options += "\n<option value=\"" + splitStrings[i] + "\" rel=\"" + splitStrings[i + 1] + "\">"  + splitStrings[i + 2] + "</option>";
            }
        }

        $(secondSelect).empty();
        $(secondSelect).append(options);

        return false;
    });
     //this method creates the second dropdown after size has been selected (for Product 3 - Cart Cross Sells)
    $("#firstDropDown3").bind("change", function(){
        // build the second drop down
        var tempStr = $(this).children("option:selected").attr("rel");
        var splitStrings = tempStr.split("|");

        var secondSelect = $("#secondDropDown3");
        var options = "<option value=\"\" rel=\"\">" + $(secondSelect).children("option:first").text() + "</option>";

        if (splitStrings.length > 2) {
            for (var i = 0; i < splitStrings.length; i = i + 3) {
                options += "\n<option value=\"" + splitStrings[i] + "\" rel=\"" + splitStrings[i + 1] + "\">"  + splitStrings[i + 2] + "</option>";
            }
        }

        $(secondSelect).empty();
        $(secondSelect).append(options);

        return false;
    });

    $('div#pdmainbottomleftbuttons div.crossSellsBtn').bind("mouseover", function(){
        $(this).addClass('crossSellsBtnHighlight');
    });
    $('div#pdmainbottomleftbuttons div.crossSellsBtn').bind("mouseout", function(){
        $(this).removeClass('crossSellsBtnHighlight');
    });

    //this method updates the color of the main image based on the clicked swatch on product detail page
    $('div.pdmainrighttopOrig div.pdswatches img').bind("click", function(){
        var tempStr = $(this).attr("rel");
        var splitStrings = tempStr.split("|");

        for (var i = 0; i < splitStrings.length; i = i + 3) {

            //update color name
            $(this).parents("div.pdmainrighttopOrig").find(".pdmainrighttopbodyheadsmall span.colorName").text(splitStrings[i]);

            //update the main image URL
            $(this).parents("div.spdcontainer").find("div.pdmainleftimg img").attr('src', splitStrings[i + 1]);

            //update the sale price
            $(this).parents("div.pdmainright").find(".pdmainrighttopbodyprice span.saletxt").text(splitStrings[i + 2]);
            if (splitStrings[i + 2].length > 0) {
                $(this).parents("div.pdmainright").find(".pdmainrighttopbodyprice span.priceFront").show();
            } else {
                $(this).parents("div.pdmainright").find(".pdmainrighttopbodyprice span.priceFront").hide();
            }
        }
        return false;
    });

    //this method updates the color of the main image based on the clicked swatch on product listing page
    $('div.sbiitem div.sbiswatches img').bind("click", function(){
        var tempStr = $(this).attr("rel");
        var splitStrings = tempStr.split("|");

        for (var i = 0; i < splitStrings.length; i = i + 3) {
            //update the main image URL
            $(this).parents("div.sbiitem").find("div.sbiimg img").attr('src', splitStrings[i + 1]);
        }
        return false;
    });

    //this method updates the color of the main image based on the clicked swatch (Product 1 - Cart Cross Sells)
    $("#ccsSwatch1 img").bind("click", function(){
        var tempStr = $(this).attr("rel");
        var splitStrings = tempStr.split("|");

        for (var i = 0; i < splitStrings.length; i = i + 3) {

            //update the main image URL
            $("#ccsImage1").attr('src', splitStrings[i + 1]);

            //update color name
            $("#ccsColor1").text(splitStrings[i]);

        }
        return false;
    });
    //this method updates the color of the main image based on the clicked swatch (Product 2 - Cart Cross Sells)
    $("#ccsSwatch2 img").bind("click", function(){
        var tempStr = $(this).attr("rel");
        var splitStrings = tempStr.split("|");

        for (var i = 0; i < splitStrings.length; i = i + 3) {

            //update the main image URL
            $("#ccsImage2").attr('src', splitStrings[i + 1]);

            //update color name
            $("#ccsColor2").text(splitStrings[i]);

        }
        return false;
    });
    //this method updates the color of the main image based on the clicked swatch (Product 3 - Cart Cross Sells)
    $("#ccsSwatch3 img").bind("click", function(){
        var tempStr = $(this).attr("rel");
        var splitStrings = tempStr.split("|");

        for (var i = 0; i < splitStrings.length; i = i + 3) {

            //update the main image URL
            $("#ccsImage3").attr('src', splitStrings[i + 1]);

            //update color name
            $("#ccsColor3").text(splitStrings[i]);

        }
        return false;
    });

});

function submenudisplay(submenuid)
{
    submenu = document.getElementById(submenuid);
    if (submenu.style.display == "block")
    {
      submenu.style.display = "none";
    }
    else
    {
      submenu.style.display = "block";
    }
}


function ShowHideEmail(ElementId)
{
    $('#' + ElementId).toggle();
}

var horizontal_offset="0px"
var vertical_offset="0"
var ie=document.all
var ns6=document.getElementById&&!document.all

function getposOffset(what, offsettype)
{
    var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
    var parentEl=what.offsetParent;
    while (parentEl!=null){
        totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
        parentEl=parentEl.offsetParent;
    }
    return totaloffset;
}

function iecompattest()
{
    return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

function clearbrowseredge(obj, whichedge)
{
    var edgeoffset=(whichedge=="rightedge")? parseInt(horizontal_offset)*-1 : parseInt(vertical_offset)*-1
    if (whichedge=="rightedge"){
        var windowedge=ie && !window.opera? iecompattest().scrollLeft+iecompattest().clientWidth-30 : window.pageXOffset+window.innerWidth-40
        dropmenuobj.contentmeasure=dropmenuobj.offsetWidth
        if (windowedge-dropmenuobj.x < dropmenuobj.contentmeasure)
            edgeoffset=dropmenuobj.contentmeasure+obj.offsetWidth+parseInt(horizontal_offset)
    }
    else
    {
        var windowedge=ie && !window.opera? iecompattest().scrollTop+iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
        dropmenuobj.contentmeasure=dropmenuobj.offsetHeight
        if (windowedge-dropmenuobj.y < dropmenuobj.contentmeasure)
            edgeoffset=dropmenuobj.contentmeasure-obj.offsetHeight
    }
    return edgeoffset
}

function showhint(menucontents, obj, e, tipwidth)
{
    if ((ie||ns6) && document.getElementById("hintbox"))
    {
        dropmenuobj=document.getElementById("hintbox")
        dropmenuobj.innerHTML=menucontents
        dropmenuobj.style.left=dropmenuobj.style.top=-500
        if (tipwidth!="")
        {
            dropmenuobj.widthobj=dropmenuobj.style
            dropmenuobj.widthobj.width=tipwidth
        }
        dropmenuobj.x=getposOffset(obj, "left")
        dropmenuobj.y=getposOffset(obj, "top")
        dropmenuobj.style.left=dropmenuobj.x-clearbrowseredge(obj, "rightedge")+obj.offsetWidth+"px"
        dropmenuobj.style.top=dropmenuobj.y-clearbrowseredge(obj, "bottomedge")+"px"
        dropmenuobj.style.visibility="visible"
        obj.onmouseout=hidetip
    }
}

function hidetip(e)
{
    dropmenuobj.style.visibility="hidden"
    dropmenuobj.style.left="-500px"
}

function createhintbox(){
    var divblock=document.createElement("div")
    divblock.setAttribute("id", "hintbox")
    document.body.appendChild(divblock)
}

if (window.addEventListener)
    window.addEventListener("load", createhintbox, false)
else if (window.attachEvent)
    window.attachEvent("onload", createhintbox)
else if (document.getElementById)
    window.onload=createhintbox

function toggleCrossSells(obj, divToShow) {
    //hide all the divs
    // show the one whose id is passed in as a param
    $('div.crossSells').hide();
    $('div.crossSells#' + divToShow).show().css("visibility", "visible");

    //remove the active class from all the buttons, and only set it on the active one
    $('div#pdmainbottomleftbuttons div.crossSellsBtn').removeClass('crossSellsBtnHighlight').removeClass('crossSellsBtnActive');
    $(obj).addClass('crossSellsBtnActive');
}

function crossSellsBtns(id, highlight)
{
  if (highlight)
    $("#" + id).addClass('crossSellsBtnHighlight');
  else
    $("#" + id).removeClass('crossSellsBtnHighlight');
}

function detectBrowser()
{
    if (browser.isSafari) {
        //chrome includes safari in the browser id
        document.write("<link href='/media/EFR001/css/static/safari.css' rel='stylesheet' type='text/css' />");
    } else if (browser.isIE8up) {
        document.write("<link href='/media/EFR001/css/static/ie8.css' rel='stylesheet' type='text/css' />");
    } else if (browser.isIE7up) {
        document.write("<link href='/media/EFR001/css/static/ie7.css' rel='stylesheet' type='text/css' />");
    } else if (browser.isIE6x) {
        document.write("<link href='/media/EFR001/css/static/ie6.css' rel='stylesheet' type='text/css' />");
    } else if (browser.isFirefox) {
        if (browser.isMac) {
            document.write("<link href='/media/EFR001/css/static/ff_mac.css' rel='stylesheet' type='text/css' />");
        } else {
            document.write("<link href='/media/EFR001/css/static/ff_win.css' rel='stylesheet' type='text/css' />");
        }
    }
}
/* the param for the storeDetails() function is the unique id for the store. the div with the
 * content should be named 'sd[unique id]'
 */
function storeDetails(id)
{
    id = "#sd" + id;
    $("#storedetails").html("");
    $("#storedetails").addClass("storedetails");
    $("#storedetails").show();
    $("#storedetails").html($(id).html());
}

function sbiSwitchColors(colorSwitch) //this works for search page too
{
    strColorName = colorSwitch.src; //this is the color, get it from the image. Images for switches should always be named sw-[colorName]
    strColorName = strColorName.substr(strColorName.indexOf("sw-") + 3, strColorName.length);

    objImage = colorSwitch.parentNode.previousSibling.previousSibling.firstChild; //the structure inside 'sbiitem' is always the same
    strNewImage = "./images/" + objImage.id + '_' + strColorName;	              //and should remain the same, the id of the image should
                                                                                 //be the name of the image without .jpg images should be
                                                                                 //named, [imageName]_[colorName].jpg
    //alert(strNewImage);
    $("#" + objImage.id).attr("src", strNewImage);
}

function pdSwitchColors(defImgName, colorSwitch)
{
    strColorName = colorSwitch.src; //this is the color, get it from the image. Images for switches should always be named sw-[colorName]
    strColorName = strColorName.substr(strColorName.indexOf("sw-") + 3, strColorName.length);

    strNewImage = "./images/" + defImgName + "_" + strColorName;

    //alert(strNewImage);
    $("#imgMainStyle").attr('src', strNewImage);
}


// Function to switch the main product image after mousing over the thumbnail image
function switchImg(obj, newImgSrc) {
    $(obj).parents('div.pdmainleft').find('div.pdmainleftimg img').attr('src', newImgSrc);
    return true;
}
