/*global $, document, Chart, LINECHART, data, options, window, $CROPER*/
$(document).ready(function () {

    'use strict';

    // ------------------------------------------------------- //
    // Parsley Validate
    // ------------------------------------------------------ //
    if ($("form").length) {
        $("form").parsley();
    }

    // ------------------------------------------------------- //
    // Custom Scrollbar
    // ------------------------------------------------------ //
    if ($("nav.side-navbar").length) {
        $("nav.side-navbar").mCustomScrollbar({
            scrollInertia: 200
        });
    }

    // ------------------------------------------------------- //
    // Side Navbar Functionality
    // ------------------------------------------------------ //
    $('#toggle-btn').on('click', function (e) {
        e.preventDefault();
        if ($(window).outerWidth() > 1194) {
            $('nav.side-navbar').toggleClass('shrink');
            $('.page').toggleClass('active');
        } else {
            $('nav.side-navbar').toggleClass('show-sm');
            $('.page').toggleClass('active-sm');
        }
    });

    // ------------------------------------------------------- //
    // Transition Placeholders
    // ------------------------------------------------------ //
    $('input').on('focus', function () {
        $(this).siblings('.label-custom').addClass('active');
    });
    $('input').on('blur', function () {
        $(this).siblings('.label-custom').removeClass('active');
        if ($(this).val() !== '') {
            $(this).siblings('.label-custom').addClass('active');
        } else {
            $(this).siblings('.label-custom').removeClass('active');
        }
    });

    // ------------------------------------------------------ //
    // jQuery DataTables Bootstrap
    // ------------------------------------------------------ //
    if ($('#dataTables').length) {
        $('#dataTables').dataTable({
            'columnDefs': [
                {
                    'targets': 'no-sort',
                    'orderable': false
                }, {
                    'sType': 'date-uk',
                    'targets': 'data-field'
                }
            ],
            'oLanguage': {
                "sEmptyTable": "Nenhum registro encontrado",
                "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
                "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
                "sInfoFiltered": "(Filtrados de _MAX_ registros)",
                "sInfoPostFix": "",
                "sInfoThousands": ".",
                "sLengthMenu": "_MENU_ resultados por página",
                "sLoadingRecords": "Carregando...",
                "sProcessing": "Processando...",
                "sZeroRecords": "Nenhum registro encontrado",
                "sSearch": "Pesquisar",
                "oPaginate": {
                    "sNext": "Próximo",
                    "sPrevious": "Anterior",
                    "sFirst": "Primeiro",
                    "sLast": "Último"
                },
                "oAria": {
                    "sSortAscending": ": Ordenar colunas de forma ascendente",
                    "sSortDescending": ": Ordenar colunas de forma descendente"
                }
            }
        });
    }

    // ------------------------------------------------------ //
    // Bootstrap FileInput
    // ------------------------------------------------------ //
    if ($('.file-input').length) {
        $('.file-input').fileinput({
            'showUpload': false,
            'showCancel': false,
            'showPreview': false,
            'language': 'pt-BR',
            'browseClass': 'btn btn-info',
            'removeClass': 'btn btn-danger',
            'browseIcon': '<i class="fa fa-search"></i>&nbsp;',
            'removeIcon': '<i class="fa fa-trash"></i>'
        });
    }

    // ------------------------------------------------------ //
    // Sorteble jQuery-UI
    // ------------------------------------------------------ //
    if ($('.sortable').length) {
        var sortable = $('.sortable');
        var table = sortable[0].dataset.table;
        sortable.sortable({
            stop: function (event, ui) {
                var data = $(this).sortable('serialize');
                $.ajax({
                    type: 'POST',
                    url: 'php/ordenar.php?table=' + table,
                    data: data
                });
            }
        });
    }

    // ------------------------------------------------------ //
    // Bootstrap Date-Time Picker
    // ------------------------------------------------------ //
    if ($('#datePicker').length) {
        $('#datePicker').datetimepicker({
            locale: 'pt-br',
            format: 'DD/MM/YYYY'
        });
    }

    // ------------------------------------------------------ //
    // DropZone
    // ------------------------------------------------------ //
    if ($('.drop').length) {
        var dataset = $('.drop')[0].dataset;
        $('.drop').dropzone({
            url: dataset.action,
            parallelUploads: 1,
            dictDefaultMessage: 'Arreste e Solte os arquivos para fazer o upload',
            params: {
                'id': dataset.id,
                'folder': dataset.folder,
                'table': dataset.table,
                'field': dataset.field
            },
            queuecomplete: function () {
                location.replace(dataset.callback);
            }
        });
    }

    // ------------------------------------------------------ //
    // Confirm Delete Item
    // ------------------------------------------------------ //
    $('.btn-delete').click(function (e) {
        $.confirm({
            title: 'Confirmação',
            content: 'Deseja realmente excluir este item?',
            type: 'red',
            buttons: {
                Sim: function () {
                    location.replace(e.currentTarget.href);
                },
                Não: function () {}
            }
        });
        return false;
    });

    // ------------------------------------------------------ //
    // Destroy Crop
    // ------------------------------------------------------ //
    $('.form-crop').change(function (e) {
        var origin = e.target.defaultValue;
        if (origin === 'S') {
            if ("undefined" !== typeof $CROPER) {
                $CROPER.cropper('destroy');
            }
        } else {
            initCropper(e.target.dataset.ratio, e.target.dataset.id);
        }
    });

    // ------------------------------------------------------ //
    // KeyWords
    // ------------------------------------------------------ //
    if ($('#keywords').length) {
        $('#keywords').selectize({
            persist: false,
            createOnBlur: true,
            create: true
        });
    }

    // ------------------------------------------------------ //
    // Save From Modal
    // ------------------------------------------------------ //
    if ($('.modal_form').length) {
        $('.modal_form').submit(function () {
            var data_set = $(this)[0].dataset;
            $.ajax({
                type: 'POST',
                url: data_set.action,
                data: $(this).serialize(),
                dataType: 'json',
                success: function (res) {
                    if (res.type === 'success') {
                        $('select[data-name="' + data_set.target + '"]').load(data_set.reload);
                        $('.modal').modal('hide');
                        $('.modal_form').trigger('reset');
                    }
                    $.confirm({
                        title: 'Confirmação',
                        content: res.message,
                        type: (res.type === 'success' ? 'green' : 'red'),
                        buttons: {
                            Ok: {}
                        }
                    });
                }
            });
            return false;
        });
    }
    
    if ($('input[data-type="money"]').length) {
        $('input[data-type="money"]').maskMoney({
            prefix: "R$ ",
            suffix: "",
            affixesStay: false,
            thousands: "",
            decimal: ".",
            precision: 2,
            allowZero: false,
            allowNegative: false,
            doubleClickSelection: true,
            allowEmpty: false,
            bringCaretAtEndOnFocus: true
        });
    }
    
    checkNotifications();
    setInterval(function() {
        checkNotifications();
    }, 15000);
    
    $('select[data-reload="profissional"]').on('change', function() {
        $('select[data-name="profissional"]').find('option').remove();
        $.ajax({
            type: 'POST',
            url: 'php/professionals.php',
            data: {
                id_ubs: $('select[data-reload="profissional"]').val()
            },
            dataType: 'json',
            success: function(res) {
                $('<option value=""></option>').appendTo('select[data-name="profissional"]');
                $.map(res, function(item, key) {
                    $('<option value="' + item.id + '">' + item.nome + '</option>').appendTo('select[data-name="profissional"]');
                });
            }
        });
    });
});
// ------------------------------------------------------ //
// Ler Imagem para Crop
// ------------------------------------------------------ //
function readImageForCrop(id, file, ratio) {
    var oFile = $('#' + file)[0].files[0];
    var oImage = document.getElementById(id);
    var oReader = new FileReader();
    oReader.onload = function (e) {
        oImage.src = e.target.result;
        $('.no-crop').removeClass('no-crop');
        if ("undefined" === typeof $CROPER) {
            initCropper(ratio, oImage);
        } else {
            $CROPER.cropper("replace", e.target.result);
        }
    };
    oReader.readAsDataURL(oFile);
}
// ------------------------------------------------------ //
// Inicia Croper.js
// ------------------------------------------------------ //
function initCropper(ratio, id) {
    $('.hidden-croper').removeClass('hidden-croper');
    $('.height200').removeClass('height200');
    $CROPER = $(id);
    var c = $("#dataX"), d = $("#dataY"), e = $("#dataHeight"), f = $("#dataWidth"), j = {
        aspectRatio: ratio,
        preview: ".img-preview",
        movable: false,
        rotatable: false,
        scalable: false,
        zoomable: false,
        minCropBoxWidth: 20,
        minCropBoxHeight: 20,
        crop: function (a) {
            c.val(Math.round(a.x)), d.val(Math.round(a.y)), e.val(Math.round(a.height)), f.val(Math.round(a.width));
        }
    };
    $CROPER.on({
        "build.cropper": function (a) {},
        "built.cropper": function (a) {},
        "cropstart.cropper": function (a) {},
        "cropmove.cropper": function (a) {},
        "cropend.cropper": function (a) {},
        "crop.cropper": function (a) {},
        "zoom.cropper": function (a) {}
    }).cropper(j);
}
// ------------------------------------------------------ //
// Verifica Notificacoes
// ------------------------------------------------------ //
function checkNotifications() {
    $.ajax({
        type: 'POST',
        url: 'php/verificar-notificacoes.php',
        dataType: 'json',
        success: function(res) {
            var dados = '';
            if (res.dados.length > 0) {
                $.map(res.dados, function(item) {
                    dados += '<li class="nav-item">';
                    dados += '<a href="' + item.uri + '" class="dropdown-item">';
                    dados += '<span>';
                    dados += '<span>' + item.usuario + '</span>';
                    dados += '<span class="time">' + item.data + '</span>';
                    dados += '</span>';
                    dados += '<span class="message">' + item.message + '</span>';
                    dados += '</a>';
                    dados += '</li>';
                });
            } else {
                dados = '<li class="nav-item"><div class="text-center"><a class="dropdown-item"><strong>Nenhuma nova notificação</strong></a></div></li>';
            }
            $('#notifications .dropdown-menu').html(dados);
            $('#notifications .badge').html(res.dados.length);
        },
        error: function(err) {
            console.log(err);
        }
    });
};