﻿function addItm(addSku, addQty, addType) { addItms(addSku + ';' + addQty, addType) }

function addItms(addItem, addType) {
    itmsToAdd = [];
    if (addItem == undefined) {
        for (var i in items)
            if (items[i].selected_sku > '')
            itmsToAdd.push(items[i].selected_sku + ';' + items[i].selected_qty);
    } else if (jQuery.isArray(addItem)) {
        itmsToAdd = addItem;
    } else {
        itmsToAdd.push(addItem);
    }

    if (addType != 'wishlist') addType = 'cart';
    if (itmsToAdd.length > 0) {
        if (addType == 'wishlist')
            alert('wish list');
        else 
            atcPopup(itmsToAdd);
    } else {
        ajaxError('You must select a specific item from the drop down selections to add to your ' + addType + '.');
    }
    return false;
}
function affItems() {
    itmsToAdd = [];
    $("input[id^='affItem']").each(function(i) {
        if (this.checked)
            itmsToAdd.push(this.value + ';' + $(this).next('.affQty').val());
    });
    if (itmsToAdd.length > 0)
        addItms(itmsToAdd);
    else
        ajaxError('You must select the accessories you would like to add to your cart using the checkboxes next to the recommended accessory.');
}
function atcPopup(addItems) {
    createPopup('Your Shopping Cart Summary');
    innerPopup('<div class="puLoad">Adding Item(s) To Your Cart, please wait...</div>', false, 40);
    wcfCall('AddBasketItem?id=' + shopperID + '&itms=' + addItems + '&kycd=' + keycode + '&chkPrm=' + (checkPromo && enblPromo) + '&getAvl=' + enblAvail + '&getBskt=true',
                function(data) {
                    if (data.d.err)
                        ajaxError("We're sorry, but a problem has occurred while adding items to your cart (" + data.d.err + ")");
                    else if(data.d.bskt)
                        displayCart(data.d);
                });
    return false;
}
function cartPopup() {
    createPopup('Your Shopping Cart Summary');
    innerPopup('<div class="puLoad">Loading Your Cart, please wait...</div>', false, 40);
    wcfCall("GetBasket?id=" + shopperID,
                function(data) {
                    if (data.d.err)
                        ajaxError("We're sorry, but a problem has occurred while loading your cart (" + data.d.err + ")");
                    else if (data.d.bskt)
                        displayCart(data.d);
                });
    return false;
}
function loadFullCart() {
    createPopup('Loading Your Shopping Cart...');
    innerPopup('<div class="puLoad">Loading Your Cart, please wait...</div>', true, 40);
}
function displayCart(rsp) {
    bskt = rsp.bskt;
    itms = bskt.itms;
    r = [];

    if (itms.length > 0) {
        if (bskt.itmsAdded.length > 0) {
            r.push('<tr class="itmAdd"><td colspan="4">Item' + ((bskt.itmsAdded.length > 1) ? 's':'') + ' added to your cart:');
            for (var i in bskt.itmsAdded) {
                r.push(' ' + bskt.itmsAdded[i].sku + ' (qty of ' + bskt.itmsAdded[i].qty + ')');
                if (i < bskt.itmsAdded.length - 1) r.push(', ');
            }
            r.push('</td></tr>');
        }

        r.push('<tr class="hdr">');
        r.push('<td style="text-align:center">Qty</td>');
        r.push(td('Product') + td('&nbsp;'));
        r.push(td('Price'));
        r.push("</tr>");

        for (var row in itms) {
            r.push("<tr>");
            r.push('<td style="text-align:center">' + itms[row].qty + '</td>');
            r.push('<td colspan="2"><a href="/link.aspx?itemNo=' + itms[row].sku + '">' + itms[row].sku + ": " + itms[row].ProductName + '</a></td>');
            r.push(td(webPrice(itms[row])));
            r.push("</tr>");
        }

        r.push('<tr class="bse">');
        r.push('<td colspan="2">' + bskt.item_count + ' item' + ((bskt.item_count != 1) ? 's' : '') + ' in your cart</td>');
        r.push('<td style="text-align:right">Cart Total:</td>');
        r.push(td( webPrice(bskt) ));
        r.push("</tr>");

        if (checkPromo) {
            r.push('<tr><td colspan="4" class="crtBsMsg">Today’s lowered prices will appear on the shopping cart page</td></tr>');
        }
        
        r.push('<tr>');
        r.push('<td colspan="2"><a href="/cart/basket.aspx" onclick="loadFullCart()" title="Click here to edit your cart by updating quantities or remove items"><img src="/images/css/btnEditCart.gif" border="0" /></a></td>');
        r.push('<td colspan="2" style="text-align:right"><a href="/cart/basket.aspx" onclick="loadFullCart()"><img title="Go to the shopping cart before you checkout" src="/images/css/btnProceedChkout.gif" border="0" /></a></td>');
        r.push("</tr>");
        updCartHeader(bskt.item_count, bskt.total);
    } else {
        r.push('<tr><td class="noItms"> - You have no items in your cart - </td></tr>');
    }

    innerPopup('<table cellspacing="0" cellpadding="4">' + r.join("") + '</table>' + analytics(rsp), true, 35);
}
function analytics(rsp) {
    var productList = '';
    for (var i in rsp.bskt.itmsAdded)
        productList = productList + ';' + rsp.bskt.itmsAdded[i].sku;

    var c = [];

    c.push('<script type="text/javascript"><!--\n');
    c.push("try {");
    c.push("pageName = 'Shopping Cart Summary';");
    c.push("channel = 'Cart';");
    c.push("events = '" + rsp.evts + "';");
    c.push("products = '" + productList + "';");
    c.push("} catch (err) {}//--></script>");
    c.push('<script type="text/javascript" src="/scripts/analytics.js"></script>');
    return c.join("");
}
function updCartHeader(item_count, total) { $("#hdrCart").html('Shopping Cart : ' + item_count + ' Item' + ((item_count != 1) ? 's' : '') + ' : ' + total); }

