﻿function vb() { var C = null; try { C = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e1) { try { C = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e2) { C = null; } } if (!C && typeof XMLHttpRequest != "undefined") { try { C = new XMLHttpRequest(); } catch (e3) { C = null; } } return C; }
function getdate() {
    var date = new Date();
    return escape(date.toString());
}

function read(url) {
    var req = vb();
    if (req) {
        req.open("GET", url, false);
        req.send(null);
        if (req.status == 200) {
            return req.responseText;
        }
        else {
            alert("error: Sorry, operation failed. Please try again later or contact the webmaster");
            return "error";
        }
    }
    else {
        alert("Your browser does not appear to suport JavaScript or it is turned off. Please consult your Browser Documentation and enable JavaScript, or upgrade your browser, then return to the page.");
        return "error";
    }
}

var reqAlimento;
function aread(url, funct) {
    if (reqAlimento) reqAlimento.abort();
    reqAlimento = vb();
    if (reqAlimento) {
        reqAlimento.open("GET", url, true);
        reqAlimento.onreadystatechange = funct;
        reqAlimento.send(null);
    }
    else {
        alert("Your browser does not appear to suport JavaScript or it is turned off. Please consult your Browser Documentation and enable JavaScript, or upgrade your browser, then return to the page.");
    }
}

function areadResponse() {
    try {
        if (reqAlimento.readyState == 4 && reqAlimento.status != 0) {
            if (reqAlimento.status == 200) {
                document.getElementById("Info").innerHTML = reqAlimento.responseText;
            }
            else {
                alert("error: Sorry, operation failed. Please try again later or contact the webmaster");
            }
        }
    }
    catch (e1) { }
}

function initListaAlimentos(IsAuthenticated) {
    alimentos.length = 0;
    var isFavCB = document.getElementById("CBFav");
    if (isFavCB.checked) {
        if (!IsAuthenticated) {
            alert("Para utilizar los filtros de favoritos es necesario estar registrador<br>Para registrarte <a href='" + root + "Access/LogIn.aspx'>pincha aquí</a>");
            return false;
        }
        else {
            try {
                eval(read(carpeta + "LoadFoods.ashx?opt=fav&date=" + getdate()));
                fill();
                return true;
            }
            catch (e1) {
                alert("Oppps!! no hemos podido cargar los alimentos\r\nPor favor vuelve a intentarlo pasado un rato.");
                return false;
            }
        }
    }
    else {
        try {
            eval(read(carpeta + "LoadFoods.ashx?date=" + getdate()));
            fill();
            return true;
        }
        catch (e1) {
            alert("Oppps!! no hemos podido cargar los alimentos\r\nPor favor vuelve a intentarlo pasado un rato.");
            return false;
        }
    }
}
function cargarListaAlimentos(IsAuthenticated) {
    if (!initListaAlimentos(IsAuthenticated)) {
        var o = document.getElementById("CBFav");
        o.checked = !o.checked;
    }
}
function cargarAlimento(idCN) {
    var regex = new RegExp("^([0-9]+)_([0-9]+)$", "g");
    var id = idCN.replace(regex, "$1");
    var catidadNormal = idCN.replace(regex, "$2");

    document.getElementById("AlimentoSeleccionado").value = id;
    document.getElementById("Cantidad").value = catidadNormal;

    aread(carpeta + "LoadFood.ashx?id=" + id + "&date=" + getdate(), areadResponse);
}

function insertaAlimentoDB(id, cant) {
    var regex = new RegExp("[^0-9]", "g");
    if (cant != "" && !regex.test(cant)) {
        var result = read(carpeta + "InsertFood.aspx?id=" + id + "&cantidad=" + cant + "&date=" + getdate());
        if (result != "error") {
            document.getElementById("Dieta").innerHTML = result;
            return true;
        }
    }
    else {
        alert("La cantidad introducida no es correcta");
    }
    return false;
}

function cambiarSeccion(seccion) {
    var result = read(carpeta + "ChangeSection.aspx?sec=" + escape(seccion) + "&date=" + getdate());
    if (result != "error")
        document.getElementById("Dieta").innerHTML = result;
}

function Nuevo() {
    if (confirm("Esto borrara todos los datos\r\n¿Está seguro?")) {
        var result = read(carpeta + "New.aspx?date=" + getdate());
        if (result != "error") {
            document.getElementById("Dieta").innerHTML = result;
        }
    }
}

function AccionEditar(position, cantidad) {
    var cant = promptJS("Pregunta", "¿Cantidad? en gramos", cantidad, "AccionEditar2(" + position + ",{var})");
}
function AccionEditar2(position, cant) {
    var regex = new RegExp("[^0-9]", "g");
    if (cant != "" && !regex.test(cant)) {
        var result = read(carpeta + "Edit.aspx?position=" + position + "&cantidad=" + cant + "&date=" + getdate());
        if (result != "error") {
            document.getElementById("Dieta").innerHTML = result;
            return true;
        }
        return false;
    }
    else {
        alert("La cantidad introducida no es correcta");
        return false;
    }
    return false;
}

