﻿

$.fn.pheRoundedBorder = function () {
    this.wrap('<table class="phe-ui-roundedbordertable"><tr><td class="tl"></td><td class="t"></td><td class="tr"></td></tr><tr><td class="l"></td><td></td><td class="r"></td></tr><tr><td class="bl"></td><td class="b"></td><td class="br"></td></tr></table>');
    this.after('');
};

// JQuery Document Ready Event
$(document).ready(function () {
    $('.dialog-opener').click(function () {
        var url = $(this).attr('dialog-target');
        var position = $(this).attr('dialog-position');
        var height = parseInt($(this).attr('dialog-height'));
        var width = parseInt($(this).attr('dialog-width'));
        $('<div id="render-dialog-temp" />')
			.dialog({
			    position: position,
			    width: width + 20,
			    height: height + 30,
			    close: function () {
			        $('#render-dialog-temp').remove();
			        return false;
			    }
			})
			.append('<iframe style="width:' + width + 'px; height:' + height + 'px; border: 0px none;" frameborder="no" />')
				.find('iframe').attr('src', url);

        return false;
    });

    //Wire-Up product quick view.
    $('#ProductQV').dialog({ width: 502, resizable: false, autoOpen: false });


    //AlertPopup for any page
    var poptitle = $('#popupAlert').attr('title')
    $('#popupAlert').dialog({ resizable: false, autoOpen: true, modal: true, title: poptitle });


    //Order confirmation synapse
    $('#synapsePop').dialog({ width: 502, resizable: false, autoOpen: false });


    OneTimePopup();
    //Wire-Up all dialogs with default settings.
    //$('.phe-ui-dialog').dialog({ autoOpen: false });

    $('.phe-ui-dialog').each(function () {

        var $this = $(this);
        var position = $this.position();
        var myOptions = {};
        var pheDialogOptions = $this.attr('pheDialogOptions');
        if (pheDialogOptions) {
            pheDialogOptions = ", " + pheDialogOptions;
        }
        var metaData = "{ autoOpen: false, position: [" + position.left + ", " + position.top + "]" + pheDialogOptions + " }";
        if (metaData) {
            eval("myOptions = " + metaData + ";");
        }
        if (myOptions) {
            $this.dialog(myOptions);
        }
        else {
            //$this.dialog();
        }
    });

    //----- Email Sign-Up Mini -----//
    $('div.phe-ui-emailsignupmini').html('<input type="text" /><div></div>');
    //Attach event handlers for all elements which match the selectors, now and in the future.
    $('div.phe-ui-emailsignupmini div').live("click", function () {
        var email = $(this).siblings(':input').val();
        document.cookie = 'emailaddress=' + email + '; path=/';
        document.location = "/t-emailsignup.aspx";
    });

    $('div.phe-ui-emailsignupmini div').bind('onKeyPress', function () {
        if (window.event.keyCode == 13) {
            var email = $(this).val();
            document.cookie = 'emailaddress=' + email + '; path=/';
            document.location = "/t-emailsignup.aspx";
        }
    });


    //----- Cart Tool Tip -----//
    createCartToolTip();

    $('.phe-ui-tooltip').each(function () {
        var id = '#' + $(this).attr('tooltip');
        $(this).tooltip({
            tip: id
        });
    });

    //-----Open Cart Tool Tip -----//
    $('.mcOpener').bind('click', function () {
        $("#CartLink").click();
    });

    //-----Stop propagation of button click for quick view mouseover overlay -----//
    $('.over-lay').click(function (event) {
        event.stopPropagation();
        event.cancelBubble = true
    });

    $('.over-layLarge').click(function (event) {
        event.stopPropagation();
        event.cancelBubble = true
    });

    $('.over-layMedium').click(function (event) {
        event.stopPropagation();
        event.cancelBubble = true
    });

    $('.over-laySmall').click(function (event) {
        event.stopPropagation();
        event.cancelBubble = true
    });

    $('.over-layCol').click(function (event) {
        event.stopPropagation();
        event.cancelBubble = true
    });

    $('.phe-ui-buy').bind("click", function (e) {
        var ProductID = $(this).attr("productID");
        var VariantID = $(this).attr("variantID");
        var SpecialItemType = $(this).attr("itemType");

        //ddl on category page
        if (VariantID == '0') {
            var ddlValue = $('.variantDD option:selected', $(".vardd[productID=" + ProductID + "]")).val();
            VariantID = ddlValue;
        }

        //product page radio buttons
        if (!VariantID) { VariantID = $("'.variantcbx':checked").val(); }

        //product page ddl
        if (!VariantID) { VariantID = $(".pvarddl option:selected").val(); }

        //quickview ddl
        if (!VariantID) { VariantID = $('option:selected', '#TypeDropDown').val(); }

        if (VariantID) {
            if ($('#MiniCart').length === 0) { //We're in the Quick View
                parent.top.$('.ui-dialog-titlebar-close').click(); //Close the Quick View
                parent.top.addItemToMiniCart(ProductID, VariantID, SpecialItemType, 'doUpdateMiniCart()');
                //makes the cart close after 6 seconds by triggering mouseout event
                parent.top.$('#MiniCart').mouseout();
            }
            else if ($(this).hasClass('phe-ui-bettertogether')) {
                addItemToMiniCart(ProductID, VariantID, SpecialItemType, 'processBetterTogether()');
            }
            else {
                addItemToMiniCart(ProductID, VariantID, SpecialItemType, 'processAddOns()');
            }
        }
        //makes the cart close after 6 seconds by triggering mouseout event
        $('#MiniCart').mouseout();
        return false;
    });

    //----- Email Signup -----//

    //get cookie and stick in field
    var cookieemail = getCookie("emailaddress");
    if (cookieemail != '') {
        $('#txtEmailx').val(cookieemail);
    }


    //handle click button
    $('#btnSubmitEmailx').bind('click', function () {
        processEmailSignup();
        return false;
    });

    function processEmailSignup() {
        var email1 = $('#txtEmailx')[0].value;
        var email2 = $('#txtEmailConfirmx')[0].value;
        var bsuccess = true;

        //reset validation
        $('#EmailErrorx').text('');

        //client  validation
        if (bsuccess) {
            if (email1.indexOf('@') == -1 || email1.indexOf('.') == -1 || email1.length < 6 || email1 == '') {
                $('#EmailErrorx').text('Please enter a valid email address.');
                bsuccess = false;
            }
        }
        if (bsuccess) {
            if (email1 != email2) {
                $('#EmailErrorx').text('"Email" and "Confirm Email" must match.');
                bsuccess = false;
            }
        }


        //process form
        if (bsuccess) {
            //run ajax here and do final validation server side
            var data = "{EmailAddress:'" + email1 + "',EmailAddressConfirm:'" + email2 + "'}";
            var url = "/ws/Ajax/form.asmx/EmailSignUp";

            $.ajax({
                type: "POST",
                url: url,
                data: data,
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {

                    if (data.d.Success == false) {
                        //FAIL
                        $('#EmailErrorx').text(data.d.Message);
                    }
                    else {
                        //SUCCESS
                        $('#divEmailFormx').hide();
                        $('#divEmailFormSuccessx').show();
                    }
                }
            });
        }
        return false;
    }
    //----- Apply Source Code Via JQuery -----//

    //handle "Enter" keypress in text field
    $('#txtSourceCodex').keypress(function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) { //"Enter" keycode
            processApplySourceCode();
            return false;
        }
    });

    //handle click button
    $('#btnSubmitSourceCodex').bind('click', function () {
        processApplySourceCode();
        return false;
    });

    function processApplySourceCode() {
        var sourcecode = $('#txtSourceCodex')[0].value;
        var bsuccess = true;

        //clear the labels
        $('#SourceCodeWhatYouGetx').html('');
        $('#SourceCodeSuccessx').html('');
        $('#SourceCodeErrorx').html('');

        //client  validation
        if (bsuccess) {
            if (sourcecode.length < 4 || sourcecode == '') {
                $('#SourceCodeErrorx').text('Please enter a valid source code.');
                $('#divSourceCodePopx').dialog('open');
                bsuccess = false;
            }
        }


        //process form
        if (bsuccess) {
            //run ajax here and do final validation server side
            var data = "{SourceCode:'" + sourcecode + "'}";
            var url = "/ws/Ajax/form.asmx/ApplySourceCode";

            $.ajax({
                type: "POST",
                url: url,
                data: data,
                async: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {

                    if (data.d.Success == false) {
                        //FAIL
                        $('#SourceCodeErrorx').html(data.d.Message);
                        $('#divSourceCodePopx').dialog('open');
                    }
                    else {
                        //SUCCESS
                        $('#SourceCodeSuccessx').html(data.d.Message);
                        $('#SourceCodeWhatYouGetx').html(unescape(data.d.Description));
                        $('#divSourceCodePopx').dialog('open');
                    }
                }
            });
        }
        return false;
    }
});

