// v1.0.0 - JOR
var Cfgedit = {
    newPortLastId: 0,

    guardaCfg: function (cfg) {
        var msg = "¿Estás seguro de modificar la configuración?";
        showModalConfirm({
            'title': 'Guardar Configuración',
            'msg': msg,
            type: "orange",
            icon: "glyphicon glyphicon-exclamation-sign",
            btnClassOk: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextyellow nextyellow',
            okTitle: 'Guardar',
            cbBtnOK: function () {
                var configAjax = {
                    formSelector: '#frmCFG-' + (cfg.toUpperCase()),
                    actionURL: '/cgi-cpn/prontus_cfg_save.cgi'
                };

                var optsAjax = {
                    success: function (json, statusText) {
                        let result_type = 'green';
                        if (json.status !== 1) {
                            result_type = 'red';
                        }
                        if (typeof json.msg !== 'undefined') {
                            showModalAlert({
                                title: 'Resultado',
                                type: result_type,
                                msg: json.msg
                            });
                        }

                        if (json.status === 1) {
                            window.location.href = '/cgi-cpn/prontus_admin_conf_' + cfg + '.cgi?_prontus_id=' + Admin.prontus_id;
                        }

                        $('form[name="frmCFG-' + cfg.toUpperCase() + '"]').parent().find('.botones').show();
                        $('form[name="frmCFG-' + cfg.toUpperCase() + '"]').parent().find('#ajax-loading').hide();
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        SubmitForm.handleError(configAjax.actionURL, XMLHttpRequest, textStatus, errorThrown);
                        $('form[name="frmCFG-' + cfg.toUpperCase() + '"]').parent().find('.botones').show();
                        $('form[name="frmCFG-' + cfg.toUpperCase() + '"]').parent().find('#ajax-loading').hide();
                    }
                };
                $('form[name="frmCFG-' + cfg.toUpperCase() + '"]').siblings().find('.btn').hide();
                $('form[name="frmCFG-' + cfg.toUpperCase() + '"]').siblings().find('#ajax-loading').show();

                if (cfg === 'art') {
                    // Armar input.
                    var form_plts = '';
                    var fids_contenido = [];
                    var fids_calendar = [];

                    $('input[id^="nombrefid_"]').each(function () {
                        if (!$(this).is(':disabled')) {
                            let id = ($(this).attr("id")).replace(/nombrefid_/, '');
                            var plantillas = '';
                            var plantillas_paralelas = '';

                            $('select[id="plantillasfid_' + id + '"] option:selected').each(function () {
                                plantillas += $(this).val() + ';';
                            });

                            $('select[id="plantillasfid_pla_' + id + '"] option:selected').each(function () {
                                plantillas_paralelas += $(this).val() + ';';
                            });


                            plantillas = plantillas.substring(0, plantillas.length - 1);
                            plantillas_paralelas = plantillas_paralelas.substring(0, plantillas_paralelas.length - 1);

                            if ($('#archivofid_' + id ).val() !== '') {
                                form_plts += $('#archivofid_' + id ).val() + ':' + $(this).val() + '(' + plantillas + ')(' + plantillas_paralelas + ')|';
                            }
                        }
                    });
                    form_plts = form_plts.substring(0, form_plts.length - 1);
                    $('input[name="FORM_PLTS"]').val(form_plts);

                    $('input[id^="fids_contenido_"]').each(function () {
                        if (!$(this).is(':disabled')) {
                            let id = ($(this).attr("id")).replace(/fids_contenido_/, '');
                            if ($(this).is(':checked')) {
                                var fid_select = $('#archivofid_' + id ).val();
                                if (typeof fid_select !== 'undefined') {
                                    fids_contenido.push(fid_select);
                                }
                            }

                        }
                    });

                    if (fids_contenido.length > 1) {
                        fids_contenido = fids_contenido.join(',');
                    } else {
                        fids_contenido = fids_contenido[0];
                    }
                    form_plts = form_plts.substring(0, form_plts.length - 1);
                    $('input[name="FIDS_CONTENIDO"]').val(fids_contenido);

                    $('input[id^="fids_calendar_"]').each(function () {
                        if (!$(this).is(':disabled')) {
                            let id = ($(this).attr("id")).replace(/fids_calendar_/, '');
                            if ($(this).is(':checked')) {
                                var fid_select = $('#archivofid_' + id ).val();
                                if (typeof fid_select !== 'undefined') {
                                    fids_calendar.push(fid_select);
                                }
                            }

                        }
                    });

                    if (fids_calendar.length > 1) {
                        fids_calendar = fids_calendar.join(',');
                    } else {
                        fids_calendar = fids_calendar[0];
                    }
                    $('input[name="FIDS_CALENDAR"]').val(fids_calendar);
                } else if (cfg == 'sitemap') {

                    let articulos_pags = [];
                    let portadas = [];
                    let articulos_news = [];

                    $("input[id*='pags_article']:checked").each(function (index, data) {
                        var myValue = $(this).attr('value');
                        articulos_pags.push(myValue);
                    });

                    $('input[name="SITEMAP_ARTICULOS"]').val(articulos_pags);

                    //console.log(articulos_pags);


                    $("input[id*='news_article']:checked").each(function (index, data) {
                        var myValue = $(this).attr('value');
                        articulos_news.push(myValue);
                    });

                    //console.log(articulos_news);

                    $('input[name="SITEMAP_ARTICULOS_NEWS"]').val(articulos_news);


                    $("input[id*='portada']:checked").each(function (index, data) {
                        var myValue = $(this).attr('value').trim();
                        portadas.push(myValue);
                    });

                    $('input[name="SITEMAP_PORTADAS"]').val(portadas);


                    //console.log($('input[name="NEWS_IMG_PORT"]').val());

                } else if (cfg === 'cache') {
                    var cache_server = '';
                    $('input[name="INPUT_CACHE_SERVER_NAME[]"]').each(function () {
                        if ($(this).val() != '') {
                            cache_server += $(this).val() + "|";
                        }
                    });
                    $('input[name="CACHE_SERVER_NAME"]').val(cache_server);

                    var cache_subdomains = '';
                    $('input[name="INPUT_CACHE_PURGE_SUBDOMAINS[]"]').each(function () {
                        if ($(this).val() != '') {
                            cache_subdomains += $(this).val() + "|";
                        }
                    });
                    $('input[name="CACHE_PURGE_SUBDOMAINS"]').val(cache_subdomains);

                    var cache_purge_exclude_fid = '';
                    $('input[name="CACHE_PURGE_EXCLUDE_FID_ARR[]"]:checked').each(function () {
                        if (!$(this).is(':disabled')) {
                            if ($(this).val() !== '') {
                                cache_purge_exclude_fid += $(this).val() + "|";
                            }
                        }
                    });

                    $('input[name="CACHE_PURGE_EXCLUDE_FID"]').val(cache_purge_exclude_fid);
                } else if (cfg === 'port') {
                    // Actualizar input con lista de valores.
                    var port_plts = '';

                    var port_elements = $('[name^="portada_"]');
                    for (let i = 0;i < port_elements.length; i++) {
                        if (!$(port_elements[i]).is(':disabled')) {
                            if( ($(port_elements[i]).val() != '' && ! /^[a-zA-Z0-9_]+\.[a-zA-Z0-9_]+$/.test($(port_elements[i]).val())) ) {
                                showModalAlert({
                                    title: 'Error',
                                    type: 'blue',
                                    msg: $(port_elements[i]).val()+ " es un nombre de plantilla no válido.<br>  Debe contener sólo caracteres alfanuméricos, incluido el underscore. Además, debe tener una extensión válida.\n\n"
                                });
                                return;
                            }

                            let id = ($(port_elements[i]).attr("name")).replace(/portada_/, '');
                            var plts = '';
                            var port_paralelas_elements = $('select[name="plt_paralelas_' + id + '"] option:selected');
                            for (var j = 0; j < port_paralelas_elements.length; j++) {
                                if( ($(port_paralelas_elements[j]).val() != '' && ! /^[a-zA-Z0-9_]+\.[a-zA-Z0-9_]+$/.test($(port_paralelas_elements[j]).val())) ) {
                                    showModalAlert({
                                        title: 'Error',
                                        type: 'blue',
                                        msg: $(port_paralelas_elements[j]).val()+ " es un nombre de plantilla paralela no válido.<br>  Debe contener sólo caracteres alfanuméricos, incluido el underscore. Además, debe tener una extensión válida.\n\n"
                                    });
                                    return;
                                }
                                plts += $(port_paralelas_elements[j]).val() + ';';
                            }
                            plts = plts.substring(0, plts.length - 1);
                            var nom_port = $('input[name="nom_portada_' + id + '"]').val();
                            if (nom_port == '') {
                                nom_port = $(port_elements[i]).val();
                            }

                            nom_port = nom_port.replace(/</g, '&lt;');
                            nom_port = nom_port.replace(/>/g, '&gt;');
                            nom_port = nom_port.replace(/'/g, '&#39;');
                            nom_port = nom_port.replace(/"/g, '&quot;');
                            nom_port = nom_port.replace(/\(/g, '&#40;');
                            nom_port = nom_port.replace(/\)/g, '&#41;');
                            nom_port = nom_port.replace(/\[/g, '&#91;');
                            nom_port = nom_port.replace(/\]/g, '&#92;');
                            nom_port = nom_port.replace(/\{/g, '&#123;');
                            nom_port = nom_port.replace(/\}/g, '&#125;');
                            nom_port = nom_port.replace(/,/g, '&#44;');
                            nom_port = nom_port.replace(/\//g, '&#47;');

                            if ($(port_elements[i]).val() !== '') {
                                port_plts += $(port_elements[i]).val() + '(' + nom_port + ')(' + plts + ')|';
                            }
                        }
                    }

                    port_plts = port_plts.substring(0, port_plts.length - 1);
                    $('input[name="PORT_PLTS"]').val(port_plts);

                    var base_ports = '';
                    $('.INPUT_BASE_PORTS').each(function () {
                        if (!$(this).is(':disabled')) {
                            let re = new RegExp($(this).val());
                            if (re.test(port_plts)) {
                                base_ports += $(this).val() + "|";
                            }
                        }
                    });
                    var new_base_ports = $('#input_base_ports').val();
                    if (typeof new_base_ports !== 'undefined') {
                        new_base_ports.forEach(function (item) {
                            let re = new RegExp(item);
                            if (re.test(port_plts)) {
                                base_ports += item + "|";
                            }
                        });
                    }
                    $('input[name="BASE_PORTS"]').val(base_ports);
                } else if (cfg === 'tax') {
                    var taxport_orden = '';
                    taxport_orden = $('select[name="TAXPORT_ORDEN_TIPO"]').val() + '(' + $('select[name="TAXPORT_ORDEN_ORD"]').val() + ')';
                    $('input[name="TAXPORT_ORDEN"]').val(taxport_orden);
                } else if (cfg === 'tag') {
                    var tagport_orden = '';
                    tagport_orden = $('select[name="TAGPORT_ORDEN_TIPO"]').val() + '(' + $('select[name="TAGPORT_ORDEN_ORD"]').val() + ')';
                    $('input[name="TAGPORT_ORDEN"]').val(tagport_orden);
                } else if (cfg === 'list') {
                    var list_orden = '';
                    list_orden = $('select[name="LIST_ORDEN_TIPO"]').val() + '(' + $('select[name="LIST_ORDEN_ORD"]').val() + ')';
                    $('input[name="LIST_ORDEN"]').val(list_orden);

                    var list_plts = '';
                    var list_plts_elements = $('[name^="list_plt_"]');

                    for (let i = 0;i < list_plts_elements.length; i++) {
                        if (!$(list_plts_elements[i]).is(':disabled')) {
                            if( ($(list_plts_elements[i]).val() != '' && ! /^\w+\.\w+$/.test($(list_plts_elements[i]).val())) ) {
                                showModalAlert({
                                    title: 'Error',
                                    type: 'blue',
                                    msg: $(list_plts_elements[i]).val() + " es un nombre de plantilla no válido.<br>  Debe contener sólo caracteres alfanuméricos, incluido el underscore. Además, debe tener una extensión válida.\n\n"
                                });
                                return;
                            }
                        }

                        if ($(list_plts_elements[i]).val() != '' && !$(list_plts_elements[i]).is(':disabled')) {
                            list_plts += $(list_plts_elements[i]).val() + '|';
                        }
                    }

                    list_plts = list_plts.substring(0, list_plts.length - 1);

                    $('input[name="LIST_PLTS"]').val(list_plts);

                } else if (cfg === 'var') {
                    var multivista = '';
                    $('input[name="INPUT_MULTIVISTA[]"]').each(function () {
                        if (!$(this).is(':disabled')) {
                            if ($(this).val() !== '') {
                                multivista += $(this).val() + "|";
                            }
                        }
                    });

                    if ($('#UPDATE_SERVER_SELECT').val() == 'custom' && !$('#UPDATE_SERVER_INPUT').val().match(/^https?:\/\//i)) {
                        showModalAlert({
                            title: 'Error',
                            type: 'red',
                            msg: 'El campo UPDATE_SERVER debe ser una URL con protocolo: debe comenzar por http:// o https:// .',
                            cbBtnOK: function () {$('#UPDATE_SERVER_INPUT').focus();}
                        });
                        return false;
                    }

                    if ($('input[name="PUBLIC_SERVER_NAME"]').val().match(/^https?:\/\//i)) {
                        showModalAlert({
                            title: 'Error',
                            type: 'red',
                            msg: 'El campo PUBLIC_SERVER_NAME debe ser una URL sin protocolo: no debe comenzar por http:// o https:// .',
                            cbBtnOK: function () {$('input[name="PUBLIC_SERVER_NAME"]').focus();}
                        });

                        return false;
                    }
                    if ($('input[name="CPAN_SERVER_NAME"]').val().match(/^https?:\/\//i)) {
                        showModalAlert({
                            title: 'Error',
                            type: 'red',
                            msg: 'El campo CPAN_SERVER_NAME debe ser una URL sin protocolo: no debe comenzar por http:// o https:// .',
                            cbBtnOK: function () {$('input[name="CPAN_SERVER_NAME"]').focus();}
                        });
                        return false;
                    }

                    $('input[name="MULTIVISTA"]').val(multivista);

                    var friendly_exclude_fid = '';
                    $('input[name="FRIENDLY_EXCLUDE_FID_ARR[]"]:checked').each(function () {
                        if (!$(this).is(':disabled')) {
                            if ($(this).val() !== '') {
                                friendly_exclude_fid += $(this).val() + "|";
                            }
                        }
                    });

                    $('input[name="FRIENDLY_EXCLUDE_FID"]').val(friendly_exclude_fid);
                } else if (cfg === 'dropbox') {
                    var dropbox = '';
                    $('input[name="INPUT_DROPBOX_CUSTOM_DIR[]"]').each(function () {
                        dropbox += $(this).val() + "|";
                    });
                    $('input[name="DROPBOX_CUSTOM_DIR"]').val(dropbox);
                } else if (cfg === 'buscador') {
                    //=============
                    let prontus_dirs = '';
                    $('.INPUT_PRONTUS_DIR').each(function () {
                        if (!$(this).is(':disabled') && $(this).val() !== '') {
                            prontus_dirs += (($(this).val()).replace(/( +)|(\t)/, '')) + "|";
                        }
                    });
                    prontus_dirs = prontus_dirs.substring(0, prontus_dirs.length - 1);
                    $('input[name="PRONTUS_DIR"]').val(prontus_dirs);
                    //=============
                    let raw_dirs = '';
                    $('.INPUT_RAW_DIR').each(function () {
                        if (!$(this).is(':disabled') && $(this).val() !== '') {
                            raw_dirs += (($(this).val()).replace(/( +)|(\t)/, '')) + "|";
                        }
                    });
                    raw_dirs = raw_dirs.substring(0, raw_dirs.length - 1);
                    $('input[name="RAW_DIR"]').val(raw_dirs);
                    //=============
                    let raw_filetypes = '';
                    $('.INPUT_RAW_FILETYPES').each(function () {
                        if (!$(this).is(':disabled')) {
                            raw_filetypes += (($(this).val()).replace(/( +)|(\t)/, '')) + " ";
                        }
                    });
                    raw_filetypes = raw_filetypes.substring(0, raw_filetypes.length - 1);
                    $('input[name="RAW_FILETYPES"]').val(raw_filetypes);
                    //=============
                    let url_dirs = '';
                    $('.INPUT_URL_DIR').each(function () {
                        if (!$(this).is(':disabled') && $(this).val() !== '') {
                            url_dirs += (($(this).val()).replace(/( +)|(\t)/, '')) + "|";
                        }
                    });
                    url_dirs = url_dirs.substring(0, url_dirs.length - 1);
                    $('input[name="URL_DIR"]').val(url_dirs);
                    //=============
                    let url_scope = '';
                    $('.INPUT_URL_SCOPE').each(function () {
                        if (!$(this).is(':disabled') && $(this).val() !== '') {
                            url_scope += (($(this).val()).replace(/( +)|(\t)/, '')) + "|";
                        }
                    });
                    url_scope = url_scope.substring(0, url_scope.length - 1);
                    $('input[name="URL_SCOPE"]').val(url_scope);
                    //=============

                    let url_filetypes = '';
                    $('.INPUT_URL_FILETYPES').each(function () {
                        if (!$(this).is(':disabled')) {
                            url_filetypes += (($(this).val()).replace(/( +)|(\t)/, '')) + " ";
                        }
                    });
                    url_filetypes = url_filetypes.substring(0, url_filetypes.length - 1);
                    $('input[name="URL_FILETYPES"]').val(url_filetypes);

                    let fids = '';
                    $('input[name="INPUT_FIDS[]"]').each(function () {
                        if ($(this).is(":checked")) {
                            fids += $(this).val() + ' ';
                        }
                    });
                    fids = fids.substring(0, fids.length - 1);
                    $('input[name="FIDS"]').val(fids);

                    let textvars = '';
                    $('.INPUT_TEXTVARS').each(function () {
                        if (!$(this).is(':disabled')) {
                            textvars += (($(this).val()).replace(/( +)|(\t)/, '')) + " ";
                        }
                    });
                    textvars = textvars.substring(0, textvars.length - 1);
                    $('input[name="TEXTVARS"]').val(textvars);
                } else if (cfg === 'elasticsearch') {
                    let prontus_dirs = '';
                    $('.INPUT_PRONTUS_DIR').each(function () {
                        if (!$(this).is(':disabled') && $(this).val() !== '') {
                            prontus_dirs += (($(this).val()).replace(/( +)|(\t)/, '')) + "|";
                        }
                    });
                    prontus_dirs = prontus_dirs.substring(0, prontus_dirs.length - 1);
                    $('input[name="ELASTICSEARCH_PRONTUS_DIR"]').val(prontus_dirs);
                    //=============
                    let raw_dirs = '';
                    $('.INPUT_RAW_DIR').each(function () {
                        if (!$(this).is(':disabled') && $(this).val() !== '') {
                            raw_dirs += (($(this).val()).replace(/( +)|(\t)/, '')) + "|";
                        }
                    });
                    raw_dirs = raw_dirs.substring(0, raw_dirs.length - 1);
                    $('input[name="ELASTICSEARCH_RAW_DIR"]').val(raw_dirs);
                    //=============
                    let raw_filetypes = '';
                    $('.INPUT_RAW_FILETYPES').each(function () {
                        if (!$(this).is(':disabled')) {
                            raw_filetypes += (($(this).val()).replace(/( +)|(\t)/, '')) + " ";
                        }
                    });
                    raw_filetypes = raw_filetypes.substring(0, raw_filetypes.length - 1);
                    $('input[name="ELASTICSEARCH_RAW_FILETYPES"]').val(raw_filetypes);
                    //=============
                    let url_dirs = '';
                    $('.INPUT_URL_DIR').each(function () {
                        if (!$(this).is(':disabled') && $(this).val() !== '') {
                            url_dirs += (($(this).val()).replace(/( +)|(\t)/, '')) + "|";
                        }
                    });
                    url_dirs = url_dirs.substring(0, url_dirs.length - 1);
                    $('input[name="ELASTICSEARCH_URL_DIR"]').val(url_dirs);
                    //=============
                    let url_scope = '';
                    $('.INPUT_URL_SCOPE').each(function () {
                        if (!$(this).is(':disabled') && $(this).val() !== '') {
                            url_scope += (($(this).val()).replace(/( +)|(\t)/, '')) + "|";
                        }
                    });
                    url_scope = url_scope.substring(0, url_scope.length - 1);
                    $('input[name="ELASTICSEARCH_URL_SCOPE"]').val(url_scope);
                    //=============

                    let url_filetypes = '';
                    $('.INPUT_URL_FILETYPES').each(function () {
                        if (!$(this).is(':disabled')) {
                            url_filetypes += (($(this).val()).replace(/( +)|(\t)/, '')) + " ";
                        }
                    });
                    url_filetypes = url_filetypes.substring(0, url_filetypes.length - 1);
                    $('input[name="ELASTICSEARCH_URL_FILETYPES"]').val(url_filetypes);

                    let fids = '';
                    $('input[name="ELASTICSEARCH_INPUT_FIDS[]"]').each(function () {
                        if ($(this).is(":checked")) {
                            fids += $(this).val() + ' ';
                        }
                    });
                    fids = fids.substring(0, fids.length - 1);
                    $('input[name="ELASTICSEARCH_FIDS"]').val(fids);

                    let textvars = '';
                    $('.INPUT_TEXTVARS').each(function (i, item) {
                        var boosts = $('.INPUT_TEXTVARS_BOOST');
                        if (!$(this).is(':disabled') && ($(this).val()).trim() != '') {
                            textvars += (($(this).val()).replace(/( +)|(\t)/, '')) + ":" + $(boosts[i]).val().replace(/( +)|(\t)/, '') + " ";
                        }
                    });
                    textvars = textvars.substring(0, textvars.length - 1);
                    $('input[name="ELASTICSEARCH_TEXTVARS"]').val(textvars);
                }
                configAjax.redirURL = '_self';
                SubmitForm.submitGenericAjax(configAjax, optsAjax);
            }
        });
    },

    // Duplicar, utilizando el primero elemento como plantilla.
    agregarPortada: function () {
        var obj = $('#plt_new_port').clone();
        $(obj).attr("id", "");
        $(obj).find('.botones').remove();
        var id = '';
        var new_id = '';

        if (Cfgedit.newPortLastId == 0) {
            id = $(obj).find('select[name^="portada_"]').attr("name");
            new_id = id.replace("portada_", "");
            new_id = parseInt(new_id);
            new_id = new_id + 1;
            Cfgedit.newPortLastId = new_id;
        } else {
            id = Cfgedit.newPortLastId;
            new_id = id + 1;
            Cfgedit.newPortLastId = new_id;
        }


        $(obj).find('select[name^="portada_"]').attr("name", "portada_" + new_id);
        $(obj).find('select[id^="portada_"]').attr("id", "portada_" + new_id);
        $(obj).find('input[name^="nom_portada_"]').attr("name", "nom_portada_" + new_id);
        $(obj).find('input[name^="nom_portada_"]').val('');
        $(obj).find('select[name^="plt_paralelas_"]').attr("name", "plt_paralelas_" + new_id);
        $(obj).find('select[id^="plt_paralelas_"]').attr("id", "plt_paralelas_" + new_id);
        $(obj).find('.selmultiple').attr("onclick", "Cfgedit.toggleCombo(this, 'plt_paralelas_" + new_id + "');");
        $(obj).find('select[name^="portada_"]').attr("onchange", "Cfgedit.setPortNom(this.value, '" + new_id + "');");
        $(obj).insertAfter("#plt_new_port");
    },

    agregarMv: function () {
        var html = '<div class="pad-top-bot5 row rowfix"><div class="col-xs-24 col-sm-16 col-md-14"><input name="INPUT_MULTIVISTA[]" class="h30px noradius pad-top-bot4 form-control" value=""></div><div class="col-xs-24 col-sm-8 col-md-10">&nbsp;</div>';
        $('#multivista_listado').append(html);
    },

    agregarRawDir: function () {
        var html = '<div class="row rowfix"><div class="col-xs-24 col-sm-16 col-md-16"><input class="form-control INPUT_RAW_DIR" value=""></div><div class="col-xs-24 col-sm-8 col-md-8"></div></div>';
        $('#rawdir_listado').append(html);
    },

    agregarProntusDir: function () {
        var html = '<div class="row rowfix"><div class="col-xs-24 col-sm-16 col-md-16"><input class="form-control INPUT_PRONTUS_DIR" value=""></div><div class="col-xs-24 col-sm-8 col-md-8"></div></div>';
        $('#prontusdir_listado').append(html);
    },

    agregarUrlDir: function () {
        var html = '<div class="row rowfix"><div class="col-xs-24 col-sm-16 col-md-16"><input class="form-control INPUT_URL_DIR" value=""></div><div class="col-xs-24 col-sm-8 col-md-8"></div></div>';
        $('#urldir_listado').append(html);
    },

    agregarUrlScope: function () {
        var html = '<div class="row rowfix"><div class="col-xs-24 col-sm-16 col-md-16"><input class="form-control INPUT_URL_SCOPE" value=""></div><div class="col-xs-24 col-sm-8 col-md-8"></div></div>';
        $('#urlscope_listado').append(html);
    },

    agregarRawftype: function () {
        var html = '<div class="row rowfix"><div class="col-xs-24 col-sm-16 col-md-16"><input class="form-control INPUT_RAW_FILETYPES" value=""></div><div class="col-xs-24 col-sm-8 col-md-8"></div></div>';
        $('#rawftype_listado').append(html);
    },

    agregarUrlftype: function () {
        var html = '<div class="row rowfix"><div class="col-xs-24 col-sm-16 col-md-16"><input class="form-control INPUT_URL_FILETYPES" value=""></div><div class="col-xs-24 col-sm-8 col-md-8"></div></div>';
        $('#urlftype_listado').append(html);
    },

    agregarTextvar: function () {
        var html = '<div class="row rowfix"><div class="col-xs-24 col-sm-16 col-md-16"><input class="form-control INPUT_TEXTVARS" value=""></div><div class="col-xs-24 col-sm-8 col-md-8"></div></div>';
        $('#textvars_listado').append(html);
    },
    agregarESTextvar: function () {
        var html = '<div class="row rowfix"><div class="col-xs-24 col-sm-14 col-md-14"><input class="form-control INPUT_TEXTVARS" type="text" value=""></div><div class="col-xs-24 col-sm-4 col-md-4"><input class="form-control INPUT_TEXTVARS_BOOST" value="" type="number" min=1 max=5></div><div class="col-xs-24 col-sm-6 col-md-6"></div></div>';
        $('#textvars_listado').append(html);
    },

    // agrega inputs de servidores (IP o dominio) a la lista de servidores en conf_cache
    agregarServidorCache: function () {
        var html = '<input name="INPUT_CACHE_SERVER_NAME[]" class="form-control" value="">';
        $('#cache_list').append(html);
    },

    // agrega inputs de subdominio a la lista de subdominios en conf_cache
    agregarSubdomain: function () {
        var html = '<input name="INPUT_CACHE_PURGE_SUBDOMAINS[]" class="form-control" value="">';
        $('#cache_purge_subdomains_list').append(html);
    },

    agregarDropboxCustomdir: function () {
        var html = '<input name="INPUT_DROPBOX_CUSTOM_DIR[]" class="form-control" value="">';
        $('#dropbox_customdir').append(html);
    },

    mostrarPermitidos: function () {
        $('input[name="UPLOADS_PERMITIDOS"]').toggle();
    },

    quitarFid: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('input[id="nombrefid_' + id + '"]').attr("disabled", "disabled").addClass('disabled-field');
            $('input[id="fids_contenido_' + id + '"]').attr("disabled", "disabled").addClass('disabled-field');
            $('input[id="fids_calendar_' + id + '"]').attr("disabled", "disabled").addClass('disabled-field');
            $('input[id="archivofid_' + id + '"]').attr("disabled", "disabled").addClass('disabled-field');
            $('select[id="plantillasfid_' + id + '"]').attr("disabled", "disabled").addClass('disabled-field');
            $('select[id="plantillasfid_pla_' + id + '"]').attr("disabled", "disabled").addClass('disabled-field');

        } else {
            $('input[id="nombrefid_' + id + '"]').removeAttr("disabled").removeClass('disabled-field');
            $('input[id="fids_contenido_' + id + '"]').removeAttr("disabled").removeClass('disabled-field');
            $('input[id="fids_calendar_' + id + '"]').removeAttr("disabled").removeClass('disabled-field');
            $('input[id="archivofid_' + id + '"]').removeAttr("disabled").removeClass('disabled-field');
            $('select[id="plantillasfid_' + id + '"]').removeAttr("disabled").removeClass('disabled-field');
            $('select[id="plantillasfid_pla_' + id + '"]').removeAttr("disabled").removeClass('disabled-field');
        }
    },

    quitarPortada: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('input[name="nom_portada_' + id + '"]').attr("disabled", "disabled").addClass('disabled-field');
            $('input[name="portada_' + id + '"]').attr("disabled", "disabled").addClass('disabled-field');
            $('select[name="plt_paralelas_' + id + '"]').attr("disabled", "disabled").addClass('disabled-field');
            $('#urlf5_port_url' + id).attr("readonly", "readonly").addClass('disabled-field');
            $('#urlf5_port_remove' + id).val('s');
        } else {
            $('input[name="nom_portada_' + id + '"]').removeAttr("disabled").removeClass('disabled-field');
            $('input[name="portada_' + id + '"]').removeAttr("disabled").removeClass('disabled-field');
            $('select[name="plt_paralelas_' + id + '"]').removeAttr("disabled").removeClass('disabled-field');
            $('#urlf5_port_url' + id).removeAttr("readonly").removeClass('disabled-field');
            $('#urlf5_port_remove' + id).val('n');
        }
    },

    quitarBaseport: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#baseport_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#baseport_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },

    quitarMV: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#mv_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#mv_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },

    quitarProntusDir: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#prontusdir_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#prontusdir_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },

    quitarRawDir: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#rawdir_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#rawdir_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },

    quitarUrlDir: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#urldir_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#urldir_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },

    quitarUrlScope: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#urlscope_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#urlscope_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },

    quitarRawftype: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#rawftype_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#rawftype_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },

    quitarUrlftype: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#urlftype_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#urlftype_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },

    quitarTextvar: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#textvar_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#textvar_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },
    quitarESTextvar: function (obj, id) {
        if ($(obj).is(':checked')) {
            // Deshabilitar inputs, para que no sean enviados en el formulario.
            $('#elasticsearch_textvar_' + id).attr("disabled", "disabled").addClass('disabled-field');
        } else {
            $('#elasticsearch_textvar_' + id).removeAttr("disabled").removeClass('disabled-field');
        }
    },

    // Cambia de multiple a single y viceversa.
    toggleCombo: function (obj, id) {
        var obj_sel = $('select[name="' + id + '"]');
        if ($(obj_sel).attr("multiple")) {
            // Es multiple, convertirlo en "single"
            $(obj_sel).removeAttr("multiple");

            $(obj).attr("src", (($(obj).attr("src")).replace('men_of', 'mas_of')));
        } else {
            $(obj_sel).attr("multiple", "multiple");

            $(obj).attr("src", (($(obj).attr("src")).replace('mas_of', 'men_of')));
        }
    },

    toggleMultiedicion: function () {
        if ($('#tr_multiedicion').is(':visible')) {
            $('#tr_multiedicion').hide();
            // Desactivar inputs para sacarlos del cfg.
            $('input[name="INPUT_BASE_PORTS[]"]').attr("disabled", "disabled");
        } else {
            $('#tr_multiedicion').show();
            $('input[name="INPUT_BASE_PORTS[]"]').removeAttr("disabled");
        }
    },

    comentEnviarPub: function () {
        if ($('.enviar_publicacion').is(':visible')) {
            $('.enviar_publicacion').hide();
            $('input[name="MAIL_PUBLICACION_ASUNTO"]').attr("disabled", "disabled");
            $('input[name="MAIL_PUBLICACION_FROM"]').attr("disabled", "disabled");
            $('input[name="MAIL_PUBLICACION_SMTP"]').attr("disabled", "disabled");
        } else {
            $('.enviar_publicacion').show();
            $('input[name="MAIL_PUBLICACION_ASUNTO"]').removeAttr("disabled");
            $('input[name="MAIL_PUBLICACION_FROM"]').removeAttr("disabled");
            $('input[name="MAIL_PUBLICACION_SMTP"]').removeAttr("disabled");
        }
    },

    setPortNom: function (value, id) {
        $('input[name="nom_portada_' + id + '"]').val(value);
    },

    cloudFlarePurgeAll: function () {
        var msg = '¿Estás seguro? Esta operación no se puede revertir ni detener.';

        showModalConfirm({
            'title': 'Ejecutar Purge',
            'msg': msg,
            type: "orange",
            icon: "glyphicon glyphicon-exclamation-sign",
            btnClassOk: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextyellow nextyellow',
            okTitle: 'Ejecutar purge de urls',
            cbBtnOK: function () {
                $.ajax({
                    url: '/cgi-cpn/prontus_cloudflare_purge.cgi',
                    data: {
                        purge_all: '1',
                        _prontus_id: Admin.prontus_id
                    },
                    type: 'POST',
                    dataType: 'json',
                    success: function (json) {
                        if (typeof json.status !== 'undefined') {
                            if (json.status === 1) {
                                showModalAlert({
                                    title: 'Resultado',
                                    type: 'green',
                                    msg: 'Se inició el proceso de limpieza. Esto puede tardar varios minutos en completarse.'
                                });
                            } else {
                                showModalAlert({
                                    title: 'Error',
                                    type: 'red',
                                    msg: json.msg
                                });

                            }
                        }
                    },

                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        SubmitForm.handleError('prontus_cloudflare_purge.cgi', XMLHttpRequest, textStatus, errorThrown);
                    }
                });
            }
        });
    },

    cloudFlarePurgeFiles: function () {
        var msg = '¿Estás seguro? Esta operación no se puede revertir ni detener.';
        var purge_files = $('#purge_files').val();

        if (!purge_files) {
            showModalAlert({
                title: 'Error',
                type: 'red',
                msg: "La lista de archivos está vacía."
            });
            return;
        }
        showModalConfirm({
            'title': 'Purge Cache',
            'msg': msg,
            type: "orange",
            icon: "glyphicon glyphicon-exclamation-sign",
            btnClassOk: 'hovwhite radius15 noborder txtnextwhite pad-top-bot7 pad-lef-rig20 int-nextyellow nextyellow',
            okTitle: 'Ejecutar purge en Cache de contenido',
            cbBtnOK: function () {
                $.ajax({
                    url: '/cgi-cpn/prontus_cloudflare_purge.cgi',
                    data: {
                        purge_files: purge_files,
                        _prontus_id: Admin.prontus_id
                    },
                    type: 'POST',
                    dataType: 'json',
                    success: function (json) {
                        if (typeof json.status !== 'undefined') {
                            if (json.status === 1) {
                                showModalAlert({
                                    title: 'En proceso',
                                    type: 'green',
                                    msg: "Se inició el proceso de limpieza. Esto puede tardar unos minutos en completarse."
                                });
                            } else {
                                showModalAlert({
                                    title: 'Error',
                                    type: 'red',
                                    msg: json.msg
                                });
                            }
                        }
                    },

                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        SubmitForm.handleError('prontus_cloudflare_purge.cgi', XMLHttpRequest, textStatus, errorThrown);
                    }
                });
            }
        });
    }
};
