﻿/// <reference path="jquery-1.2.6-vsdoc.js" />

$(document).ready(function() {

//    $(".categoryTree").treeTable();
    jQuery126(".categoryTree").treeTable();

    // Init the category tree.
    //    $("#categoryTree").treeview({
    //        collapsed: true,
    //        persist: "cookie",
    //        cookieId: "treeviewTracking"
    //    });

    // Set odd/even on products table.
    $("table.products tr:even").addClass("even");
    $("table.products tr:odd").addClass("odd");

    // Set click event on the customer type radio button selection.
    $("input[name='CustomerType']").click(function() {
        var $privatePerson = $('#PrivatePersonDetails');
        var $company = $('#CompanyDetails');

        if ($("input[name='CustomerType']:checked").val() == "0") {
            $privatePerson.show();
            $company.hide();
        } else {
            $privatePerson.hide();
            $company.show();
        }
    });

    // Set keyup event on the billing zip code field.
    $("#BillingAddressZipCode").keyup(function() {
        var billingZipCode = $("#BillingAddressZipCode").val();

        if (billingZipCode.length == 5) {
            $.ajax({
                type: "GET",
                url: $("#GetCityUrl").attr("value") + "/" + escape(billingZipCode),
                data: null,
                success: function(result) {
                    $("#BillingAddressCity").val(result);
                },
                error: null
            });
        }
    });

    // Set keyup event on the shipping zip code field.
    $("#ShippingAddressZipCode").keyup(function() {
        var billingZipCode = $("#ShippingAddressZipCode").val();

        if (billingZipCode.length == 5) {
            $.ajax({
                type: "GET",
                url: $("#GetCityUrl").attr("value") + "/" + escape(billingZipCode),
                data: null,
                success: function(result) {
                    $("#ShippingAddressCity").val(result);
                },
                error: null
            });
        }
    });

    // Set click event on product thumbnails on product page.
    $(".ProductThumbnail").click(function() {
        $("#ProductImage").attr("src", $(this).attr("src").replace('thumb', 'medium'));
        $("#ProductImageLink").attr("href", $(this).attr("src").replace('.thumb', ''));
    });

    // Set click event on the "add to cart" buttons.
    $(".AddToCart").click(function() {

        $("#added-to-cart").hide();
        $("#spinner").show();

        var $button = $(this);
        var productID = $button.attr("id");
        var size = $("#Size_" + productID).val();
        var quantity = $("#Quantity_" + productID).val();

        size = ((size != null) ? size : '');
        quantity = ((quantity != null) ? quantity : 1);

        $.ajax({
            type: "GET",
            url: $("#AddProductForm").attr("action") + "/" + productID + "/" + quantity + "/" + escape(size),
            data: null,
            success: function(result) {
                //$("#ShoppingCartSummary").html(result);
                var info = eval(result);
                $("#ShoppingCartSum").html(info[0]);
                $("#ShoppingCartQuantity").html(info[1]);

                if (info[2] == "0") {
                    $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar_null.png)');
                    $("#AmountSaved").html('');
                } else {
                    $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar.png)');
                    $("#AmountSaved").html(info[2] + ":-");
                }

                $("#spinner").hide();
                $("#varukorg_huvud").effect("highlight", {}, 3000); ;
                $("#added-to-cart").show();
            },
            error: function(result) {
                $('#spinner').hide();
            }
        });

        return false;
    });

    // Set click event on the "remove from cart" button.
    $(".RemoveFromCart").click(function() {
        var $button = $(this);
        var orderItemID = $button.attr("id");

        $.getJSON($("#RemoveFromCartUrl").attr("value") + "/" + orderItemID, null,
            function(result) {
                var cartSummary = result[0];
                var orderAmount = result[1];
                var itemCount = result[2];

                if (itemCount == 0) {
                    $("#CartIsEmptyMessage").show();
                    $("#CartContents").hide();
                } else {
                    $("#OrderAmount").html(orderAmount);
                    $("#CartIsEmptyMessage").hide();
                    $("#CartContents").show();

                    $("#ShoppingCartSum").html(orderAmount);
                    $("#ShoppingCartQuantity").html(itemCount);

                    if (orderAmount == "0") {
                        $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar_null.png)');
                        $("#AmountSaved").html('');
                    } else {
                        $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar.png)');
                        $("#AmountSaved").html(orderAmount + ":-");
                    }
                }

                //$("#ShoppingCartSummary").html(cartSummary);
                $("#Row_" + orderItemID).replaceWith("");

                $("table.products tr:even").removeClass("odd").addClass("even");
                $("table.products tr:odd").removeClass("even").addClass("odd");
            });
    });

    // Set click event on the "clear cart" button.
    $("#ClearCart").click(function() {
        $.ajax({
            type: "GET",
            url: $("#ClearCartUrl").attr("value"),
            data: null,
            success: function(result) {
                $("#CartIsEmptyMessage").show();
                $("#CartContents").hide();
                //$("#ShoppingCartSummary").html(result);
                $("#ShoppingCartSum").html("0 kr");
                $("#ShoppingCartQuantity").html("0");
                $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar_null.png)');
                $("#AmountSaved").html('');
            },
            error: null
        });
    });

    // Set click event on the "update cart" button.
    $("#UpdateCart").click(function() {
        var items = "";

        $("table.products tbody tr").each(function() {
            var itemID = $(this).attr("id").replace(/Row_/, "");
            items += itemID + "=" + $('#Quantity_' + itemID).attr("value") + "|";
        });

        $.getJSON($("#UpdateCartUrl").attr("value"), { cart: items },
            function(result) {
                var cartSummary = result[0];
                var orderAmount = result[1];
                var itemCount = result[2];
                var lineTotals = result[3].split("|");

                if (itemCount == 0) {
                    $("#CartIsEmptyMessage").show();
                    $("#CartContents").hide();
                } else {
                    $("#OrderAmount").html(orderAmount);
                    $("#CartIsEmptyMessage").hide();
                    $("#CartContents").show();
                }

                var id; var total; var tmp;
                for (i = 0; i < lineTotals.length; i++) {
                    tmp = lineTotals[i].split("=");
                    id = tmp[0];
                    total = tmp[1];
                    $("#LineTotal_" + id).html(total);
                }

                $("#ShoppingCartSummary").html(cartSummary);
            });
    });

    // Set click event on the "plus" button.
    $(".UpdateItemPlus").click(function() {
        var id = $(this).attr("id");
        var qty = $('#Quantity_' + id).attr("value");
        var item = id + "=" + qty;

        $.getJSON($("#UpdateItemPlusUrl").attr("value"), { cart: item },
            function(result) {
                var cartSummary = result[0];
                var orderAmount = result[1];
                var itemCount = result[2];
                var lineTotals = result[3].split("|");
                var amountSaved = result[4];

                if (itemCount == 0) {
                    $("#CartIsEmptyMessage").show();
                    $("#CartContents").hide();
                    $("#ShoppingCartSum").html("0 kr");
                    $("#ShoppingCartQuantity").html("0");
                    $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar_null.png)');
                    $("#AmountSaved").html('');
                } else {
                    $("#OrderAmount").html(orderAmount);
                    $("#CartIsEmptyMessage").hide();
                    $("#CartContents").show();
                    $("#ShoppingCartSum").html(orderAmount);
                    $("#ShoppingCartQuantity").html(itemCount);
                    $("#AmountSaved").html(amountSaved);

                    if (amountSaved == "0") {
                        $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar_null.png)');
                        $("#AmountSaved").html('');
                    } else {
                        $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar.png)');
                        $("#AmountSaved").html(amountSaved + ":-");
                    }
                }

                var id; var qty; var total; var tmp;
                for (i = 0; i < lineTotals.length; i++) {
                    tmp = lineTotals[i].split("=");
                    id = tmp[0];
                    total = tmp[1];
                    qty = tmp[2];

                    $("#LineTotal_" + id).html(total);
                    $("#Quantity_" + id).val(qty);
                }

                //$("#ShoppingCartSummary").html(cartSummary);
            });
    });

    // Set click event on the "minus" button.
    $(".UpdateItemMinus").click(function() {
        var id = $(this).attr("id");
        var qty = $('#Quantity_' + id).attr("value");
        var item = id + "=" + qty;

        $.getJSON($("#UpdateItemMinusUrl").attr("value"), { cart: item },
            function(result) {
                var cartSummary = result[0];
                var orderAmount = result[1];
                var itemCount = result[2];
                var lineTotals = result[3].split("|");
                var amountSaved = result[4];

                if (itemCount == 0) {
                    $("#CartIsEmptyMessage").show();
                    $("#CartContents").hide();
                    $("#ShoppingCartSum").html("0 kr");
                    $("#ShoppingCartQuantity").html("0");
                    $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar_null.png)');
                    $("#AmountSaved").html('');
                } else {
                    $("#OrderAmount").html(orderAmount);
                    $("#CartIsEmptyMessage").hide();
                    $("#CartContents").show();
                    $("#ShoppingCartSum").html(orderAmount);
                    $("#ShoppingCartQuantity").html(itemCount);

                    if (amountSaved == "0") {
                        $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar_null.png)');
                        $("#AmountSaved").html('');
                    } else {
                        $("#topmenu").css('background-image', 'url(/Content/Pictures/menu_bar.png)');
                        $("#AmountSaved").html(amountSaved + ":-");
                    }
                }

                var id; var total; var tmp;
                for (i = 0; i < lineTotals.length; i++) {
                    tmp = lineTotals[i].split("=");
                    id = tmp[0];
                    total = tmp[1];
                    qty = tmp[2];

                    $("#LineTotal_" + id).html(total);
                    $("#Quantity_" + id).val(qty);
                }

                //$("#ShoppingCartSummary").html(cartSummary);
            });
    });

    $("#BeginPayment").click(function() {
        var termsAccepted = $("input[name='TermsOfUseAccepted']:checked").val();

        if (termsAccepted == undefined) {
            alert("Du måste godkänna köp- och leveransvillkoren!");
            return;
        }

        var paymentMethodID = $("input[name='PaymentMethodID']:checked").val();

        if (paymentMethodID == undefined) {
            alert("Vänligen välj ett betalningsalternativ för din order.");
            return;
        }

        if (paymentMethodID == 1) {
            popupWindow('payment/invoice');
            $(this).attr("disabled", "disabled");
            $(this).attr("value", "Var god vänta...");
        } else if (paymentMethodID == 2) {
            popupWindow('payment/creditcard');
            $(this).attr("disabled", "disabled");
            $(this).attr("value", "Var god vänta...");
        } else if (paymentMethodID == 3) {
            popupPayExWindow('payment/payexcreditcard');
            $(this).attr("disabled", "disabled");
            $(this).attr("value", "Var god vänta...");
        } else if (paymentMethodID == 4) {
            var paymentClassId = $("input[name='KlarnaPaymentType']:checked").val();
            popupWindow('payment/klarnapayment/' + paymentClassId);
            $(this).attr("disabled", "disabled");
            $(this).attr("value", "Var god vänta...");
        }
    });

    function popupWindow(url) {
        newwindow = window.open(url, 'Betalning', 'height=600,width=500');
        if (window.focus) {
            newwindow.focus();
        }
        return false;
    }

    function popupPayExWindow(url) {
        newwindow = window.open(url, 'Betalning', 'height=600,width=800');
        if (window.focus) {
            newwindow.focus();
        }
        return false;
    }

});

var BRAND = {

    resizeSidebar: function() {

        var contentDom = document.getElementById('mainContent_with_sidebar');
        var sidebarDom = document.getElementById('sidebarWrapper');

        if (contentDom.offsetHeight > sidebarDom.offsetHeight) {
            sidebarDom.style.height = contentDom.offsetHeight + 'px';
            return;
        }

        if (contentDom.offsetHeight < sidebarDom.offsetHeight) {
            contentDom.style.height = sidebarDom.offsetHeight + 'px';
            return;
        }

    },


    autoResizeSidebar: function() {
        setInterval(BRAND.resizeSidebar, 100);
    },

    product: {

        resizeBoxes: function() {
            $(window).load(function() {

                $('.prod_row').each(function() {

                    var maxHeight = 0;

                    $('.prodimg', $(this)).each(function() {
                        if ($(this).height() > maxHeight) {
                            maxHeight = $(this).height();
                        }
                    });

                    $('.prodimg', $(this)).each(function() {
                        $(this).height(maxHeight);
                    });

                });
            });

        }
    }
}