function processAddOns() {
    $(".cbxAddOn").each(function (index) {
        var aoSpan = $(this);

        if ($('input:checked', aoSpan).val() == 'on') {
            var aoProductID = aoSpan.attr("productID");
            var aoItemType = aoSpan.attr("itemType");
            var aoVariantID = aoSpan.attr("variantID");

            // now add this item to the cart
            if (aoVariantID) {
                addItemToMiniCart(aoProductID, aoVariantID, aoItemType, 'doUpdateMiniCart()');
            }
        }
    });
}
function processBetterTogether() {
    var ProductID = $('#btProductID').val();
    var VariantID = $('#btVariantID').val();
    var SpecialItemType = $('#btItemType').val();
    if (VariantID) {
        addItemToMiniCart(ProductID, VariantID, SpecialItemType, 'doUpdateMiniCart()');
    }
}


function addItemToMiniCart(ProductID, VariantID, ItemType, SuccessFunction) {
    var CategoryTag = $('#CategoryID');
    var CategoryID;
    if (CategoryTag.length > 0) {
        CategoryID = CategoryTag.val();
    }
    else {
        CategoryID = 0;
    }
    var data = "{ProductID:" + ProductID + ",VariantID:" + VariantID + ",Quantity:1, SpecialItemType:" + ItemType + ",CategoryID:" + CategoryID + "}";
    var url = "/ws/Ajax/ShoppingCart.asmx/AddItemWithType";
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $('#MiniCart').removeClass('populated');
            eval(SuccessFunction);
            ShowMiniCart();
        }
    });
}