function td(txt) { return "<td>" + txt + "</td>"; }

function wcfCall(url, success) {
    $.ajax({
        type: 'GET',
        url: '/cart/services/commerce.svc/' + url,
        dataType: 'json', 
        cache: false,
        success: success,
        error: ajaxFailed
    });
}
function ajaxFailed(r) { ajaxError("We're sorry, but an error has occurred. " + r.status + " " + r.statusText); }
function ajaxError(msg) {
    createPopup('Your Attention Is Needed...');
    innerPopup('<div style="padding:25px 0px 50px 15px">' + msg + '</div>', false, 20);
}
function signInPU() {
    chkSignIn = true;
    puIframe('Sign In', '/cart/sign_in_quick.aspx?mp=s', 400, 600);
}
function newsletterPU(em) {
    puIframe('Receive Our Email Updates', '/cart/EmailMarketingSignUp.aspx?subscribe=true&email=' + escape(em) + '&mp=s', 350);
}
function puIframe(hdr, url, h, secsToClose) {
    if (secsToClose == undefined) secsToClose = 300;
    createPopup(hdr);
    innerPopup('<iframe src="' + location.protocol + '//' + location.hostname + url + '" height="' + h + '" width="500" id="puIframe" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></iframe>', false, secsToClose);
}
function createPopup(hdr) {
    r = [];
    r.push('<tr class="puR1"><td class="c1">&nbsp;</td><td class="c2">&nbsp;</td><td class="c3">&nbsp;</td></tr>');
    r.push('<tr class="puR2"><td class="c1">&nbsp;</td><td class="main">');
    r.push('<h1><a class="puClose" title="Click here to close this window and continue shopping" onclick="showPopup(false);"></a>' + hdr + '</h1>');
    r.push('<div id="puOuter"><div id="innr"></div></div><a onclick="showPopup(false);" class="clBs">Close Window</a></td><td class="c3">&nbsp;</td></tr>');
    r.push('<tr class="puR3"><td class="c1">&nbsp;</td><td class="c2">&nbsp;</td><td class="c3">&nbsp;</td></tr>');
    $("#puCnt").html('<table class="puTbl">' + r.join('') + '</table>');
}
function innerPopup(txt, animateMove, secsToClose) { //execute this code once the txt is loaded
    txt = txt + '<script type="text/javascript"> placePopup(' + animateMove + '); showPopup(true, ' + secsToClose + ');</script>'
    $("#innr").html(txt);
}
function placePopup(animateMove) {
    windowWidth = $(window).width();
    windowHeight = $(window).height();
    scrollTop = $(window).scrollTop();
    pDiv = $("#puDiv");
    pHeight = pDiv.height();
    popupTop = Math.round((windowHeight - pHeight) / 2 + scrollTop) - 20;
    popupLft = Math.round(windowWidth - pDiv.width()) / 2 + $(window).scrollLeft();


    if (popupTop - 20 < scrollTop) {
	// window.location = '/cart/basket.aspx'; //if its too large go to the cart
    }

    if (animateMove) {
        if ((popupTop + pHeight + 350) > (windowHeight + scrollTop)) pDiv.animate({ "top": popupTop, "left": popupLft }, 300);
    } else {
        pDiv.css({ "top": popupTop, "left": popupLft });
        $("#bgPu").css({ "width": windowWidth - 20, "height": windowHeight - 10 });
    }
}
function showPopup(openWin, secsToClose) {
    if (openWin && puStatus == 0) {
        puStatus = 1;
        $("#bgPu").show();
        $("#puDiv").fadeIn(250);
        clearTimeout(tm);
        tm = setTimeout('showPopup(false)', (secsToClose * 1000));
        if (isBrw('msie',6)) $("select").hide();
    } else if (!openWin && puStatus == 1) {
        puStatus = 0;
        $("#bgPu").hide();
        $("#puDiv").slideUp(200);
        clearTimeout(tm);
        if (chkSignIn) setSignedIn();
        if (isBrw('msie',6)) $("select").show();
    }
}
function setSignedIn() {
    wcfCall('IsSignedIn', function(data) {
        if (data.d) $(".signIn").html('Sign Out').attr('href', '/cart/sign_off.aspx');
    });
    chkSignIn = false;
}
function buildHeaderRow(h, itm) {
    h.push('<tr class="hdr">');
    for (var column in itm.lbls)
        h.push('<td>' + itm.lbls[column] + '</td>');
    if (itm.qtyLmt > 1) h.push('<td>Qty</td>');
    h.push('</tr>');
}
function buildSelections(h, itm) {
    h.push('<tr>');
    for (c = 0; c < itm.columns; c++) {
        h.push('<td>');
        buildDropDown(h, c, itm);
        h.push('</td>');
    }
    if (itm.qtyLmt > 1) h.push('<td><input type="text" value="1" id="qty' + itm.index + '" size="2" maxlength="3" /></td>');
    h.push('</tr>');
}
function buildDropDown(h, column, itm) {
    var t = [];
    if (itm.at_column >= column) {//time to choose
        choices = itm.column_choices[column];
        if (choices.length > 1) {//more than one selection, show as drop down
            t.push('<select id="sel' + itm.index + '' + column + '" onchange="chgSel(' + itm.index + ',' + column + ',this)">');
            t.push('<option value="">-Select-</option>');
            for (var s in choices) {
                t.push('<option ');
                if (choices[s].selected) t.push('selected="selected" ');
                t.push('value="' + choices[s].val + '">');
                t.push(choices[s].val);
                t.push('</option>');
            }
            t.push('</select>');
        } else if (choices.length == 1) {//only one choice, show as text
            t.push('<center>' + choices[0].val + '</center>');
        }
    } else {//not time to select
        t.push('<select disabled="true"><option value="">-Select-</option></select>');
    }
    h.push(t.join(''));
}
function setSelectedColumnStyle(itm, column, selected_value) {
    setSelected(itm, column, selected_value);
    for (nxt = column + 1; nxt < itm.columns; nxt++) { //go ahead to the upcoming stys and set them all to false
        for (var s in itm.skus) //each sku in the itm
            itm.skus[s].stys[nxt].selected = false;
    }
    itm.at_column = column;

    for (ac = itm.at_column; ac < itm.columns; ac++) { //build the next stys to load
        if (selected_value > '') itm.at_column = ac + 1;
        if (itm.at_column < itm.columns) {
            choices = getColumnChoices(itm.at_column, itm);
            itm.column_choices[itm.at_column] = choices;
            if (choices.length == 1) //if only one choice, auto select it and check the next choice
                setSelected(itm, itm.at_column, choices[0].val);
            else
                break;
        }
    }
    itm.selected_sku = selectSKU(itm);
}
function setSelected(itm, column, selected_value) {
    for (var s in itm.skus) {//each sku in the itm
        if (itm.skus[s].stys[column].val == selected_value) //set the selected stys for this column
            itm.skus[s].stys[column].selected = true;
        else
            itm.skus[s].stys[column].selected = false;
    }
}
function selectSKU(itm) {
    for (var s in itm.skus) {
        var isSel = true;
        for (c = 0; c <= itm.columns; c++) {
            if (!itm.skus[s].stys[c].selected || !isSel) {
                isSel = false;
                break;
            } else if (isSel && c == itm.columns - 1) {
                return itm.skus[s].sku;
            }
        }
    }
    return '';
}

