var Login = {
    dir_cgi_cpan: '',
    prontus_id: '',
    two_fa_enabled: false,
    updating: false,

    // -------------------------------------------------------------------------
    init: function() {
        Login.dir_cgi_cpan = Admin.dir_cgi_cpn;
        Login.prontus_id = document.getElementById('_prontus_id').value

        $('#_usr').on('blur', function () {
            Login.validaUsr();
        });
        $('#_psw').on('blur', function () {
            Login.validaPwd();
        });

        $('#FrmLogin').submit(function() {
            Login.doLogin();
            return false;
        });
        $('#login-forgotten').on('click', function() {
            document.location = '/' + Login.dir_cgi_cpan + '/prontus_olvidopass.cgi?_prontus_id=' + window.document.FrmLogin._prontus_id.value;
            return false;
        });
        if (Login.updating) {
            $('#modal-loading .modal-title').html('Actualizando Prontus');
            $('#modal-loading-mensaje').html('Realizando tareas posteriores a la actualización: 0%');
            $('#modal-loading').modal({backdrop: 'static', keyboard: false});
            Login.checkUpdateStatus();
        } else {
            Login.getSSOList();
        }
    },
    // -------------------------------------------------------------------------
    doLogin: function() {
        if (!Login.validaUsr()) {
            return false;
        }
        if (!Login.validaPwd()) {
            return false;
        }

        if (Login.two_fa_enabled && !Login.validaCode()) {
            return false;
        }

        var configAjax = {
            formSelector: '#FrmLogin',
            actionURL: '/' + Login.dir_cgi_cpan + '/prontus_login.cgi',
            method: 'post'
        };

        var optsAjax = {
            success:   function(json, statusText) {
                if(json === null) {
                    return;
                }
                if (json.status=='2') {    // buffer html
                    $('body').html(json.msg);
                    $('.boton-ingresar').show();
                    Login.hideLoadingModal();
                } else if (json.status=='1') {
                    Login.goToProntus();
                } else if (json.status=='3') {
                    Login.hideLoadingModal();
                    Login.two_fa_enabled = true;

                    $('.boton-ingresar').show();
                    $('#prontus-2fa').show();
                    $('#_2fa_code').removeAttr("disabled");
                    $('#_2fa_token').removeAttr("disabled");
                    document.getElementById('_2fa_token').value = json.token;

                    $('#login-alert span.msg').html(unescape(json.msg));
                    $('#login-alert').show();

                    $('#_2fa_code').focus();
                    $('#_2fa_code').on('blur', function () {
                        Login.validaCode();
                    });
                } else  {
                    $('#login-alert span.msg').html(unescape(json.msg));
                    $('#login-alert').show();
                    $('.boton-ingresar').show();
                    Login.hideLoadingModal();
                }
            }, // success
            complete: function(XMLHttpRequest, textStatus) {
                if (textStatus != 'success') {
                    $('.boton-ingresar').show();
                    Login.hideLoadingModal();
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                SubmitForm.handleError(configAjax.actionURL, XMLHttpRequest, textStatus, errorThrown);
            }
        }
        $('.boton-ingresar').hide();
        Login.showLoadingModal();
        SubmitForm.submitGenericAjax(configAjax, optsAjax);
    },
    // -------------------------------------------------------------------------
    validaCode: function () {
        if ($('#_2fa_code').val() == '') {
            $('#_2fa_code').focus();
            return false;
        }
        return true;
    },
    // -------------------------------------------------------------------------
    validaUsr: function () {
        if ($('#_usr').val() == '') {
            $('#login-alert').show();
            $('#login-alert span.msg').html('Ingresa usuario');
            $('#login-alert span.sr-only').html('Ingresa usuario');
            return false;
        }
        return true;
    },
    // -------------------------------------------------------------------------
    validaPwd: function () {
        if ($('#_psw').val() == '') {
            $('#login-alert').show();
            $('#login-alert span.msg').html('Ingresa contraseña');
            $('#login-alert span.sr-only').html('Ingresa contraseña');
            return false;
        }
        return true;
    },
    // -------------------------------------------------------------------------
    checkSession: function () {
        $.ajax({
            type: "GET",
            url: '/' + Login.dir_cgi_cpan + '/prontus_check_session.cgi',
            data: "_prontus_id=" + window.document.FrmLogin._prontus_id.value,
            success: function (data) {
                if (data.status == '1') {
                    if (data.session == '1') {
                        Login.goToProntus();
                    } else {
                        $('#checkSession').hide();
                        $('#loginbox').show();
                    }
                } else {
                    $('#login-alert').show();
                    $('#login-alert span.msg').html(data.msg);
                    $('#login-alert span.sr-only').html(data.msg);
                    $('#loginbox').show();
                    $('#checkSession').hide();
                    showModalAlert({
                        title: 'Prontus ha encontrado un error',
                        type: 'red',
                        msg: data.msg + "<br><br>Es posible que Prontus no funcione correctamente si no se soluciona"
                    });
                }
            }
        });
    },
    // -------------------------------------------------------------------------
    getSSOList: function () {
        $.ajax({
            type: "GET",
            url: '/' + Login.dir_cgi_cpan + '/prontus_sso_get_list.cgi',
            data: "_prontus_id=" + window.document.FrmLogin._prontus_id.value,
            success: function (data) {
                if (data.status) {
                    var combo = document.getElementById('prontus-sso-select');
                    for (var i in data.prontus_list) {
                        combo.appendChild(new Option(data.prontus_list[i],data.prontus_list[i], data.prontus_list[i] == Login.prontus_id, data.prontus_list[i] == Login.prontus_id));
                    }
                    $('#prontus-sso-select').on('blur', Login.updateProntusID);
                    $('#prontus-sso').show();
                } else {
                    $('#prontus-sso').remove();
                }
            },
            error: function() {
                document.getElementById('prontus-sso').remove();
            },
            complete: function() {
                Login.checkSession();
            }
        });
    },
    // -------------------------------------------------------------------------
    updateProntusID: function() {
        var prontus = document.getElementById('prontus-sso-select').value;
        Login.prontus_id = prontus;
        document.getElementById('_prontus_id').value = prontus;
    },
    // -------------------------------------------------------------------------
    goToProntus: function() {
        window.location.href = '/' + Login.dir_cgi_cpan + '/prontus_port_admin.cgi' + "?_prontus_id=" + document.getElementById('_prontus_id').value;
    },
    showLoadingModal: function() {
        $('#modal-loading .modal-title').html('Ingresando a Prontus');
        $('#modal-loading-mensaje').html('Por favor espere...');
        $('#modal-loading').modal({backdrop: 'static', keyboard: false});
    },
    hideLoadingModal: function() {
        $('#modal-loading').modal('hide');
    },
    checkUpdateStatus: function() {
        var status_url = '/prontus/cpan/data/prontus_updated.json';
        $.ajax({
            url: status_url,
            dataType: 'json',
            cache: false,
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                Admin.counterError++;
                if (Admin.counterError >= Admin.maxErrorCounter) {
                    SubmitForm.handleError(status_url, XMLHttpRequest, textStatus, errorThrown);
                    $('#modal-loading').modal('hide');
                } else {
                    setTimeout(Login.checkUpdateStatus, 1000);
                }
            },
            success: function(data, textStatus) {
                Admin.counterError = 0;
                if (data.status == 1) {
                    if (data.progress < 100) {
                        $('#modal-loading-mensaje').html('Realizando tareas posteriores a la actualización: '+data.progress+'%');
                        setTimeout(Login.checkUpdateStatus, 1000);
                    } else {
                        Login.hideLoadingModal();
                        Login.getSSOList();
                    }
                } else if (data.status == 0) {
                    Login.hideLoadingModal();
                    Login.getSSOList();
                    showModalAlert({
                        title: 'Ha ocurrido un error durante el proceso de actualización',
                        type: 'red',
                        msg: data.msg + "<br><br>Es posible que Prontus no funcione correctamente si no se soluciona"
                    });
                } else {
                    setTimeout(Login.checkUpdateStatus, 1000);
                }
            }
        });

    }
};

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