
/**
 * Usata nella lista prodotti, dove presente il campo quantita.
 * richiama a sua volta addProductBase
 */
function addProduct(idProdotto){

    var qta = $('qta_' + idProdotto).value;
    if(qta.value == "")
        qta = 1;

    addProductBase(idProdotto, qta);
}

/**
 * funzione base per aggiungere un prodotto al carrello con Ajax
 */
function addProductBase(idProdotto, qta){

    //controllo che qta sia un numero intero
    if(!IsNumeric(qta)){
        alert("Valore non valido nel campo quantita\'");
    }else{

        var url = base_url + 'carrello/add_product_js/'+idProdotto+'/'+qta;

        var params = {
            method: 'get',
            onSuccess: function(transport) {
                //var notice = $('notice');
                if (transport.responseText == "1"){
                    if(qta > 1)
                        alert(qta + " prodotti aggiunti con successo al carrello!");
                    else
                        alert("Prodotto aggiunto con successo al carrello!");
                    //notice.update('Yeah! You are in the Top 10!').setStyle({ background: '#dfd' });

                    //aggiorno il valore del campo TOT prodotti in carrello nel menu TOP
                    updateStringaTotCart(qta);
                }
                else{
                    alert("Attenzione! Problemi in aggiunta del prodotto al carrello.\n\n Riprova per favore");
                //notice.update('Damn! You are beyond #10...').setStyle({ background: '#fdd' });
                }

            }
        };

        new Ajax.Request(url, params);

    }
}

function updateStringaTotCart(qta){

    
    var totale_curr = 0;
    //forzo la conversione a intero della stringa, in radice 10 (decimale)
    qta = parseInt(qta, 10);
    var str_messaggio_cart = "";

    var totale_prec = $('tot_prodotti_cart').value;
    totale_prec = parseInt(totale_prec, 10);
    
    totale_curr = totale_prec + qta;

    if(totale_curr == 0) str_messaggio_cart = "il carrello è vuoto";
    if(totale_curr == 1) str_messaggio_cart = "1 prodotto";
    if(totale_curr > 1) str_messaggio_cart = totale_curr+" prodotti";

    $('tot_prodotti_cart').value = totale_curr;
    $('tot_prodotti_cart_str').innerHTML = str_messaggio_cart;



}


/**
 * funzione per verificare se una stringa è un numero
 */
function IsNumeric(sText){
    var ValidChars = "0123456789";
    var IsNumber=true;
    var Char;


    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;

}