function buildItemLabel(itm) { $('#itemSku').html('<b>Item No:</b> ' + ((itm.selected_sku > '') ? itm.selected_sku : itm.itemNo)); }

function getPrice(itm) {
    var msg = '&nbsp;';
    if (itm.prcs != undefined) {
        if (itm.prcs.length == 1) {//one price
            msg = '<b>Price:</b> ' + webPrice(itm.prcs[0]);
        } else if (itm.prcs.length > 1) {//price breaks
            var qtyArr = [];
            var prcArr = [];
            var col1Qty = [];
            var col1Prc = [];
            var col2Qty = [];
            var col2Prc = [];
            for (var pb in itm.prcs) {
                var lowQty = itm.prcs[pb].qty;
                var qtyStr = lowQty;
                if (pb < itm.prcs.length - 1) {
                    var highQty = (parseInt(itm.prcs[parseInt(pb) + 1].qty) - 1);
                    if (lowQty != highQty) qtyStr = qtyStr + " - " + highQty;
                } else {
                    qtyStr = qtyStr + " +";
                }
                qtyArr.push(qtyStr);
                prcArr.push(webPrice(itm.prcs[pb]));
            }
            for (var b in qtyArr) {
                if (b < 2) {
                    col1Qty.push('<p>' + qtyArr[b] + '</p>');
                    col1Prc.push('<p>' + prcArr[b] + '</p>');
                } else {
                    col2Qty.push('<p>' + qtyArr[b] + '</p>');
                    col2Prc.push('<p>' + prcArr[b] + '</p>');
                }
            }
            msg = '<DIV class=tblPrice><DIV><H4>Qty</H4>' + col1Qty.join('') + '</DIV><DIV><H4>Price</H4>' + col1Prc.join('') + '</DIV>';
            if (col2Qty.length > 0)
                msg = msg + '<DIV id=ln>&nbsp;</DIV><DIV><H4>Qty</H4>' + col2Qty.join('') + '</DIV><DIV><H4>Price</H4>' + col2Prc.join('') + '</DIV>';
            msg = msg + '</DIV>';

        } else {
            msg = '<p>Please <b>Call</b> for pricing and availability<br />';
        }
    }
    return msg;
}
function webPrice(price) {
    var p = '';
    if (!isNaN(price.lst)) {
        p = money(price.lst);
        if (!isNaN(price.prm)) {
            if (price.prm > 0 && price.prm < price.lst)
                p = '<SPAN class=stk>' + p + '</SPAN><SPAN class=deal>' + money(price.prm) + '</SPAN>';
        }
    }
    return p;
}
function money(amount) {
    var i = parseFloat(amount) / 100;
    if (isNaN(i)) { i = 0.00; }
    i = (parseInt((Math.abs(i) + .005) * 100) / 100);
    s = new String(i);
    if (s.indexOf('.') < 0) { s += '.00'; }
    if (s.indexOf('.') == (s.length - 2)) { s += '0'; }
    return '$' + s;
}
function getavailUpdate(itm) {
    avlMsg = '';
    if (itm.avl == 'g') {
        avlMsg = '<span class="green">In stock!</span>';
    } else if (itm.avl == 'y') {
        avlMsg = '<span class="yellow">Usually ships in 5-15 business days.</span>';
    } else if (itm.avl == 'r') {
        avlMsg = '<span class="red">Back ordered. You may still order.</span>';
    } else if (itm.avl == 'd') {
        avlMsg = '<span class="gray">Drop shipped from manufacturer.</span>';
    } else {
        return 'Please make a selection below...'
    }
    return '<b>Stock: </b>' + avlMsg;
}
function chgSel(index, column, opt) {
    setSelectedColumnStyle(items[index], column, opt.value);
    loadItem(items[index], false);
}
function loadProductPage(itm) {
    if (itm.qtyLmt > 1 == undefined) itm.shwQty = 999;
    itm.selected_sku = '';
    itm.avl = '';
    if (itm.skus.length == 1) {//auto load the one style
        itm.selected_sku = itm.skus[0].sku;
        itm.prcs = itm.skus[0].prcs;
        itm.avl = itm.skus[0].avl;
    }
    itm.at_column = 0;
    itm.index = 0;
    itm.columns = itm.lbls.length;
    itm.column_choices = [];
    for (x = 0; x < itm.columns; x++)
        itm.column_choices.push(getColumnChoices(x, itm));
    items.push(itm);

    if (itm.column_choices.length > 0) {
        if (itm.column_choices[0].length == 1)
            setSelectedColumnStyle(itm, itm.at_column, itm.column_choices[0][0].val);
    }

    loadItem(itm, true);

    $('#imgATC').hover(
      function() {
          $(this).attr('src', '/images/css/addtocartOver.gif');
      },
      function() {
          $(this).attr('src', '/images/css/addtocart.gif');
      }
    ).click(
        function() {
            setInputQtys();
            addItms();
            return false;
        }
    );
}
function loadItem(itm, isFirstLoad) {
    var h = [];
    buildHeaderRow(h, itm);
    buildSelections(h, itm);
    printSelect(h, itm);
    buildItemLabel(itm);

    sku = getSelectedSkuObj(itm);
    itm.avl = (sku.avl != undefined) ? sku.avl : '';
    
    lookupPrice = ((sku.prcs == undefined && !itm.grpPrc && itm.selected_sku > '') || (itm.prcs == undefined && sku.prcs == undefined && itm.selected_sku > ''));
    lookupAvail = (itm.avl == '' && itm.shwAvl && enblAvail && itm.selected_sku > '');
    lookupPromo = (enblPromo && checkPromo && itm.selected_sku > '');

    if (itm.grpPrc && itm.prcs != undefined) sku.prcs = itm.prcs;
    if (!itm.grpPrc && sku.prcs != undefined) itm.prcs = sku.prcs;

    if (lookupPrice && lookupAvail) {
        availUpdate('', true);
        priceUpdate('', true);
        displayLoading(true);
        wcfCall('GetSku?sku=' + sku.sku + '&kycd=' + keycode + '&chkPrm=' + lookupPromo + '&getAvl=' + lookupAvail,
            function(data) {
                sku.avl = data.d.avl;
                itm.avl = data.d.avl;
                sku.prcs = data.d.prcs;
                itm.prcs = data.d.prcs;
                availUpdate(getavailUpdate(itm), true);
                priceUpdate(getPrice(itm), true);
                displayLoading(false);
            });

    } else if (lookupPrice) {
        priceUpdate('', true);
        displayLoading(true);
        wcfCall('GetSku?sku=' + sku.sku + '&kycd=' + keycode + '&chkPrm=' + lookupPromo + '&getAvl=' + lookupAvail,
            function(data) {
                sku.prcs = data.d.prcs;
                itm.prcs = data.d.prcs;
                priceUpdate(getPrice(itm), true);
                displayLoading(false);
            });

    } else if (lookupAvail) {
        availUpdate('', true);
        displayLoading(true);
        wcfCall('GetAvailabilityStatus?sku=' + sku.sku,
            function(data) {
                sku.avl = data.d;
                itm.avl = data.d;
                availUpdate(getavailUpdate(itm), true);
                displayLoading(false);
            });

    } else {
        if (itm.shwAvl && enblAvail) {
            availUpdate(getavailUpdate(itm), !isFirstLoad);
        } else {
            $('#stockOuter').hide();
        }

        if (itm.prcs != undefined && (isFirstLoad || itm.grpPrc)) {
            $('#itemPrice').show();
            priceUpdate(getPrice(itm), !isFirstLoad);
            $('#priceOuter').height($('#itemPrice').height());
        } else if (!itm.grpPrc && itm.selected_sku == '') {
            priceUpdate('', true);
        } else {
            priceUpdate(getPrice(itm), !isFirstLoad);
        }
    }
}