function AccionBorrar(position) {
    if (confirm("Borrara el alimento de la tabla\r\n¿Esta seguro?")) {
        var result = read(carpeta + "Remove.aspx?position=" + position + "&date=" + getdate());
        if (result != "error") {
            document.getElementById("Dieta").innerHTML = result;
            return true;
        }
        return false;
    }
}
function AccionArriba(position) {
    var result = read(carpeta + "Order.aspx?direccion=arriba&position=" + position + "&date=" + getdate());
    if (result != "error") {
        document.getElementById("Dieta").innerHTML = result;
        return true;
    }
    return false;
}
function AccionAbajo(position) {
    var result = read(carpeta + "Order.aspx?direccion=abajo&position=" + position + "&date=" + getdate());
    if (result != "error") {
        document.getElementById("Dieta").innerHTML = result;
        return true;
    }
    return false;
}
function AccionAddFav(id, nombre, cantidad) {
    try {
        read(carpeta + "AddFav.ashx?id=" + id + "&nombre=" + escape(nombre) + "&cantidad=" + cantidad + "&date=" + getdate());
        if (document.getElementById("CBFav").checked) initListaAlimentos(true);
        alert("Has agregado '" + nombre + "' a favoritos.");
    }
    catch (E1) {
    }
}
function isMatch(text, filter) {
    if (filter == "") return true;
    var lFilter = filter.split(" ");
    var match = true;
    for (var i = 0; i < lFilter.length && match; i++) {
        var regExp = new RegExp(lFilter[i], "i");
        match = text.match(regExp);
    }
    return match != null;
}

function fill() {
    var filter = document.getElementById("txtFilter").value.toLowerCase();
    if (filter != "") {
        var regExp = new RegExp("[^a-z0-9ñáéíóú_ ]+", "ig");
        filter = filter.replace(regExp, " ");
        filter = filter.replace(/[aá]/gi, "[aá]");
        filter = filter.replace(/[eé]/gi, "[eé]");
        filter = filter.replace(/[ií]/gi, "[ií]");
        filter = filter.replace(/[oó]/gi, "[oó]");
        filter = filter.replace(/[uú]/gi, "[uú]");
        filter = filter.replace(/^ +/, "");
        filter = filter.replace(/ +$/, "");
        filter = filter.replace(/ {2,}/, " ");
    }

    var tipo = document.getElementById(idTipo).value
    var marca = document.getElementById(idMarca).value

    var objSelect = document.getElementById("Alimentos");
    var parent = objSelect.parentNode;
    parent.removeChild(objSelect);
    objSelect = document.createElement("select");
    parent.appendChild(objSelect)
    objSelect.onchange = function() { return cargarAlimento(this.options[this.selectedIndex].value); };
    objSelect.ondblclick = function() { insertaAlimentoDB(document.getElementById('AlimentoSeleccionado').value, document.getElementById('Cantidad').value); };
    objSelect.className = "multiple";
    objSelect.multiple = true;
    objSelect.id = "Alimentos";

    var j = 0;
    for (var i = 0; i < alimentos.length; i++) {
        if (filter == "" || isMatch(alimentos[i][1], filter) && (tipo == 0 || alimentos[i][3] == tipo) && (marca == 0 || alimentos[i][4] == marca)) {
            objSelect.options[j] = new Option(alimentos[i][1] + alimentos[i][5], alimentos[i][0] + "_" + alimentos[i][2]);
            objSelect.options[j].title = alimentos[i][1] + alimentos[i][5];
            j++;
        }
    }
}

window.alert = function(msg) {
    var panel;
    panel = document.getElementById('p_alert');
    if (panel)
        document.body.removeChild(panel);
    panel = document.createElement("div");
    panel.id = "p_alert";
    if (navigator.userAgent.match(/MSIE [123456]/i)) {
        panel.className = "panelAlert";
        panel.style.top = ShowPosyScroll() + 300 + "px";
    }
    else {
        panel.className = "panelAlertFix";
    }
    panel.innerHTML = "<table class=\"tableshadow\" align=\"right\"><tr><td class=\"tl\"></td><td class=\"tc\"></td><td class=\"tr\"></td></tr><tr><td class=\"ml\"></td><td class=\"mc\" style=\"padding-right:12px\">" + msg.replace(/\r\n/, "<br />") + "<button style=\"display:block;margin-top:5px\" onclick=\"document.body.removeChild(document.getElementById('p_alert'))\">Aceptar</button></td><td class=\"mr\"></td></tr><tr><td class=\"bl\"></td><td class=\"bc\"></td><td class=\"br\"></td></tr></table>";
    document.insertBefore(panel, document.body.childNodes[0]);
}

function promptJS(caption, msg, cant, funct) {
    var mPopupMask = document.createElement("div");
    mPopupMask.id = "popupMask";
    document.body.insertBefore(mPopupMask, document.getElementById("container1"));
    var mPopupContainer = document.createElement("div");
    mPopupContainer.id = "popupContainer";
    document.body.insertBefore(mPopupContainer, document.getElementById("container1"));
    mPopupContainer.innerHTML = "<h1>" + caption + "</h1><div>" + msg + "<br /><input type='text' name='promptValue' id='promptValue' value='" + cant + "' /><div><input type='button' onclick='closePrompt(\"" + funct + "\")' value='Aceptar' /> <input type='button' onclick='alertClose();' value='Cancelar' /></div></div>";
}
function closePrompt(funct) {
    funct = funct.replace("{var}", "'" + document.getElementById('promptValue').value + "'");
    alertClose();
    eval(funct);
}

function alertClose() {
    document.body.removeChild(document.getElementById('popupContainer'));
    document.body.removeChild(document.getElementById('popupMask'));
}