if ($('.date-picker').length > 0) {
    $('.date-picker').datetimepicker({
        format: 'YYYY-MM-DD'
    });
}

if ($('.modal').length > 0) {
    $('.modal').draggable({handle: 'div.modal-header'});
}

if ($('#btnSearchPeople').length > 0) {
    $(document).on('click', "#btnSearchPeople", function () {
        $('.add-people-ajax').html('');
        $('.show-message-result').html('');
        var name_people = $("#name_people").val();
        if (name_people === "") {
            messageFlash('MENSAJE...', 'Ingrese nombre a buscar...', 'danger');
        } else {
            $.ajax({
                url: LA.base_url + 'persona/buscar/' + name_people,
                type: 'POST',
                dataType: 'json',
                headers: {'X-CSRF-Token': $("input[name=_token]").val()},
                beforeSend: function () {
                    $('.page-loader').css("display", "block");
                    //swal_accion_resultado('MENSAJE...','CARGANDO RESULTADOS ','info',false);
                },
                success: function (response) {
                    console.log("response:::", response);
                    if (response === null) {
                        messageFlash('<i class="zmdi zmdi-alert-triangle"></i> ATENCIÓN...', 'No hay resultado a la búsqueda...', 'danger');
                    } else {
                        if (response.data.length > 0) {
                            var options = "";
                            $.each(response.data, function (i, item) {
                                options += '<div class="lv-item media" >' +
                                    '<a href="' + LA.base_url + 'persona/' + item.slug + '">' +
                                    '<div class="pull-left">' +
                                    '<img class="lv-img-sm" src="' + item.foto + '" onerror="this.src=\'' + item.fotoError + '\'">' +
                                    '</div>' +
                                    '</a>' +
                                    '<div class="media-body p-l-10">' +
                                    '<a href="' + LA.base_url + 'persona/' + item.slug + '">' +
                                    '<div class="lv-title" style="white-space: initial;">' + item.apellidos_nombres + '</div>' +
                                    '<small class="lv-small" style="white-space: initial;">' + item.sedeAreaCargo + '</small>';
                                if (item.email !== null) {
                                    options += '<small class="lv-small">' + item.email + '</small>';
                                }
                                if (item.anexo !== null) {
                                    options += '<small class="lv-small">Anexo:' + item.anexo + '</small>';
                                }
                                options += '</a>';
                                if (item.favorito === null) {
                                    options += '<div class="lv-actions actions dropdown ">' +
                                        '<a href="javascript:;" data-toggle="dropdown" aria-expanded="true">' +
                                        '<i class="zmdi zmdi-more-vert"></i>' +
                                        '</a>' +

                                        '<ul class="dropdown-menu dropdown-menu-right dropdown-menu-customize">' +
                                        '<li>' +
                                        '<a href="javascript:;" data-persona-id="' + item.id + '" class="add-favorite-person" data-persona="' + item.apellidos_nombres + '"><i class="zmdi zmdi-favorite favorite-heart"></i> Favorito</a>' +
                                        '</li>' +
                                        '</ul>' +
                                        '</div>';
                                }
                                options += '</div>' +
                                    '</div>';
                                $('.add-people-ajax').html(options);
                            });
                            messageFlash('<i class="zmdi zmdi-notifications"></i>', 'Se encontraron ' + response.data.length + ' coincidencias', 'success');
                        } else {
                            messageFlash('<i class="zmdi zmdi-alert-triangle"></i>', 'No se encontraron resultados', 'danger');
                        }
                    }
                },
                error: function (err) {
                    console.log("error:::", err);
                },
                complete: function () {
                    $('.page-loader').css("display", "none");
                }
            });
            var isMobile = /Mobi/.test(navigator.userAgent);
            if (isMobile) {
                hiddenKeyboard();
            }
        }
    });
}

function hiddenKeyboard() {
    var field = document.createElement('input');
    field.setAttribute('type', 'text');
    document.body.appendChild(field);

    setTimeout(function () {
        field.focus();
        setTimeout(function () {
            field.setAttribute('style', 'display:none;');
        }, 50);
    }, 50);
}

$(document).on('click', '.add-favorite-person', function () {
    var $item = $(this);
    var nombres = $item.data('persona');
    var idPersona = $item.data('persona-id');
    var url = LA.base_url + 'favorito/' + idPersona;

    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        beforeSend: function () {
        },
        success: function (response) {
            // console.log('response:::', response);
            messageFlash('<i class="zmdi zmdi-notifications"></i>', 'Se guardo como favorito a "' + nombres + '"', 'success');
        },
        error: function (err) {
            console.log("err:::", err);
        },
        complete: function () {
            $item.parents('.lv-actions').fadeOut();
        }
    });
});

$(document).on('click', '.close-busqueda', function () {
    $("#name_people").val("");
    $('.add-people-ajax').html('');
});

