﻿    //Variables for urls and resource-strings needs to be set before including this script

    function addToCart(amount, specificId, addElement, loadingElement) {
        $.ajax({
            type: "POST",
            url: addToCartUrl,
            dataType: "json",
            data: "specificId=" + specificId + "&amount=" + amount,
            beforeSend: function () {
                addElement.attr("disabled", true);
                loadingElement.prepend($("#async_load_div"));
            },
            success: function (response) {
                addElement.attr("disabled", false);
                if (response.result == "ok") {
                    updateCartOverview(response.total, response.totalPrice, specificId);
                    displayMessage($("#userMessage"), resAdded, "success");
                } else {
                    displayMessage($("#userMessage"), error, "fail");
                }
            }
        });
    }

    function showCart(){
        $.ajax({ type: "GET",
            url: getCartUrl,
            dataType: "json",
            success: function (response) {

                if (response.check == "ok") {
                    if (!inCheckout) {
                        jQuery.facebox(function () {
                            jQuery.facebox(displayResult(response.data, false), "style='width:600px;height:600px;'");
                        });
                    }
                }
                else {                 
                }
            }
       
        });    
    }

    //Is this used?
    function showCartCheckout(container){  //change to ajax GET?
        jQuery.facebox(function () {
            $.getJSON(getCartUrl, null, function (result) {

                if (result.response != null || result.response.length == 0) {
                    container.html(displayResult(result.response, true));
                } 
            });
        });
    }
    
    function displayResult(result,inCheckout){
        localCurrency = currency == undefined ? "" : currency;
        var html = "<div id='cart-inner' style='width:550px;'><h1>" + resYourCart + "</h1>";
        if (result.length > 0) {
            html += "<table id='cart-table' class='checkout-cart'><thead><tr><th></th><th>" + resTitle + "</th><th>" + resColSize + "</th><th>" + resQuantity + "</th><th>" + resPrice + "</th><th>" + resDelete + "</th></tr></thead><tbody>";

            for (var i = 0; i < result.length; i++) {
                html += "<tr id='tr" + result[i].SpecificId + "'>";
                html += "<td><img src='/Helpers/ImageTransformer.ashx?fileName=/media/images/" + result[i].Image + "&Width=70&Height=70&mode=fit'/></td>";
                html += "<td>" + result[i].Title + "</td>";

                html += "<td>" + result[i].Color + "/" + result[i].Size + "</td>";

                html += "<td>" + result[i].Amount + "</td>";
                html += "<td>" + result[i].LineTotal + " " + currency + "</td>";
         
                html += "<td><span class='link-button' onclick='javascript:deleteFromCart(" + result[i].SpecificId + ")'>" + resDelete + "</span></td>";

                html += "</tr>";
            }
            html += "</tbody><tfoot><tr><td colspan='2'></td><td></td><td>" + resSubTotal + ": </td><td id='total'>" + result[0].TotalPrice + " " + localCurrency + "</td><td></td></tr></tfoot>";
            html += "</table><span id='cart-message'></span>";
            if (!inCheckout) {
                html += "<div class='button-container'><button class='button-default' type='button' onclick='javascript:toCheckout()'>" + resProceedCheckout + "</button></div>";

            }
        } else {
            html += "<p>" + resEmptyCart + "!</p>";
        }
        return html;
    }

    function toCheckout(){
        window.location = checkoutUrl;
    }

    function deleteFromCart(specificId) {

        $.ajax({ type: "POST",
            url: deleteFromCartUrl,
            data: "specificId=" + specificId,
            dataType: "json",
            beforeSend: function () {
                $("#cart-delete").attr("disabled", true);
                        
            },
            success: function (response) {
                $("#cart-delete").attr("disabled", false);
               
                if (response.result == "ok") {
                    var subTotal = response.SubTotalCost;
                    var itemCount = response.ItemCount;
                    var lineTotal = response.LineTotal;
                    deleteFromCartDisplay(specificId, subTotal, itemCount, lineTotal);
                    updateCartDelete(parseFloat(subTotal).toFixed(2), itemCount, subTotal, specificId);  //In master 
                }
                else {
               
                    displayMessage($("#cart-message"), error, "fail");
                }
            }
        });
    }

    function deleteFromCartDisplay(specificId,subTotalCost,totalAmount,lineTotal){
        var table = $("#cart-table");
        var trToRemove = table.find("#tr" + specificId);
        var tdAmount = trToRemove.find("td:nth-child(4)");
        var amount = tdAmount.html();
        if(amount == undefined){
            amount = 1;
        }
        if(table.find("tr").length == 3 && amount == 1){ //cart is empty after delete
            $("#cart-inner").html("<p>" + resEmptyCart + "!</p>");
            $("#cart-summary").html(resEmptyCart + "!");
        }
        else{
            var tdPrice = trToRemove.find("td:nth-child(5)");
            var digits = 2;
            var priceEach = parseFloat(lineTotal/amount).toFixed(digits);
            table.find("#total").html(parseFloat(subTotalCost).toFixed(digits).replace(".",","));
            if(amount > 1){
              tdAmount.html(amount -1);
              tdPrice.html(parseFloat(lineTotal).toFixed(digits).replace(".",","));
            }else{
                trToRemove.remove();
            }
        }
    }

    function displayMessage(element,text,statusClass){
        element.html("<span class='" + statusClass + "'>" +  text + "</span>");
        element.fadeOut(600).fadeIn(600);
    }