function validateNumbers(e) {
    var key = (document.all) ? e.keyCode : e.which;
    if (key === 8) return true;
    if (e.ctrlKey && key === 86) return true; //Ctrl v
    if (e.ctrlKey && key === 67) return true; //Ctrl c
    if (e.ctrlKey && key === 88) return true; //Ctrl x
    if (key < 58 && key > 47) return true;

    var patron = /\d/;
    var te = String.fromCharCode(key);
    return patron.test(te);
    // patron = /\d/; // Solo acepta números
    // patron = /\w/; // Acepta números y letras
    // patron = /\D/; // No acepta números
}

function validateLetter(e) {
    var key = (document.all) ? e.keyCode : e.which;
    if (key === 8) return true; // backspace
    if (key === 32) return true; // espacio
    if (e.ctrlKey && key === 86) return true;//Ctrl v
    if (e.ctrlKey && key === 67) return true;//Ctrl c
    if (e.ctrlKey && key === 88) return true;//Ctrl x

    var patron = /[a-zA-Z]/; //patron
    var te = String.fromCharCode(key);
    return patron.test(te);
}

function validateLetterNumbers(e) { // 1
    var key = (document.all) ? e.keyCode : e.which;
    if (key === 8) return true;
    var patron = /\w/;
    var te = String.fromCharCode(key);
    return patron.test(te);
}

if ($('.select')[0]) {
    $('.select').select2({
        language: "es"
    });
}

if ($('.date-picker')[0]) {
    // console.log("picker");
    $('.date-picker').datepicker({
        locale: "es",
        format: 'dd-mm-yyyy'
    });
}
$(document).on('keypress', '.onlyNumbers', function (e) {
    return validateNumbers(e);
});

$(document).on('keypress', '.onlyLetters', function (e) {
    return validateLetter(e);
});

$(document).on('keypress', '.onlyLettersNumbers', function (e) {
    return validateLetterNumbers(e);
});

function tablaListadoDataTable(id_tabla) {
    var tabla_id = id_tabla || "tablaListado";
    var tableId = $('#' + tabla_id);
    tableId.dataTable({
        "language": {
            "sSearch": "",
            "searchPlaceholder": "Buscar...",
            "sLengthMenu": 'Mostrando <select class="form-control input-sm">' +
            '<option value="5">5</option>' +
            '<option value="10">10</option>' +
            '<option value="20">20</option>' +
            '<option value="30">30</option>' +
            '<option value="40">40</option>' +
            '<option value="50">50</option>' +
            '<option value="-1">Todos</option>' +
            '</select> registros',
            "oPaginate": {
                "sFirst": "<i class='fa fa-angle-double-left'></i>",
                "sLast": "<i class='fa fa-angle-double-right'></i>",
                "sNext": "<i class='fa fa-angle-right'></i>",
                "sPrevious": "<i class='fa fa-angle-left'></i>"
            },
            "sInfoEmpty": "0 registros que mostrar",
            "sInfoFiltered": " ",
            "sZeroRecords": "<div class='text-center'><i class='zmdi zmdi-mood-bad zmdi-hc-5x'></i><h3>No hay registro que mostrar</h3></div>",
            "sLoadingRecords": "Por favor espere - cargando...",
            "sInfo": "Mostrando _START_ de _END_ registros, Total _TOTAL_ registros"
        }
    });
    var table = tableId.DataTable();
    $('#' + tabla_id + ' tfoot th').each(function () {
        var title = $('#' + tabla_id + ' thead tr.th-head-inputs th').eq($(this).index()).text();
        $(this).html('<input type="text" placeholder="' + title + '" />');
    });
    table.columns().eq(0).each(function (colIdx) {
        $('input', table.column(colIdx).footer()).on('keyup change', function () {
            table.column(colIdx).search(this.value).draw();
        });
    });
}

$(document).on('click', '[data-target=#openModal]', function (e) {
    e.preventDefault();
    var target = $(this).attr("href");
    var small = $(this).data('tamanio');
    var category = (typeof $(this).data('categoria') === "undefined") ? "" : $(this).data('categoria');

    if (target.indexOf('#') === 0) {
        $(target).modal('open');
    } else {
        $.get(target, function (data) {
            $('<div class="modal fade mimodalpe ' + category + '" data-backdrop="static" data-keyboard="false"><div class="modal-dialog modal-darkorange modal-' + small + '"><div class="modal-content">' + data + '</div></div></div>').modal();
        }).success(function () {

        });
    }
});

