$(function(){

    var screenWidth = $(window).width();

    $('.has-sub').each(function(index, el) {
        el.firstChild.nextElementSibling.outerHTML += '<i class="right fa fa-angle-left"></i>';
    });
    $('.has-sub').click(function(ev){
        ev.preventDefault();
        var a = $(this);
        var ul = $(this.nextElementSibling);
        if(!a.attr('data-opened') || a.attr('data-opened') == 'false'){
            ul.show();
            var h = ul.height();
            ul.height(0);
            a.addClass('active');
            a.attr('data-opened', 'true');

            ul.animate({
                "height": h
            }, "fast", function(){
                a.find('.fa-angle-left').removeClass('fa-angle-left').addClass('fa-angle-down');
            });

        }else{
            var h = ul.height();
            ul.animate({
                "height": 0
            }, "fast", function(){
                a.removeClass('active');
                a.attr('data-opened', 'false');
                a.find('.fa-angle-down').removeClass('fa-angle-down').addClass('fa-angle-left');
                ul.hide();
                ul.height(h);

            });
        }
    });

    var openedMenu = 0;
    function mobile(){
        if(screenWidth <= 700){
            $('.mobile-menu').click(function(ev){
                ev.preventDefault();
                if(openedMenu == 0){
                    $('.menu').animate({
                        "left": 0
                    }, 500, function(){
                        openedMenu = 1;
                        $('.mobile-menu').find('i').removeClass('fa-bars').addClass('fa-arrow-left');
                    });
                }else{
                    $('.menu').animate({
                        "left": "-250px"
                    }, 500, function(){
                        openedMenu = 0;
                        $('.mobile-menu').find('i').removeClass('fa-arrow-left').addClass('fa-bars');
                    });
                }
            });

            $('.spacer').click(function() {
                if(openedMenu == 1){
                    $('.mobile-menu').click();
                }
            });
        }
    }

    $(window).resize(mobile);

    mobile.call();

    // $(window).load(function(){
    //     $('.loading-page').hide();
    // });

    function removeCampo() {
        $(".delete-field").unbind("click");
        $(".delete-field").bind("click", function(event){
            event.preventDefault();
            var campo = $(this).attr('data');
            i = $(campo).length;
            var toRemove = $(this);
            if (i>1) {
                var stop = false;
                while(stop == false){
                    if( toRemove.hasClass( campo.replace('.', '') ) ){
                        stop = true;
                    }else{
                        toRemove = toRemove.parent();
                    }
                }
                toRemove.remove();
            }
        });
    }

    function adicionarCampo(event){
        event.preventDefault();
        var campo = $(this).attr('data');
        novoCampo = $(campo + ":first").clone();
        novoCampo.find("input").each(function() { $(this).val("")});
        novoCampo.insertAfter(campo + ":last");
        removeCampo();
    }

    removeCampo();
    $(".add-field").click(adicionarCampo);

    $('.money').maskMoney({
        prefix:'R$ ',
        allowNegative: true,
        decimal:'.',
        affixesStay: false
    });

    $('.grama').maskMoney({
        allowNegative: true,
        decimal:'.',
        precision: 3,
        suffix: 'g',
        affixesStay: false
    });

    $('.cm').maskMoney({
        allowNegative: false,
        suffix: ' cm',
        thousands: '',
        precision: 0,
        affixesStay: false
    });

    $('.porcent').maskMoney({
        allowNegative: true,
        decimal: '.',
        precision: 0,
        suffix: '%',
        affixesStay: false
    });
    
    $(".date").pickadate({
        format: "dd/mm/yyyy",
        hiddenName: true
    });

    var maskBehavior = function(val) {
        return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
    };
    var options = {
        onKeyPress: function(val, e, field, options) {
            field.mask(maskBehavior.apply({}, arguments), options);
        }
    };

    $('.cpf').mask('999.999.999-99');
    $('.cnpj').mask('99.999.999/9999-99');
    $(".data").mask('99/99/9999');
    $(".cep").mask('99999-999');
    $(".fixo").mask('(99) 9999-9999');
    $('.cel').mask(maskBehavior, options);

    $('.select2').select2();

    $('body').on("keyup",".cep-autocomplete", function(e) {
        var value = $(this).val();
        var form = $(this).parents(".endereco");;
        if(value.length == 9) {
            
            $('.loading-page').show();

            $.ajax({
                type: 'POST',
                url: '/sistema/base/buscacep?noui=1',
                data: {
                    cep: value
                },
                success: function(res) {
                    $('.loading-page').hide();
                    if(res != 0) {
                        if(res.code == 1) {

                            if(res.response.logradouro) {
                                
                                form.find('#rua')
                                    .val(res.response.tipo + ' ' + res.response.logradouro)
                                    .attr('readonly', true);
                                
                                form.find('#numero').focus();

                            }else {
                                form.find('#rua').val(null).attr('readonly', false).focus();
                            }

                            if(res.response.bairro) {
                                
                                form.find('#bairro')
                                    .val(res.response.bairro)
                                    .attr('readonly', true);

                            }else {
                                form.find('#bairro').val(null).attr('readonly', false);
                            }

                            form.find('#cidade').val(res.response.cidade);
                            form.find('#estado').val(res.response.uf);

                        } else {
                            alert('Cep não encontrado');
                        }
                    }
                }
            });
        }
    });

});

tinymce.init({
    selector: '.html-editor',
    language: "pt_BR",
    height: 250,
    menubar: false,
    plugins: [
        "advlist autolink autosave link image lists charmap hr searchreplace visualblocks visualchars code",
        "table contextmenu paste textcolor colorpicker textpattern spellchecker fullscreen"
    ],

    toolbar1: "cut copy paste | searchreplace | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | forecolor backcolor | fullscreen",
    toolbar2: "bold italic underline strikethrough | alignleft aligncenter alignright alignjustify | fontselect fontsizeselect | table | hr | subscript superscript | spellchecker",
    menubar: false,
    toolbar_items_size: 'small',
    external_filemanager_path: '/sistema/filemanager/',
    filemanager_title: 'Gerenciador de Arquivos',
    external_plugins: {
        'filemanager': '/sistema/filemanager/plugin.min.js'
    },
    relative_urls: false,
    convert_urls: false
});
