//============================== Generic Javascript Functions
var user_config = {
    log: 1,
    theme: 'default',
    menu_default: false, // true - Collapsed | false - Open
    allways_ajax: true
};

function log(message, importance = 0) {
    if (user_config.log === 0) {
        return;
    }

    if (importance === 0) {
        console.log("LOG:: |" + message + "|");
    }
    if (importance === 1) {
        console.log(message);
    }
    if (importance === 2) {
        alert("LOG:: |" + message + "|");
}
}

function isDefined(data) {
    if (typeof data === 'undefined') {
        return false;
    } else {
        return true;
    }
}

function definedOr(data, value = '') {
    if (typeof data === 'undefined') {
        return value;
    } else {
        return data;
}
}

//============================== Generic Template Functions

function revalidate_screen() {
    $('[data-format]').each(function () {
        $(this).mask($(this).data('format'), {});
    });

    $('[data-toggle="popover"]').popover();

    $('select').each(function () {
        if (typeof $(this).data('value') !== "undefined" && $(this).data('value') !== '') {
            $(this).val($(this).data('value'));
        }
    });

    $('.datepicker').each(function () {
        $(this).datepicker({
            format: "dd/mm/yyyy",
            todayBtn: "linked",
            clearBtn: true,
            autoclose: true,
            todayHighlight: true
        });
    });

    $('.selectpicker').each(function () {
        $(this).select2({
            liveSearch: true
        });
    });

    $('.popup-toggle').each(() => {
        var template = '<div class="modal-dialog"> <div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"> X </button><h4 class="modal-title">Modal Header</h4></div><div class="modal-body">{{aaa}}</div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div>';
        if ($(this).hasClass('processed')) {
            return true;
        }
        $(this).addClass('processed');
        $(this).on('click', function (e) {
            e.preventDefault();
            $.ajax({
                method: 'GET',
                url: $(this).data('source')
            }).done(function (msg) {
                template = template.replace('{{aaa}}', msg);
                $('#modal').html(template).modal('show');
                revalidate_screen();
            });
        });
        $('#modal').on('shown.bs.modal', function () {
            revalidate_screen();
            $(this).find('.datatable-anchor').focus();
        });
    });

    $('.remote-popup').each((i, element) => {

        if ($(element).hasClass('processed')) {
            return true;
        }

        var instance = $(element);
        var number = $(element).find('.remote-popup-number');
        var button = $(element).find('button');
        var label = $(element).find('.remote-popup-label');

        searchRemote = (value = null) => {
            if (value == null) {
                value = $(number).val();
            }
            $.ajax({
                method: 'GET',
                url: $(instance).data('relay') + '/' + value
            }).done(function (msg) {
                $(label).val(msg.name);
            }).fail(function () {
                $(number).val('');
                $(label).val('');
            });
        }

        remotePopup = (source) => {
            $($('#modal')).off();
            var template = '<div class="modal-dialog"> <div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"> X </button><h4 class="modal-title">Modal Header</h4></div><div class="modal-body">{{aaa}}</div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div>';
            $.ajax({
                method: 'GET',
                url: source
            }).done(function (msg) {
                template = template.replace('{{aaa}}', msg);
                $('#modal').html(template).modal('show');
                $('#modal').on('hide.bs.modal', () => {
                    $(number).val($("#modal .selected").data('info').id);
                    searchRemote();
                });
                revalidate_screen();
            });
        };

        $(button).on('click', () => {
            remotePopup($(instance).data('relay') + '/' + $(instance).data('mode'));
        });

        $(number).on('keyup', (e) => {
            if (e.keyCode == 112) {
                remotePopup($(instance).data('relay') + '/' + $(instance).data('mode'));
            }
        });

        $(number).on('focusout', () => {
            console.log($(number).val() == '');
            if ($(number).val() == '') {
                $(label).val('');
                return;
            }
            searchRemote($(number).val());
        });
        
        if($(number).val() != ''){
            searchRemote( $(number).val() )
        }
        
        /*console.log($(element))
        console.log(number);
        console.log(button);
        console.log(label);*/
        
        $(element).addClass('processed');
        
    });

    $('.live-selectpicker').each(function () {

        $(this).select2({
            liveSearch: true
        });

        var object = $(this);
        var source = definedOr($(this).data('source'), false);
        var placeholder = definedOr($(this).data('placeholder'));
        var filter_name = definedOr($(this).data('filter'));
        var value = definedOr($(this).data('value'));

        if (!source) {
            return;
        }
        object.ajax = {
            "url": source,
            "data": function (params) {
                var query = {
                    "name": params.value
                }
            }
        };
        /*$(this).ajaxSelectPicker({
         ajax: {
         url: source + "/combo_data",
         method: 'GET',
         data: {
         nome: '{{{q}}}',
         filter: function() {
         if (filter_name === '') {
         return ''
         }
         return $("[name='" + filter_name + "'] option:selected").val();
         }
         }
         },
         locale: {
         emptyTitle: placeholder
         },
         preprocessData: function(data) {
         var registers = [];
         registers.push({
         'value': '0',
         'text': 'Selecione'
         });
         for (var i in data) {
         registers.push({
         'value': data[i].id,
         'text': data[i].nome
         });
         }
         return registers;
         },
         preserveSelected: true
         });*/
    });

    /*===========================================*/

    $('.icon-colapser').on('click', function () {
        $(this).parent().parent().find('.panel-collapse').collapse('toggle');
    });

    /*$('form').each(function () {
     $(this).validator();
     });*/

    $('.data-table').each(function () {
        if ($(this).hasClass('processed')) {
            return;
        }
        var wrapper = $(this);
        var table_anchor = $(this).find('a');
        var table = $(this).find('table');

        var str = '<thead> <tr class="header">';
        for (var i in table.data('columns')) {
            if (typeof table.data('columns')[i].name === 'undefined') {
                str = str + '<th>' + table.data('columns')[i].data + "</th>";
            } else {
                str = str + '<th>' + table.data('columns')[i].name + "</th>";
            }
        }
        str += '<th>*</th>';
        str += "</tr> </thead>";
        $(table).html(str);
        var datatable = $(table).DataTable({
            'createdRow': function (row, data) {
                $(row).attr('data-info', JSON.stringify(data));
                var content = '';
                if (typeof $(table).data('update') != 'undefined') {
                    content += '<a href="' + $(table).data('update') + '"> <i class="fa fa-pencil-square"></i> </a>'
                }
                if (typeof $(table).data('delete') != 'undefined') {
                    content += '<a href="' + $(table).data('delete') + '"> <i class="fa fa-trash"></i> </a>'
                }
                if (typeof $(table).data('purge') != 'undefined') {
                    content += '<a href="' + $(table).data('purge') + '"> <i class="fa fa-minus-square"></i> </a>'
                }

                $(row).append('<td>' + content + '</td>');
            },
            "drawCallback": function (settings) {
                if ($(wrapper).hasClass('selectable')) {
                    $($(table).find('tr')[1]).addClass('selected');
                    if (!$(wrapper).hasClass('processed')) {
                        $(table_anchor).focus();
                    }
                }
            },
            "initComplete": function (settings, json) {
                $(wrapper).addClass('processed');
            },
            processing: true,
            serverSide: true,
            searchDelay: 800,
            ajax: {'url': table.data('source'), 'type': 'POST'},
            columns: table.data('columns')
        });

        var search = $(this).find('input');

        $(search).on('keyup', function (e) {
            if (e.keyCode == 13) {
                $(table_anchor).focus();
            }
        });

        if ($(wrapper).hasClass('selectable')) {
            $(this).on('contextmenu', 'tr', function () {

            });

            $(this).on('click', 'tr', function () {
                $(table_anchor).focus();
                if ($(this).hasClass('selected')) {
                    $(this).removeClass('selected');
                    return;
                }
                $(this).parent().find('tr').each(function () {
                    $(this).removeClass('selected');
                });
                $(this).addClass('selected');
            });

            $(table_anchor).on('focus', function () {
                $('body').addClass('no-scroll');
                $($(table).find('tr')[1]).addClass('selected');
            });

            $(table_anchor).on('focusout', function () {
                $('body').removeClass('no-scroll');
                $(table).find('tr').each((i, value) => {
                    $(value).removeClass('selected');
                });
            });

            $(table_anchor).on('keypress', function (e) {

            });

            $(table_anchor).on('keyup', function (e) {

                e.preventDefault();

                if (e.keyCode == 70) {
                    $(search).focus();
                }

                if (e.keyCode == 112) {
                    ajax_call($(this).data('insert'));
                }

                if (e.keyCode == 113) {
                    id = $(table).find('.selected').data('info').id;
                    ajax_call($(this).data('insert') + '/' + id);
                }

                if (e.keyCode == 39 && e.ctrlKey) {
                    datatable.page('last').draw('page');
                }
                if (e.keyCode == 37 && e.ctrlKey) {
                    datatable.page('first').draw('page');
                    $($(table).find('tr')[1]).addClass('selected');
                }
                if (e.keyCode == 37) { //left
                    datatable.page('previous').draw('page');
                    $($(table).find('tr')[1]).addClass('selected');
                }
                if (e.keyCode == 39) { //right
                    datatable.page('next').draw('page');
                    $($(table).find('tr')[1]).addClass('selected');
                }
                if (e.keyCode == 38) { //up
                    var last = null;
                    var line = null;

                    $(table).find('tr').each((i, value) => {
                        if ($(value).hasClass('selected')) {
                            ;
                            line = $(value)
                            return false;
                        }
                        last = $(value)
                    });
                    if ($(last).hasClass('header')) {
                        datatable.page('previous').draw('page');
                    }
                    if (line != null) {
                        $(line).removeClass('selected');
                        $(last).addClass('selected');
                    }

                }
                if (e.keyCode == 40) { //up
                    var next = false;

                    $(table).find('tr').each((i, value) => {
                        if (next) {
                            $(value).addClass('selected');
                            next = false;
                            return false;
                        }
                        if ($(value).hasClass('selected')) {
                            next = true;
                            $(value).removeClass('selected');
                        }
                    });
                    if (next) {
                        datatable.page('next').draw('page');
                    }
                }
                if (e.keyCode == 13) {
                    if ($(this).parent().parent().hasClass('modal-body')) {
                        $(this).parent().parent()
                                .parent().parent()
                                .parent().modal('hide');
                        //console.log($(this).parent().find('.selected').data('info'));
                    }
                }
            })
        }
    });

    popover_help();
}

