$(document).ready(function(){
    function getTireShipmentCost(obj,category){
        var amount = parseInt(obj.val() );
        if (isNaN(amount) || amount == 'NaN' || amount < 1 || amount > 20) {
            amount = 4;
        }
        else {
            obj.val(amount);
        }
        tmp = obj.attr('id');
        tmpSplit = tmp.split('_');
        idProduct = tmpSplit[1];
        // uaktualnienie ukrytego inputa z liczbą sztuk
        $(tmp).val(amount);
        // uaktualnienie wartości opisu
        var  data = "productCategory="+category
        data += "&id="+idProduct;
        data += "&amount="+amount;
        $.ajax({
            type: "POST",
            url: "/oblicz-koszty-dostawy.html",
            data: data,
            dataType: 'json',
            success: function(response){
                if( response.shipmentCost != -1 ){
                    $("#spanShipmentCost_"+idProduct).html('Koszt dostawy: ' +response.shipmentCost);
                }
                else{
                    $("#spanShipmentCost_"+idProduct).html('Koszt dostawy ustalany indywidualnie');
                }
            }
        });
    }
    $(".amountAccumulators").change(function(){
        getTireShipmentCost($(this),3);
    });

    $(".amountTires").change(function(){
        getTireShipmentCost($(this),1);
    });
});

function decreaseAmount(id){
    var value = Number($('#' + id).val());
    value = value - 1;
    if (value < 0)
        $('#' + id).val(0);
    else
        $('#' + id).val(value);
    if (isNaN(value) || value == 'NaN' || value < 1 || value > 20) {
        value = 4;
    }
    $('#' + id).val(value);
}

function increaseAmount(id){
    var value = Number($('#' + id).val());
    value = value + 1;
    $('#' + id).val(value);
    if (isNaN(value) || value == 'NaN' || value < 1 || value > 20) {
        value = 4;
    }
    $('#' + id).val(value);
}