// $(document).on('change', "#role_id", function () {
//     $('input:checkbox').removeAttr('checked');
//     if (this.value !== "") {
//         var id = parseInt(this.value);
//         loadRol(id);
//     }
// });
//
// function loadRol(id) {
//     $.ajax({
//         url: LA.base_url + 'admin/ajax/modulerole/' + id,
//         type: 'POST',
//         headers: {'X-CSRF-Token': $("input[name=_token]").val()},
//         dataType: 'json',
//         beforeSend: function () {
//         },
//         success: function (response) {
//             // console.log("data_: ", response.data);
//             $.each(response.data, function (key, value) {
//                 // console.log("response[" + key + "] = ", value.permission);
//                 var permissions = value.permisos.split(',');
//                 // console.log("permissions", permissions);
//                 $.each(permissions, function (keyp, permission) {
//                     // console.log(parseInt(value.sub_module_id) + "_" + parseInt(permission));
//                     $('#' + parseInt(value.sub_module_id) + "_" + parseInt(permission)).val(permission).attr('checked', true).click();
//                 });
//             });
//         },
//         error: function (err) {
//             console.log("show_error_: ", err.responseText);
//         }
//     });
// }

function message_pass(text_) {
    $("#password").focus();
    $('.message_').text(text_);
    $('.alert-password').removeClass('d-none');
}

$(document).on('click', '.btn-envio-cumpleanios', function () {
    var form_ = $("#form-cumpleanio");
    var id = $("#persona_id").val();
    var url = LA.base_url + 'superadmin/cumpleanios/cumpleanio/' + id;
    swal({
        title: "Saludo de cumpleaño...",
        html: "¿Está seguro de enviar saludo de cumpleaños?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "SI, ENVIAR",
        cancelButtonColor: '#d33',
        cancelButtonText: "Cancelar"
    }).then(function () {
        $.ajax({
            url: url,
            type: 'POST',
            headers: {'X-CSRF-Token': $("input[name=_token]").val()},
            dataType: 'json',
            beforeSend: function () {

            },
            success: function (response) {
                swal({
                    title: "Resultado",
                    html: response.data.message,
                    type: "success"
                }).then(function () {
                    window.location.href = response.data.route
                }).catch(swal.noop);
            },
            error: function (err) {
                swal("Respuesta", "NO pudo enviar saludo de cumpleaño.", "error");
                console.log("show_error_err: ");
            }
        });
    }).catch(swal.noop);
});

$(document).on('click', '.restore-item', function () {
    var row = $(this).parents('tr');
    var name = row.find('td.child-text-delete').text();
    var id = $(this).data('id');
    var url = $(this).data('href');
    var mensaje = $(this).data('mensaje');
    var csrf = $(this).data('csrf');
    // console.log("id_restore", id);
    swal({
        title: "Atención...",
        html: "¿Está seguro de activar " + mensaje + " <strong>" + name + "</strong> ?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "SI, RESTAURARLO",
        cancelButtonColor: '#d33',
        cancelButtonText: "Cancelar"
    }).then(function () {
        $.ajax({
            url: url,
            type: 'POST',
            headers: {'X-CSRF-Token': csrf},
            dataType: 'json',
            beforeSend: function () {

            },
            success: function (response) {
                // row.fadeOut('slow');
                swal({
                    title: "Resultado",
                    html: response.data.message,
                    type: "success"
                }).then(function () {
                    window.location.href = response.data.route
                }).catch(swal.noop);
            },
            error: function (err) {
                swal("Respuesta", "NO pudo restaurarse.", "error");
                console.log("show_error_err: ", err);
                console.log("show_error_errResponseText: ", err.responseText);
            }
        });
    }).catch(swal.noop);
});

$(document).on('click', '.delete-item', function () {
    var row = $(this).parents('tr');
    var name = row.find('td.child-text-delete').text();
    var id = $(this).data('id');
    var url = $(this).data('href');
    var mensaje = $(this).data('mensaje');
    var csrf = $(this).data('csrf');
    // console.log("id_delete", id);
    swal({
        title: "Atención...",
        html: "¿Está seguro de eliminar " + mensaje + " <strong>" + name + "</strong> ?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "SI, ELIMINARLO",
        cancelButtonColor: '#d33',
        cancelButtonText: "Cancelar"
    }).then(function () {
        $.ajax({
            url: url,
            type: 'DELETE',
            headers: {'X-CSRF-Token': csrf},
            dataType: 'json',
            beforeSend: function () {

            },
            success: function (response) {
                swal({
                    title: "Resultado",
                    html: response.data.message,
                    type: "success"
                }).then(function () {
                    window.location.href = response.data.route
                }).catch(swal.noop);
            },
            error: function (err) {
                swal("Respuesta", "NO pudo eliminarse.", "error");
                console.log("show_error_err: ", err);
                console.log("show_error_errResponseText: ", err.responseText);
            }
        });
    }).catch(swal.noop);
});