function createCartToolTip() {
    var CartToolTip = $("#CartLink").tooltip({
        effect: 'slide',
        tip: '#MiniCart',
        position: 'bottom center',
        offset: [0, -137],
        direction: 'down',
        slideOffset: 0,
        slideOutSpeed: 400,
        slideInSpeed: 200,
        delay: 6000,
        onBeforeShow: function () {
            doUpdateMiniCart();
        },
        onShow: function () {
            $('.mcClose').bind('click', function () {
                $('#MiniCart').hide();
            });
        },
        events: {
            def: "click,mouseout"
        }
    });
}




function ShowMiniCart() {
    $('html, body').animate({ scrollTop: 0 }, 'normal');
    if ($('#MiniCart').is(':hidden')) {
        $("#CartLink").click();
    }
    else if ($('#MiniCart').is(':visible')) {
        doUpdateMiniCart();
        $('.mcClose').bind('click', function () {
            $('#MiniCart').hide();
        });
    }
}

function doUpdateMiniCart() {
    if (!($("#MiniCart").hasClass("populated"))) {
        var data = $.toJSON({ foo: 1 });
        $.ajax({
            type: "Post",
            url: "/ws/Ajax/ShoppingCart.asmx/GetCartItems",
            data: data,
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                $('#MiniCart').empty();
                var temp = $('#templates .MiniCartItem');
                if (data.d.ItemCount === 0) {
                    //cart header
                    $('#templates .MiniCartEmpty').clone().appendTo('#MiniCart');
                }
                else {
                    //cart header
                    $('#templates .MiniCartTop').clone().appendTo('#MiniCart');

                    //cart items
                    $(data.d.CartItems).each(function () {
                        $('.Name', temp).text(this.Name);
                        $('.Type', temp).text(this.Type);
                        $('.mcPrice', temp).html(this.Price);


                        //more stuff
                        $('#mcProductImage', temp).attr('src', this.ProductImgURL);
                        $('.mcProductAnchor', temp).attr('href', this.ProductURL);
                        $('.mcInStockMsg', temp).html(this.InStockMsg);
                        $('.mcQty', temp).text(this.Qty);
                        $('.mcDiscountMsg', temp).html(this.DiscountMsg);

                        temp.clone().appendTo('#MiniCart');
                    });

                    //$('.MiniCartItem:odd').css('background-color', '#F7F7F7');
                    $('#MiniCart').addClass('populated');
                    $('#headerLogout').attr('cartItemCount', data.d.CartItems.length);

                    //cart bottom
                    var BottomTemp = $('#templates .MiniCartBottom');

                    $('.mcItemCount', BottomTemp).text(data.d.ItemCount);
                    $('.mcSubTotal', BottomTemp).text(data.d.SubTotal);
                    $('.mcShipping', BottomTemp).text(data.d.Shipping);
                    $('.mcTotal', BottomTemp).text(data.d.EstOrderTotal);

                    //Discount display: if no discount, hide divs
                    if (data.d.EstDiscount != '$0.00') {
                        $('.mcDiscount', BottomTemp).text(data.d.EstDiscount);
                    }
                    else {
                        $('#dvEstDiscountTitle', BottomTemp).hide();
                        $('#dvEstDiscountValue', BottomTemp).hide();
                    }

                    $('.mcDiscountMsg', BottomTemp).html(data.d.DiscountMsg);
                    $('.mcAdtnlDiscounts', BottomTemp).html(data.d.AdtnlDiscounts);

                    BottomTemp.clone().appendTo('#MiniCart');
                }

                //lastly, update the count on the page and make checkout visible
                $('#cartHeaderCount').text(data.d.ItemCount);
                $('.checkout-link1-1').attr('style', 'visibility:visible;');
            }
        });
        $('.phe-ui-tiptip').tipTip({ defaultPosition: 'top', fadeIn: 50 }).bind('click', function () { return false; });
    }
}


