var UrlAdmin = {
    ajax_request: null,
    timeout: 0,
    page: 1,
    types: {
        artic: "Artículos",
        tax: "Taxonómicas",
        tag: "Tagonómicas",
        port: "Portadas",
        list: "Listados",
        redirect: "Redirección"
    },
    init: function () {
        UrlAdmin.order = $('#order-by').val();
        UrlAdmin.filter = $('#filter-url').val();
        UrlAdmin.type = $('#type-url').val();
        UrlAdmin.getList();
        UrlAdmin.bindEvents();
        UrlF5.init();
    },
    getList: function(page) {
        UrlAdmin.page = page;
        var data = {
            _prontus_id: Admin.prontus_id,
            order : UrlAdmin.order,
            type: UrlAdmin.type,
            search: $('#input-search').val(),
            page: UrlAdmin.page
        };

        $.ajax({
            url: '/' + Admin.dir_cgi_cpn + '/urlf5/prontus_urlf5_get_list.cgi',
            type: 'POST',
            dataType: 'json',
            data: data,
            success: function (response) {
                UrlAdmin.parseList(response);
            },
            error: function(xhr, ajaxOptions, thrownError) {
                console.log(xhr, ajaxOptions, thrownError);
            }
        });
    },
    parseList: function (data) {
        var tpl_list = $('#tpl_list').html();
        var list = '';
        for (let i = 0; i < data.list.length; i++) {
            var aux = tpl_list;
            for (var prop in data.list[i]) {
                aux = aux.replace(new RegExp( '{{'+prop+'}}', "g"), data.list[i][prop]);
            }
            var tipo = UrlAdmin.types[data.list[i]['type']];
            if (data.list[i]['type'] == 'redirect') {
                tipo += ' ' + data.list[i]['subtype'];
            }
            aux = aux.replace(new RegExp( '{{tipo}}', "g"), tipo);
            if (data.list[i]['type'] !== 'artic' ) {
                aux = aux.replace(/<!--ARTIC-->.*?<!--\/ARTIC-->/sg, '');
            }
            if (data.list[i]['type'] !== 'tax' ) {
                aux = aux.replace(/<!--TAX-->.*?<!--\/TAX-->/sg, '');
            }
            if (data.list[i]['type'] !== 'tag' ) {
                aux = aux.replace(/<!--TAG-->.*?<!--\/TAG-->/sg, '');
            }
            if (data.list[i]['type'] !== 'list' && data.list[i]['type'] !== 'redirect' ) {
                aux = aux.replace(/<!--OTHER-->.*?<!--\/OTHER-->/sg, '');
            }
            if (data.list[i]['type'] !== 'redirect' && data.list[i]['type'] !== 'port') {
                aux = aux.replace(/<!--REDIR-->.*?<!--\/REDIR-->/sg, '');
            }
            list += aux;
        }
        $('#url-list').html(list);
        UrlAdmin.buildPagination(data.pagination);
    },
    ui: {
        selectors: {
            panelRecentArtics: '.admin-search .panel-recent-artics',
            urlList: '#url-list',
            // Paginacion articulos recientes
            listFirst: '.list_first',
            listLast:  '.list_last',
            listNext:  '.list_next',
            listPrev:  '.list_prev',
        }
    },
    buildPagination: function (data) {
        if ((data.start + data.current) > data.total) {
            $(UrlAdmin.ui.selectors.listNext).addClass("disabled");
            $(UrlAdmin.ui.selectors.listLast).addClass("disabled");
        } else {
            $(UrlAdmin.ui.selectors.listNext).removeClass("disabled");
            $(UrlAdmin.ui.selectors.listLast).removeClass("disabled");
        }
        if (data.start == 1) {
            $(UrlAdmin.ui.selectors.listPrev).addClass("disabled");
            $(UrlAdmin.ui.selectors.listFirst).addClass("disabled");
        } else {
            $(UrlAdmin.ui.selectors.listPrev).removeClass("disabled");
            $(UrlAdmin.ui.selectors.listFirst).removeClass("disabled");
        }
        $(".info-pagination").html("{0}-{1} de {2}".format(data.start, (data.start + data.current -1 ), data.total));
        $(".artic-search nav").show();
        $(".artic-search .info-pagination").show();

        UrlAdmin.bindPagination(data);
        UrlAdmin.page = data.page;
    },
    bindPagination: function (data) {
        $(".list_first > a").off("click").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();

            if (data.start > 1) {
                UrlAdmin.getList(1);
            }
        });
        $(".list_next > a").off("click").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();

            if (data.start + data.current < data.total) {
                UrlAdmin.getList(data.page + 1);
            }
        });
        $(".list_prev > a").off("click").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();

            if (data.start > 1) {
                UrlAdmin.getList(data.page - 1);
            }
        });
        $(".list_last > a").off("click").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();

            if (data.start + data.current < data.total) {
                UrlAdmin.getList((data.total - data.total % 20)/20 +1);
            }
        });
    },
    importURL: function(){
        $('#modal_urlf5_import').modal({show:true, backdrop: 'static', keyboard: false});
        $('#FILE1').filestyle();

        var file = $('#FILE1');
        var msgError = $('#form1 .msg-error');
        var fileFormatIsValid = true;

        file.on('change', function(event) {
            event.preventDefault();
            fileFormatIsValid = UrlAdmin.fileValidateFormat(file, msgError);
        });

        $('#form1').on('submit', function(e){
            e.preventDefault();

            if (file.val() === '') {
                alert('Debes ingresar un archivo para Importar.');
                return;
            }

            var form_action = '/'+Admin.dir_cgi_cpn+'/urlf5/prontus_urlf5_import.cgi';
            var form = $(this);
            var formdata = false;

            if (window.FormData){
                formdata = new FormData(form[0]);
            }

            if (fileFormatIsValid) {
                $.ajax({
                    url         : form_action,
                    data        : formdata ? formdata : form.serialize(),
                    cache       : false,
                    contentType : false,
                    processData : false,
                    type        : 'POST',
                    success     : function(data, textStatus, jqXHR){
                        $('#modal_urlf5_import .modal-content').html(data);
                        Opciones.checkStatus('/' + Admin.prontus_id + '/cpan/procs/result_urlf5_import.json');
                    }
                });
            }
        });
    },
    fileValidateFormat: function(fileUpload, idMsgError) {
        idMsgError.fadeOut();
        var allowedFiles = [".csv"];
        var regex = new RegExp("([a-zA-Z0-9\s_\\.\-:\(\) ])+(" + allowedFiles.join('|') + ")$");
        if (!regex.test(fileUpload.val().toLowerCase())) {
            idMsgError.fadeIn();
            idMsgError.find('p').html('<span class="glyphicon glyphicon-remove text-danger"></span> Formato de archivo no válido');
            return false;
        }
        return true;

    },
    bindEvents: function () {
        $('#importar-uls').on('click', UrlAdmin.importURL);
        $('#url-list').on('click', '.show-f5-tax', UrlF5.actions.editUrlTax);
        $('#url-list').on('click', '.show-f5-tag', UrlF5.actions.editUrlTag);

        $('#url-list').on('click', '.urlf5-borrar', function (e) {
            e.preventDefault();
            e.stopPropagation();
            var input_id = $(this).attr("data-input-id");
            var urlf5_type = $(this).attr("data-urlf5-type");
            var urlf5_subtype = $(this).attr("data-urlf5-subtype");
            var urlf5_subtype_id = $(this).attr("data-urlf5-subtype-id");
            var urlf5_file = $(this).attr("data-urlf5-file");

            showModalConfirm({
                'title':'Borrar URL',
                'msg': 'Se borrará la URL ¿Estás seguro?',
                type: "orange",
                icon: "glyphicon glyphicon-exclamation-sign",
                btnClassOk: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextred nextred',
                okTitle: 'Borrar',
                cbBtnOK: function() {
                    UrlF5.actions.borrarUrl(input_id, urlf5_type, urlf5_subtype, urlf5_subtype_id, urlf5_file);
                }
            });
        });
        // actualiza listado al cerrar los modales
        $("#modal_f5, #modal_edit_url").on("hidden.bs.modal", function () {
            UrlAdmin.getList(UrlAdmin.page);
        });

        $('#url-list').on('click', '.show-f5-url', function (e) {
            e.preventDefault();
            e.stopPropagation();
            var file = $(this).data('file');
            var url = $(this).data('url');
            $('#file-path').html(file);
            $('#urlf5-input').val(url);
            // asigna nombre distinto al campo para evitar el autocompletar
            $('#urlf5-input').attr('name', Date.now());
            $('#_last_url').val(url);

            // asigna valores a botones del modal
            var selector = '.urlf5-guardar, .urlf5-borrar, .urlf5-open';
            $(selector).attr("data-input-id", 'urlf5-input');
            $(selector).attr("data-urlf5-type", $(this).data('type'));
            $(selector).attr("data-urlf5-subtype", $(this).data('subtype'));
            $(selector).attr("data-urlf5-subtype-id", $(this).data('subtype-id'));
            $(selector).attr("data-urlf5-file", file);
            $(selector).attr("data-urlf5-url", url);
            let combo = document.getElementById('url-sub-type');
            combo.options.length = 0;
            if ($(this).data('subtype') == 200) {
                combo.options[0] = new Option(200, 200);
            } else {
                combo.options[0] = new Option(301, 301);
                combo.options[1] = new Option(302, 302);
                $('#url-sub-type').val($(this).data('subtype'));
            }

            $('#modal_edit_url').modal('show');

            // quitar caracteres no válidos
            $('#urlf5-input').off('keyup').on('keyup', function () {
                this.value = this.value.replace(/[^a-zA-Z0-9\-\/_.]+/g, '');

                let url1 = $(this).val();
                var old_url_input = $('#_last_url');
                UrlF5.actions.checkUrl(url1, $(this), old_url_input);
            });

            $('#url-sub-type').on('change', function(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                $(selector).attr("data-urlf5-subtype", $('#url-sub-type').val());
            });
        });

        $('#new-redirect-urlf5').on('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            // asigna nombre distinto al campo para evitar el autocompletar
            $('#new-urlf5, #new-path-urlf5').attr('name', Date.now());
            $('#new-urlf5, #new-path-urlf5').val('');
            UrlF5.methods.removeInputHelp($('#new-urlf5').parent());
            $('#_last_url').val('');

            // asigna valores a botones del modal
            var selector = '.urlf5-guardar';
            $(selector).attr("data-input-id", 'new-urlf5');
            $(selector).attr("data-urlf5-type", 'redirect');
            $(selector).attr("data-urlf5-subtype", 301);
            $(selector).attr("data-urlf5-subtype-id", '');
            $('#modal_new_url').modal('show');

            // quitar caracteres no válidos
            $('#new-urlf5').off('keyup').on('keyup', function () {
                this.value = this.value.replace(/[^a-zA-Z0-9\-\/_.]+/g, '');
                this.value = this.value.replace(/\/\/+/g, '/');
                let url1 = $(this).val();
                document.getElementById('_last_url').value = document.getElementById('new-path-urlf5').value;
                // setea time out para mejorar usabilidad
                clearTimeout(UrlAdmin.timeout);
                if (UrlF5.ajax_request != null) {
                    UrlF5.ajax_request.abort();
                }
                var old_url_input = $('#_last_url');
                UrlAdmin.timeout = setTimeout(UrlF5.actions.checkUrl, 300, url1, $(this), old_url_input);
            });
            $('#new-path-urlf5').off('keyup').on('keyup', function () {
                this.value = this.value.replace(/[^a-zA-Z0-9\-\/_.]+/g, '');
                this.value = this.value.replace(/\/\/+/g, '/');
                if (this.value.substr(0, 1) != '/') {
                    this.value = '/' +this.value;
                }
                $(selector).attr("data-urlf5-file", document.getElementById('new-path-urlf5').value);
                if (/([^\/]+)\/site\/artic\/\d{8}\/pags/.test(this.value) ||
                    /([^\/]+)\/site\/ta[xg]\/port/.test(this.value) ||
                    /([^\/]+)\/site\/edic\/([^\/]+)\/port/.test(this.value) ||
                    /([^\/]+)\/site\/list\/port/.test(this.value)) {
                    showModalAlert({
                        title: "Error en el destino de la url",
                        type: "orange",
                        msg: "Este destino no se puede utilizar para configurar una url en este administrador."
                    });
                    this.value = this.value.replace(/\/(pags|port|edic)[\w\.\/_-]*/ ,'');
                }
            });

            $('#new-url-sub-type').on('change', function(evt) {
                evt.preventDefault();
                evt.stopPropagation();
                $(selector).attr("data-urlf5-subtype", $('#new-url-sub-type').val());
            });
        });

        $(".artic-search .button-search").on("click", function (e) {
            e.preventDefault();
            e.stopPropagation();
            UrlAdmin.getList(UrlAdmin.page);
        });

        // enter en campo a buscar, lanza busqueda
        $("#input-search").on("keyup", function (e) {
            e.preventDefault();
            e.stopPropagation();
            if (e.keyCode == 13) {
                UrlAdmin.getList(UrlAdmin.page);
            } else {
                // quitar caracteres no válidos
                this.value = this.value.replace(/[^a-zA-Z0-9\-\/_.]+/g, '');
            }
        });

        $('#type-url').on('change', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var type = $('#type-url').val();
            if (type == UrlAdmin.type) {
                // en chrome hacer click fuera del combo ejecuta la búsqueda nuevamente, por lo que chequeamos que efectivamente haya cambio
                return false;
            } else {
                UrlAdmin.type = type;
                UrlAdmin.getList(1);
            }
        });

        $('#order-by').on('change', function(e) {
            e.preventDefault();
            e.stopPropagation();
            var orden = $('#order-by').val();
            if (orden == UrlAdmin.order) {
                // en chrome hacer click fuera del combo ejecuta la búsqueda nuevamente, por lo que chequeamos que efectivamente haya cambio
                return false;
            } else {
                UrlAdmin.order = orden;
                UrlAdmin.getList(UrlAdmin.page);
            }
        });
    }
};

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