function getCarrito() {
    var carrito = getCookie('carrito');
    if(!carrito) {
        return {'p': [], 'i': 0, 'c': 0};
    } else {
        return carrito.evalJSON();
    }
}

function setCarrito(carrito) {
    setCookie('carrito', Object.toJSON(carrito));
}

function resetCarrito() {
    var carrito = {'p': [], 'i': 0, 'c': 0};
    setCookie('carrito', Object.toJSON(carrito));
}

function setCookie(nombre, valor) {
    document.cookie = nombre + '=' + escape(valor);
    if(getCookie(nombre) != valor) {
        throw {};
    }
    //document.cookie = nombre + '=' + escape(valor) + "; expires=Mon, 31 Dec 2010 23:59:59 UTC;";
}

function getCookie(nombre) {
    var cookie = document.cookie;
    if(cookie.length > 0) {
        var begin = cookie.indexOf(nombre + '=');
        if(begin != -1) {
            var end = cookie.indexOf(';', begin)
            if(end == -1) end = cookie.length;
            return unescape(cookie.substring(begin + nombre.length + 1, end));
        }
    }
    return null;
}

function anadirProductoCarrito(idProducto,num_cartuchos,num_opciones) {
    var precio = $('productoPrecio' + idProducto).value;
    var cantidad = $('productoCantidad' + idProducto) != null ?  parseInt($('productoCantidad' + idProducto).value, 10) : 1;
    var listaCargas = [];
    var listaSabores = [];
    var listaOtros = [];

    for(i=0;i<num_cartuchos;i++){
        listaSabores.push($('productoSabor' + idProducto + '_' + i) != null ? parseInt($('productoSabor' + idProducto + '_' + i).value, 10) : null);
        listaCargas.push( $('productoCarga' + idProducto + '_' + i) != null ? parseInt($('productoCarga' + idProducto + '_' + i).value, 10) : null);
    }
    for(i=0;i<num_opciones;i++){
        listaOtros.push($('productoOpciones' + idProducto + '_' + i) != null ? parseInt($('productoOpciones' + idProducto + '_' + i).value, 10) : null);
        
    }

    var idPC = idProducto + '-' + eval(listaSabores.join("+")) + eval(listaCargas.join("+")) + eval(listaOtros.join("+"));
    //alert(idPC);

    var c = getCarrito();

    var encontrado = false;
    c.p.each(function(p) {
        if(p.i2 == idPC) {
            encontrado = true;
            p.c += cantidad;
        }
    });

   if(!encontrado) {
        c.p.push({
            'i1': idProducto,
            'c': cantidad,
            's': listaSabores,
            'n': listaCargas,
            'p': precio,
            'i2': idPC,
            'o':listaOtros

        });
    }

    recalcularInfoCarrito(c);

    try {
        setCarrito(c);
        mostrarInfoCarrito(c);

        efectoCarrito('imgProd' + idProducto);
    } catch(e) {
        alert('Se ha alcanzado la capacidad máxima del carrito.');
    }
}

function mostrarInfoCarrito(carrito) {
    var c = $('carritoCantidad');
    var i = $('carritoImporte');

    c.update(formatearNumero(carrito.c, 0, SEPARADOR_DECIMALES, SEPARADOR_MILES));
    i.update(formatearImporte(carrito.i,'&euro;', SEPARADOR_DECIMALES, SEPARADOR_MILES, POSICION_MONEDA));
}


var __productosMarcarEliminar = [];
function marcarEliminarProductoCarrito(idPC) {
    __productosMarcarEliminar.push(idPC);
}

function eliminarProductoCarrito(idPC) {
    var c = getCarrito();

    if(c) {
        c.p.each(function(p, i) {
            if(p.i2 == idPC) {
                c.p[i] = null
            }
        });
        c.p = c.p.compact();
    }
    recalcularInfoCarrito(c)
    setCarrito(c);
}

function aplicarCambiosCarrito() {
    __productosMarcarEliminar.each(function(idPC) {
        eliminarProductoCarrito(idPC);
    });
    var c = getCarrito();
    recalcularInfoCarrito(c);
    setCarrito(c);
    
    __productosMarcarEliminar = [];
}

function recalcularInfoCarrito(c) {
    if(!c) { c = getCarrito() }
    if(c) {
        var cantidad = 0;
        var importe = 0;
        c.p.each(function(p, i) {
            cantidad += parseInt(p.c, 10);
            importe += parseInt(p.c, 10) * p.p;
        });
        c.c = cantidad;
        c.i = importe;
    }
}

var __efectoCarrito = null;
function efectoCarrito(imgProducto) {
    imgProducto = $(imgProducto);
    try {

        if(__efectoCarrito) {
            __efectoCarrito.cancel();
            __efectoCarrito = null;
        }

        var m = $('modCarrito');
        var iAux = $('_imgCarritoAux');
        if(!iAux) {
            iAux = new Element('img', {'id': '_imgCarritoAux', 'style': 'display: none; border: 0px solid #A6CE46;'});
            document.body.appendChild(iAux);
            iAux.absolutize();
        }
        iAux.src = imgProducto.src;
        var p = imgProducto.positionedOffset();
        var d = imgProducto.getDimensions();
        iAux.setStyle({
            'top': p.top + 'px',
            'left': p.left + 'px',
            'width': d.width + 'px',
            'height': d.height + 'px'
        });
        iAux.show();

        var p2 = m.positionedOffset();

        __efectoCarrito = new Effect.Parallel([
                new Effect.Move('_imgCarritoAux', { sync: true, x: p2.left, y: p2.top, mode: 'absolute' }),
                new Effect.Opacity('_imgCarritoAux', { sync: true, from: 1, to: 0 })
            ], {
            duration: 1.5,
            afterFinish: function() { iAux.hide(); }
        });
                
    } catch(e) {}
}