var UrlF5 = {
    timeout: 0,
    ajax_request: null,
    init: function () {
        UrlF5.methods.bindEvents();
    },
    methods:  {
        bindEvents: function () {
            $('.urlf5-input').off('keyup').on('keyup', function () {
                this.value = this.value.replace(/[^a-zA-Z0-9\-\/_.]+/g, '');
                var url = this.value;
                clearTimeout(UrlF5.timeout);
                if (UrlF5.ajax_request != null) {
                    UrlF5.ajax_request.abort();
                }
                var urlf5_number = $(this).attr("data-urlf5-number");
                // setea time out para mejorar usabilidad
                var old_url_input = $('#urlf5_port_old_url' + urlf5_number);
                UrlF5.timeout = setTimeout(UrlF5.actions.checkUrl, 1000, url, $(this), old_url_input);
            });

            $('.urlf5-guardar').off('click').on('click', 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");

                UrlF5.actions.guardarUrl(input_id, urlf5_type, urlf5_subtype, urlf5_subtype_id, urlf5_file);
            });

            $('.urlf5-borrar').off('click').on('click', 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);
                    }
                });
            });

            $('.urlf5-open').off('click').on('click', function (e) {
                e.preventDefault();
                e.stopPropagation();

                var input_id = $(this).attr("data-input-id");
                var urlf5_file = $(this).attr("data-urlf5-file");
                var friendly = $('#' + input_id).val();

                if (friendly) {
                    let type = input_id.substring(0, 13);
                    if (type == 'urlf5_tax_url' || type == 'urlf5_tag_url') {
                        friendly = friendly +'/p/1';
                    }
                    window.open(Admin.publicHost + friendly);
                } else {
                    window.open(Admin.publicHost + urlf5_file);
                }
            });
        },
        showInputHelp: function ($parent, msg, style) {
            var $elem = $parent.find('.urlf5-input-help');

            $elem.removeClass('text-danger text-success text-warning');
            $elem.html(msg);
            if (style != '') {
                $elem.addClass('text-' + style);
            }

            var $input = $parent.find('input');

            if (style == 'danger') {
                $input.addClass('input-danger');
            } else {
                $input.removeClass('input-danger');
            }
        },
        removeInputHelp: function ($parent) {
            var $elem = $parent.find('.urlf5-input-help');

            $elem.removeClass('text-danger text-success text-warning');
            $elem.text('');

            var $input = $parent.find('input');
            $input.removeClass('input-danger');
        },
        validUrl: function (url) {
            return /^[a-zA-Z0-9_\-\/\.]+$/.test(url);
        },
        checkFriendlyUrl: function (url, type, callback) {
            var data = {
                url: url,
                _prontus_id: Admin.prontus_id,
                type: type
            };

            UrlF5.ajax_request = $.ajax({
                url: '/' + Admin.dir_cgi_cpn + '/prontus_check_friendly.cgi',
                type: 'POST',
                dataType: 'json',
                data: data,
                beforeSend: function () {
                    if (UrlF5.ajax_request != null) {
                        UrlF5.ajax_request.abort();
                    }
                },
                success: function (response) {
                    if (response.status == 0) {
                        showModalAlert({
                            title: 'Error',
                            type: 'red',
                            msg: response.msg
                        });
                    } else {
                        callback(response);
                    }
                },
                error: function(_xhr, _ajaxOptions, thrownError) {
                    if (thrownError != 'abort') {
                        showModalAlert({
                            title: 'Error',
                            type: 'red',
                            msg: thrownError
                        });
                    }
                }
            });

        },
    },
    actions: {
        editUrlTax: function(e){
            e.preventDefault();
            e.stopPropagation();
            var tipo = $(this).data('tipo');
            var id = $(this).data('elid');
            var url = '/' + Admin.dir_cgi_cpn + '/urlf5/prontus_urlf5_tax_ficha.cgi?_prontus_id=' + Admin.prontus_id + '&_entidad=' + tipo + '&_id=' + id;

            $('#modal_f5_content').load(url, function (responseText, textStatus) {
                if (textStatus == 'error') {
                    showModalAlert({
                        title: 'Error de servidor',
                        type: 'red',
                        msg: responseText
                    });
                } else {
                    $('#modal_f5').modal();
                    UrlF5.init();
                }
            });
        },
        editUrlTag: function(e) {
            e.preventDefault();
            e.stopPropagation();
            var id = $(this).data('elid');
            var url = '/' + Admin.dir_cgi_cpn + '/urlf5/prontus_urlf5_tag_ficha.cgi?_prontus_id=' + Admin.prontus_id + '&_id=' + id;

            $('#modal_f5_content').load(url, function (responseText, textStatus) {
                if (textStatus == 'error') {
                    showModalAlert({
                        title: 'Error de servidor',
                        type: 'red',
                        msg: responseText
                    });
                } else {
                    $('#modal_f5').modal();
                    UrlF5.init();
                }
            });
        },
        checkUrl: function (url, $input, old_url_input) {
            url = url.replace(/\/$/, "");
            var $parent = $input.parent();
            var old_url = old_url_input.val();

            if (url) {
                if (url.substring(0, 1) != '/') {
                    url = '/' + url;
                    $input.val(url);
                }

                if (UrlF5.methods.validUrl(url)) {
                    UrlF5.methods.removeInputHelp($parent);
                    UrlF5.methods.showInputHelp($parent, '<img src="/prontus/cpan/imag/loading.gif" alt="loading..." height="17"/>', '');

                    let type = $input.attr("data-urlf5-type");
                    if (typeof type === 'undefined') {
                        type = '';
                    }

                    UrlF5.methods.checkFriendlyUrl(url, type, function (response) {
                        if (response.res > 0) {
                            // Existe o no se puede crear
                            if (old_url != '' && old_url == url) {
                                UrlF5.methods.removeInputHelp($parent);
                            } else {
                                UrlF5.methods.showInputHelp($parent, 'No se puede crear la url. ' + response.msg, 'warning');
                            }
                        } else {
                            if (response.prefix != '') {
                                let msg = 'La URL es correcta y se puede usar.';
                                if (type == '') {
                                    msg = msg + '(<span class="glyphicon glyphicon-exclamation-sign"></span> Prefijo de url activado. Todas las url comenzarán con "' + response.prefix + '" ).';
                                }
                                UrlF5.methods.showInputHelp($parent, msg, 'success');
                            } else {
                                UrlF5.methods.showInputHelp($parent, 'La URL es correcta y se puede usar.', 'success');
                            }
                            $input.val(response.url);
                        }
                    });
                } else {
                    UrlF5.methods.showInputHelp($parent, 'La URL no es válida.', 'danger')
                }
            } else {
                UrlF5.methods.removeInputHelp($parent);
            }
        },
        borrarUrl: function (input_id, urlf5_type, urlf5_subtype, urlf5_subtype_id, urlf5_file) {
            var $parent = $('#' + input_id).parent();
            var url = $('#' + input_id).val();
            var data = {
                url: url,
                type: urlf5_type,
                file: urlf5_file,
                subtype: urlf5_subtype,
                subtype_id: urlf5_subtype_id,
                _prontus_id: Admin.prontus_id
            };

            $.ajax({
                url: '/' + Admin.dir_cgi_cpn + '/urlf5/prontus_urlf5_borrar.cgi',
                type: 'POST',
                dataType: 'json',
                data: data,
                success: function (response) {
                    if (response.status == 1) {
                        showModalAlert({
                            title: 'URL borrada correctamente',
                            type: 'green',
                            msg: "La URL [" + url + "] fue eliminada con éxito."
                        });
                        UrlF5.methods.removeInputHelp($parent);
                        $('#' + input_id).val('');
                        if (typeof UrlAdmin !== "undefined") {
                            UrlAdmin.getList();
                        }
                    } else {
                        showModalAlert({
                            title: 'Error',
                            type: 'red',
                            msg: response.msg
                        });
                    }
                },
                error: function(_xhr, _ajaxOptions, thrownError) {
                    showModalAlert({
                        title: 'Error',
                        type: 'red',
                        msg: thrownError
                    });
                }
            });
        },
        guardarUrl: function (input_id, urlf5_type, urlf5_subtype, urlf5_subtype_id, urlf5_file, urlf5_url) {
            var $parent = $('#' + input_id).parent();
            var url = $('#' + input_id).val();
            var data = {
                type: urlf5_type,
                subtype: urlf5_subtype,
                subtype_id: urlf5_subtype_id,
                url: url,
                file: urlf5_file,
                _prontus_id: Admin.prontus_id
            };

            $.ajax({
                url: '/' + Admin.dir_cgi_cpn + '/urlf5/prontus_urlf5_guardar.cgi',
                type: 'POST',
                dataType: 'json',
                data: data,
                success: function (response) {
                    if (response.status == 1) {
                        showModalAlert({
                            title: 'URL guardada',
                            type: 'green',
                            msg: "La URL [" + url + "] fue guardada con éxito."
                        });
                        if (document.getElementById('urlf5_port_old_url' + input_id.substring(14)) != null) {
                            document.getElementById('urlf5_port_old_url' + input_id.substring(14)).value = url;
                        }
                        document.getElementById(input_id).value = url;
                        UrlF5.methods.removeInputHelp($parent);
                        if (typeof UrlAdmin !== "undefined") {
                            UrlAdmin.getList();
                        }
                    } else {
                        showModalAlert({
                            title: 'Error',
                            type: 'red',
                            msg: response.msg
                        });
                    }
                },
                error: function(_xhr, _ajaxOptions, thrownError) {
                    showModalAlert({
                        title: 'Error',
                        type: 'red',
                        msg: thrownError
                    });
                }
            });

        }
    }
};

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