$(document).ready(function(){
    // first example
        $("#browser").treeview({
            //persist: "location",
            collapsed: false,
            unique: true
        });
    /*
    $("#add").click(function() {
        var branches = $("<li><span class='folder'>New Sublist</span><ul>" +
            "<li><span class='file'>Item1</span></li>" +
            "<li><span class='file'>Item2</span></li></ul></li>").appendTo("#browser");
        $("#browser").treeview({
            add: branches
        });
    });*/
});


function crear_elemento(nombre,atributos)
{
    if ((document.all && navigator.appName.indexOf("Microsoft") >= 0) || nombre == "object") {
        var str = " ";
        if (atributos != "") {
            var arr = atributos.split(";");
            for (var i=0; i < arr.length; i++) {
                if ((pos = arr[i].indexOf('=')) >= 0) {
                    var arr2 = arr[i].split("=");
                    if (arr[i].indexOf("'") > 0) {
                        if (arr2.length == 2) str += arr2[0] + "=" + arr2[1] + " ";
                        else str += arr2[0] + "=" + arr[i].substring(pos + 1, arr[i].length) + " ";
                    } else {
                        if (arr2.length == 2) str += arr2[0] + "=" + "'" + arr2[1] + "' ";
                        else str += arr2[0] + "=" + "'" + arr[i].substring(pos + 1, arr[i].length) + "' ";
                    }
                }//if
            }//for
        }//if
        var elemento = document.createElement("<" + nombre + str + ">");
    } else {
        var elemento = document.createElement(nombre);
        if (atributos != "") {
            var arr = atributos.split(";");
            for (var i=0; i < arr.length; i++) {
                if ((pos = arr[i].indexOf('=')) >= 0) {
                    var arr2 = arr[i].split("=");
                    //var regexp = new RegExp("'","gi");
                    //arr2[1] = arr2[1].replace(regexp,"");
                    if (arr2.length == 2) elemento.setAttribute(arr2[0],arr2[1]);
                    else elemento.setAttribute(arr2[0],arr[i].substring(pos + 1,arr[i].length));
                }
            }//for
        }//if
    }//else
    return elemento;
}//crear_elemento

function isInteger(cantidad)
{
    var lon = cantidad.length;
    for (i=0; i < lon; i++)
    {
        if ((cantidad.charCodeAt(i) < 48) || (cantidad.charCodeAt(i) > 57))
        {
            return false;
        }
    }
    return true;
}//isInteger

function roundNumber(floatn,dec)
{
    if (floatn.toFixed) return new Number(floatn).toFixed(dec);
    floatn_str = (Math.round(floatn * Math.pow(10, dec)) / Math.pow(10, dec)).toString();
    var pos = 0;
    if ((pos = floatn_str.lastIndexOf(".")) > 0 && floatn_str.substring(pos + 1).length > dec)
        return floatn_str.substring(0, pos) + floatn_str.substr(pos, dec + 1);
    else return floatn_str;
}//roundNumber