$(document).on('submit', '.formAjax', function (e) {
    e.preventDefault();
    var $form = $(this);
    var url = $form.attr('action');
    var data = $form.serialize();
    $("button[type=submit]").attr('disabled', true);

    $.ajax({
        url: url,
        type: 'POST',
        headers: {'X-CSRF-Token': $("input[name=_token]").val()},
        dataType: 'json',
        data: data,
        beforeSend: function () {
            $('.error-result-json').remove();
        },
        success: function (response) {
            if (response.route) {
                window.location.href = response.route;
            }
        },
        error: function (err) {
            console.log("err:::", err.responseJSON);
            $.each(err.responseJSON, function (key, value) {
                $("#" + key).parent().append('<span class="text-danger error-result-json">' +
                    '<strong>' + value[0] + '</strong>' + '</span>');
            });
        },
        complete: function () {
            $("button[type=submit]").attr('disabled', false);
            // $('.btnSubmitForm').attr("disabled", false);
        }
    });

});

$(document).on('change', '#sede_id', function () {
    if (this.value !== "") {
        // console.log("sede_id::: ", this.value);
        loadArea(parseInt(this.value));
    } else {
        $("#area_id").html('<option value="">Seleccione</option>').trigger('change.select2');
        $("#cargo_id").html('<option value="">Seleccione</option>').trigger('change.select2');
    }
});

$(document).on('change', '#area_id', function () {
    if (this.value !== "") {
        // console.log("area_id::: ", this.value);
        loadCargo(parseInt(this.value));
    } else {
        $("#cargo_id").html('<option value="">Seleccione</option>').trigger('change.select2');
    }
});

function loadArea(sede_id) {
    $("#area_id").html('<option value="">Seleccione</option>').trigger('change.select2');
    $("#cargo_id").html('<option value="">Seleccione</option>').trigger('change.select2');
    $.ajax({
        url: LA.base_url + 'superadmin/ajax/area/' + sede_id,
        type: 'POST',
        headers: {'X-CSRF-Token': $("input[name=_token]").val()},
        dataType: 'json',
        beforeSend: function () {
            // console.log("load data area...");
            $('.load-area').addClass('opacity-select');
            $('.load-cargo').addClass('opacity-select');
        },
        success: function (response) {
            // console.log("response:::", response);
            var select = "";
            select += '<option value="">Seleccione</option>';
            $.each(response.data, function (key, value) {
                var select_selcapaci = "";
                select += '<option value="' + value + '" ' + select_selcapaci + '>' + key + '</option>';
            });
            $("#area_id").html(select);
        },
        error: function (err) {
            console.log("show_error_: ", err.responseText);
        },
        complete: function () {
            $("#area_id").trigger('change.select2');
            // $('.load-area').removeClass('opacity-select');
            // $('.load-cargo').removeClass('opacity-select');
        }
    });
}

function loadCargo(area_id) {
    $("#cargo_id").html('<option value="">Seleccione</option>').trigger('change.select2');
    $.ajax({
        url: LA.base_url + 'superadmin/ajax/cargo/' + area_id,
        type: 'POST',
        headers: {'X-CSRF-Token': $("input[name=_token]").val()},
        dataType: 'json',
        beforeSend: function () {
            // console.log("load data cargo_id...");
            $('.load-cargo').addClass('opacity-select');
        },
        success: function (response) {
            // console.log("responseCargo:::", response);
            var select = "";
            select += '<option value="">Seleccione</option>';
            $.each(response.data, function (key, value) {
                var select_selcapaci = "";
                select += '<option value="' + value + '" ' + select_selcapaci + '>' + key + '</option>';
            });
            $("#cargo_id").html(select);
        },
        error: function (err) {
            console.log("show_error_: ", err.responseText);
        },
        complete: function () {
            $("#cargo_id").trigger('change.select2');
            $('.load-cargo').removeClass('opacity-select');
        }
    });
}

$(document).on('click', '.btnDeleteModal', function () {
    setTimeout(function () {
        $('.mimodalpe').remove();
        $('.datepicker.dropdown-menu').remove();
    }, 500);
});

// $(document).on('change', '.tipo-documento', function () {
//     var typeDoc = parseInt($(this).val());
//     var numDoc = $('.numero-documento');
//     numDoc.attr('disabled', true);
//     numDoc.removeClass('onlyLettersNumbers text-up');
//     numDoc.val("");
//     switch (typeDoc) {
//         case 1: //DNI
//             numDoc.attr('maxlength', 8);
//             numDoc.removeClass('onlyLettersNumbers');
//             numDoc.addClass('onlyNumbers');
//             numDoc.attr('disabled', false);
//             break;
//         case 2: //CE
//             numDoc.attr('maxlength', 12);
//             numDoc.removeClass('onlyNumbers');
//             numDoc.addClass('onlyLettersNumbers text-up');
//             numDoc.attr('disabled', false);
//             break;
//     }
// });

