﻿var addBasketItemUrl;

function addItemToBasket(product, element) {
    $.ajax({
        type: 'POST',
        url: addBasketItemUrl,
        data: 'product=' + product,
        dataType: 'json',
        success: function(info) {
            if (info && info.Count && info.ProductCount) {
                $("#basket-amount").html(info.Count);
                $(element).siblings(".product-count-in-basket").val(info.ProductCount);
                setBuyButtonName(element);
            }
            //            else {
            //                alert('error - 1');
            //            }
        },
        error: function(err) {
            //alert('error - 2');
        }
    });
}

function addItemBatchToBasket(product, element, childsString) {
    $.ajax({
        type: 'POST',
        url: '/Basket/AddItemsBatch?product=0&childs=',
        data: 'product=' + product + '&childs=' + childsString,
        dataType: 'json',
        success: function(info) {
            if (info && info.Count && info.ProductCount) {
                $("#basket-amount").html(info.Count);
                $(element).siblings(".product-count-in-basket").val(info.ProductCount);
                setBuyButtonName(element);
            }
        },
        error: function(err) {
        }
    });
}

function countInBasket(element) {
    var countInBasket = parseInt($(element).siblings(".product-count-in-basket").val());
    return isNaN(countInBasket) ? 0 : countInBasket;
}

function setBuyButtonName(element) {
    var count = countInBasket(element);
    var text = count == 0 ? "В корзину" : "Корзина(" + count + ")";
    $(element).html(text);
}

/* -------------------- STEP 1 ----------------------------------------------*/
var defaultRegion;
var cashPaymentType;
var sberbankPaymentType;
var nalogenPaymentType;
var changeDeliveryTypesUrl;
function onAmountChanged() {
    updateLotTotalPrices();
    updateBasketTotalValues();
    updateOrderTotalPrice();
    updateOrderTotalPriceWithDiscount();
}

function onRegionChanged() {
    var region = getSelectedRegion();
    $(".selected-region").val(region);
    togglePaymentType(region == defaultRegion, cashPaymentType);
    togglePaymentType(region != defaultRegion, nalogenPaymentType);
    var selectedPaymentType = (region == defaultRegion) ? cashPaymentType : sberbankPaymentType;
    selectPaymentType(selectedPaymentType);    
    changeDeliveryTypes();
}

function togglePaymentType(show, paymentType) {
    var cashRow = $("input[name='payment-type'][value=" + paymentType + "]").parent().parent();
    var display = cashRow.css("display");
    if (show && display == "none") {
        cashRow.css("display", "table-row");            
    }
    else if (!show && (!display || display == null || display == "table-row")) {
        cashRow.css("display", "none");        
    }
}

function selectPaymentType(type) {
    var selected = $(".selected-payment-type").val();
    if (type != selected) {
        $("input[name='payment-type'][value=" + selected + "]").removeAttr("checked");
        $("input[name='payment-type'][value=" + type + "]").attr("checked", true);
        $(".selected-payment-type").val(type);
    }   
}

function onPaymentTypeChanged() {
    $(".selected-payment-type").val($("input[name='payment-type']:checked").val());
    changeDeliveryTypes();
}

function changeDeliveryTypes() {
    var region = $(".selected-region").val();
    var type = $(".selected-delivery-type").val();
    var weight = getBasketWeight();
    var basketPrice = getBasketPrice();
    $.ajax({
        type: 'POST',
        url: changeDeliveryTypesUrl,
        data: { region: region, weight: weight, price: basketPrice, selectedType: type },
        dataType: 'html',
        success: function(response, textStatus, request) {
            $("#delivery-type-prices").html(response);
            onDeliveryTypeChecked();
        },
        error: function(err) {
            alert(err);
        }
    });    
}

function onDeliveryTypeChecked() {
    $(".selected-delivery-type").val($("input[name='delivery-type']:checked").val());
    showDeliveryTypePrice();
    updateOrderTotalPrice();
    updateOrderTotalPriceWithDiscount();
}

function updateLotTotalPrices() {
    $("table.basket-table").find("tbody").find("tr").each(function(i, tr) {
        var price = getNumber($(tr).find("td.price").find("span").html());
        var amount = getNumber($(tr).find("td.amount").find("input").val());
        var sum = price * amount;
        $(tr).find("td.total-price").find("span").html(roundNumber(sum));
    });
}
function updateBasketTotalValues() {
    var rows = $("table.basket-table").find("tbody").find("tr");
    var tr = $("table.basket-table").find("tfoot").find("tr");

    var weigth = 0;
    rows.find('td.weight').each(function(i, td) {
        var tdWeight = getNumber($(td).find("span").html());
        var tdAmount = getNumber($(td).parent().find("td.amount").find("input").val());
        weigth += (tdWeight * tdAmount);
    });
    $(tr).find("td.weight").find("span").html(roundNumber(weigth));

    var amount = 0;
    rows.find('td.amount').each(function(i, td) {
        amount += getNumber($(td).find("input").val());
    });
    $(tr).find("td.amount").find("span").html(amount);

    var totalPrice = 0;
    rows.find('td.total-price').each(function(i, td) {
        totalPrice += getNumber($(td).find("span").html());
    });
    $(tr).find("td.total-price").find("span").html(roundNumber(totalPrice));
}

function showDeliveryTypePrice() {
    var notChecked = $("input[name='delivery-type']:not(:checked)").parent().parent();
    notChecked.find('td.total-price').html('');

    var checked = $("input[name='delivery-type']:checked").parent().parent();
    checked.find('td.total-price').html(checked.find('td.price').html());
}

function updateOrderTotalPrice() {
    var basketPrice = getBasketPrice();
    var deliveryPrice = getDeliveryPrice();
    var totalPrice = basketPrice + deliveryPrice;
    $("div.total-price").find("span").html(roundNumber(totalPrice));
}

function updateOrderTotalPriceWithDiscount() {
    var basketPrice = getBasketPrice();
    var deliveryPrice = getDeliveryPrice();
    var discount = getNumber($("div.discount-content").find(".discount").val());
    var discountValue = basketPrice * discount/100;
    var totalPriceWithDiscount = basketPrice + deliveryPrice - discountValue;
    $("div.total-price-with-discount").find("span.discount").html(roundNumber(discount));
    $("div.total-price-with-discount").find("span.discount-value").html(roundNumber(discountValue));
    $("div.total-price-with-discount").find("span.price-with-discount").html(roundNumber(totalPriceWithDiscount));
}

function getSelectedRegion() {
    return $(".region-select").find("option:selected'").val();
}

function getBasketWeight() {
    return getNumber($("table.basket-table").find("tfoot").find("tr").find("td.weight").find("span").html());
}

function getBasketPrice() {
    return getNumber($("table.basket-table").find("tfoot").find("tr").find("td.total-price").find("span").html());
}

function getDeliveryPrice() {
    return $("input[name='delivery-type']:checked").length > 0
                ? getNumber($("input[name='delivery-type']:checked").parent().parent().find('td.price').find('span').html()) 
                : 0;
}

function getNumber(text) {
    text = text.replace(",", ".");
    var number = parseFloat(text);
    if (number)
        return number;
    return 0;
}

function roundNumber(number) {
    if (number != null) {
        return Math.round(number * Math.pow(10, 2)) / Math.pow(10, 2);
    }
    return 0;
}

function onKeyPressNumbers(e) {
    var key = window.event ? e.keyCode : e.which;
    var keychar = String.fromCharCode(key);
    reg = /\D/;
    return !reg.test(keychar);
}
/* --------------------------------------------------------------------------*/