function messageFlash(title, message, type) {
    var isMobile = /Mobi/.test(navigator.userAgent);
    if (isMobile) {
        showMessage(message, type);
    } else {
        $('.bootstrap-growl').remove();
        $.bootstrapGrowl(title + ' ' + message, {
            type: type,
            align: 'center',
            width: 'auto',
            delay: 5000,
            allow_dismiss: false
        });
    }
}

function showMessage(message, type) {
    $("#main").append('<div class="showMessageResultAjax"><p class="' + type + '">' + message + '</p></div>');
    setTimeout(function () {
        $('.showMessageResultAjax').remove();
    }, 5000);
}

$("#persona-search-form").submit(function (e) {
    return false;
});

$(document).on('keyup', "#searchPersona", function () {
    searchBox('.contacts', '.listadoPersona', 'strong', $(this).val());
});
$(document).on('click', '.close-search', function () {
    $("#searchPersona").val("");
    searchBox('.contacts', '.listadoPersona', 'strong', "");
});

function searchBox(id_box, child_box, element, inputVal) {
    var box = $(id_box);
    box.find(child_box).each(function (index, row) {
        var allDivs = $(row).find(element);
        if (allDivs.length > 0) {
            var found = false;
            allDivs.each(function (index, strong) {
                var regExp = new RegExp(inputVal, 'i');
                if (regExp.test($(strong).text())) {
                    found = true;
                    return false;
                }
            });
            if (found) $(row).show(); else $(row).hide();
        }
    });
}

$(document).on('submit', '.formAjaxPerfilBasica', function (e) {
    e.preventDefault();
    var $form = $(this);
    var url = $form.attr('action');
    var data = $form.serialize();
    $('.btnSubmitFormPerfilBasica').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);
            $.each(err.responseJSON, function (key, value) {
                $("#" + key).parent().append('<span class="text-danger error-result-json">' +
                    '<strong>' + value[0] + '</strong>' +
                    '</span>');
            });
        },
        complete: function () {
            $('.btnSubmitFormPerfilBasica').attr("disabled", false);
        }
    });
});

$(document).on('keypress', '.onlyNumber', function (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);
});


$(document).on('click', '.href-form-image', function () {
    $('.file-form-image').click();
    $('.form-image').removeClass('hidden');
    $('.show-image-profile').addClass('hidden');
    $(this).addClass('hidden');
});

$(document).on('click', '.fileinput-delete-profile', function () {

    $('.show-image-profile').removeClass('hidden');
    $('.href-form-image').removeClass('hidden');
    $('.form-image').addClass('hidden');
});

$(document).on('submit', '.formAjaxPerfilContact', function (e) {
    e.preventDefault();
    var $form = $(this);
    var url = $form.attr('action');
    var data = $form.serialize();
    $('.btnSubmitFormPerfilContact').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) {
            // console.log("response:::", response);
            if (response.route) {
                window.location.href = response.route;
            }
        },
        error: function (err) {
            console.log("err:::", err);
            $.each(err.responseJSON, function (key, value) {
                $("#" + key).parent().append('<span class="text-danger error-result-json">' +
                    '<strong>' + value[0] + '</strong>' +
                    '</span>');
            });
        },
        complete: function () {
            $('.btnSubmitFormPerfilContact').attr("disabled", false);
        }
    });
});

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

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

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

        });
    }
});

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

$("#btn-cumple").submit(function (e) {
    e.preventDefault();
    $('.page-loader').css("display", "block");
    var textSaludo = $('.text-saludo').val();
    var url = $(this).attr('action');
    var method = $(this).attr('method');
    console.log("textSaludo::: ", textSaludo);
    if (textSaludo !== "") {
        var data = {
            message: textSaludo,
            persona_cumpleanio_id: $("input[name=persona_cumpleanio_id]").val()
        };

        $.ajax({
            url: url,
            type: method,
            headers: {'X-CSRF-Token': $("input[name=_token]").val()},
            dataType: 'json',
            data: {data: data},
            beforeSend: function () {

            },
            success: function (response) {
                console.log("response::: ", response);
                messageFlash('<i class="zmdi zmdi-notifications"></i>', response.data.message, 'success');
            },
            error: function (err) {
                console.log("error::: ", err);
                messageFlash('<i class="zmdi zmdi-notifications"></i>', 'Ocurrio un inconveniente, intentelo nuevamente', 'danger');
            },
            complete: function () {
                console.log("se completo con exito");
                $('.text-saludo').val("");
                $('.page-loader').css("display", "none");
            }
        });
    } else {
        messageFlash('<i class="zmdi zmdi-notifications"></i>', 'No puede enviar un saludo vacio', 'danger');
        $('.page-loader').css("display", "none");
    }
    $('.pmop-message').removeClass('open');
});