$(document).on('click', "#closeNuevoNombreTipoEgreso", function () {
    $('.addInputEgreso').addClass('d-none');
    $("#nombre").val("");
    $("#add_tipo_egreso").removeClass('d-none');
    $('.btnSubmit').attr("type", "submit");
});


$(document).on('click', "#add_tipo_egreso", function () {
    $(this).addClass('d-none');
    $('.addInputEgreso').removeClass('d-none');
    $('.btnSubmit').attr("type", "button");
});

$(document).on('click', "#saveNuevoNombreTipoEgreso", function () {
    var nombreSubLista = $("#nombre").val();

    if (nombreSubLista !== "") {
        var listaId = $(".lista_id").text();
        // console.log("empezando ajax");
        $.ajax({
            url: LA.base_url + 'admin/ajax/agregarsublista/' + listaId + '/' + nombreSubLista,
            type: 'POST',
            headers: {'X-CSRF-Token': $("input[name=_token]").val()},
            dataType: 'json',
            beforeSend: function () {
                // console.log("load data distrito...");
                $('.loading').addClass('opacity-select');
            },
            success: function (response) {
                // console.log("response:::", response);
                var select = "";
                $.each(response.data, function (key, value) {
                    var select_selcapaci = "";
                    select += '<option value="' + value + '" ' + select_selcapaci + '>' + key + '</option>';
                });
                $("#tipo_egreso_lista_id").html(select);
                Notify(response.message, 'top-right', '5000', 'success', 'fa-times', true);
            },
            error: function (err) {
                console.log("show_error_: ", err.responseText);
                Notify("Ocurrio un inconveniente", 'top-right', '5000', 'danger', 'fa-times', true);
            },
            complete: function () {
                // console.log("completado");
                $("#tipo_egreso_lista_id").trigger('change.select2');
                $('.loading').removeClass('opacity-select');
                $("#closeNuevoNombreTipoEgreso").click();

            }
        });
    } else {
        Notify("Porfavor agregue Texto", 'top-right', '5000', 'danger', 'fa-times', true);
        // console.log("agregue texto");
    }

});

$(document).on('click', '.welcome-item', function () {
    var row = $(this).parents('tr');
    var name = row.find('td.child-text-delete').text();
    var id = $(this).data('id');
    var url = $(this).data('href');
    var csrf = $(this).data('csrf');

    // console.log("id_restore", id);

    swal({
        title: "Atención...",
        html: "¿Está seguro de enviar el Saludo de Bienvenida a <strong>" + name + "</strong> ?",
        type: "warning",
        showCancelButton: true,
        confirmButtonText: "SI, ENVIAR SALUDO",
        cancelButtonColor: '#d33',
        cancelButtonText: "CANCELAR"
    }).then(function () {
        $.ajax({
            url: url,
            type: 'POST',
            headers: {'X-CSRF-Token': csrf},
            dataType: 'json',
            beforeSend: function () {

            },
            success: function (response) {
                console.log("send response::: ", response);
                if (response.data) {
                    Notify(response.data.message, 'top-right', '5000', 'success', 'fa-check', true);
                } else {
                    Notify(response.message, 'top-right', '5000', 'danger', 'fa-times', true);
                }
            },
            error: function (err) {
                swal("Respuesta", "Ocurrio un inconveniente.", "error");
                console.log("show_error_err: ", err);
                console.log("show_error_errResponseText: ", err.responseText);
            }
        });
    }).catch(swal.noop);
});

function notifyAlert(message, position, type) {
    switch (type) {
        case 'success':
            Notify(message, position, '5000', 'success', 'fa-check', true);
            break;
        case 'warning':
            Notify(message, position, '5000', 'warning', 'fa-warning', true);
            break;
        case 'danger':
            Notify(message, position, '5000', 'danger', 'fa-bolt', true);
            break;
        case 'info':
            Notify(message, position, '5000', 'info', 'fa-bolt', true);
            break;
    }
}

function Notify(message, position, timeout, theme, icon, closable) {
    $("#toast-container").remove();
    toastr.options.positionClass = 'toast-' + position;
    toastr.options.extendedTimeOut = 0; //1000;
    toastr.options.timeOut = timeout;
    toastr.options.closeButton = closable;
    toastr.options.iconClass = icon + ' toast-' + theme;
    toastr['custom'](message);
}