function actualizar_precio(id, campo, iva)
{
    var valor = campo.value;
    if (valor == "" || !isInteger(valor)) {
        //campo.value = 0;
        //alert("Ha de proporcionar un valor válido para el artículo: " + id);
    }

    var tarifa = parseFloat(document.getElementById("tarifa_" + id).value);
    var precio = 0;

    var capa_caja = document.getElementById("cantidad_caja_" + id);
    var unidades_caja = document.getElementById("unidades_caja_" + id);
    if (capa_caja != null && unidades_caja != null) {
        if (unidades_caja.value == "" || !isInteger(unidades_caja.value)) unidades_caja.value = 1;
        if (capa_caja.value == "" || !isInteger(capa_caja.value)){
            //capa_caja.value = 0;
            precio = 0
        }else precio = (parseInt(unidades_caja.value, 10) * tarifa) * parseInt(capa_caja.value, 10);
    }

    var capa_pack = document.getElementById("cantidad_pack_" + id);
    var unidades_pack = document.getElementById("unidades_pack_" + id);
    if (capa_pack != null) {
        if (unidades_pack.value == "" || !isInteger(unidades_pack.value)) unidades_pack.value = 1;
        if (capa_pack.value == "" || !isInteger(capa_pack.value)){
            //capa_pack.value = 0;
        }else precio += (parseInt(unidades_pack.value, 10) * tarifa) * parseInt(capa_pack.value, 10);
    }

    // alert("actualizar_precio: cantidad*precio: " + precio + " " + preciostr);
    // alert(tarifa + "," + parseInt(unidades_caja.value, 10) + "," + parseInt(capa_caja.value, 10) + "," + parseInt(unidades_pack.value, 10) + "," + parseInt(capa_pack.value, 10) + "," + precio);
    var preciostr = roundNumber(precio, 2);
    document.getElementById("precio_total_" + id).value = preciostr;            
    
    /*if (iva > 0){
        // xxx ev 1-10-08
        var iva = parseFloat(document.getElementById("iva").value);
        var dto = parseFloat(document.getElementById("dto").value);
        var implin = precio - (precio * dto);
        var coniva = implin + (implin * iva);
        
        // alert( "actualizar_precio: " +iva + " " + dto + " " + implin + " " + coniva);
        // xxx fin ev 1-10-08    
        //var coniva=precio + (precio * iva);
        coniva=roundNumber(coniva, 2);
        document.getElementById("span_precio_total_" + id).innerHTML = coniva + " &euro;";
    }else {*/
    // alert("preciostr:" + preciostr);
    document.getElementById("span_precio_total_" + id).innerHTML = preciostr + "     &euro;";
    //actualizar_importe_cesta();
    //}
    //actualizar_importe_cesta();

    // Activamos o desactivamos el checkbox dependiendo de si hay cantidad
    var check_item = document.getElementById("seleccionar_" + id);
    if (check_item != null){
        if ((capa_caja != null && capa_caja.value != "" && isInteger(capa_caja.value)) || (capa_pack != null && capa_pack.value != "" && isInteger(capa_pack.value))) check_item.checked=true;
        else check_item.checked=false;
    }//if
}//actualizar_precio

function actualizar_importe_cesta()
{
    var capa = null;
    if ((capa = document.getElementById("importe_cesta")) != null) {
        var form = document.getElementById("form_cesta");
        var importe = 0;
        for (var i=0; i < form.elements.length; i++) {
            if (form.elements[i].id.indexOf("precio_total_") >= 0 && form.elements[i].value != "") {
                importe += parseFloat(form.elements[i].value);
                // alert("ACTUALIZAR: " + importe);
            }
        }
        var iva = parseFloat(document.getElementById("iva").value);
        var dto = parseFloat(document.getElementById("dto").value);
        // xxx ev
        var implin = importe - (importe * dto);
        var coniva = implin + (implin * iva);
        
        // alert( "actualizar_importe_cesta: " +iva + " " + dto + " " + implin + " " + coniva);
        //importe = importe - implin + coniva;
        // xxx fin ev
        // importe = importe + (importe * iva) - (importe * dto);
        capa.innerHTML = roundNumber(coniva, 2) + " &euro;";
        actualizar_num_articulos_cesta();
    }
}//actualizar_importe_cesta

function actualizar_num_articulos_cesta()
{
    var capa = null;
    if ((capa = document.getElementById("num_articulos_cesta")) != null) {
        var form = document.getElementById("form_cesta");
        var num_articulos_cesta = 0;
        for (var i=0; i < form.elements.length; i++) {
            if (form.elements[i].id.indexOf("precio_total_") >= 0 && form.elements[i].value != "" && parseFloat(form.elements[i].value) > 0) {
                num_articulos_cesta++;
            }
        }
        capa.innerHTML = num_articulos_cesta;
    }
}//actualizar_num_articulos_cesta

