
function comprobar_cart() {

    if (cart.configuraciones.length> 0 ) {
        loadDialog('dialog_cart', null)
    }
    else   {
        alert("El carro de compra se encuentra vacío. Debe añadir al menos un producto a su carro de compra.\n"  +
            "Para añadir un producto inicie sesión y guárdelo en su sección 'Mis muebles'") ;
    }
    
}

function load_cart() {

    document.getElementById("body_derecha_cart").style.visibility="visible"

    var url = urlServ + "ConfiguracionEscena"  ;

    new Ajax.Request(url, {
        method: 'post',
        parameters: {
            action: "obtenerCart"
        },
        onSuccess: function(transport) {
            pr_load_cart(transport.responseXML);
        },
        onFailure: function(transport) {
            alert('Error LOADCART');
            alert("\n\n" + transport.responseText);
        }
    });

}

function pr_load_cart(data) {

    unmarshallCart(data) ;

    clearDiv("contenedor_config_cart");

    if (cart.configuraciones.length > 0) {
        for (i=0; i<cart.configuraciones.length ; i++ )
        {
            add_configuracion_cart(cart.configuraciones[i]);
        }
    }
    else {
        hideDialog()  ;
    }
}

function unmarshallCart(data){

    cart.configuraciones = new Array() ;

    var configuraciones = data.getElementsByTagName("configuraciones")[0];
    var numConfiguraciones = configuraciones.childNodes.length ;

	for (i=0; i<numConfiguraciones; i++)
	{
		configuracion = configuraciones.childNodes[i];

        var modelo = configuracion.getElementsByTagName("modelo")[0].firstChild.nodeValue;
        var fabricante = configuracion.getElementsByTagName("fabricante")[0].firstChild.nodeValue;
        var id = configuracion.getElementsByTagName("id")[0].firstChild.nodeValue;
        var cantidad = configuracion.getElementsByTagName("cantidad")[0].firstChild.nodeValue;

        var c = new Configuration();
        c.id = id;
        c.cantidad = cantidad;//ç
        var producto_aux = new Product();
        for (j=0; j<products.productos.length; j++) {
            if ((products.productos[j].nombre == modelo) &&  (products.productos[j].fabricante == fabricante))
            {
                producto_aux = products.productos[j];

                var imagen = configuracion.getElementsByTagName("imagen")[0].firstChild.nodeValue;
                var escena = configuracion.getElementsByTagName("escena")[0].firstChild.nodeValue;

                for (k=0; k<producto_aux.imagenes.length; k++)
                {
                    if (producto_aux.imagenes[k].fichero == imagen && producto_aux.imagenes[k].escena == escena)
                    {
                        producto_aux.imagenSeleccionada = producto_aux.imagenes[k];
                        producto_aux.numImagenSeleccionada = k;
                    }
                }
                break;
            }
        }
        c.producto = producto_aux;

        cart.configuraciones[i] = c;
	}

}