//Jquery Functions
function QueryStringParameter(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results === null) {
        return "";
    }
    else {
        return results[1];
    }
}
//Jquery Functions
function ShowDialog(ID, URL, Title) {
    var $this = $('div#' + ID);
    var scrolltop = $(window).scrollTop();
    var position = $('a[rel = ' + ID + ']').position();
    var positionArray = [];
    if (position) {
        positionArray[0] = position.left;
        positionArray[1] = position.top - scrolltop;
        $this.load(URL).dialog('option', 'position', positionArray).dialog('option', 'title', Title).dialog('open');
    }
    else {
        $this.load(URL).dialog('open');
    }
}

function overlayclickclose() {
    $('#centerpagemessage').dialog('close');
}

function OneTimePopup() {
    var cdata = getCookie("PopUpMessage");
    var dt = "{'PHEOfferCode':'" + cdata + "'}";
    if (cdata.length > 0 && cdata != 'undefined' && cdata != '0') {
        var alreadyshown = getCookie(cdata + "-SHOWN");
        if (!alreadyshown) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: 'ws/ajax/Authentication.asmx/GetOneTimePopUpMessage',
                data: dt,
                cache: false,
                dataType: "json",
                success: function (data) {
                    var x = data.d;
                    $("body").append(x.html);
                    $('#centerpagemessage').dialog({ autoOpen: true,
                        title: "Special Offer",
                        modal: false,
                        draggable: false,
                        resizable: false,
                        open: function () { $(document).bind('click', overlayclickclose); },
                        close: function () { $(document).unbind('click'); del_cookie("PopUpMessage"); writeSessionCookie(cdata + "-SHOWN", "1"); }
                    });

                }
            });
        }
    }
}

//Jquery quick view
function ShowProductQV(ProductID, QSParams, HeaderText, leftcoord, topcoord, isdumppage) {
    //first close any previous dialog so that this one can reposition in the center of the page
    parent.top.$('.ui-dialog-titlebar-close').click();

    var params;
    if (QSParams) {
        params = QSParams;
    }
    else {
        params = '';
    }


    //URLDecode
    HeaderText = unescape(HeaderText);
    var intIndexOfMatch = HeaderText.indexOf("+");

    // Loop over the string value replacing out each matching
    // substring.
    while (intIndexOfMatch != -1) {
        // Relace out the current instance.
        HeaderText = HeaderText.replace("+", " ");

        // Get the index of any next matching substring.
        intIndexOfMatch = HeaderText.indexOf("+");
    }

    $('div#ProductQV iframe').attr('src', 'qv.aspx?ProductID=' + ProductID + QSParams).load(function () {
        $('div#ProductQV').dialog('option', 'title', HeaderText).dialog('open');
    });

    //    }
}

//**************************************************************************
//include("/jscripts/Ajax.js"); //8k
// MULTIPLE XMLHttpRequest FrameWork [BEGIN]
var maxCon = 10; // maximum connection
var tailCon = 1; // initial tail
var HTTPCon = [];  // array of connection

// init connection array
for (i = 1; i <= maxCon; i++) {
    HTTPCon[i] = false;
}

// function to find one available connection
// either find used empty or create new if available
function fine1Con() {
    var i;

    // try to find 1 used empty (completed)
    for (i = 1; i < tailCon; i++) {
        if (HTTPCon[i]) {
            if (HTTPCon[i].readyState === 0 || HTTPCon[i].readyState == 4) {
                return i; // return empty one
            }
        }
    }

    // if can not 1 used empty, pick 1 new
    if (tailCon <= maxCon) {

        // crate new object
        if (window.XMLHttpRequest) {
            HTTPCon[tailCon] = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            HTTPCon[tailCon] = new ActiveXObject("Microsoft.XMLHTTP");
        }

        // if new object was created successfully
        if (HTTPCon[tailCon]) {
            i = tailCon;
            tailCon = tailCon + 1;
            return i; // increase the tail of stack and exit
        }
        else {
            return false; // new object was failed (browser may not be ajax anable)
        }
    }
    else {
        return false; // maximum connection reached
    }

}

