/// <reference path="../../assets/libs/jam/jquery/dist/jquery.js" />
///
require(["app-config", "handlebars"], function (app_config, Handlebars) {

    $().ready(function () {
        initCart(); 
    }); 

    function initCart(){
        simpleCart({
            //Setting the Cart Columns for the sidebar cart display.
            update: _refreshCart
            , shippingFlatRate: "20.00"
        });

        simpleCart.currency({
            code: "U$D",
            name: "US Dollar",
            symbol: "<span style='float:left;text-indent:5px;'>$ </span>",
            accuracy: 2
        });

        simpleCart.update();

        $(".btn-checkout").click(_checkout);
        $(".empty-cart").click(emptyCart);
    };
    
    function emptyCart() {
        animate = true;
        simpleCart.empty();
    }

    function _checkout() {
        try {

            var items = {};
            simpleCart.each(function (item, x) {
                items[x] = {
                    Name: item.get("name")
                    , Quantity: item.get("quantity")
                    , Price: item.get("price")
                    , Subtotal: item.get("total")
                    , Id: item.get("id")
                };
            });

            var sendObject = {
                itemsRequested: items
                , Total: simpleCart.total()
                //, AccountNumber: user.GetAccountNumber()
                //, Email: user.GetUserEmail()
            };

            simpleCart({
                checkout: {
                    type: "PayPal"
                    , sandbox: false
                    , success: "http://www.dzsupervision.com/paymentSuccess"
                    , cancel: "http://www.dzsupervision.com/viewcart?status=cancel"
                    , custom: window.Core.Json.Encode(sendObject)
                    , customActionURL: 'process-order.aspx'
                    , extraOptions: {
                        //userLanguage: Global.Language
                        //, accountNumber: sendObject.AccountNumber
                    }
                }
                , excludeFromCheckout:
                    ['maxQuantity', 'type', 'checkoutCustomParams']
            });

            simpleCart.checkout();

        } catch (ex) { }
    }

    function _trashItem(e) {
        var $target = $(e.target);
        var $item = $target.parents("[data-item-row]");

        if ($item && $item.length > 0 && ($item = $($item.get(0)))) {
            var itemId = $item.data("item-id");
            var item = simpleCart.find(itemId);
            item.remove(); 
        }
    }

    function _qtyChanged(e) {
        var $target = $(e.target);
        var $item = $target.parents("[data-item-row]");

        if ($item && $item.length > 0 && ($item = $($item.get(0)))) {
            var itemId = $item.data("item-id");
            var item = simpleCart.find(itemId);

            var newQty = $target.val(); 
            item.quantity(parseInt(newQty));
            simpleCart.update();
        }
    }

    function _refreshCart() {
        var quantity = simpleCart.quantity();
        var total = simpleCart.total();
        var currency = simpleCart.currency(); 

        $(".cart-count-bubble").text(quantity);
        $(".cart-total-items").text(quantity);
        $(".cart-total").text(total);

        var items_data = simpleCart.items();
        var items = [];
        for (var i = 0, len = items_data.length; i < len; i++) {
            var item_data = items_data[i];
            var item = {
                name: item_data.get("name"),
                price: item_data.get("price"),
                quantity: item_data.get("quantity"),
                id: item_data.get("id"),
                currency_code: currency.code, 
            };

            items.push(item);
        }

        var rows_template = Handlebars.compile($("#cart-row-template").html());
        $(".cart-overview-panel-body").html(rows_template({ items: items }));

        $(".cart-total").text(currency.code + " " + total); 

        $(".btn-trash-item").click(_trashItem);
        $(".item-qty-input").change(_qtyChanged);
        $(".item-qty-input").keydown(function (e) { if (e.keyCode == 13) $(e.target).blur(); });
    }

}); 