﻿if (!Data) {
    var Data = new function() {
        this.wsPath = null;
        this.idTipo = null;
        this.idMarca = null;
        this.listaFavoritos = null;

        this.CargarAlimento = function(obj, id, cantidadNormal) {
            document.getElementById("AlimentoSeleccionado").value = id;
            document.getElementById("Cantidad").value = cantidadNormal;
            $.ajax({
                url: Data.wsPath + "cargarAlimento.ashx?id=" + id,
                success: function(html) {
                    document.getElementById("Info").innerHTML = html;
                    $("#Alimentos > a.current").each(function(i) { this.className = ""; });
                    obj.className = "current";
                },
                complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
            });
        }
        this.InsertaAlimentoDB = function(id, cant) {
            var regex = new RegExp("[^0-9]", "g");
            if (cant != "" && !regex.test(cant)) {
                $.ajax({
                    url: Data.wsPath + "insertarAlimento.aspx?id=" + id + "&cantidad=" + cant,
                    cache: false,
                    success: function(html) { document.getElementById("Dieta").innerHTML = html; },
                    complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
                });
            }
            else {
                alert("La cantidad introducida no es correcta.");
            }
            return false;
        }
        this.EditarAlimentoDB = function(position, cant) {
            var regex = new RegExp("[^0-9]", "g");
            if (cant != "" && !regex.test(cant)) {
                $.ajax({
                    url: Data.wsPath + "Editar.aspx?position=" + position + "&cantidad=" + cant,
                    cache: false,
                    success: function(html) { document.getElementById("Dieta").innerHTML = html; },
                    complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
                });
            }
            else {
                alert("La cantidad introducida no es correcta.");
                return false;
            }
            return false;
        }
        this.AccionEditar = function(position, cantidad) {
            var cant = promptJS("Pregunta", "¿Cantidad? en gramos", cantidad, "Data.EditarAlimentoDB(" + position + ",{var})");
        }
        this.AccionBorrar = function(position) {
            if (confirm("Borrara el alimento de la tabla\r\n¿Esta seguro?")) {
                $.ajax({
                    url: Data.wsPath + "borrar.aspx?position=" + position,
                    cache: false,
                    success: function(html) { document.getElementById("Dieta").innerHTML = html; },
                    complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
                });
            }
        }
        this.AccionArriba = function(position) {
            $.ajax({
                url: Data.wsPath + "ordenar.aspx?direccion=arriba&position=" + position,
                cache: false,
                success: function(html) { document.getElementById("Dieta").innerHTML = html; },
                complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
            });
        }
        this.AccionAbajo = function(position) {
            $.ajax({
                url: Data.wsPath + "ordenar.aspx?direccion=abajo&position=" + position,
                cache: false,
                success: function(html) { document.getElementById("Dieta").innerHTML = html; },
                complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
            });
        }
        this.CambiarSeccion = function(seccion) {
            $.ajax({
                url: Data.wsPath + "cambiarSeccion.aspx?sec=" + escape(seccion),
                cache: false,
                success: function(html) { document.getElementById("Dieta").innerHTML = html; },
                complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
            });
        }
        function isInFav(id) {
            for (var i = 0; i < Data.listaFavoritos.length; i++) {
                if (Data.listaFavoritos[i].Id == id) {
                    return true;
                }
            }
            return false;
        }
        function isMatch(id, text, idTipo, idMarca, filter, tipoSeleccionado, marcaSeleccionada, checkFav) {
            if (tipoSeleccionado != 0 && idTipo != tipoSeleccionado) return false;
            if (marcaSeleccionada != 0 && idMarca != marcaSeleccionada) return false;
            var isMatch = true;
            if (filter != "") {
                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);
                }
                isMatch = match != null;
            }
            if (isMatch && checkFav) {
                isMatch = isInFav(id);
            }
            return isMatch;
        }
        function getSearchPattern() {
            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,}/, " ");
            }
            return filter;
        }
        this.AccionAddFav = function(id, nombre, cantidad) {
            $.ajax({
                url: Data.wsPath + "AddFav.ashx?id=" + id + "&nombre=" + escape(nombre) + "&cantidad=" + cantidad,
                cache: false,
                success: function(html) { alert("Has agregado '" + nombre + "' a favoritos."); },
                complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
            });
        }
        this.FavChanged = function() {
            var cbFav = document.getElementById("CBFav");
            if (cbFav.checked) {
                $.ajax({
                    url: Data.wsPath + "CargarFavorios.ashx",
                    cache: false,
                    dataType: "json",
                    success: function(obj) {
                        if (obj == null) {
                            alert("Para utilizar los filtros de favoritos es necesario estar registrador<br />Para identificarte o registrarte <a href='" + common.UrlBase + "Registro/registro.aspx'>pincha aquí</a>");
                            cbFav.checked = false;
                        }
                        else {
                            Data.listaFavoritos = obj;
                            Data.Fill();
                        }
                    },
                    complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); cbFav.checked = false; } }
                });
            }
            else {
                Data.Fill();
            }
        }
        this.Fill = function() {
            var filter = getSearchPattern();
            var checkFav = document.getElementById("CBFav").checked;
            var tipo = document.getElementById(Data.idTipo).value
            var marca = document.getElementById(Data.idMarca).value
            var objSelect = $("#Alimentos > a").each(function(i) { this.style.display = isMatch(this.getAttribute("i"), this.innerHTML, this.getAttribute("t"), this.getAttribute("m"), filter, tipo, marca, checkFav) ? "block" : "none" });
        }
        this.Inicializar = function(tipoAlimentoClientId, idMarcaClientId) {
            this.wsPath = common.UrlBase + "webservices/";
            this.idTipo = tipoAlimentoClientId;
            this.idMarca = idMarcaClientId;
            $.ajax({
                url: Data.wsPath + "CargarAlimentos.ashx",
                cache: true,
                success: function(json) {
                    var div = document.getElementById("Alimentos");
                    while (div.childNodes.length > 0)
                        div.removeChild(div.childNodes[0]);
                    for (var i = 0; i < json.length; i++) {
                        var row = document.createElement("A");
                        row.href = "#";
                        row.setAttribute("i", json[i].Id);
                        if (json[i].Marca != null)
                            row.setAttribute("m", json[i].Marca.Id);
                        if (json[i].TipoAlimento != null)
                            row.setAttribute("t", json[i].TipoAlimento.Id);
                        row.innerHTML = json[i].Nombre + (json[i].Marca != null ? " (" + json[i].Marca.Nombre + ")" : "");
                        div.appendChild(row);
                        row.setAttribute("onclick", "Data.CargarAlimento(this, " + json[i].Id + ", " + json[i].CantidadNormal + ");");
                        row.setAttribute("ondblclick", "Data.InsertaAlimentoDB(" + json[i].Id + ", " + json[i].CantidadNormal + ");");
                        row.onselectstart = function() { return false; }
                    }
                    json.length = 0;
                    json = null;
                },
                complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
            });
        }
        this.Nuevo = function() {
            if (confirm("Esto borrara todos los datos\r\n¿Está seguro?")) {
                $.ajax({
                    url: Data.wsPath + "nuevo.aspx",
                    cache: false,
                    success: function(html) { document.getElementById("Dieta").innerHTML = html; },
                    complete: function(xMLHttpRequest, textStatus) { if (textStatus != "success") { alert("opps: la operación ha fallado."); } }
                });
            }
        }

        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"));

            var capaCaption = document.createElement("h1");
            capaCaption.innerHTML = caption;
            var capaMensaje = document.createElement("div");
            var capaMensaje_text = document.createElement("span");
            capaMensaje_text.innerHTML = msg;
            var capaMensaje_saltoLinea = document.createElement("br");
            var capaMensaje_input = document.createElement("input");
            capaMensaje_input.type = "text";
            capaMensaje_input.name = "promptValue";
            capaMensaje_input.id = "promptValue";
            capaMensaje_input.value = cant;
            var capaMensaje_capaAction = document.createElement("div");
            var capaMensaje_capaAction_input = document.createElement("input");
            capaMensaje_capaAction_input.type = "button";
            capaMensaje_capaAction_input.value = "Aceptar";
            capaMensaje_capaAction_input.onclick = function() {
                document.body.removeChild(mPopupContainer);
                document.body.removeChild(mPopupMask);
                eval(funct.replace("{var}", "'" + capaMensaje_input.value + "'"));
            };
            var capaMensaje_capaAction_inputCancel = document.createElement("input");
            capaMensaje_capaAction_inputCancel.type = "button";
            capaMensaje_capaAction_inputCancel.value = "Cancelar";
            capaMensaje_capaAction_inputCancel.onclick = function() {
                document.body.removeChild(mPopupContainer);
                document.body.removeChild(mPopupMask);
            }

            capaMensaje_capaAction.appendChild(capaMensaje_capaAction_input);
            capaMensaje_capaAction.appendChild(capaMensaje_capaAction_inputCancel);

            capaMensaje.appendChild(capaMensaje_text);
            capaMensaje.appendChild(capaMensaje_saltoLinea);
            capaMensaje.appendChild(capaMensaje_input);
            capaMensaje.appendChild(capaMensaje_capaAction);

            mPopupContainer.appendChild(capaCaption);
            mPopupContainer.appendChild(capaMensaje);
        }
    }
}