
function ShoppingBasket() {
    this.subscribers = [];
    var basket = this;
    this.addProduct = function(productId, quantity, data) {

        var json = $.toJSON(data);

        $.post('/ECommerce/AddProductToBasket', { productId: productId, quantity: quantity, additionalData: json },
            function(message) {
                if (message) {
                    alert(message);
                }

                basket.updateBasket();
            });
    };

    this.updateQuantity = function (productId, quantity, callback) {
        $.post("/ECommerce/UpdateBasketAndCalculateProductPrice",
            {
                productId: productId,
                quantity: quantity
            }, function(data) {
                basket.totalPrice = data.TotalPriceString;
                basket.quantity = quantity;
                //basket.notify();

                if (callback) {
                    callback(data.UnitPriceString, data.TotalPriceString);
                }

                basket.updateBasket();
            });
    };

    this.setTaxRate = function(tax, callback) {
        $.post("/ECommerce/SetTaxRate",
            {
                tax: tax
            }, function () {
                basket.updateBasket();
                if (callback) {
                    callback();
                }
            });
    };

    this.taxExempt = function (status, callback) {
        $.post("/ECommerce/UpdateBasketTaxExemptStatus",
            {
                status: status
            }, function () {
                basket.updateBasket();
                if (callback) {
                    callback();
                }
            });
    };

    this.updateBasket = function() {
        $(".shopping-basket").load("/ECommerce/RenderBasketItems");
        this.notify();
    };

    this.showConfirmation = function() {
        alert("this item has now been added to your basket");
    };

    this.removeProduct = function(productId) {
        $.post("/ECommerce/RemoveProductFromBasket",
            {
                productId: productId
            }, function() {
                basket.notify();
                $(".shopping-basket").load("/ECommerce/RenderBasketItems", function() {
                });
            });
    };

    this.clear = function() {
        $.post("/ECommerce/ClearBasket", function () {
            basket.notify();
        });
    };

    this.subscribe = function(subscriber) {
        this.subscribers.push(subscriber);
    };

    this.notify = function() {
        for (var i = 0; i < this.subscribers.length; i++) {
            this.subscribers[i].update();
        }
    };
};

ShoppingBasket.Singleton(new ShoppingBasket);
