﻿$(function () { 
    var $currentBtn = null;

    $('.product-list-buy').each(function () {
        var fieldset = $(this);
        var hdn = fieldset.find('.attribute');
        var qnt = fieldset.find('.quantity');
        var btn = fieldset.find('.form-button');
        var oos = fieldset.find('.oos');
        var img = fieldset.parents('.list-item').find('.product-image');
        var processOutOfStock = function (ident) {
            if (ident.length <= 0) return;
            var lio = ident.lastIndexOf('|');
            if (lio < 0) return;
            var outofstock = (ident.substring(lio + 1) === 'true');
            if (outofstock) {
                btn.hide();
                qnt.hide();
                oos.show();
            } else {
                btn.show();
                qnt.show();
                oos.hide();
            }
        };
        var getCleanIdent = function (ident) {
            if (ident.length <= 0) return "";
            var lio = ident.lastIndexOf('|');
            if (lio < 0) return "";
            return ident.substring(0, lio);
        };
        if (hdn[0].tagName.toLowerCase() == "select") {
            hdn.change(function () {
                processOutOfStock($(this).val());
                return false;
            });
            hdn.change();
        } else {
            processOutOfStock(hdn.val());
        }
        btn.click(function () {
            if ($currentBtn)
                return false;
            var ident = getCleanIdent(hdn.val());
            if (ident.length <= 0)
                return;
            $currentBtn = $(this).activateLoader();
            $.ajax({
                type: "POST",
                url: "/Services/ShopWebService.asmx/AddProductToBasket",
                data: "{'productIdent': '" + ident + "', 'quantity': " + qnt.val() + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    if ($currentBtn) {
                        $currentBtn.show();
                        $currentBtn.next().remove();
                        $currentBtn = null;
                    }
                    if (typeof msg.d == "object") {
                        setBasketDetails(msg.d);
                        shrinkImageToBasket(img);
                    } else {
                        alert(msg.d);
                    }
                }
            });
            return false;
        });
    });
});
