﻿
/// <reference path="jquery-1.2.6-vsdoc.js" />


$(function () {
    var $container = $('div.box-content'); // product details

    if ($container.length == 0) {
        $container = $('div.box-content-left'); // category boxes page
    }

    if ($container.length == 0) {
        $container = $('div#content'); // standard content page
    }

    if ($container.length == 1) {
        var $footer_link_div = $('div#footer-reservation');
        $container.append($footer_link_div);

        // special content page, e.g. campaign page
        if ($('#content').children('.cufon').length == 1) {
            $footer_link_div.css('text-align', 'right');
        }
    }
});

$(document).ready(function() {

    $(".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() {

        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") + "/" + escape(productID) + "/" + quantity + "/" + escape(size),
            data: null,
            success: function(result) {
                $("#ShoppingCartSummary").html(result);
            },
            error: null
        });
    });

    // 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();
                }

                $("#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);
            },
            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("|");

                if (itemCount == 0) {
                    $("#CartIsEmptyMessage").show();
                    $("#CartContents").hide();
                } else {
                    $("#OrderAmount").html(orderAmount);
                    $("#CartIsEmptyMessage").hide();
                    $("#CartContents").show();
                }

                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("|");

                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];
                    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...");
        }
    });

    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 BADGE = {

    align: function (contextId) {

        $(document).ready(function () {
            BADGE.hide(contextId);
        });

        $(window).load(function () {
            BADGE.expandAndShow(contextId);
        });
    },

    alignIfAlreadyLoaded: function (contextId) {
        BADGE.hide(contextId);
        BADGE.expandAndShow(contextId);
    },

    hide: function (contextId) {
        $(contextId).find("td").each(function () {
            var $img = $(this).find("img").css("visibility", "hidden");
        });
    },

    expandAndShow: function (contextId) {
        $(contextId).find("td").each(function () {
            var $wrapper = $(this).find("div.product-image-small-div");

            $wrapper.height($(this).height());

            var $img = $(this).find("img");
            var padding = $wrapper.height() - $img.height();

            $img.css("padding-top", padding).css("visibility", "visible");
        });
    }
}