function add_configuracion_cart(configuracion) {

    var div_scroll_config = document.getElementById("div1_cart") ;
    var div_config = document.createElement("div");
    div_config.className = "div_cart_config";

        var div_IMG = document.createElement("div");
        div_IMG.className = "div_cart_config_IMG";
            var imgElement = document.createElement("img");
            imgElement.src = "IMG/ajax-loader_" + DIM_PRODUCT_REV_MISMUEBLES[0] + "x" + DIM_PRODUCT_REV_MISMUEBLES[1] + ".gif";
            imgElement.setAttribute('border', 0);
            div_IMG.appendChild(imgElement);
        div_config.appendChild(div_IMG);

        var div_info = document.createElement("div");
        div_info.className = "div_cart_config_info";
        div_config.appendChild(div_info);

            var div_cart_config_info_producto = document.createElement("div");
            div_cart_config_info_producto.className = "div_cart_config_info_producto";
            div_info.appendChild(div_cart_config_info_producto);

                var div_producto_nombre = document.createElement("div");
                div_producto_nombre.className = "div_cart_producto_nombre";
                newText = document.createTextNode(configuracion.producto.nombre);
                div_producto_nombre.appendChild(newText );
                div_cart_config_info_producto.appendChild(div_producto_nombre);

                var div_producto_cantidad = document.createElement("div");
                div_producto_cantidad.className = "div_cart_producto_cantidad";
                newText =  document.createTextNode("");
                if (configuracion.cantidad > 1)
                    newText = document.createTextNode("( " + configuracion.cantidad + " unidades" + " )");

                div_producto_cantidad.appendChild(newText);
                div_cart_config_info_producto.appendChild(div_producto_cantidad);

        var div_botones = document.createElement("div");
        div_botones.className = "div_cart_config_botones";
        div_config.appendChild(div_botones);

            var div_boton1 = document.createElement("div");
            div_boton1.className = "div_cart_config_botones_boton";
            div_boton1.title = "Configurar el producto";
                var imgElementBoton1 = document.createElement("img");
                imgElementBoton1.src = "IMG/button_config.png";
                imgElementBoton1.setAttribute('border', 0);
                imgElementBoton1.style.cursor = "pointer";
                div_boton1.appendChild(imgElementBoton1);
            div_botones.appendChild(div_boton1);

            /* EVENTOS BOTON1 */
            Event.observe(div_boton1, 'click', function() {
                hideDialog();
                cargar_configuracion(configuracion);
            }, false); 

            var div_boton2 = document.createElement("div");
            div_boton2.className = "div_cart_config_botones_boton";
            div_boton2.title = "Eliminar la configuración del carro de compra"
                var imgElementBoton2 = document.createElement("img");
                imgElementBoton2.src = "IMG/button_eliminar.png";
                imgElementBoton2.setAttribute('border', 0);
                imgElementBoton2.style.cursor = "pointer";
                div_boton2.appendChild(imgElementBoton2);
            div_botones.appendChild(div_boton2);

            /* EVENTOS BOTON2 */
            Event.observe(div_boton2, 'click', function() {
                eliminar_configuracion_cart(configuracion);
            }, false);


    div_scroll_config.appendChild(div_config);

    imgElement.src = urlServ + "RecuperarImagenGenerada"   +
        "?action=configuracion" +
        "&usuario=" + "" +
        "&pwd=" + "" +

        "&producto=" + escape(configuracion.producto.nombre) +
        "&fabricante=" + escape(configuracion.producto.fabricante) +
        "&imagen=" + escape(configuracion.producto.imagenSeleccionada.fichero) +
        "&escena=" + escape(configuracion.producto.imagenSeleccionada.escena)  +
        "&config_id=" + escape(configuracion.id)  +

        "&dimensionesRev=" + DIM_PRODUCT_REV_MISMUEBLES[0] + "," + DIM_PRODUCT_REV_MISMUEBLES[1] +

        "&inputMode=" + inputModeRev +
        "&outputMode=" + outputModeRev  +

        "&id=" + configuracion.id  +

        "&param=" + Math.floor(Math.random()*111)

}



function eliminar_configuracion_cart(configuracion) {
    
    var mensaje = "¿Desea eliminar la configuraci\u00f3n seleccionada?\n" +
                    "Pulse 'Aceptar' para eliminar la configuración seleccionada. \n ";

    if (confirm(mensaje)) {
        var url = urlServ + "ConfiguracionEscena";

        new Ajax.Request(url, {
            method: 'post',
            parameters: {
                action: "eliminarCart",
                modelo: configuracion.producto.nombre, /* encodeURIComponent*/
                escena: configuracion.producto.imagenSeleccionada.escena,
                fabricante: configuracion.producto.fabricante ,
                id: configuracion.id
            },
            onSuccess: function(transport) {
                pr_eliminar_configuracion_cart(transport.responseXML);
            },
            onFailure: function(transport) {
                alert('Error ELIMINAR CONFIGURACION DEL CARRO');
                alert("\n\n" + transport.responseText);
            }
        });
    }
}


