﻿window.products = new Ext.util.MixedCollection();
window.individualProducts = new Ext.util.MixedCollection();
window.premierSupportProducts = new Ext.util.MixedCollection();
window.enterpriseProducts = new Ext.util.MixedCollection();

for (var i = 0; i < window.productsJSON.length; i++)
    window.products.add(window.productsJSON[i].productId, window.productsJSON[i]);

Ext.onReady(function() {
    
    var elements = Ext.query("*[id^=quantity-]");
    for (var i = 0; i < elements.length; i++) {
        var x = new Ext.form.NumberField({ applyTo: elements[i].id });
        Ext.get(elements[i].id).on('keyup', function(e) { return quantity_onkeyup(this.id.split('quantity-')[1]); });
        Ext.get(elements[i].id).on('change', function(e) { return quantity_onkeyup(this.id.split('quantity-')[1]); });
        Ext.get(elements[i].id).on('blur', function(e) {
            if (this.getValue().trim() == "") {
                this.dom.value = "1";
                quantity_onkeyup(this.id.split('quantity-')[1]);
            }
        }
        );
    }

    var elements = Ext.query("*[id^=add-product-]");
    for (var i = 0; i < elements.length; i++) {

        Ext.get(elements[i]).on("click", function() {
            var productId = this.id.split('add-product-')[1];
            product = getCurrentProduct(productId);
            this.dom.href = "/store/addproductstocart?productId=" + product.productId + '&quantity=' + Ext.get('quantity-' + productId).getValue();
            return false;
        });

    }

    Ext.get('purchase-previous-quote').dom.href = "javascript: void(0)";
    Ext.get('purchase-previous-quote').on('click', function() {
        Ext.MessageBox.prompt('Quote Number', 'Please enter your quote number:', purchaseQuote);
    });

    function purchaseQuote(btn, text) {
        if (btn == 'ok') {
            Ext.Ajax.request({
                url: '/ShoppingCart/ValidateQuoteNumber',
                method: 'POST',
                params: { orderId: (text != "" ? text : 0) },
                success: function(result, request) {
                    try {
                        if (result.responseText == "True")
                            window.location = "/ShoppingCart/QuoteToPurchase/" + text;
                        else
                            Ext.Msg.show({
                                title: 'Quote Error',
                                msg: "Invalid Quote #" + text,
                                buttons: Ext.Msg.OK
                            });
                    }
                    catch (ex) {
                        Ext.Msg.show({
                            title: 'Quote Error',
                            msg: "Error: " + ex.message,
                            buttons: Ext.Msg.OK
                        });
                    }
                },
                failure: function(result, request) {
                    Ext.Msg.show({
                        title: 'Failed',
                        msg: result.responseText,
                        buttons: Ext.Msg.OK
                    });
                }
            });
        }
    }

    Ext.get('purchase-previous-invoice').dom.href = "javascript: void(0)";
    Ext.get('purchase-previous-invoice').on('click', function() {
    Ext.MessageBox.prompt('Invoice Number', 'Please enter your invoice number:', purchaseInvoice);
    });

    function purchaseInvoice(btn, text) {
        if (btn == 'ok') {
            Ext.Ajax.request({
                url: '/ShoppingCart/ValidateInvoiceNumber',
                method: 'POST',
                params: { invoiceId: (text != "" ? text : 0) },
                success: function(result, request) {
                    try {
                        if (result.responseText == "True")
                            window.location = "/ShoppingCart/InvoiceToPurchase/" + text;
                        else
                            Ext.Msg.show({
                                title: 'Invoice Error',
                                msg: "Invalid Invoice #" + text,
                                buttons: Ext.Msg.OK
                            });
                    }
                    catch (ex) {
                        Ext.Msg.show({
                            title: 'Invoice Error',
                            msg: "Error: " + ex.message,
                            buttons: Ext.Msg.OK
                        });
                    }
                },
                failure: function(result, request) {
                    Ext.Msg.show({
                        title: 'Failed',
                        msg: result.responseText,
                        buttons: Ext.Msg.OK
                    });
                }
            });
        }
    }
});

function getCurrentProduct(productId) {
    return getProduct(productId);
}

function getDiscountPercentage(p, quantity) {
    var percentage = 0;
    for (var i = 0; i < p.discounts.length; i++) {
        if (quantity >= p.discounts[i].quantity) {
            if( p.discounts[i].percentage > percentage )
                percentage = p.discounts[i].percentage;
        }
    }
    return percentage;
}

function getProduct(id) {
    return window.products.get(id);
}

function getRelatedProduct(e) {
    return getProduct(getProduct(e).relatedProductId);
}

function quantity_onkeyup(e) {

    var product = getCurrentProduct(e);
    var quantityField = Ext.get('quantity-' + e);
    var priceField = Ext.get('price-' + e);

    if (quantityField.getValue() != product.quantity) {
        updatePrice(quantityField, priceField, product);
    }
}

function toggleDisplay() {

    var isPremierSupport = Ext.get('premier-support').dom.checked;

    window.products.each(function (item, index, length) {
        if (item.CategoryId == 1 && !item.IsPremierSupport) {
            var quantity = Ext.get('quantity-' + item.productId);
            if (isPremierSupport)
                product = getRelatedProduct(item.productId)
            else
                product = item;
            updatePrice(quantity, Ext.get('price-' + item.productId), product);
        }
    });

}

function updatePrice(quantityField, priceField, currentProduct) {

    var totalPrice = 0
    currentProduct.quantity = quantityField.getValue();
    var discountPercentage = getDiscountPercentage(currentProduct, quantityField.getValue());

    if (discountPercentage > 0)
        totalPrice = (quantityField.getValue() * currentProduct.price) - (quantityField.getValue() * currentProduct.price * discountPercentage);
    else
        totalPrice = (quantityField.getValue() * currentProduct.price)

    priceField.update(Ext.util.Format.usMoney(totalPrice));

    if (discountPercentage > 0)
        priceField.update(priceField.dom.innerHTML + ' <span class="volume-discount">(' + discountPercentage * 100 + '%)</span>');

}