﻿/// <reference path="~/Resources/js/jquery-1.2.6-intellisense.js" />
/// <reference path="~/Resources/js/start.js" />
/// <reference path="~/Resources/js/cart.js" />

VVM.cartPage = {
    // Adds the accessory in context to the cart page
    add: function(context) {
        var accessoryName = $(context).parents("tr").find('.brand').text();
        var accessoryCount = $(context).parents("#recomended-accessories").find(".brand:contains('" + accessoryName + "')").length;

        var id = "ID" + $(context).attr("rel") + "-" +
            $.trim($(".price-list-id", $(context).parent()).text());

        if (this.contains("#" + id)) {
            var qty = $("#" + id + " input");
            qty.val(qty.val() * 1 + 1);
        } else {
            if (accessoryCount < 2) {
                var parentId = $(context).parents(".product-accessories:first")[0].id.replace("_", "-");
                var price = VVM.formatPrice($(context).parent().siblings(".price").text());
                $("#" + parentId).after(
                '<tr id="' + id + '" class="accessory">' +
                '<td class="name-column">' +
                    '<input class="cart-amount-textbox" type="text" value="1" />' +
                    $(context).parent().siblings(".name").text() +
                '</td>' +
                '<td class="price-column">' + price + '</td>' +
                '<td class="row-price-column">' + price + '</td>' +
                '<td class="delete-column"><img class="delete" src="/Resources/images/trash.png" alt=""/></td>' +
                '</tr>');
            } else {
                var price = VVM.formatPrice($(context).parent().siblings(".price").text());
                // fix, remove static id selection
                $("#AccessoryListContainer").removeClass("hidden");
                $("#ctl00_SiteContent_AcessoryList").append(
                    '<tr id="' + id + '" class="cart-alternating" ' + 'title="' + $(context).parent().siblings(".brand").text() + '">' +
                    '<td class="name-column">' +
                        '<input class="cart-amount-textbox" type="text" value="1" />' + " " +
                        $(context).parent().siblings(".name").text() +
                    '</td>' +
                    '<td class="price-column">' + price + '</td>' +
                    '<td class="row-price-column">' + price + '</td>' +
                    '<td class="delete-column"><img class="delete" src="/Resources/images/trash.png" alt=""/></td>' +
                    '</tr>');
            }

            AddClickEventToDeleteButton(id);
            updateRowBackground();
        }
    },

    // Removes the accessory list for the specified item from the page
    // @param   itemId: string
    removeAccessoryList: function(itemId) {
        $("#" + itemId.replace("-", "_")).remove();
    },

    // Removes the item and all of its accessories in context from the page
    // Optionally invokes callback to item and its accessories
    // @param   callback: function({ id, priceListId })
    remove: function(context, callback) {
        var container = $(context).parents("tr:first");

        if (!container.hasClass("accessory")) {
            $("#" + container[0].id + " ~ tr").each(function(i) {
                if (!$(this).hasClass("accessory"))
                    return false;

                if (callback) callback(VVM.cartPage.getItem(this));
                $(this).remove();
            });

            MoveAccessoriesBetweenColumnsIfNeeded(container);
        }
        if (callback) callback(VVM.cartPage.getItem(container));

        this.removeAccessoryList(container[0].id);
        container.remove();

        HideAccessoryListIfEmpty();
        updateRowBackground();
    },

    // Updates all quantities and prices in the cart page
    // If an item's quantity is 0, the item is removed including accessories
    // Optionally invokes callback to each item 
    // @param   callback: function({ id, priceListId }, qty)
    update: function(callback) {
        $("#cart-listing :text").each(function(i) {
            var item = VVM.cartPage.getItem(this);
            if (callback) callback(item, $(this).val());

            if (parseInt($(this).val(), 10) <= 0) {
                VVM.cartPage.remove(this, function(cartItem) {
                    if (callback) callback(cartItem, 0);
                });
                return;
            }

            var siblings = $(this).parent().siblings();
            siblings.filter(".row-price-column").text(
                VVM.formatPrice($(this).val() * VVM.toInt(siblings.filter(".price-column").text()))
            );
        });
    },

    setQuantity: function(qty) {
        $("#product-count").text(qty);
    },

    setSubTotal: function(subTotal) {
        $("#cart .cart-sum-right").text(subTotal);
    },

    contains: function(id) {
        return $(id).length > 0;
    },

    getItem: function(context) {
        if (!context)
            return null;

        var container = $(context).filter("tr").length > 0
            ? $(context)
            : $(context).parents("tr:first");
        if (container.length < 1)
            return null;

        var id = container[0].id.split("-");
        if (id.length != 2)
            return null;

        var product = id[0].substring(2);
        var priceList = id[1];
        return { id: product, priceListId: priceList };
    },

    refresh: function(cart) {
        if (cart.quantity == 0) {
            $("img.update").remove();
            $("#cart-listing table").remove();
            $(".description").remove();
        }

        if ($('.cart-accessory-list tr').length == 1) {
            $('.cart-accessory-list').remove();
        }

        $("#cart-listing table tr:even").removeClass("cart-alternating");
        $("#cart-listing table tr:odd").addClass("cart-alternating");
        this.setQuantity(cart.quantity);
        this.setSubTotal(VVM.formatPrice(cart.subtotal));
    }
};