function displayLoading(isLoading) {
    if(isLoading)
        $('#itemSku').addClass('itemLoading');
    else
        $('#itemSku').removeClass('itemLoading');
}

function printSelect(h, itm) {
    $("#itemSelections").html('<table cellpadding="2">' + h.join('') + '</table>');
    if (itm.selected_sku == '') $('#sel' + itm.index + '' + itm.at_column).focus();
}
function setInputQtys() {
    for (var i in items) {
        items[i].selected_qty = 1;
        var qty = $('#qty' + i).val();
        if(qty != undefined){
            if (isNumeric(qty)) items[i].selected_qty = parseInt(qty);
        }
    }
}
function availUpdate(msg, animate) {
    avlQue.push(msg);
    showQueMsg($('#stockOuter'), $('#itemStock'), avlQue, animate, 'avail');
}
function priceUpdate(msg, animate) {
    prcQue.push(msg);
    showQueMsg($('#priceOuter'), $('#itemPrice'), prcQue, animate, 'price');
}
function showQueMsg(outerDiv, innerDiv, que, animate, typ) {
    if (animate) {
        if (que.length == 1) {
            if (innerDiv.html().toLowerCase().replace(/\s/g, '') != que[0].toLowerCase().replace(/\s/g, '') || typ == 'avail') {//only fade if two messages aren't the same
                innerDiv.fadeOut(150,
                    function() {
                        if (isBrw('msie', 6)) outerDiv.height(innerDiv.height() + 4);
                        innerDiv.hide().html(que.shift());
                        innerDiv.fadeIn(250,
                            function() {
                                if (que.length == 0) {
                                    if (innerDiv.height() > 15 && !isBrw('msie', 6))
                                        outerDiv.animate({ 'height': innerDiv.height() }, 500);
                                }
                            });
                            showQueMsg(outerDiv, innerDiv, que, animate, typ);
                    });
            } else {
                que.shift();
            }
        }
    } else {
        innerDiv.html(que.shift());
    }
}