function getXMLData(dataSource, divID, HTMLOnly) {
    // find me one available Connection
    var gotOne = fine1Con();
    if (gotOne) {
        if (HTTPCon[gotOne]) {
            var obj = document.getElementById(divID);
            HTTPCon[gotOne].open("GET", dataSource);
            HTTPCon[gotOne].onreadystatechange = function () {
                if (HTTPCon[gotOne].readyState == 4 && HTTPCon[gotOne].status == 200) {
                    var result = HTTPCon[gotOne].responseText;
                    var tabnumber = 0;
                    if (HTMLOnly > 0) {
                        // make sure that this is the correct format   
                        t1 = result.indexOf('">');
                        t2 = result.indexOf('</string>');
                        if ((t1 > 0) && (t2 > 0) && (t2 > t1)) {
                            result = cleanGTLT(result.substring(t1 + 2, t2));
                            t1 = result.indexOf('#A#');
                            t2 = result.indexOf('#B#');
                            if ((t1 > 0) && (t2 > 0) && (t2 > t1)) {
                                tabnumber = result.substring(t1 + 3, t2);
                                result = result.substring(0, t1);
                            }
                        }
                    }
                    if (obj) { obj.innerHTML = result; }
                    if (aftergetXMLData) {
                        aftergetXMLData(tabnumber, result); // if there is aftergetXMLData function, call it
                    }
                }
            };
            HTTPCon[gotOne].send(null);
        }
    } else {
        // All Connection full 
        alert('Connection Full');
    }
}



function cleanGTLT(s) {
    while (s.indexOf('&gt;') > -1) {
        s = s.replace('&gt;', '>');
    }
    while (s.indexOf('&lt;') > -1) {
        s = s.replace('&lt;', '<');
    }
    return s;
}

function updateHelpfulness(ReviewID, isHelpful, isExpert) {

    var data = "{ReviewID:" + ReviewID + ",Helpfulness:" + isHelpful + "}";
    var prev = -1;

    if (isHelpful != prev) {
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/ws/Ajax/Review.asmx/ReviewHelpfulness",
            data: data,
            dataType: "json",
            async: false,
            success: function (obj) {

                var revtype = '';

                if (isExpert && isExpert == true) {
                    revtype = 'Expert';
                }

                var countHelpful = parseInt(parseFloat($('#span' + revtype + 'FoundHelpful1_' + ReviewID.toString()).text()));
                var countNotHelpful = parseInt(parseFloat($('#span' + revtype + 'FoundHelpful0_' + ReviewID.toString()).text()));

                prev = obj.d.prev;

                if (prev != -1) {
                    if (prev == 0) {
                        countNotHelpful -= 1;
                    }
                    else {
                        countHelpful -= 1;
                    }

                    obj.d.msg = '';
                }
                if (isHelpful == 0) {
                    countNotHelpful += 1;
                }
                else {
                    countHelpful += 1;
                }

                if (countHelpful < 0) {
                    countHelpful = 0;
                }

                if (countNotHelpful < 0) {
                    countNotHelpful = 0;
                }


                $('#span' + revtype + 'FoundHelpful0_' + ReviewID.toString()).empty();
                $('#span' + revtype + 'FoundHelpful0_' + ReviewID.toString()).text(countNotHelpful.toString());

                $('#span' + revtype + 'FoundHelpful1_' + ReviewID.toString()).empty();
                $('#span' + revtype + 'FoundHelpful1_' + ReviewID.toString()).text(countHelpful.toString());

                $('#span' + revtype + 'PeopleOrPerson_' + ReviewID.toString()).empty();

                if (countHelpful == 1) {
                    $('#span' + revtype + 'PeopleOrPerson_' + ReviewID.toString()).text('person');
                }
                else {
                    $('#span' + revtype + 'PeopleOrPerson_' + ReviewID.toString()).text('people');
                }

                if ($('#spanHelpfulTotal_' + ReviewID.toString()).length == 1) {
                    $('#spanHelpfulTotal_' + ReviewID.toString()).empty();
                    $('#spanHelpfulTotal_' + ReviewID.toString()).text(countHelpful + countNotHelpful);
                }

                $.get("clearcache.aspx");

                if (obj.d.msg.length != 0) {
                    alert(obj.d.msg);
                }

            }
        });
    }
}

function openQV(findControl, qvURL, leftcoord, topcoord) {
    var oWnd = $find(findControl);
    oWnd.setUrl(qvURL);
    oWnd.moveTo(leftcoord, topcoord);
    oWnd.show();
}
function GetRadWindow() {
    var oWindow = null;
    if (window.radWindow) {
        oWindow = window.radWindow;
    }
    else if (window.frameElement.radWindow) {
        oWindow = window.frameElement.radWindow;
    }
    return oWindow;
}


