var ArticList = {
    self: false,
    idTlpArticList: "#tpl_artic_list",
    idTplAlertInfo: "#tpl_alert_info",
    idTplAlertWarning: "#tpl_alert_warning",
    idTplAlertDanger: "#tpl_alert_danger",
    idTplfilter: "#tpl_filter",
    idTplFavoriteSearch: "#tpl_favorite_search",
    idTplArticListNoNesult: "#tpl_artic_list_no_result",
    searchParams: {
        "diapubhasta": "",
        "autoinc": "",
        "alta": "",
        "diapub": "",
        "autor": "",
        "diaexp": "",
        "tipart": "",
        "seccion": "",
        "subtema": "",
        "multitag_s": "",
        "multitag_t": "",
        "multitag_st": "",
        "diahasta": "",
        "dia": "",
        "ts": "",
        "baja": "",
        "titu": "",
        "tema": "",
        "_orden_lista": "C",
        "_filas_x_pag": "25",
        "diaexphasta": "",
    },
    artics: {},
    rec_ini: 0,
    prontus_id: null,
    taxonomia: null,
    ui: {
        selectors: {
            panelRecentArtics: '.admin-search .panel-recent-artics',
            articList: '#artic-list',
            // Paginacion articulos recientes
            articListFirst: '#artic_list_first',
            articListLast: '#artic_list_last',
            articListNext: '#artic_list_next',
            articListPrev: '#artic_list_prev',
            // Informativo
            lastMod: '#lastmod'
        }
    },
    init: function () {
        self = this;
        self.prontus_id = $("body").attr("data-prontus-id");
        self.list.setupOrderBy();
        self.list.loadArtics(0, {'_orden_lista': $('#articles-order-by').val()});
        self.search.init();
        self.methods.initDatePicker();
        self.list.initBorrarMasivo();
        $('#artic-list').on('blur', ' .quick-edit_titular', function(_event) {
            var $form = $('#artic-list .quick-edit_titular').parent().parent().parent().parent();
            var $item = $form.parent().parent();
            self.list.checkValidTitle($item, $form, 0);
        });
        // buscamos las taxonomías para filtros.
        $.ajax({
            type: "GET",
            dataType: 'json',
            url: '/' + Admin.prontus_id + '/cpan/procs/data4fids/taxs.json',
            cache: false,
            success: function (data, _textStatus, _jqXHR) {
                ArticList.taxonomia = data;
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                SubmitForm.handleError(dataURL, XMLHttpRequest, textStatus, errorThrown);
            }
        });
    },
    list: {
        loadArtics: function (rec_ini, extraOptions) {
            $('#artic-list').empty();
            $("form[name='artic-list-form'] .loading").show();
            var options = {
                _prontus_id: self.prontus_id,
                _rec_ini: rec_ini,
            };

            self.rec_ini = rec_ini;

            $.extend(options, self.searchParams);
            $.extend(options, extraOptions);

            $.ajax({
                url: "/{0}/prontus_port_art_list.cgi".format(Admin.dir_cgi_cpn),
                method: "POST",
                dataType: "json",
                data: options,
                success: function (response) {
                    // Actualiza los parametros de busqueda.
                    self.searchParams = response.search_params;
                    self.artics = response.list;
                    self.list.buildList(response);
                    self.search.buildPagination(response.pagination, rec_ini);
                    self.methods.initClipboard();

                }
            });
        },
        // configura el selector de ordenamiento de artículos.
        setupOrderBy: function() {
            var order_by = self.helper.getValueLS('_art_orden_lista');
            if (order_by) {
                $("#articles-order-by option").each(function(_e) {
                    if($(this).val() == order_by) {
                        $(this).prop('selected', 'selected');
                    }
                });
            }
        },
        initBorrarMasivo: function () {
            $("button[name='borrar-seleccion']").off("click").on("click", function (e) {
                e.preventDefault();

                if ($("input[name^='borrar_']:checked").length === 0) return false;
                //
                showModalConfirm({
                    msg: "Se eliminarán los elementos seleccionados. ¿Estás seguro?",
                    type: 'blue',
                    icon: "glyphicon glyphicon-question-sign",
                    okTitle: 'Eliminar',
                    btnClassOk: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextred nextred',
                    cbBtnOK: function () {
                        self.list.borrarSeleccion();
                    },
                    cbBtnCancel: function () {

                    }
                });
            });
        },
        borrarSeleccion: function () {
            var data = $("form[name='artic-list-form']").serialize();

            $("input[name^='borrar_']:checked").each(function () {
                var $item = $(this).closest(".list-group-item");
                $item.find(".group-btns").hide();
                $item.find(".row-loading").show();
            });

            $.ajax({
                url: "/{0}/prontus_art_borrar.cgi".format(Admin.dir_cgi_cpn),
                type: 'POST',
                dataType: 'json',
                data: data,
                success: function (response) {
                    var x;

                    if (response.status == 1) {
                        var strerr = "";
                        if (response.publicados.length) {
                            strerr += "Los siguientes artículos no se pueden borrar porque están publicados en una o más portadas:<br>";

                            for (x = 0; x < response.publicados.length; x++) {
                                strerr += "- " + response.publicados[x] +  "<br>";
                            }
                        }

                        if (response.noexisten.length) {
                            strerr += "<br><br>Los siguientes artículos no existen:<br>";

                            for (x = 0; x < response.noexisten.length; x++) {
                                strerr += "- " + response.noexisten[x] + "<br>";
                            }
                        }

                        var msg = "Se eliminaron " + Object.keys(response.eliminados).length + " artículos";
                        var type = "green";

                        if (strerr) {
                            msg += ", con observaciones:<br>" + strerr;
                            type = "orange";
                        } else {
                            msg += ".";
                        }

                        showModalAlert({
                            title: "Eliminación de artículos",
                            msg: msg,
                            type: type,
                            cbBtnOK: function () {
                                $("input[name^='borrar_']:checked").each(function () {
                                    var $item = $(this).closest(".list-group-item");
                                    var ts = $(this).val();

                                    if (response.eliminados[ts]) {
                                        $item.fadeOut('fast');
                                        $item.remove();
                                    } else {
                                        // No fue eliminado.
                                        $item.removeClass("list-group-item-danger");
                                        $item.find(".group-btns").show();
                                        $item.find(".row-loading").hide();
                                        $(this).trigger("click");
                                    }
                                });
                            }
                        });
                    } else {
                        showModalAlert({
                            type: "red",
                            title: "Se ha producido un error",
                            icon: "glyphicon glyphicon-exclamation-sign",
                            msg: response.msg,
                            cbBtnOK: function () {
                                $("input[name^='borrar_']:checked").each(function () {
                                    var $item = $(this).closest(".list-group-item");
                                    $item.removeClass("list-group-item-danger");
                                    $item.find(".group-btns").show();
                                    $item.find(".row-loading").hide();
                                });
                            }
                        });
                    }
                },
                error: function (_XMLHttpRequest, _textStatus, errorThrown) {
                    showModalAlert({
                        type: "red",
                        title: "Se ha producido un error",
                        icon: "glyphicon glyphicon-exclamation-sign",
                        msg: errorThrown,
                        cbBtnOK: function () {
                            $("input[name^='borrar_']:checked").each(function () {
                                var $item = $(this).closest(".list-group-item");
                                $item.removeClass("list-group-item-danger");
                                $item.find(".group-btns").show();
                                $item.find(".row-loading").hide();
                            });
                        }
                    });
                }
            });
        },
        buildList: function (data, only_return) {
            var html = $(self.idTlpArticList).html();
            var $output = $();

            if (data.list.length > 0) {
                $.each(data.list, function (_i, v) {
                    var clone = html;
                    var aux = v.titular.replace(/%/g, '&#37;');
                    clone = clone.replace(/%%titulo%%/g, aux);
                    clone = clone.replace(/%%custom_slug%%/g, v.custom_slug);
                    clone = clone.replace(/%%friendly_urls_version%%/g, v.friendly_urls_version);
                    clone = clone.replace(/%%fechapub%%/g, v.fechapub);
                    clone = clone.replace(/%%fechaexp%%/g, v.fechaexp);
                    clone = clone.replace(/%%fid%%/g, v.fid);
                    clone = clone.replace(/%%edit_url%%/g, v.edit_url);
                    clone = clone.replace(/%%ts%%/g, v.ts);
                    clone = clone.replace(/%%id%%/g, v.id);
                    clone = clone.replace(/%%autor%%/g, v.autor);

                    if (!v.nom_seccion) {
                        clone = clone.replace(/%%taxonomia%%/g, "-");
                    } else {
                        clone = clone.replace(/%%taxonomia%%/g, v.nom_seccion);
                    }

                    if (!v.total_size) {
                        clone = clone.replace(/%%total_size%%/g, "0 KiB");
                    } else {
                        clone = clone.replace(/%%total_size%%/g, v.total_size);
                    }

                    if (!v.disk_size) {
                        clone = clone.replace(/%%disk_size%%/g, "0 KiB");
                    } else {
                        clone = clone.replace(/%%disk_size%%/g, v.disk_size);
                    }

                    if (v.s3_size == '0 B') {
                        clone = clone.replace(/%%s3_size%%/g, "");
                    } else {
                        clone = clone.replace(/%%s3_size%%/g, ' | ' + v.s3_size);
                    }

                    if (v.corrupto == 1) {
                        clone = clone.replace(/%%corrupto%%/g, "list-group-item-danger");
                        clone = clone.replace(/%%corrupto_msg%%/g, v.corrupto_msg);
                    }

                    if (v.ult_modif) {
                        var fec = "{0}/{1}/{2} {3}:{4}".format(v.ult_modif.substr(6, 2), v.ult_modif.substr(4, 2), v.ult_modif.substr(0, 4), v.ult_modif.substr(8, 2), v.ult_modif.substr(10, 2));
                        clone = clone.replace(/%%ult_modif%%/g, fec);
                    } else {
                        clone = clone.replace(/%%ult_modif%%/g, 'No disponible');
                    }

                    if (v.editable === 0) {
                        clone = clone.replace(/%%editable%%/g, "noedit list-group-item-warning");
                        clone = clone.replace(/%%handler%%/g, "fake-handler");
                    } else {
                        clone = clone.replace(/%%editable%%/g, "");
                        clone = clone.replace(/%%handler%%/g, "handler");
                    }

                    if (v.tiene_vista != 1) {
                        clone = clone.replace(/<!--LINK-->.*?<!--\/LINK-->/g, '');
                        clone = clone.replace(/<!--NOLINK-->/g, '');
                        clone = clone.replace(/<!--\/NOLINK-->/g, '');
                    }

                    if (v.st_pub == 1) {
                        clone = clone.replace(/%%alta%%/g, "checked");
                        clone = clone.replace(/%%class_estado%%/g, "ok");
                        clone = clone.replace(/%%class_estado_glyph%%/g, "check");
                        clone = clone.replace(/%%title_estado%%/g, "El artículo está publicado");
                        clone = clone.replace(/%%art_url%%/g, v.art_url);
                        clone = clone.replace(/<!--NOLINK-->.*?<!--\/NOLINK-->/g, '');
                        clone = clone.replace(/<!--LINK-->/g, '');
                        clone = clone.replace(/<!--\/LINK-->/g, '');
                    } else {
                        clone = clone.replace(/%%alta%%/g, "");
                        clone = clone.replace(/%%class_estado%%/g, "nok");
                        clone = clone.replace(/%%class_estado_glyph%%/g, "check");
                        clone = clone.replace(/%%title_estado%%/g, "El artículo no está publicado");
                        clone = clone.replace(/<!--LINK-->.*?<!--\/LINK-->/g, '');
                        clone = clone.replace(/<!--NOLINK-->/g, '');
                        clone = clone.replace(/<!--\/NOLINK-->/g, '');
                    }

                    if (data.open_newtab == 'SI') {
                        clone = clone.replace(/%%open_newtab%%/g, 'open_newtab');
                    } else {
                        clone = clone.replace(/%%open_newtab%%/g, '');
                    }

                    if (v.tiene_fotos == 1) {
                        clone = clone.replace(/%%tiene_fotos%%/g, "");
                        clone = clone.replace(/%%no_tiene_fotos%%/g, "hidden");
                    } else {
                        clone = clone.replace(/%%tiene_fotos%%/g, "hidden");
                        clone = clone.replace(/%%no_tiene_fotos%%/g, "");
                    }

                    if (typeof v.portadas != 'undefined' && Object.keys(v.portadas).length >= 1) {
                        var portadas = "";

                        $.each(v.portadas, function (edic, ports) {
                            portadas += "Edición: [{0}] - Portadas: [{1}], ".format(edic, Object.keys(ports).join(','));
                        });

                        portadas = portadas.substring(0, portadas.length-2);

                        clone = clone.replace(/%%tiene_portadas%%/g, "in-ports");
                        clone = clone.replace(/%%no_tiene_portadas%%/g, "hidden");
                        clone = clone.replace(/%%en_portadas%%/g, portadas);
                    } else {
                        clone = clone.replace(/%%tiene_portadas%%/g, "hidden");
                        clone = clone.replace(/%%no_tiene_portadas%%/g, "");
                        clone = clone.replace(/%%en_portadas%%/g, "");
                    }

                    if (v.fechaexp === "") {
                        clone = clone.replace(/%%hidden_fechaexp%%/, "hidden");
                    } else {
                        clone = clone.replace(/%%hidden_fechaexp%%/, "");
                    }

                    clone = clone.replace(/%%.*?%%/g, "");

                    let $clone = $(clone);

                    if (v.corrupto === 0) {
                        $clone.find(".art-corrupto").remove();
                    } else {
                        $clone.find(".art-corrupto").removeClass('hide-element');
                        $clone.find(".datos").remove();

                        if (v.corrupto_num === 0 || v.corrupto_num == 3) {
                            $clone.find(".art-corrupto .btn-edit-artic").remove();
                            $clone.find(".art-corrupto .btn-repair-artic").remove();
                        }

                        if (v.corrupto_num == 2) {
                            $clone.find(".art-corrupto .btn-edit-artic").remove();
                        }

                        if (v.corrupto_num == 4) {
                            $clone.find(".art-corrupto .btn-repair-artic").remove();
                        }
                    }

                    $output = $output.add($clone);
                });
            } else {
                html = $("#tpl_artic_list_no_result").html();
                $output = $output.add(html);
            }

            if (typeof only_return != 'undefined' && only_return) {
                return $output;
            }

            $("form[name='artic-list-form'] .loading").hide();
            $('#artic-list').hide().html($output).fadeIn('fast');

            self.list.bindListEvents();

            $('.open_newtab').off('click').on('click', function(e) {
                e.preventDefault();
                var href = $(this).attr("href");
                window.open(href);

            });
        },
        bindListEvents: function () {
            $("input[name^='borrar_']").off("click").on("click", function (_e) {
                var $checkbox = $(this);
                if ($("input[name^='borrar_']:checked").length > 10) {
                    showModalAlert({
                        title: "Información",
                        msg: "Solo puedes eliminar simultáneamente 10 artículos.",
                        type: "blue",
                        cbBtnOK: function () {
                            $checkbox.closest(".list-group-item").removeClass("list-group-item-danger");
                            $checkbox.trigger("click");
                        }
                    });
                }
            });

            $(".btn-remove-artic").off("click").on("click", function (e) {
                e.preventDefault();

                var $item = $(this).closest(".list-group-item");
                var ts = $item.attr("data-ts");

                $item.find(".group-btns").hide();
                $item.find(".row-loading").show();

                showModalConfirm({
                    msg: "El artículo será eliminado. ¿Estás seguro?",
                    type: 'blue',
                    icon: "glyphicon glyphicon-question-sign",
                    btnClassOk: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextred nextred',
                    cbBtnOK: function () {
                        Admin.borrarArticulo(ts, $item);
                    },
                    cbBtnCancel: function () {
                        $item.find(".group-btns").show();
                        $item.find(".row-loading").hide();
                    }
                });
            });

            $(".btn-repair-artic").off("click").on("click", function (e) {
                e.preventDefault();

                var $item = $(this).closest(".list-group-item");
                var ts = $item.attr("data-ts");

                showModalConfirm({
                    msg: "El campo <strong>_art_autoinc</strong> del XML se encuentra vacío. Se le asignará automáticamente el registrado en la tabla índice, ya que este es necesario para el funcionamiento normal del artículo.",
                    title: "Reparar XML del artículo {0}".format(ts),
                    type: 'red',
                    icon: "glyphicon glyphicon-question-sign",
                    cbBtnOK: function () {
                        $.ajax({
                            url: "/{0}/prontus_art_repair.cgi".format(Admin.dir_cgi_cpn),
                            type: 'POST',
                            dataType: 'json',
                            data: {_prontus_id: Admin.prontus_id, _ts: ts},
                            success: function (response) {
                                if (response.status === 1) {
                                    window.location.href = response.href;
                                } else {
                                    showModalAlert({
                                        title: "Mensaje del servidor",
                                        msg: response.msg,
                                        type: "red",
                                        icon: "glyphicon glyphicon-exclamation-sign",
                                        cbBtnOK: function () {
                                        }
                                    });
                                }
                            },
                            error: function (_XMLHttpRequest, _textStatus, errorThrown) {
                                showModalAlert({
                                    title: "Ha ocurrido un error",
                                    msg: "El artículo no se pudo eliminar.<br><br>Mensaje del servidor: {0}".format(errorThrown),
                                    type: "red",
                                    icon: "glyphicon glyphicon-exclamation-sign",
                                    cbBtnOK: function () {
                                    }
                                });
                            }
                        });
                    },
                    cbBtnCancel: function () {
                    }
                });
            });

            $('.btn-quick-edit').off('click').on('click', function (e) {
                e.preventDefault();

                var isSaveBtn = false;
                var $item = $(this).parent().parent().parent().parent().parent().parent();
                var ts = $item.attr("data-ts");
                var html = $('#tpl_quick_edit').html();
                var artic_data = self.list.getArticData(ts);

                if ($(this).hasClass('quick-edit-save-mode')) {
                    isSaveBtn = true;
                }

                if (artic_data) {
                    if (isSaveBtn === false) {
                        $item.children('.row-item').hide();

                        html = html.replace(/%%ts%%/g, ts);
                        html = html.replace(/%%id%%/g, artic_data.id);

                        if (artic_data.tiene_vista != 1) {
                            html = html.replace(/<!--LINK-->.*?<!--\/LINK-->/g, '');
                            html = html.replace(/<!--NOLINK-->/g, '');
                            html = html.replace(/<!--\/NOLINK-->/g, '');
                        }
                        if (artic_data.st_pub == 1) {
                            html = html.replace(/%%art_url%%/g, artic_data.art_url);
                            html = html.replace(/<!--NOLINK-->.*?<!--\/NOLINK-->/g, '');
                            html = html.replace(/<!--LINK-->/g, '');
                            html = html.replace(/<!--\/LINK-->/g, '');
                        } else {
                            html = html.replace(/<!--LINK-->.*?<!--\/LINK-->/g, '');
                            html = html.replace(/<!--NOLINK-->/g, '');
                            html = html.replace(/<!--\/NOLINK-->/g, '');
                        }

                        if (artic_data.custom_slug !== 'SI') {
                            artic_data.custom_slug = '';
                        }

                        html = html.replace(/%%custom_slug%%/g, artic_data.custom_slug);
                        html = html.replace(/%%friendly_urls_version%%/g, artic_data.friendly_urls_version);

                        $item.find('.quick-edit').empty().append(html).show(); // metodo .html() elimina tag <form>
                        $item.find('.quick-edit input[name="quick-edit_titular"]').val(artic_data.titular);
                        $item.find('.quick-edit select[name="quick-edit_seccion1"]').val(artic_data.id_seccion);
                        $item.find('.quick-edit input[name="quick-edit_ts"]').val(artic_data.ts);
                        $item.find('.quick-edit .quick-edit_id').text(artic_data.id);
                        $item.find('.quick-edit .quick-edit_fid').text(artic_data.fid);
                        $item.find('.quick-edit input[name="quick-edit_alta"]').text(artic_data.alta);
                        $item.find('.quick-edit input[name="quick-edit_fechapub"]').val(artic_data.fechapub);
                        $item.find('.quick-edit .btn-quick-edit-normal').attr('href', artic_data.edit_url);
                        $item.addClass('quick-edit-style');

                        if (Object.keys(artic_data.portadas).length === 0) {
                            $item.find('.quick-edit .quick-edit_in_port').text('No');
                        } else {
                            $item.find('.quick-edit .quick-edit_in_port').text('Sí');
                        }

                        if (artic_data.alta == 1) {
                            $item.find('.quick-edit .alta').prop("checked", true);
                        } else {
                            $item.find('.quick-edit .alta').prop("checked", false);
                        }

                        // Cancelar edicion rapida.
                        $item.find('.quick-edit .btn-cancelar').off("click").on("click", function (_event) {
                            $item.find('.row-item').show();
                            $item.find('.quick-edit').empty().hide();
                            $item.removeClass('quick-edit-style');
                        });

                        // Guardar cambios.
                        $item.find('.quick-edit form[name="quick-edit_form"]').off("submit").on("submit", function (_event) {
                            _event.preventDefault();
                            var $form = $(this);
                            if (artic_data.friendly_urls_version == '4' && artic_data.custom_slug != 'SI') {
                                self.list.checkValidTitle($item, $form, 1);
                            } else {
                                self.list.quickEditArtic($form);
                            }
                        });

                        $item.find('.quick-edit select[name="quick-edit_tema1"]').off("change").on("change", function (_e) {
                            var combo_subtemas = $item.find('.quick-edit select[name="quick-edit_subtema1"]')[0];
                            combo_subtemas.options.length = 0;
                            combo_subtemas.options[0] = new Option('Sin Subtemas', '0');
                            combo_subtemas.options[0].selected = true;

                            var id_seccion = $item.find('.quick-edit select[name="quick-edit_seccion1"]').val();
                            var id_tema = $(this).val();
                            if (typeof ArticList.taxonomia[id_seccion] !== "undefined" && typeof ArticList.taxonomia[id_seccion]['temas'][id_tema] !== "undefined") {
                                var i = 1;
                                var subtemas = ArticList.taxonomia[id_seccion]['temas'][id_tema]['subtemas'];
                                for (var id_subtema in subtemas) {
                                    if (i == 0) {
                                        combo_subtemas.options.length = 0;
                                    }
                                    combo_subtemas.options[i] = new Option(subtemas[id_subtema]['nombre'], id_subtema);
                                    i++;
                                }
                                if (i > 1) {
                                    combo_subtemas.options[0] = new Option('Selecciona Subtema', '0');
                                    combo_subtemas.options[0].selected = true;
                                }
                            }

                            $item.find('.quick-edit select[name="quick-edit_subtema1"]').val(artic_data.id_subtema);
                        });

                        $item.find('.quick-edit select[name="quick-edit_seccion1"]').off("change").on("change", function (_e) {
                            var combo_temas = $item.find('.quick-edit select[name="quick-edit_tema1"]')[0];
                            combo_temas.options.length = 0;
                            combo_temas.options[0] = new Option('Sin Temas', '0');
                            combo_temas.options[0].selected = true;

                            var id_seccion = $(this).val();
                            if (id_seccion > 0 && typeof ArticList.taxonomia[id_seccion]['temas'] !== "undefined") {
                                var i = 1;
                                var temas = ArticList.taxonomia[id_seccion]['temas'];
                                for (var id_tema in temas) {
                                    if (i == 0) {
                                        combo_temas.options.length = 0;
                                    }
                                    combo_temas.options[i] = new Option(temas[id_tema]['nombre'], id_tema);
                                    i++;
                                }
                                if (i > 1) {
                                    combo_temas.options[0] = new Option('Selecciona Tema', '0');
                                    combo_temas.options[0].selected = true;
                                }
                            }

                            $item.find('.quick-edit select[name="quick-edit_tema1"]').val(artic_data.id_tema);
                            $item.find('.quick-edit select[name="quick-edit_tema1"]').trigger("change");
                        }).trigger("change");

                        self.methods.initDateTimePicker();
                    }

                    if (isSaveBtn === true) {
                        $item.find('.quick-edit form[name="quick-edit_form"]').trigger('submit');
                    }

                } else {
                    showModalAlert({
                        type: "red",
                        title: "Se ha producido un error",
                        icon: "glyphicon glyphicon-exclamation-sign",
                        msg: "No se pudo obtener la información del artículo",
                        cbBtnOK: function () {
                        }
                    });

                    return false;
                }
            });

            $('[data-toggle="tooltip"]').tooltip();
        },
        checkValidTitle: function($item, $form, save) {
            $('#url_art_ts').html('');
            $('#url_art_id').html('');
            $('#url_art_titu').html('');
            $('#url_art_editar').attr("href", '#');
            $('#url_art_path').html('');
            $('#url_art_slug').html('');

            $.ajax({
                type: 'POST',
                url: '/' + Admin.dir_cgi_cpn + '/prontus_art_check_url.cgi',
                data: { _txt_titular: $item.find('.quick-edit input[name="quick-edit_titular"]').val(),
                        _ts: $item.attr("data-ts"),
                        _prontus_id: Admin.prontus_id
                    },
                dataType: 'json',
                success: function (data) {
                    if (data.status) {
                        if (save) {
                            self.list.quickEditArtic($form);
                        }
                    } else {
                        $('#url_art_ts').html(data.ts);
                        $('#url_art_id').html(data.id);
                        $('#url_art_titu').html(data.titular);
                        var link = '/' + Admin.dir_cgi_cpn + '/prontus_art_ficha.cgi?_prontus_id='+ Admin.prontus_id+'&_file='+data.ts + '.' + data.ext+'&_fid='+data.fid;
                        $('#url_art_editar').attr("href", link);
                        var path = '/' + Admin.prontus_id + '/site/artic/' + data.ts.substr(0,8) + '/pags/' + data.ts + '.' + data.ext;
                        $('#url_art_path').html(path);
                        $('#url_art_slug').html(data.uri_titular);

                        $('#info_url_conflict').modal('show');
                        $("#info_url_conflict").on("hidden.bs.modal", function () {
                            $item.find('.quick-edit input[name="quick-edit_titular"]').focus();
                        });
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    SubmitForm.handleError(Admin.urlUpdate, XMLHttpRequest, textStatus, errorThrown);
                    $('#info_url_conflict').modal('hide');
                    $form.find('button').prop("disabled", false);
                    $form.find('button.btn-quick-edit-fake').hide();
                    $form.find('button.btn-quick-edit').show();
                }
            });
        },
        getArticData: function (ts) {
            for (var x = 0; x < self.artics.length; x++) {
                if (self.artics[x].ts == ts) {
                    return self.artics[x];
                }
            }

            return false;
        },
        updateArticData: function (ts, data) {
            for (var x = 0; x < self.artics.length; x++) {
                if (self.artics[x].ts == ts) {
                    self.artics[x] = $.extend(self.artics[x], data);

                    // actualizamos el estado del elemento en el listado.
                    var elementoCheckAlta = $('#artic-list li[data-ts="'+ts+'"] div.col-btns span.check-alta');

                    if (ArticList.methods.estaPublicado(data)) {
                        $(elementoCheckAlta).removeClass('nok').addClass('ok').prop('title', 'El artículo está publicado');
                    } else {
                        $(elementoCheckAlta).removeClass('ok').addClass('nok').prop('title', 'El artículo no está publicado');
                    }
                    return;
                }
            }
        },
        quickEditArtic: function ($form) {
            showModalConfirm({
                msg: "El artículo será modificado. ¿Estás seguro?",
                type: 'blue',
                icon: "glyphicon glyphicon-question-sign",
                cbBtnOK: function () {
                    $form.find('button').prop("disabled", true);
                    $form.find('button.btn-quick-edit-fake').show();
                    $form.find('button.btn-quick-edit').hide();
                    $.ajax({
                        url: "/{0}/prontus_art_quick_edit.cgi".format(Admin.dir_cgi_cpn),
                        method: "POST",
                        dataType: "json",
                        data: $form.serialize(),
                        success: function (response) {
                            if (response.status == 1) {
                                var $row = self.list.buildList({list: [response.data]}, 1);
                                $('#artic-list [data-ts="' + response.data.ts + '"]').replaceWith($row);
                                self.list.updateArticData(response.data.ts, response.data);
                                self.list.bindListEvents();

                            } else {
                                showModalAlert({
                                    type: "red",
                                    title: "Se ha producido un error",
                                    icon: "glyphicon glyphicon-exclamation-sign",
                                    msg: response.msg,
                                    cbBtnOK: function () {
                                        $form.find('button').prop("disabled", false);
                                        $form.find('button.btn-quick-edit-fake').hide();
                                        $form.find('button.btn-quick-edit').show();
                                    }
                                });
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            SubmitForm.handleError('prontus_art_quick_edit.cgi', XMLHttpRequest, textStatus, errorThrown);
                            $form.find('button').prop("disabled", false);
                            $form.find('button.btn-quick-edit-fake').hide();
                            $form.find('button.btn-quick-edit').show();
                        }
                    });
                },
                cbBtnCancel: function () {}
            });
        }
    },
    search: {
        busquedas: {},
        ordenActual: false, // para evitar problemas con chrome en onblur del selector de orden de articulos.
        init: function () {
            $(".artic-search .search .button-search").off("click").on("click", function (e) {
                e.preventDefault();
                self.search.basicSearch();
            });

            ArticList.search.ordenActual = $('#articles-order-by').val();

            $(".artic-search .search .button-refresh").off("click").on("click", function (e) {
                e.preventDefault();
                self.search.cleanSearch();
                var visibility = $("#input-visible").val();
                self.list.loadArtics(0, {
                    tipart: "",
                    seccion: "",
                    ts: "",
                    titu: "",
                    alta: "",
                    visible: visibility
                });
            });
            $('#articles-order-by').on('change', function(e) {
                e.preventDefault();
                var orden = $('#articles-order-by').val();
                if (orden == ArticList.search.ordenActual) {
                    // en chrome hacer click fuera del combo gatilla la búsqueda nuevamente,
                    // por lo que chequeamos que efectivamente haya cambiado el orden.
                    return false;
                } else {
                    ArticList.search.ordenActual = orden;
                    self.list.loadArtics(0, {_orden_lista: orden});
                }
            });

            $(".artic-search .input-search").on("keyup", function (e) {
                if (e.keyCode == 13) {
                    self.search.basicSearch();
                }
            });

            self.search.setupVisibilityFilter();
            $("#button-search-visible").off("click").on("click", function (e) {
                e.preventDefault();
                self.search.filterVisibleArticles();
            });

            $("select[name='filtro_fid']").off("change").on("change", function (e) {
                e.preventDefault();
                self.list.loadArtics(0, {tipart: $(this).val()});
            });

            $("select[name='filtro_secc']").off("change").on("change", function (e) {
                e.preventDefault();
                self.list.loadArtics(0, {seccion: $(this).val()});
            });

            $("select[name='filtro_mostrar']").off("change").on("change", function (e) {
                e.preventDefault();
                self.list.loadArtics(0, {_filas_x_pag: $(this).val()});
            });

            $("select[name='filtro_estado']").off("change").on("change", function (e) {
                e.preventDefault();
                self.list.loadArtics(0, {alta: $(this).val()});
            });

            self.search.bindFilterSearch();
            $("#modal_search").off("show.bs.modal").on("show.bs.modal", function (_e) {
                self.search.bindFilterSearch();
            });

            $("#modal_favorite_search").off("show.bs.modal").on("show.bs.modal", function (_e) {
                self.search.handleFavoriteModal();
            });

        },
        handleFavoriteModal: function () {
            var html = $(ArticList.idTplFavoriteSearch).html();
            var output = "";

            $.ajax({
                url: "/{0}/prontus_port_carga_busquedas.cgi".format(Admin.dir_cgi_cpn),
                dataType: "json",
                data: { _prontus_id: ArticList.prontus_id },
                type: 'POST',
                success: function (response) {
                    if (response.status == 1) {
                        $.each(response.data, function (_index, value) {
                            var tmp = html;
                            tmp = tmp.replace(/%%nombre%%/g, value.info.nombre);
                            tmp = tmp.replace(/%%id%%/g, value.info.ts); // ts no tiene nada que ver con articulos.

                            output += tmp;

                            self.search.busquedas[value.info.ts] = value.params;
                        });

                        $("#favorite_search_list").html(output);
                        self.search.bindBusquedaFav();
                    } else {
                        showModalAlert({
                            title: "Mensaje del servidor",
                            msg: repsonse.msg,
                            type: "red",
                            icon: "glyphicon glyphicon-exclamation-sign",
                            cbBtnOK: function () {
                            }
                        });
                    }
                },
                error: function (_XMLHttpRequest, _textStatus, errorThrown) {
                    showModalAlert({
                        title: "Ha ocurrido un error",
                        msg: "No se pudo cargar el listado de búsquedas.<br><br>Mensaje del servidor: {0}".format(errorThrown),
                        type: "red",
                        icon: "glyphicon glyphicon-exclamation-sign",
                        cbBtnOK: function () {
                        }
                    });
                }
            });
        },
        resetSearchParams: function () {
            $.each(ArticList.searchParams, function (index, _value) {
                ArticList.searchParams[index] = "";
            });

            $("select[name='filter_subtema']").find('option').remove().end().append('<option value="">Subtema</option>');
            $("select[name='filter_tema']").find('option').remove().end().append('<option value="">Tema</option>');

            $("select[name='filter_visibilidad']").val('');
            $("select[name='filter_multitag_s']").val('');
            $("select[name='filter_multitag_t']").val('');
            $("select[name='filter_multitag_st']").val('');
            $("input[name='filter_save']").removeAttr("checked");
            $("input[name='filter_name']").attr("disabled", "disabled");
            $("input[name='input-search']").val('');
        },
        rellenaFormFiltros: function (data) {
            for (var prop in data) {
                $("[name='filter_{0}']".format(prop)).val(data[prop]);
            }
            $("[name='filter_seccion']").val(data.seccion);
            $("[name='filter_seccion']").trigger('change');

            $("[name='filter_tema']").val(data.tema).trigger('change');
            $("[name='filter_subtema']").val(data.subtema);
        },
        bindBusquedaFav: function () {
            $(".aplica-busqueda-fav").off("click").on("click", function (e) {
                e.preventDefault();

                var id = $(this).attr("data-id");

                if (typeof self.search.busquedas[id]) {
                    self.list.loadArtics(0, self.search.busquedas[id]);
                    self.search.rellenaFormFiltros(self.search.busquedas[id]);
                    self.search.mostrarFiltros();
                    self.search.bindEliminaFiltros();

                    $("#modal_favorite_search").modal("toggle");
                } else {
                    // !! ERROR.
                }
            });

            $(".elimina-busqueda-fav").off("click").on("click", function (e) {
                e.preventDefault();
                var id = $(this).attr("data-id");
                var $item = $(this).parent();
                var data = {
                    _prontus_id: ArticList.prontus_id,
                    _id_busqueda: id
                };

                $item.addClass("disabled");

                $.ajax({
                    url: "/{0}/prontus_port_borra_busqueda.cgi".format(Admin.dir_cgi_cpn),
                    dataType: "json",
                    data: data,
                    success: function (response) {
                        if (response.status == 1) {
                            $.each(response.data, function (_index, value) {
                                self.search.busquedas[value.info.ts] = value.params;
                            });
                            $item.remove();
                        } else {
                            showModalAlert({
                                title: "Mensaje del servidor",
                                msg: response.msg,
                                type: "red",
                                icon: "glyphicon glyphicon-exclamation-sign",
                                cbBtnOK: function () {
                                    $item.removeClass("disabled");
                                }
                            });
                        }
                    },
                    error: function (_XMLHttpRequest, _textStatus, errorThrown) {
                        showModalAlert({
                            title: "Ha ocurrido un error",
                            msg: "No se pudo borrar la búsqueda.<br><br>Mensaje del servidor: {0}".format(errorThrown),
                            type: "red",
                            icon: "glyphicon glyphicon-exclamation-sign",
                            cbBtnOK: function () {
                                $item.removeClass("disabled");
                            }
                        });
                    }
                });

            });
        },
        bindFilterSearch: function () {
            $("select[name='filter_seccion']").off("change").on("change", function (_e) {
                var combo_temas = $("select[name='filter_tema']")[0];
                combo_temas.options.length = 0;
                var combo_subtemas = $("select[name='filter_subtema']")[0];
                combo_subtemas.options.length = 0;
                var id_seccion = $("select[name='filter_seccion']").val();
                if (typeof ArticList.taxonomia[id_seccion] !== "undefined") {
                    var i = 1;
                    var temas = ArticList.taxonomia[id_seccion]['temas'];
                    for (var id_tema in temas) {
                        combo_temas.options[i] = new Option(temas[id_tema]['nombre'], id_tema);
                        i++;
                    }
                    if (i > 1) {
                        combo_temas.options[0] = new Option('Tema', '0');
                        combo_temas.options[0].selected = true;
                    }
                }
            });

            $("select[name='filter_tema']").off("change").on("change", function (_e) {
                var id_tema = $("select[name='filter_tema']").val();
                var combo_subtemas = $("select[name='filter_subtema']")[0];
                combo_subtemas.options.length = 0;
                if (id_tema !== 0) {
                    var id_seccion = $("select[name='filter_seccion']").val();

                    if (typeof ArticList.taxonomia[id_seccion] !== "undefined" && typeof ArticList.taxonomia[id_seccion]['temas'][id_tema] !== "undefined") {
                        var i = 1;
                        var subtemas = ArticList.taxonomia[id_seccion]['temas'][id_tema]['subtemas'];
                        for (var id_subtema in subtemas) {
                            combo_subtemas.options[i] = new Option(subtemas[id_subtema]['nombre'], id_subtema);
                            i++;
                        }
                        if (i > 1) {
                            combo_subtemas.options[0] = new Option('Subtema', '0');
                            combo_subtemas.options[0].selected = true;
                        }
                    }
                }
            });

            $("input[name='filter_save']").off("click").on("click", function () {
                if ($(this).is(":checked")) {
                    $("input[name='filter_name']").removeAttr("disabled");
                } else {
                    $("input[name='filter_name']").attr("disabled", "disabled");
                }
            });

            $("button[name='aplicar_filter']").off("click").on("click", function (_e) {
                self.list.loadArtics(0, {
                    tipart:         $("select[name='filter_tipart']").val(),
                    seccion:        $("select[name='filter_seccion']").val(),
                    tema:           $("select[name='filter_tema']").val(),
                    subtema:        $("select[name='filter_subtema']").val(),
                    visible:        $("select[name='filter_visibilidad']").val(),
                    multitag_s:     $("select[name='filter_multitag_s']").val(),
                    multitag_t:     $("select[name='filter_multitag_t']").val(),
                    multitag_st:    $("select[name='filter_multitag_st']").val(),
                    autor:          $("input[name='filter_autor']").val(),
                    titu:           $("input[name='filter_titu']").val(),
                    bajada:         $("input[name='filter_bajada']").val(),
                    autoinc:        $("input[name='filter_autoinc']").val(),
                    alta:           $("select[name='filter_alta']").val(),
                    dia:            $("input[name='filter_dia']").val(),
                    diahasta:       $("input[name='filter_diahasta']").val(),
                    diapub:         $("input[name='filter_diapub']").val(),
                    diapubhasta:    $("input[name='filter_diapubhasta']").val(),
                    diaexp:         $("input[name='filter_diaexp']").val(),
                    diaexphasta:    $("input[name='filter_diaexphasta']").val(),
                    save_search:    $("input[name='filter_save']").is(':checked'),
                    name_search:    $("input[name='filter_name']").val(),
                });

                $("input[name='input-search']").val($("input[name='filter_titu']").val());
                $("#modal_search").modal("toggle");

                self.search.mostrarFiltros();
                self.search.bindEliminaFiltros();
            });
        },
        bindEliminaFiltros: function () {
            $("button[name='elimina-filtros']").off("click").on("click", function (_e) {
                $(".admin-search .search-filters li").not(".button-elimina-filtros").remove();

                $("[name^='filter_']").each(function (_index, _value) {
                    $(this).val("");
                });

                $(self.ui.selectors.panelRecentArtics + ' .button-elimina-filtros').addClass("hidden");
                self.search.resetSearchParams();

                var visibility = $("#input-visible").val();
                self.list.loadArtics(0, {visible: visibility});
            });
        },
        mostrarFiltros: function () {
            var html = $(ArticList.idTplfilter).html();
            var output = "";
            var val, ignore, nom_filtro;

            $(".admin-search .search-filters li").not(".button-elimina-filtros").remove();

            $("[name^='filter_']").each(function (_index, _value) {
                var tmp = html;

                if ($(this)[0].nodeName == "SELECT") {
                    val = $(this, 'option:selected').val();
                    ignore = $(this).attr("data-ignore");

                    if (val && !ignore) {
                        // El primer elemento se considera como el nombre/titulo
                        nom_filtro = $(this).find("option:first-child").text();
                        var nom_option = $(this).find("option:selected").text();

                        if (nom_filtro) {
                            tmp = tmp.replace(/%%filter_name%%/g, nom_filtro);
                            tmp = tmp.replace(/%%filter_value%%/g, nom_option);

                            output += tmp;
                        }
                    }
                } else if ($(this)[0].nodeName == "INPUT") {
                    val = $(this).val();
                    ignore = $(this).attr("data-ignore");

                    if (val && !ignore) {
                        nom_filtro = $(this).attr("placeholder");

                        if (nom_filtro) {
                            tmp = tmp.replace(/%%filter_name%%/g, nom_filtro);
                            tmp = tmp.replace(/%%filter_value%%/g, val);

                            output += tmp;
                        }
                    }
                }
            });

            if (output) {
                $(".admin-search .search-filters").prepend(output);
                $(self.ui.selectors.panelRecentArtics + ' .button-elimina-filtros').removeClass("hidden");
            }
        },
        /** Asegura durante la carga de la página que el botón refleje el estado del filtro de visibilidad.
         * A veces, al recargar, el botón queda en un estado incorrecto.
         */
        setupVisibilityFilter: function() {
            var filter_state = $('#input-visible').val();
            if (filter_state == 1) {
                $('#button-search-visible span').removeClass("fa-eye").addClass('fa-eye-slash');
            } else {
                $('#button-search-visible span').removeClass('fa-eye-slash').addClass("fa-eye");
            }
        },
        /** Aplica la búsqueda excluyendo o incluyendo artículos sin vista. */
        filterVisibleArticles: function() {
            var filter_state = $('#input-visible').val();

            // configuramos apariencia del botón de filtro y seteamos valor de búsqueda.
            if (filter_state == 1) { // pasa a mostrar todo
                $('#button-search-visible span').removeClass('fa-eye-slash').addClass("fa-eye");
                $('#input-visible').val(0);
            } else { // pasa a excluir artículos sin vista
                $('#button-search-visible span').removeClass("fa-eye").addClass('fa-eye-slash');
                $('#input-visible').val(1);
            }
            // finalmente ejecutamos la búsqueda nuevamente.
            self.search.basicSearch();
        },
        basicSearch: function () {
            var inputValue = $(".artic-search .search .input-search").val();
            var regxp = /^\d{14}$/;

            var visibility = $("#input-visible").val();

            if(regxp.test(inputValue)) {
                self.list.loadArtics(0, {ts: inputValue, titu: '', visible: visibility});
            } else {
                self.list.loadArtics(0, {ts: '', titu: inputValue, visible: visibility});
            }
        },
        cleanSearch: function () {
            $(".artic-search .input-search").val("");
            $("select[name='filtro_fid']").val("");
            $("select[name='filtro_secc']").val("");
            $("select[name='filtro_estado']").val("");

        },
        buildPagination: function (data, rec_ini) {
            if (data.next < 0) {
                $(self.ui.selectors.articListNext).addClass("disabled");
                $(self.ui.selectors.articListLast).addClass("disabled");
            } else {
                $(self.ui.selectors.articListNext).removeClass("disabled");
                $(self.ui.selectors.articListLast).removeClass("disabled");
            }
            if (data.prev < 0) {
                $(self.ui.selectors.articListPrev).addClass("disabled");
                $(self.ui.selectors.articListFirst).addClass("disabled");
            } else {
                $(self.ui.selectors.articListPrev).removeClass("disabled");
                $(self.ui.selectors.articListFirst).removeClass("disabled");
            }

            rec_ini = rec_ini + 1;
            var next = data.next;

            if (next == -1) next = data.total;

            $(".artic-search .info-pagination").html("{0}-{1} de {2}".format(rec_ini, next, data.total));

            self.search.bindPagination(data);

            $(".artic-search nav").show();
            $(".artic-search .info-pagination").show();
        },
        bindPagination: function (data) {
            $("#artic_list_first > a").off("click").on("click", function (e) {
                e.preventDefault();

                if (data.first >= 0) {
                    self.list.loadArtics(data.first);
                }
            });
            $("#artic_list_next > a").off("click").on("click", function (e) {
                e.preventDefault();

                if (data.next > 0) {
                    self.list.loadArtics(data.next);
                }
            });
            $("#artic_list_prev > a").off("click").on("click", function (e) {
                e.preventDefault();

                if (data.prev >= 0) {
                    self.list.loadArtics(data.prev);
                }
            });
            $("#artic_list_last > a").off("click").on("click", function (e) {
                e.preventDefault();

                if (data.last > 0) {
                    self.list.loadArtics(data.last);
                }
            });
        }
    },
    methods: {
        estaPublicado(data) {
            // devuelve true si el artículo tiene alta == 1, fechahorapub <= now, fechahoraexp >= now.
            var datenow = new Date();
            var fechapub = data.fechapub.split(' ');
            var horapub = fechapub[1].split(':');
            fechapub = fechapub[0].split('/');
            var datepub = new Date(fechapub[2]+'-'+fechapub[1]+'-'+fechapub[0]+'T'+ horapub[0]+':'+horapub[1]+':00');

            var fechaexp = data.fechaexp;

            if (fechaexp == '') {
                fechaexp = '31/12/9999 23:59';
            }

            fechaexp = fechaexp.split(' ');

            var horaexp = fechaexp[1].split(':');
            fechaexp = fechaexp[0].split('/');

            var dateexp = new Date(fechaexp[2]+'-'+fechaexp[1]+'-'+fechaexp[0]+'T'+ horaexp[0]+':'+horaexp[1]+':00');

            return (data.alta == 1 && datepub <= datenow && (fechaexp == '' || dateexp >= datenow));
        },
        initDatePicker: function () {
            $(".datepicker").datetimepicker({
                format:'DD/MM/YYYY',
                locale:'es',
                useCurrent: false
            });
        },
        initClipboard: function () {
            $(".clipboard").off("click").on("click", function (e) {
                e.preventDefault();
            });

            if (self.clipboard) self.clipboard.destroy();

            self.clipboard = new ClipboardJS('.clipboard', {
                text: function (trigger) {
                    return trigger.getAttribute("data-text");
                }
            });

            self.clipboard.on('success', function(e) {
                e.clearSelection();
            });
        },
        initDateTimePicker: function () {
            $('.datetimepicker').datetimepicker({
                locale: 'es',
                ignoreReadonly: true
            });
        }
    },
    helper: {
        setValueLS: function (name, value) {
            localStorage.setItem(name, value);
        },
        getValueLS: function (name) {
            return localStorage.getItem(name);
        },
    }
};

$(document).ready(function () {
    ArticList.init();
});