function getColumnChoices(column, itm) {//get all the stys for a certain column
    var rtnArr = [];
    for (var s in itm.skus) {//go through each sku
        var insrt = true;
        if (column > 0) {//if not first column, insert selected
            for (c = 0; c < column; c++) {
                if (!itm.skus[s].stys[c].selected || !insrt) {
                    insrt = false;
                    break;
                }
            }
        }
        if (insrt) {
            if (!containsStyle(rtnArr, itm.skus[s].stys[column]))
                insertByOrder(rtnArr, itm.skus[s].stys[column]);
        }
    }
    return rtnArr;
}
function getSelectedSkuObj(itm){
    for(s = 0; s < itm.skus.length; s++){
        if (itm.skus[s].sku == itm.selected_sku)
            return itm.skus[s];
    }
    return '';
}
function containsStyle(array, sty) {
    for (var c in array)
        if (array[c].val == sty.val) return true;
    return false;
}
function insertByOrder(orderedArr, sty) {
    if (orderedArr.length > 0) {
        for (x = 0; x < orderedArr.length; x++) {
            if (sty.ord < orderedArr[x].ord) {
                orderedArr.splice(x, 0, sty);
                return;
            }
        }
    }
    orderedArr.push(sty);
}
function isBrw(brw, ver) {
    var isBrwr = false;
    jQuery.each(jQuery.browser, function(i, val) { if (i == brw && val) isBrwr = true; });
    if (isBrwr && ver != undefined)
        return (parseInt(jQuery.browser.version) == ver);
    else if (isBrwr)
        return true;
    return false;
}
function isNumeric(n) {
    if (n.length < 1) return false;
    var ValidChars = "0123456789";
    for (i = 0; i < n.length; i++)
        if (ValidChars.indexOf(n.charAt(i)) == -1) return false;
    return true;
}

items = []; //array of all the items being purchased
avlQue = [];
prcQue = [];
chkSignIn = false;
var tm; //timer
