﻿function addOrderItem(item, num) {
    $("#smallCart").showLoading();
    num = parseInt(num);
    num = num > 0 ? num : 1;
    $.post("/Order/AddItem/", { itemId: item, quantity: num }, function done(data) { handleCartUpdate(data); }, "json");
    return false;
}

function removeOrderItem(item, num) {
    $("#smallCart").showLoading();
    $.post("/Order/RemoveItem/", { itemId: item, quantity: num }, function done(data) { handleCartUpdate(data); }, "json");
    return false;
}

function removeAllOrderItems(item, num) {
    $("#smallCart").showLoading();
    $("#itemRow" + item).attr("class", "removed");
    removeOrderItem(item, num);
    return false;
}

function deleteOrder(item) {
    $.post("/Order/Delete/", { Item: item }, function done(data) { handleCartUpdate(data); }, "json");
    return false;
}

function loadItems() {
    $("#smallCart").showLoading();
    $.post("/Order/GetOrderItems/", null, function done(data) { handleCartUpdate(data); }, "json");
}

function roundNumber(num, dec) {
    var result = Math.round(num * Math.pow(10, dec)) / Math.pow(10, dec);
    return result;
}

function handleCartUpdate(data) {
    document.getElementById("smallCartButton").click();
    $(".inCart").removeClass("inCart");
    $(".productInCart").html("");

    var freeDeliveryPrice = 1500;
    var halfDeliveryPrice = 1000;
    var totalPrice = 0;

    for (i = 0; i < data.length; i++) {
        var price = data[i].Quantity * roundNumber(data[i].Price, 0);
        totalPrice += price;

        var productContainer = document.getElementById("productContainer:" + data[i].ProductId);
        if (productContainer) {
            productContainer.setAttribute("class", "product inCart");
            if (data[i].Quantity > 0) {
                $("#numInCart_" + data[i].ProductId).html(data[i].Quantity + " шт.");
            }
        }
    }

    var deliveryPrice = 0;
    
    if (data.length > 0) {
        if (totalPrice >= freeDeliveryPrice) {
        } else if (totalPrice >= halfDeliveryPrice) {
            deliveryPrice = 100;
        } else {
            deliveryPrice = 200;
        }
    }
    if (deliveryPrice == 0) {
        $("#headerBasketValue").html(totalPrice);
    } else {
        $("#headerBasketValue").html(totalPrice + " + " + deliveryPrice);
    }

    $("#smallCart").hideLoading();
}