function reservar_articulo(id, articulo)
{
    var capa_precio = document.getElementById("precio_total_" + articulo);
    if (capa_precio != null && capa_precio.value != "" && !isNaN(capa_precio.value)) {
        var param = "";
        var capa_caja = document.getElementById("cantidad_caja_" + articulo);
        if (capa_caja != null && isInteger(capa_caja.value)) {
            param += "&cajas=" + capa_caja.value;
        } else capa_caja.value = 0;
        var capa_pack = document.getElementById("cantidad_pack_" + articulo);
        if (capa_pack != null) {
            if (isInteger(capa_pack.value)) {
                param += "&packs=" + capa_pack.value;
            } else capa_pack.value = 0;
        }
        if (rowst > 0) {
            param += "&rowst=" + rowst + "&offset=" + offset + "&pag=" + pag;
        }
        if (ord != "") {
            param += "&ord=" + escape(ord);
        }

        if (campo_buscador != "") {
            param += "&campo_buscador=" + escape(campo_buscador);
        }

        if (busc_avan_precio1_1 != "" && busc_avan_precio1_2 != "") {
            param += "&busc_avan_precio1_1=" + escape(busc_avan_precio1_1) + "&busc_avan_precio1_2=" + escape(busc_avan_precio1_2);
        }

        if (busc_avan_fecha1_1 != "" && busc_avan_fecha1_2 != "") {
            param += "&busc_avan_fecha1_1=" + escape(busc_avan_fecha1_1) + "&busc_avan_fecha1_2=" + escape(busc_avan_fecha1_2);
        }

        if (buscador_catalogo_1 != "" && buscador_catalogo_2 != "") {
            param += "&buscador_catalogo_1=" + buscador_catalogo_1 + "&buscador_catalogo_2=" + buscador_catalogo_2;
        }

        if (oportunidades == "1") {
            param += "&oportunidades=" + oportunidades;
        }

        if (idsugerencia != "") {
            param += "&idsugerencia=" + idsugerencia;
        }

        window.location.href = http_root_path + "includes/procesar_articulos_catalogo.php?id=" + id + "&articulo=" + articulo + "&importe=" + escape(capa_precio.value) + param;
    } else alert("No hay asignado un importe válido para el artículo: " + articulo);
}//reservar_articulo


function reservar_varios_articulo(id,form)
{
    // Se comprueban los articulos que esten chequeados
    var param = "?varios=1&id=" + id;
    var alguno=false;
    for (var i=0;i<form.length;i++){
        if (form.elements[i].type == "checkbox" && form.elements[i].checked){
            var id_producto=form.elements[i].name.substring(12,form.elements[i].name.length);
            var capa_precio = document.getElementById("precio_total_" + id_producto);
            if (capa_precio != null && capa_precio.value != "" && capa_precio.value != "0" && !isNaN(capa_precio.value)) {
                alguno=true;
                // Importe
                // alert("catalogo.js reservar_varios_articulo: " +capa_precio.value);
                param += "&importe_" + id_producto + "=" + capa_precio.value;
                // Cantidad Cajas
                var capa_caja = document.getElementById("cantidad_caja_" + id_producto);
                if (capa_caja != null){
                    if (isInteger(capa_caja.value)) param += "&cajas_" + id_producto + "=" + capa_caja.value;
                    else capa_caja.value = 0;
                }//if
                // Cantidad Packs
                var capa_pack = document.getElementById("cantidad_pack_" + id_producto);
                // alert('packs: ' + capa_pack.value);
                if (capa_pack != null){
                    if (isInteger(capa_pack.value)) param += "&packs_" + id_producto + "=" + capa_pack.value;
                    else capa_pack.value = 0;
                }//if

            }//if
        }//if
    }//for
    if (alguno){
        if (rowst > 1) {
            param += "&rowst=" + rowst + "&offset=" + offset + "&pag=" + pag;
        }
        if (ord != "") {
            param += "&ord=" + escape(ord);
        }

        if (campo_buscador != "") {
            param += "&campo_buscador=" + escape(campo_buscador);
        }

        if (busc_avan_precio1_1 != "" && busc_avan_precio1_2 != "") {
            param += "&busc_avan_precio1_1=" + escape(busc_avan_precio1_1) + "&busc_avan_precio1_2=" + escape(busc_avan_precio1_2);
        }

        if (busc_avan_fecha1_1 != "" && busc_avan_fecha1_2 != "") {
            param += "&busc_avan_fecha1_1=" + escape(busc_avan_fecha1_1) + "&busc_avan_fecha1_2=" + escape(busc_avan_fecha1_2);
        }

        if (buscador_catalogo_1 != "" && buscador_catalogo_2 != "") {
            param += "&buscador_catalogo_1=" + buscador_catalogo_1 + "&buscador_catalogo_2=" + buscador_catalogo_2;
        }

        if (oportunidades == "1") {
            param += "&oportunidades=" + oportunidades;
        }

        if (idsugerencia != "") {
            param += "&idsugerencia=" + idsugerencia;
        }
		
		if (novedades != "") {
            param += "&novedades=1";
        }

        //alert(param);

		window.location.href = http_root_path + "includes/procesar_articulos_catalogo.php" + param;
    }else alert(noseleccionados);
}//reservar_varios_articulo


