/**
 * Funkcja sumująca wartość towaru w koszyku.
 */
function deleteProductFromCart(productId){
    $.ajax({
        url: '/usun-z-koszyka.html',
        type: 'POST',
        data: 'id='+productId,
        dataType: 'json',
        success: function(response){
            if(response.done){
                refreshCart();
                refreshCartTop();
            }
        }
    });
}

function refreshCart(){
    $.ajax({
        url: '/odswiez-koszyk.html',
        type: 'POST',
        dataType: 'html',
        success: function(response){
            $('#cartContainer').empty().append(response);
        }
    });
}

function refreshCartTop(){
    $.ajax({
        url: '/odswiez-koszyk-mini.html',
        type: 'POST',
        dataType: 'html',
        success: function(response){
            $('#cart').empty().append(response);
        }
    });
}

function decreaseAmount(id,recount){
    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);
    if (recount){
        recountCart($('#' + id));
    }
}

function increaseAmount(id,recount){
    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);
    if (recount){
        recountCart($('#' + id));
    }
}

function setProductAmount(productId,amount){
    $.ajax({
        url: '/zmien-ilosc-towaru.html',
        type: 'POST',
        data: 'productId='+productId+'&productAmount='+amount,
        dataType: 'json',
        success: function(response){
            if(response.done){
                refreshCart();
                refreshCartTop();
            }
        }
    });
}

function recountCart(obj){
    amount = obj.val();
    tmp = obj.attr('id').split('_');
    productId = tmp[1];
    setProductAmount(productId, amount);
}

function setCartAttribute(attribute,value){
     $.ajax({
        url: '/ustaw-atrybut.html',
        type: 'POST',
        data: 'attribute='+attribute+'&value='+value,
        dataType: 'json',
        success: function(response){
            if(response.done){
                refreshCart();
                refreshCartTop();
            }
        }
    });
}