/*===========================================*/

$('.remote-element').each(function () {

    var element = $(this);
    var source = $(this).data('source');
    var value = $(this).data('value');

    $.ajax({
        method: "GET",
        url: source,
        data: {value: value}
    }).done(function (msg) {
        $(element).html(msg);
    });

});

//============================== Template Boot

/* Função de aparecer ou desaparecer o menu lateral */
$("#menu-toggle").on('click', function (e) {
    e.preventDefault();
    //e.preventPropagation();
    $("#wrapper").toggleClass("toggled");
    window.dispatchEvent(new Event('resize'));
});

if (user_config.menu_default) {
    $('#wrapper').addClass('toggled');
    window.dispatchEvent(new Event('resize'));
}

/* Função de aparecer ou desaparecer o menu lateral Secundário*/
$("#menu-toggle").on('contextmenu', function (e) {
    e.preventDefault();
    //e.preventPropagation();
    alert("Configs maluquinhas");
    window.dispatchEvent(new Event('resize'));
});

$('#side-menu').metisMenu();

revalidate_screen();

//============================== - MouseTrap
/* Atalho, Ao apertar alt, foca no primeiro ítem do menu lateral */
Mousetrap.bind('alt', function (e) {
    e.preventDefault();
    $('#side-menu li:first-child a').focus();
    $("#wrapper").removeClass("toggled");
    return false;
});