//**************************************************************************
//include("/jscripts/internationalsites.js"); //1k
function change_url(form, strFormTitle) {
    var new_window = window.open();
    new_window.location.href = document.InternationalSitesForm.InternationalSites.options[document.InternationalSitesForm.InternationalSites.selectedIndex].value;
}


//**************************************************************************
//include("/jscripts/PHE_Utility.js"); //4k
function trim(sBuf) {
    if (!sBuf) {
        return "";
    }
    var iNum = parseInt(sBuf);
    if (!isNaN(iNum)) {
        return iNum.toString();
    }
    while (sBuf.lastIndexOf(" ") == sBuf.length - 1) {
        sBuf = sBuf.substring(0, sBuf.lastIndexOf(" "));
        if (sBuf === "") {
            return sBuf;
        }
    }
    while (sBuf.indexOf(" ") === 0) {
        sBuf = sBuf.substring(1, sBuf.length);
    }
    return sBuf;
}

function getBetweenText(sBuffer, sStartText, sEndText) {
    if ((sBuffer.indexOf(sStartText) > -1) && (sBuffer.indexOf(sEndText) > -1)) {
        return (sBuffer.substring(sBuffer.indexOf(sStartText) + sStartText.length, sBuffer.indexOf(sEndText)));
    }
    else {
        return (null);
    }
}


function clearDropDown(selectName) {
    document.getElementById(selectName).options.length = 0;
}

function findPos(obj) {
    var curleft = 0;
    var curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft;
        curtop = obj.offsetTop;
        while (obj == obj.offsetParent) {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
    }
    return [curleft, curtop];
}
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
function writeSessionCookie(cookieName, cookieValue) {
    document.cookie = escape(cookieName) + "=" + escape(cookieValue) + "; path=/";
    return true;
}

function SetCookie(cookieName, cookieValue, nDays) {
    var today = new Date();
    var expire = new Date();
    if (nDays === null || nDays === 0) {
        nDays = 1;
    }
    expire.setTime(today.getTime() + 3600000 * 24 * nDays);
    document.cookie = cookieName + "=" + escape(cookieValue) + ";expires=" + expire.toGMTString();
}
function del_cookie(cookie_name) {
    var cookie_date = new Date();  // current date & time
    cookie_date.setTime(cookie_date.getTime() - 1);
    document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

// Merged in from PopUp.js
function OpenBrWindow(theURL, winName, features) {
    //v2.0
    var new_window = window.open(theURL, winName, features);
    //added check for null to stop js error
    if (new_window !== null) {
        new_window.focus();
    }
}


//**************************************************************************
//include("/jscripts/CompareChecks.js"); //4k
var xmlHttp;
var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5") != -1) ? 1 : 0;
var is_opera = ((navigator.userAgent.indexOf("Opera6") != -1) || (navigator.userAgent.indexOf("Opera/6") != -1)) ? 1 : 0;
//netscape, safari, mozilla behave the same???  
var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0;
var theCheckedProds = "";

function LogCompareClick(chk, productid, catID, custID) {
    var theBegin = "/";
    var Url = theBegin + "CompareList.aspx?CustomerID=" + custID + "&ProductID=" + productid + "&CategoryID=" + catID + "&Action=";
    if (chk.checked) {
        Url = Url + 'Add';
        theCheckedProds = theCheckedProds + "~" + productid + "~";
    }
    else {
        Url = Url + 'Remove';
        theCheckedProds = theCheckedProds.replace("~" + productid + "~", "");
    }
    xmlHttp = GetXmlHttpObject(stateChangeHandler);
    xmlHttp_Get(xmlHttp, Url);
    return true;
}
function stateChangeHandler() { if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete') { } }

// XMLHttp send GET request 
function xmlHttp_Get(xmlhttp, url) {
    xmlhttp.open('GET', url, true);
    xmlhttp.setRequestHeader('Cache-Control', 'no-store, no-cache, must-revalidate');
    xmlhttp.setRequestHeader('Pragma', 'no-cache');
    xmlhttp.send(null);
}

function GetXmlHttpObject(handler) {
    var objXmlHttp = null;

    if (is_ie) {
        var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';
        try {
            objXmlHttp = new ActiveXObject(strObjName);
            objXmlHttp.onreadystatechange = handler;
        }
        catch (e) {
            alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled');
            return;
        }
    }
    else if (is_opera) {
        alert('Opera detected. The page may not behave as expected.');
        return;
    }
    else {
        objXmlHttp = new XMLHttpRequest();
        objXmlHttp.onload = handler;
        objXmlHttp.onerror = handler;
    }
    return objXmlHttp;
}
function ClearChecks() {
    theCheckedProds = theCheckedProds.replace("~~", "~");
    var splitArray = theCheckedProds.split("~");
    for (var x = 0; x < splitArray.length; x++) {
        if (x === 0 || x == (splitArray.length - 1)) {
            var nothing_here = "";
        }
        else {
            if (splitArray[x].length > 0) {
                document.getElementById("Compare_" + splitArray[x]).checked = false;
            }
        }
    }
    theCheckedProds = "";
}


function navTo(goLocationLeft, goLocationRight, find, replace) {
    //add back in http and .aspx so it is a proper link
    temp = 'http:' + goLocationLeft + '.aspx' + goLocationRight;

    //replace chars
    while (temp.indexOf(find) > -1) {
        pos = temp.indexOf(find);
        temp = "" + (temp.substring(0, pos) + replace + temp.substring((pos + find.length), temp.length));
    }
    window.location.href = (temp);
}


//**************************************************************************
//

function setCoremetricsItem(iPID, iCategoryID, iItemType, anchor) {
    var href = $(anchor).attr("href");
    var data = "{ productID:" + iPID + ", itemType:" + iItemType + ", categoryID:" + iCategoryID + " }";
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "/ws/Ajax/Coremetrics.asmx/CoremetricsAddCartItem",
        data: data,
        dataType: "json",
        success: function (msg) {

            //FIRST REMOVE ONCLICK BEFORE RE-CLICKING THE ANCHOR
            $(anchor).removeAttr("onclick");

            if (navigator.appName == 'Microsoft Internet Explorer') {
                //WORKS IN IE ONLY  
                anchor.click();
            }
            else {
                ////CAUSES US TO LOSE REFERRER IN IE ONLY WHICH IS NEEDED FOR BREADCRUMBS ON PRODUCT PAGE
                window.location = $(anchor).attr("href");
            }
        }
    });
}
//gets value from collection of radios
function getButtonVal(radioName) {
    var checkRadio = document.getElementsByName(radioName);
    for (i = checkRadio.length - 1; i > -1; i--) {
        if (checkRadio[i].checked) {
            return checkRadio[i].value;
        }
    }
}