function validar_form_buscador_catalogo(form)
{
    var valor1 = form.buscador_catalogo_1.value;
    var valor2 = form.buscador_catalogo_2.value
    valor1 = valor1.replace(new RegExp("( |€)","g"), "");
    valor2 = valor2.replace(new RegExp("( |€)","g"), "");
    if (!isNaN(valor1) && !isNaN(valor2) && valor1!="" && valor2!="") {
        if (valor1.length < 11 && valor2.length < 11) {
            if (parseFloat(valor1) >= 0 && parseFloat(valor2) >= 0) {
                if (parseFloat(valor1) <= parseFloat(valor2)) {
                    form.buscador_catalogo_1.value = valor1;
                    form.buscador_catalogo_2.value = valor2;
                    return true;
                } else men = "El valor del campo \"hasta\" no puede ser menor que el valor del campo \"desde\".";
            } else men = "Las tarifas no pueden ser negativas.";
        } else men = "El valor de las tarifas ha excedido los 10 dígitos.";
    } else men = "Los valores suministradors no son correctos.";
    alert(men);
    return false;
}//validar_form_buscador_catalogo


function get_request()
{
    var req = null;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        if (req.overrideMimeType) {
            req.overrideMimeType('text/xml');
        }
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");
        } catch(e){
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch(e) {}
        }
    }//if
    return req;
}//get_request

function comprobar_tiene_hijos(id)
{
    var capa;
    if ((capa = document.getElementById("menu_nodo_" + id)) != null && capa.hasChildNodes()) {
        var nodo = capa.firstChild;
        while (nodo != null) {
            if (nodo.nodeName.toLowerCase() == "ul") {
                capa.className = "closed";
                capa.removeChild(nodo);
                return true;
            }
            nodo = nodo.nextSibling;
        }
    }
    return false;
}//comprobar_tiene_hijos