Mousetrap.bind("alt+1", function (e) {
    $("#wrapper").addClass("toggled");
    e.preventDefault();
});

Mousetrap.bind("alt+2", function (e) {
    $('#menu-usuario > li').addClass('open');
    $('#menu-usuario > li >a').focus();
    e.preventDefault();
});

//Foca na barra de pesquisa
Mousetrap.bind("ctrl+shift+f", function (e) {
    $(".search-nav input").focus();
});

function popover_help() {
    $('input').each(function () {
        Mousetrap($(this)[0]).bind('ctrl+f1', function () {
            //alert(10);    
        });
    })
}

Mousetrap.bind("ctrl+f1", function (e) {
    //alert(10);
});


//============================== MenuSearch

var menu = Array();
$("#side-menu a").each(function () {
    if ($(this).attr('href') !== "") {
        menu.push("<li>" + $(this).parent().html() + "</li>")
    }
});

$("#side-second-menu").html(menu);

$(".search-nav >input").on("keyup", function () {
    var search = $(this).val().toLowerCase();
    if ($(this).val() === "") {
        $("#side-menu").removeClass("hidden");
        $("#side-second-menu").addClass("hidden");
    } else {
        $("#side-menu").addClass("hidden");
        $("#side-second-menu").removeClass("hidden");
        $("#side-second-menu li").each(function () {
            if ($(this).html().toLowerCase().indexOf(search) > -1) {
                $(this).removeClass('hidden');
            } else {
                $(this).addClass('hidden');
            }
        });
    }
});

//============================== Ajax Page Handler
$('a').on('click', function (e) {
    if (!user_config.allways_ajax) {
        return true;
    }

    var target = $(this).attr('href');
    var method = $(this).data('method');

    if (typeof target === 'undefined' ||
            target === '' ||
            target === '#' ||
            target == 'javascript:void(0)') {
        return;
    }

    if (method === 'reload') {
        return true;
    }

    e.preventDefault();

    if (typeof method === 'undefined') {
        method = 'GET';
    }

    $('#progress').removeClass('hidden');

    $.ajax({
        method: method,
        url: target
    }).done(function (msg) {
        $('#content').html(msg);
        history.replaceState({}, '', target);
    }).fail(function () {
        alert('fail');
    }).always(function () {
        $('#progress').addClass('hidden')
        revalidate_screen();
    });
});

function ajax_call(target) {
    $('#progress').removeClass('hidden');

    $.ajax({
        method: 'GET',
        url: target
    }).done(function (msg) {
        $('#content').html(msg);
        history.replaceState({}, '', target);
    }).fail(function () {
        alert('fail');
    }).always(function () {
        $('#progress').addClass('hidden')
        revalidate_screen();
    });
}

function open_popup(source) {
    var template = '<div class="modal-dialog"> <div class="modal-content"><div class="modal-header"><button type="button" class="close" data-dismiss="modal"> X </button><h4 class="modal-title">Modal Header</h4></div><div class="modal-body">{{aaa}}</div><div class="modal-footer"><button type="button" class="btn btn-default" data-dismiss="modal">Close</button></div></div>';
    $.ajax({
        method: 'GET',
        url: source
    }).done(function (msg) {
        //alert(msg);
        template = template.replace('{{aaa}}', msg);
        $('#modal').html(template).modal('show');
        revalidate_screen();
    });
}