function addItemToCart(ProductID, VariantID, anchor) {
    var href = "/shoppingcart.aspx?AddItem=" + ProductID + "." + VariantID;
    navigateTo(href, anchor);
}

function addItemToWishList(ProductID, VariantID, anchor) {
    var href = "/wishlist.aspx?AddItem=" + ProductID + "." + VariantID;
    navigateTo(href, anchor);
}

function navigateTo(href, anchor) {
    if (navigator.appName == 'Microsoft Internet Explorer') {
        //WORKS IN IE ONLY
        $(anchor).removeAttr("href");
        $(anchor).attr("href", href);
        anchor.click();
    }
    else {
        ////CAUSES US TO LOSE REFERRER IN IE ONLY WHICH IS NEEDED FOR BREADCRUMBS ON PRODUCT PAGE
        window.location = href;
    }
}

function flipGuidedNavImage(name, img, minus, plus) {
    var elementName = '#' + name;
    var imgName = '#' + img;

    if ($(elementName).is(':hidden')) {
        $(elementName).show();
        $(imgName).attr('src', minus);
    }
    else {
        $(elementName).hide();
        $(imgName).attr('src', plus);
    }
}
$(function () {
    $('#signup-email').keypress(
	function (event) {
	    if (event.keyCode == 13) {
	        $("#sign-me-up").click()
	        return false;
	    }
	});
});
$(function () {
    $('#sign-me-up').click(function () {
        if ($('#signup-email').val() == 'Enter your email here') {
            $('#signup-email').val('');
        }

        writeSessionCookie('emailaddress', $('#signup-email').val());
        window.location.href = '/t-emailsignup.aspx';
    });
});