function ver_rama_menu(id){
    // Cambiamos el + por -
    /*
    var ico=document.getElementById("ico_" + id);
    if (ico != null){
        if (ico.src.indexOf("plus.gif")!=-1){
            ico.src=http_root_path + 'img/minus.gif';
        }else{
            ico.src=http_root_path + 'img/plus.gif';
        }//else
    }//if
    */
    if (!comprobar_tiene_hijos(id)) {
        var req = null;

        req = get_request();

        if (!req) {
            alert("No se ha podido iniciar la petición. Disculpa las molestias. 1");
            return false;
        }
        req.onreadystatechange = function() {
            recoger_ok_ver_rama_menu(req);
        };
        req.open('POST', http_root_path + 'includes/ver_rama_menu.php', true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        var param = "id=" + id;
        req.send(param);
    }


}//ver_rama_menu

function ver_rama_menu2(id,nivel){
    var req = null;

    req = get_request();

    if (!req) {
        alert("No se ha podido iniciar la petición. Disculpa las molestias. 1");
        return false;
    }
    req.onreadystatechange = function() {
        recoger_ok_ver_rama_menu2(req);
    };
    req.open('POST', http_root_path + 'includes/ver_rama_menu2.php', true);
    req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var param = "id=" + id + "&nivel=" + nivel;
    req.send(param);
}//ver_rama_menu2

function recoger_ok_ver_rama_menu(req)
{
    var men = "";
    try {
        if (req.readyState == 4) {
            if (req.status == 200) {
                var xmlDoc = req.responseXML.documentElement;
                var nodoError = xmlDoc.getElementsByTagName('Error')[0];
                if (nodoError && nodoError.hasChildNodes()) {
                    var numeroError = nodoError.firstChild.nodeValue;
                    switch (numeroError) {
                        case "1":
                            alert("No hay parámetros.");
                        break;
                        case "2":
                            alert("No existe la rama.");
                        break;
                    }
                } else {
                    var nodoRama = xmlDoc.getElementsByTagName('Rama')[0];
                    if (nodoRama != null)  {
                        var id = nodoRama.attributes.getNamedItem("id").nodeValue;
                        var capa = document.getElementById("menu_nodo_" + id);
                        if (capa != null) {
                            var rama = nodoRama.firstChild;
                            // Agregamos nodos
                            if (rama != null) agregar_nodos(capa, rama);
                        }
                    }
                }
            } else {
                alert("No existe la rama del menú.");
            }
        }
    } catch (e) {
        alert("No se pudo recoger la rama del menú." + e);
    }
}//recoger_ok_ver_rama_menu

function recoger_ok_ver_rama_menu2(req)
{
    var men = "";
    try {
        if (req.readyState == 4) {
            if (req.status == 200) {
                var xmlDoc = req.responseXML.documentElement;
                var nodoError = xmlDoc.getElementsByTagName('Error')[0];
                if (nodoError && nodoError.hasChildNodes()) {
                    var numeroError = nodoError.firstChild.nodeValue;
                    switch (numeroError) {
                        case "1":
                            alert("No hay parámetros.");
                        break;
                        case "2":
                            alert("No existe la rama.");
                        break;
                    }
                } else {
                    var nodoRama = xmlDoc.getElementsByTagName('Rama')[0];
                    if (nodoRama != null)  {
                        var id = nodoRama.attributes.getNamedItem("id").nodeValue;
                        var nivel = nodoRama.attributes.getNamedItem("nivel").nodeValue;
                        if (tree.hasChildren(id)==0){ // Se construyen una sola vez los hijos
                            var xRows = xmlDoc.getElementsByTagName('nodo');
                            if (nivel == 2) nivel3=new Array();
                            for (i=0; i < xRows.length; i++) {
                                var theId = xRows[i].childNodes[0].firstChild.nodeValue;
                                var theTitle = xRows[i].childNodes[1].firstChild.nodeValue;
                                tree.insertNewChild(id,theId,theTitle,0,'folderClosed.gif');
                                if (nivel == 2) nivel3.push(theId);
                            }//for
                        }//if
                        if (nivel == 3){
                           for (var i=0;i<nivel3.length;i++){
                             tree.closeAllItems(nivel3[i]);
                          }//for
                        }
                        tree.openItem(id);
                    }
                }
            } else {
                alert("No existe la rama del menú.");
            }
        }
    } catch (e) {
        alert("No se pudo recoger la rama del menú." + e);
    }
}//recoger_ok_ver_rama_menu


function agregar_nodos(padre, nodo)
{
    if (padre != null && nodo != null) {
        var nodoAux = nodo;
        var nodoHtml = null;
        var strAtributos = "";
        while (nodoAux != null) {
            switch (nodoAux.nodeType) {
                case 1:

                    if (nodoAux.attributes.length > 0) {
                        for (var x = 0; x < nodoAux.attributes.length; x++ ) {
                            strAtributos += nodoAux.attributes[x].nodeName.toLowerCase() + "=" + nodoAux.attributes[x].nodeValue + ";";
                        }
                    }
                    nodoHtml = crear_elemento(nodoAux.nodeName.toLowerCase(), (strAtributos.length > 0)?strAtributos.substring(0, strAtributos.length - 1):strAtributos);
                    padre.appendChild(nodoHtml);
                break;
                case 3:
                    //padre.appendChild(document.createTextNode(Utf8.decode(nodoAux.nodeValue)));
                    padre.appendChild(document.createTextNode(nodoAux.nodeValue));
                break;
            }
            if (nodoAux.hasChildNodes()) {
                agregar_nodos(nodoHtml, nodoAux.firstChild);
            }
            nodoAux = nodoAux.nextSibling;
            strAtributos = "";
        }
    }
}//agregar_nodos

function comprobar_reservar(destino){    
    // Se comprueban si hay artículos checkeados
    var hay_chequeados=false;
    for (var i=0;i<document.form_cesta.length;i++){
        if (document.form_cesta.elements[i].type == "checkbox" && document.form_cesta.elements[i].checked){            
            hay_chequeados=true;
            break;
        }//if
    }//for
    if (hay_chequeados){
        if (confirm(haychequeados)) {
           window.location.href = destino;
        }//if
    }else window.location.href = destino;
}//comprobar_reservar