$(function() {
    // Delete item handler
    $("img.delete").click(function() {
        if (!confirmDelete())
            return false;

        VVM.cartPage.remove(this, function(cartItem) {
            VVM.cart.remove(cartItem);
        });
        VVM.cartPage.refresh(VVM.cart);
        VVM.renderCart();
    });

    // Update quantity handler
    $("img.update").click(function() {
        VVM.cartPage.update(function(item, qty) {
            VVM.cart.update(item, qty);
        });
        VVM.cartPage.refresh(VVM.cart);
        VVM.renderCart();
    });

    // Buy accessory handler
    $("#cart-area .accessories button.buy-accessory").click(function() {
        // adding to cart handled by product.js
        VVM.cartPage.add(this);
        VVM.cartPage.refresh(VVM.cart);
    });

    // Show hidden accessorylist if it contains items
    $("#AccessoryListContainer table tr").each(function() {
        if ($(this).attr("id") != "") {
            $("#AccessoryListContainer").removeClass("hidden");
        }
    });
});

function confirmDelete() {
    return confirm("Är du säker på att du vill ta bort varan ur din kundvagn?");
}

function PrintConfirmationPage() {
    window.print();
}

function HideAccessoryListIfEmpty() {
    var accessoryCounter = 0;
    $("#AccessoryListContainer table tr").each(function() {
        if ($(this).attr("id") != "") {
            accessoryCounter++;
        }
    });

    if (accessoryCounter == 0) {
        $("#AccessoryListContainer").addClass("hidden");
    }
}

function AddClickEventToDeleteButton(id) {
    $("#" + id + " img.delete").click(function() {
        if (!confirmDelete())
            return false;

        VVM.cartPage.remove(this, function(cartItem) {
            VVM.cart.remove(cartItem);
        });
        VVM.cartPage.setQuantity(VVM.cart.quantity);
        VVM.renderCart();
    });
}

function MoveAccessoriesBetweenColumnsIfNeeded(container) {
    if (!$("#AccessoryListContainer").hasClass("hidden")) {
        $("#AccessoryListContainer tr").each(function() {
            //GridView adding empty td, to avoid it check for title attribute
            var title = $(this).attr("title");
            if (title != "") {
                // Get accessory from #recomended-accessories
                var recomendedAccessoryItem = $("#" + container[0].id.replace("-", "_"));
                if (recomendedAccessoryItem.find(".brand:contains('" + title + "')").length > 0) {
                    // Count accessories
                    var currentAccessoryCount = $("#recomended-accessories").find(".brand:contains('" + title + "')").length;
                    if (currentAccessoryCount > 1) {
                        // Get the row that we will manipulate                                                
                        var accessoryRow = $(this);
                        var countMovedRows = 0;

                        // look through all items in main cart and check if any of them has got the accessory                        
                        $("#" + container.parents("table").attr("id") + " tr").each(function() {
                            var currentCartRowId = $(this).attr("id");
                            var clickedRowId = $("#" + container[0].id).attr("id");
                            // Skip clicked row (it is going to be removed), and make sure that the row has an ID
                            if (clickedRowId != currentCartRowId && currentCartRowId != "" && countMovedRows == 0) {
                                var rowActions = $("#recomended-accessories").find(".brand:contains('" + title + "'):first").siblings(".actions");
                                var id = "ID" + title + "-" + rowActions.find("span.price-list-id").text();
                                var price = VVM.formatPrice(accessoryRow.find(".price-column").text());
                                var rowPriceTotal = VVM.formatPrice(accessoryRow.find(".row-price-column").text());
                                $("#" + currentCartRowId).after(
                                        '<tr id="' + id + '" class="accessory">' +
                                            '<td class="name-column">' +
                                                '<input class="cart-amount-textbox" type="text" value="' + accessoryRow.find(".cart-amount-textbox").val() + '" />' +
                                                accessoryRow.find(".name-column").text() +
                                            '</td>' +
                                            '<td class="price-column">' + price + '</td>' +
                                            '<td class="row-price-column">' + rowPriceTotal + '</td>' +
                                            '<td class="delete-column"><img class="delete" src="/Resources/images/trash.png" alt=""/></td>' +
                                        '</tr>'
                                        );

                                AddClickEventToDeleteButton(id);
                                accessoryRow.remove();
                                countMovedRows++;
                            }
                        });
                    }
                    // Accessory only attatched to one item, go ahead and remove it
                    if (currentAccessoryCount == 1) {
                        $("#AccessoryListContainer tr[title='" + title + "']").remove();
                    }
                }
            }
        });
    }
}

function updateRowBackground() {
    $("#ctl00_SiteContent_CartView tr:odd").css("background-color", "#EBEBEB");
    $("#ctl00_SiteContent_CartView tr:even").css("background-color", "#FFFFFF");
}