$(document).ready(function (e) {

    var checkExistsRequestType = $('#tcuRequestType');

    if (checkExistsRequestType.length) {

        $('#btntcuSubmit').bind('click', function () {
            var value = $("#aspnetForm").valid();
            if (value) {

                var FirstName = $('#tcuFirstName')[0].value;
                var LastName = $('#tcuLastName')[0].value;
                var Email = $('#tcuEmail')[0].value;
                var PhoneNumber = $('#tcuPhone')[0].value;
                var RequestType = $('#tcuRequestType')[0].value;
                var Comments = $('#tcuComments')[0].value;
                var OrderNumber = $('#tcuOrderNumber')[0].value;
                var HowContact = $('#tcuHowContact')[0].value;
                var WhenContact = $('#tcuWhenContact')[0].value;

                var data = "{FirstName:'" + FirstName + "',LastName:'" + LastName + "',EmailAddress:'" + Email + "',PhoneNumber:'" + PhoneNumber + "',RequestType:'" + RequestType + "',Comments:'" + Comments + "',OrderNumber:'" + OrderNumber + "',HowContact:'" + HowContact + "',WhenContact:'" + WhenContact + "'}";

                var url = "/ws/Ajax/form.asmx/ContactUs";
                $.ajax({
                    type: "POST",
                    url: url,
                    data: data,
                    async: false,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        if (data.d.Success == false) {
                            //FAIL
                            $('#divtcuError').show();
                            $('#tcuErrorMessage').text(data.d.Message);
                        }
                        else {
                            //SUCCESS
                            $('#divtcuContactUs').hide();
                            $('#divtcuThankYou').show();
                        }
                    }
                });
            }
            return false;
        });

        $.validator.addMethod("valueNotEquals", function (value, element, arg) {
            return arg != value;
        },
		"* Please select a request type");

        $('#aspnetForm').validate({
            rules: {
                tcuFirstName: { required: true },
                tcuLastName: { required: true },
                tcuComments: { required: true, maxlength: 5000 },
                tcuEmail: { required: true, email: true },
                tcuRequestType: { valueNotEquals: "Select One" }
            },
            messages: {
                tcuFirstName: "* Please enter your First Name",
                tcuLastName: "* Please enter your Last Name",
                tcuComments: "* Please enter your comments",
                tcuEmail: "* Please enter a valid e-mail address",
                tcuRequestType: "* Please select a request type"
            }
        });

        $("#tcuRequestType").change(function () {
            var RequestType = $('#tcuRequestType')[0].value;
            if (RequestType == "Where's My Order?") {

                var url = "/ws/Ajax/form.asmx/WhereIsMyOrder";
                $.ajax({
                    type: "POST",
                    url: url,
                    async: true,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        window.location.href = data.d.toString();
                    }
                });
            }
        });
    }
    //end doc ready
});


jQuery(function ($) {
    var checkExists = $('#tcuTrackOrder');

    if (checkExists.length) {
        $('#divtcuThankYou').hide();
        $('#divtcuError').hide();

        var url = "/ws/Ajax/form.asmx/ContactUsLinks";
        $.ajax({
            type: "POST",
            url: url,
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var returnData = data.d.toString();
                var values = returnData.split('*');
                for (var i = 0; i < values.length - 1; i++) {
                    var linkValue = values[i].split('|');
                    switch (linkValue[0]) {
                        case "TrackOrder":
                            $('#tcuTrackOrder').attr("href", linkValue[1]);
                            break;
                        case "MyAccountEmail":
                            $('#tcuMyAccount').attr("href", linkValue[1]);
                            break;
                        case "forgotpassword":
                            $('#tcuForgotPassword').attr("href", linkValue[1]);
                            break;
                        case "satisfaction":
                            $('#tcuSatisfaction').attr("href", linkValue[1]);
                            break;
                        default:
                            break;
                    }
                }
            }
        });
    }

    //end doc ready
});



//creates function to detect if mouse is over selected item
(function ($) {
    jQuery.mlp = { x: 0, y: 0 }; // Mouse Last Position 
    $(document).mousemove(function (e) {
        jQuery.mlp = { x: e.pageX, y: e.pageY }
    });
    function notNans(value) {
        if (isNaN(value)) {
            return 0;
        } else {
            return value
        }
    }
    $.fn.ismouseover = function (overThis) {
        var result;
        this.eq(0).each(function () {
            var offSet = $(this).offset();
            var w = Number($(this).width())
			+ notNans(Number($(this).css("padding-left").replace("px", "")))
			+ notNans(Number($(this).css("padding-right").replace("px", "")))
			+ notNans(Number($(this).css("border-right-width").replace("px", "")))
			+ notNans(Number($(this).css("border-left-width").replace("px", "")));
            var h = Number($(this).height())
			+ notNans(Number($(this).css("padding-top").replace("px", "")))
			+ notNans(Number($(this).css("padding-bottom").replace("px", "")))
			+ notNans(Number($(this).css("border-top-width").replace("px", "")))
			+ notNans(Number($(this).css("border-bottom-width").replace("px", "")));
            if (offSet.left < jQuery.mlp.x && offSet.left + w > jQuery.mlp.x
			 && offSet.top < jQuery.mlp.y && offSet.top + h > jQuery.mlp.y) {
                result = true;
            } else {
                result = false;
            }
        });
        return result;
    };
})(jQuery);

$.maxZIndex = $.fn.maxZIndex = function (opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>    
    /// <param name="opt" type="object">
    /// inc: increment value, 
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function () {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function () {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}

