﻿
// jquery.jStepper.js
function AddOrSubtractTwoFloats(d, h, f) { var b = d.toString(), c = h.toString(), a = ""; if (b.indexOf(".") > -1 || c.indexOf(".") > -1) { b.indexOf(".") == -1 && (b += ".0"); c.indexOf(".") == -1 && (c += ".0"); a = b.substr(b.indexOf(".") + 1); d = c.substr(c.indexOf(".") + 1); b = b.substr(0, b.indexOf(".")); h = c.substr(0, c.indexOf(".")); for (c = !0; c; ) a.length != d.length ? a.length < d.length ? a += "0" : d += "0" : c = !1; for (var c = a.length, e = 0; e <= a.length - 1; e++) b += a.substr(e, 1), h += d.substr(e, 1); a = Number(b); d = Number(h); a = (f ? a + d : a - d).toString(); for (f = 0; f < c - a.length + 1; f++) a = "0" + a; a.length >= c && (a = a.substring(0, a.length - c) + "." + a.substring(a.length - c)) } else a = f ? Number(d) + Number(h) : Number(d) - Number(h); return Number(a) } (function (d) { function h(b, c) { var a = d(c), e = a.val(); b.disableNonNumeric && (e = e.replace(/[^\d\.,\-]/gi, "")); if (b.maxValue !== null && e >= b.maxValue) e = b.maxValue; if (b.minValue !== null && e <= b.minValue && e != "") e = b.minValue; a.val(e) } function f(b, c, a, e) { var f = d(e), i; i = a ? a.ctrlKey ? b.ctrlStep : a.shiftKey ? b.shiftStep : b.normalStep : b.normalStep; var a = f.val(), m = a.length - e.selectionStart, n = a.length - e.selectionEnd, a = a.replace(/,/g, "."), a = a.replace(b.decimalSeparator, "."); a += ""; a.indexOf(".") != -1 && (a = a.match(/-{0,1}[0-9]+[\.][0-9]*/)); a += ""; a.indexOf("-") != -1 && (a = a.match(/-{0,1}[0-9]+[\.]*[0-9]*/)); a += ""; a = a.match(/-{0,1}[0-9]+[\.]*[0-9]*/); if (a === "" || a == "-" || a === null) a = b.defaultValue; a = c == 1 ? AddOrSubtractTwoFloats(a, i, !0) : AddOrSubtractTwoFloats(a, i, !1); i = !1; if (b.maxValue !== null && a >= b.maxValue) a = b.maxValue, i = !0; if (b.minValue !== null && a <= b.minValue) a = b.minValue, i = !0; a += ""; if (b.minLength !== null) { var g = a.length; a.indexOf(".") != -1 && (g = a.indexOf(".")); var k = !1; a.indexOf("-") != -1 && (k = !0, a = a.replace(/-/, "")); if (g < b.minLength) for (var l = 1; l <= b.minLength - g; l++) a = "0" + a; k && (a = "-" + a) } a += ""; if (b.minDecimals > 0) { var j; a.indexOf(".") != -1 ? (g = a.length - (a.indexOf(".") + 1), g < b.minDecimals && (j = b.minDecimals - g)) : (j = b.minDecimals, a += "."); for (g = 1; g <= j; g++) a += "0" } b.maxDecimals > 0 && a.indexOf(".") != -1 && (g = a.length - (a.indexOf(".") + 1), b.maxDecimals < g && (a = a.substring(0, a.indexOf(".")) + "." + a.substring(a.indexOf(".") + 1, a.indexOf(".") + 1 + b.maxDecimals))); b.allowDecimals || (a += "", a = a.replace(/[\.].+/, "")); a = a.replace(/\./, b.decimalSeparator); f.val(a); e.selectionStart = a.length - m; e.selectionEnd = a.length - n; h(b, this); if (b.onStep) b.onStep(f, c, i); return !1 } d.fn.jStepper = function (b) { var c = d.extend({}, d.fn.jStepper.defaults, b); return this.each(function () { var a = d(this), b = d.meta ? d.extend({}, c, a.data()) : c; b.disableAutocomplete && a.attr("autocomplete", "off"); d.isFunction(a.mousewheel) && a.mousewheel(function (a, c) { if (c > 0) return f(b, 1, null, this), !1; else if (c < 0) return f(b, 0, null, this), !1 }); a.keydown(function (a) { var c = a.keyCode; c == 38 && f(b, 1, a, this); c == 40 && f(b, 0, a, this) }); a.keyup(function () { h(b, this) }) }) }; d.fn.jStepper.defaults = { maxValue: null, minValue: null, normalStep: 1, shiftStep: 5, ctrlStep: 10, minLength: null, disableAutocomplete: !0, defaultValue: 1, decimalSeparator: ",", allowDecimals: !0, minDecimals: 0, maxDecimals: null, disableNonNumeric: !0, onStep: null} })(jQuery);

// Checks sku on quickorder form
function checkSku(){$(".fieldsku").each(function(){function c(){d!=null&&d.abort();if(a.val().length==0)b.removeClass(e),b.removeClass(f);else{var c="{sku:'"+a.val()+"'}";d=$.ajax({type:"POST",url:"/WebServiceSF.asmx/IsProductVisible",data:c,contentType:"application/json; charset=utf-8",dataType:"json",success:function(a){a.d?(b.removeClass(f),b.addClass(e),g.val().length==0&&g.val("1")):(b.addClass(f),b.removeClass(e),g.val(""))}})}}var a=$(this),b=a.parent(),d=null,e="valid",f="invalid",g=a.parent().parent().parent().find(".fieldquantity").first(); c();a.keyup(function(){c()});a.change(function(){c()})})};