function pr_eliminar_configuracion_cart(data) {

    var msg = data.getElementsByTagName("msg")[0].firstChild.nodeValue;

    if (msg != 0)
    {
        alert("Se ha producido un error al intentar eliminar la configuraci\u00f3n. \n" +
                    "Por favor, int\u00e9ntelo de nuevo. Si el problema persiste,\n" +
                    "contacte con su administrador.\n");
    }
    else
    {
        load_cart();
    }
}


function vaciar_cart() {

    var mensaje = "¿Desea vaciar su carro de compra por completo ?\n" ;

    if (confirm(mensaje)) {
        var url = urlServ + "ConfiguracionEscena";

        new Ajax.Request(url, {
            method: 'post',
            parameters: {
                action: "vaciarCart"
            },
            onSuccess: function(transport) {
                pr_vaciar_cart(transport.responseXML);
            },
            onFailure: function(transport) {
                alert('Error VACIAR CART');
                alert("\n\n" + transport.responseText);
            }
        });
    }
}

function pr_vaciar_cart( data) {
    var msg = data.getElementsByTagName("msg")[0].firstChild.nodeValue;

    if (msg != 0)
    {
        alert("Se ha producido un error al intentar vaciar el carro de compra. \n" +
                    "Por favor, int\u00e9ntelo de nuevo. Si el problema persiste,\n" +
                    "contacte con su administrador.\n");
    }
    else
    {
        load_cart();
    }
}

//function cargar_configuracion_cart(configuracion) {
//
//    var url = urlServ + "ConfiguracionEscena";
//
//    new Ajax.Request(url, {
//        method: 'post',
//        parameters: {
//            action: "cargar",
//            modelo: configuracion.producto.nombre, /* encodeURIComponent*/
//            escena: configuracion.producto.imagenSeleccionada.escena ,
//            imagen: configuracion.producto.imagenSeleccionada.fichero,
//            id: configuracion.id,
//            fabricante: configuracion.producto.fabricante
//        },
//        onSuccess: function(transport) {
//            pr_cargar_configuracion_cart(transport.responseXML, configuracion);
//        },
//        onFailure: function(transport) {
//            alert('Error ELIMINAR CONFIGURACION');
//            alert("\n\n" + transport.responseText);
//        }
//    }) ;
//}

//function pr_cargar_configuracion_cart(data, configuracion) {
//
//    var msg = data.getElementsByTagName("msg")[0].firstChild.nodeValue;
//
//    if (msg != 0)
//    {
//        mensaje = "Se ha producido un error al cargar su configuraci\u00f3n.\n" +
//                        "Por favor,inténtelo de nuevo. Si el problema persiste contacte con su administrador.\n";
//        alert(mensaje);
//    }
//
//    else
//    {
//        if (configuracion.producto != null)
//           //loadProducto(configuracion.producto);
//           navigate("loadProducto", configuracion.producto, false);
//    }
//}


function confirmar_cart() {

    var mensaje = "¿Desea formalizar la compra de los productos introducidos ?\n" ;

    if (confirm(mensaje)) {
        pr_confirmar_cart();

//        var url = urlServ + "ConfiguracionEscena";
//
//        new Ajax.Request(url, {
//            method: 'post',
//            parameters: {
//                action: "confirmarCart"
//            },
//            onSuccess: function(transport) {
//                pr_confirmar_cart(transport.responseXML);
//            },
//            onFailure: function(transport) {
//                alert('Error CONFIRMAR CART');
//                alert("\n\n" + transport.responseText);
//            }
//        });
    }

}

function pr_confirmar_cart() {

    var msg = data.getElementsByTagName("msg")[0].firstChild.nodeValue;

//    if (msg != 0)
//    {
//        alert("Se ha producido un error al intentar confirmar la compra seleccionada. \n" +
//                    "Por favor, int\u00e9ntelo de nuevo. Si el problema persiste,\n" +
//                    "contacte con su administrador.\n");
//    }

    alert("Pedido generado correctamente.\nPróximamente recibirá confirmación del fabricante. ");

}