function toggleBox(){$(this).next().slideToggle("fast");var a=$(this).children("img");a.toggleClass("collapsed");a.toggleClass("expanded");a.filter("img.collapsed").attr("src","images/plus.png").end().filter("img.expanded").attr("src","images/minus.png")};

// Guided Search
function initGuidedSearch() {
    var m = "<span>More</span>"; var l = "<span>Less</span>"; 
    var b = $(".moreless a");
    b.html(m);
    b.click(function () {
        var a = $(this); var c = a.parent().parent().prev();
        c.slideToggle("fast");
        a.html(a.html() == m ? l : m);
        return !1;
    });
};

var cpopup;

$(function () {

    initGuidedSearch();

    $(".fieldquantity").jStepper({ minValue: 0, maxValue: 100000 });

    cpopup = new shoppingCartPopup();
    var addToCartComplete_old = addToCartComplete;
    addToCartComplete = function () {
        if (addToCartComplete_old != null) addToCartComplete_old();
        //cpopup.showPopup(true);
        $('.cartpopup').trigger('addtocart');
    };

    initPlaceholders();
});


// Initializes placeholders/watermarks
function initPlaceholders() { $("[placeholder]").focus(function () { var a = $(this); a.val() == a.attr("placeholder") && (a.val(""), a.removeClass("placeholder")) }).blur(function () { var a = $(this); if (a.val() == "" || a.val() == a.attr("placeholder")) a.addClass("placeholder"), a.val(a.attr("placeholder")) }).blur().parents("form").submit(function () { $(this).find("[placeholder]").each(function () { var a = $(this); a.val() == a.attr("placeholder") && a.val("") }) }) };

function showWait() { $("#wait").show(); }
function hideWait() { $("#wait").hide(); }

function addToCartComplete() {}

function shoppingCartPopup() {
    var showTimeoutId;
    var hideTimeoutId;
    var cp = $(".cartpopup");
    var ct = $(".carttotalsblk");
    var d = this;
    var ctt = ct.scrollTop();

    cp.mouseenter(function () {
        clearTimeouts();
    });

    cp.mouseleave (function () {
        clearTimeouts();
        hideTimeoutId = setTimeout(d.hidePopup, 500);
    });

    cp.bind('addtocart', function() {
        d.showPopup(true);
    });

    this.initPopup = function(k) {
        if (k != null) {
            k.mouseenter(function () {
                showTimeoutId = setTimeout(d.showPopup, 1000);
            });
            k.mouseleave(function () {
                clearTimeout(showTimeoutId);
            });
        }
    };
    
    this.showPopup = function (hide) {
        clearTimeouts();
        $(document).scrollTop(ctt);
        cp.slideDown();
        if (hide)
            hideTimeoutId = setTimeout(d.hidePopup, 3000);
    };

    function clearTimeouts() {
        clearTimeout(showTimeoutId);
        clearTimeout(hideTimeoutId);
    }

    this.hidePopup = function () {
        cp.slideUp();
        cp.hide();
        clearTimeouts();
    };

    d.initPopup(ct);
};


// Product Views
function initProductList(productList, target) {
    var items = target.find(".pl_item");
    items.each(function () {
        var pgvItem = $(this);
        var i = items.index($(this));
        var item = productList.Items[i];

        // compare
        pgvItem.find(".chkcompare:first").click(function () {
            var args = { Item: item, Checkbox: $(this) };
            updateCompare(args);
        });

        // add to cart
        var btn = pgvItem.find(".btnaddtocart:first");
        var qtyField = pgvItem.find(".fieldquantity:first");
        btn.attr("onclick", "return false;");
        btn.click(function () {
            var qty = 1;
            if (qtyField != null) { qty = parseInt(qtyField.val()); }
            qty = isNaN(qty) ? 1 : qty;
            siteAddToCart(item.Id, qty, $(this));
        });
    });
}

function siteAddToCart(id, qty, source) {
    $.ajax({
        type: "POST",
        url: "/WebServiceSF.asmx/AddToCartById",
        beforeSend: function () {
            showWait();
            if (source != null) { source.attr('disabled', 'disabled'); }
        },
        complete: function () {
            hideWait();
            if (source != null) { source.removeAttr('disabled'); }
        },
        data: ("{id:'" + id + "', quantity:'" + qty + "'}"),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (a) {
            Anthem_InvokePageMethod();
        }
    });
    
}

var itemComparer = {
    CompareItems: $('.compare-items'),
    Max: 3,
    Items: [],
    update: function (item) {
        var ret = false;
        var idx = -1; for (var i = 0; i < this.Items.length; i++) { if (this.Items[i].Item === item.Item) { idx = i; break; } }

        if (item.Checkbox.is(':checked')) {
            if (idx == -1 && this.Items.length < this.Max) {
                this.Items.push(item);
                ret = true;
            }
        } else {
            if (idx != -1) {
                this.Items.splice(idx, 1);
                ret = true;
            }
        }
        if (ret) { this.render(); };
        return ret;
    },
    render: function () {
        if (this.CompareItems != null) {
            this.CompareItems.empty();
            for (var i = 0; i < this.Max; i++) {
                var li = '<li>';
                if (i < this.Items.length) {
                    var item = this.Items[i];
                    li += "<a href=\"#\"><img src=\"" + item.Item.Thumbnail + "\" onclick=\"javascript:itemComparer.removeAt(" + i + ")\" /></a>";
                }
                li += '</li>';
                this.CompareItems.append(li);
            }
        }
    },
    removeAt: function (index) {
        var item = this.Items[index];
        if (item != null) {
            item.Checkbox.attr('checked', false);
            this.Items.splice(index, 1);
            this.render();
        }
    }

};

function updateCompare(item) {
    itemComparer.update(item);
}

function removeCompare(index) {
    itemComparer.removeAt(index);
}
