window.maskAll = function(context) {
  if (typeof context == 'undefined') {
    context = $('body');
  }

  context.find('.mask-number1').mask('0');
  context.find('.mask-number2').mask('00');
  context.find('.mask-number3').mask('000');
  context.find('.mask-date').mask('00/00/0000');
  context.find('.mask-time').mask('00:00:00');
  context.find('.mask-date-time').mask('00/00/0000 00:00:00');
  context
    .find('.mask-date-time-complete')
    .mask('00/00/0000 00:00:00')
    .on('change', function() {
      if (
        $(this)
          .val()
          .trim().length == 10
      ) {
        $(this).val(
          $(this)
            .val()
            .trim() + ' 00:00:00'
        );
      }
    });
  context.find('.mask-cep').mask('00000-000');

  var SPMaskBehavior = function(val) {
      return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
    },
    spOptions = {
      onKeyPress: function(val, e, field, options) {
        field.mask(SPMaskBehavior.apply({}, arguments), options);
      },
    };
  context.find('.mask-celular').mask(SPMaskBehavior, spOptions);
  context.find('.mask-phone').mask('(00) 0000-0000');
  context.find('.mask-mixed').mask('AAA 000-S0S');

  var SPMaskWeight = function(val) {
      return val.replace(/\D/g, '').length === 3 ? '00.0' : '0.00';
    },
    spOptionsWeight = {
      onKeyPress: function(val, e, field, options) {
        field.mask(SPMaskWeight.apply({}, arguments), options);
      },
    };

  context.find('.mask-weight').mask(SPMaskWeight, spOptionsWeight);

  context.find('.mask-cpf').mask('000.000.000-00', { reverse: true });
  context.find('.mask-cnpj').mask('00.000.000/0000-00', { reverse: true });
  context.find('.mask-money').mask('000.000.000.000.000,00', { reverse: true });
  context.find('.mask-money2').mask('#.##0,00', { reverse: true });
  context.find('.mask-percent').mask('##0,00', { reverse: true });
  context.find('.mask-money-point').mask('##0.00', { reverse: true, placeholder: '0.00' });

  $('.mask-alphanumeric-no-spaces').mask('A', {
    translation: {
      A: { pattern: /[A-Za-z0-9]/, recursive: true },
    },
  });
  $('.mask-alpha-no-spaces').mask('A', {
    translation: {
      A: { pattern: /[\w@\-.+]/, recursive: true },
    },
  });
  $('.mask-text').mask('A', {
    translation: {
      A: { pattern: /[A-Za-z\s]/, recursive: true },
    },
  });
  $('.mask-number').mask('A', {
    translation: {
      A: { pattern: /[0-9]/, recursive: true },
    },
  });

  $('.mask-number-negative').mask('A', {
    translation: {
      A: { pattern: /[0-9\-]/, recursive: true },
    },
  });

  // $('.mask-number-decimal').mask('##0,00', { reverse: true });
  $('.mask-number-decimal').mask('A', {
    translation: {
      A: { pattern: /[0-9\,]/, recursive: true },
    },
  });

  $('.mask-number-en-decimal').mask('A', {
    translation: {
      A: { pattern: /[0-9\.]/, recursive: true },
    },
  });

  $('.mask-int').mask('A', {
    translation: {
      A: { pattern: /[0-9]/, recursive: true },
    },
  });

  $('.mask-link').mask('A', {
    translation: {
      A: { pattern: /[A-Za-z0-9\,\/]/, recursive: true },
    },
  });
};

$(document).ready(function() {
  $('.input-mask').on('input', function() {
      var currentValue = $(this).val();
      var modifyValue = currentValue.trimStart();
      var maskedValue = modifyValue.replace(/[^A-Za-z\s]/g, '');

      $(this).val(maskedValue);
  });
});

$(document).ready(function() {
  var token = $('body').data('token'),
    widthViewport = getViewportWidth();
  function getViewportWidth() {
    return Math.max(document.documentElement.clientWidth, window.innerWidth || 0); // Tamanho da janela do navegador sem o scrollbar
  }

  $(window).resize(function(event) {
    widthViewport = getViewportWidth();
    closeMenu();
  });

  $(document).on('keyup', function(event) {
    if (event.keyCode == '27') {
      // Esc
      closeSuspendedSide();
      closeMenu();
    }
  });

  /* Inicio - Menu */
  function closeMenu() {
    $('.js-menu.active').removeClass('active');
    $('.js-menu-overlay').remove();
    resetMenu();
  }
  function resetMenu() {
    $('.js-submenu.active').removeClass('active');
    $('.js-menu .js-menu-item.hidden').removeClass('hidden');
    $('.js-menu .js-menu-item.focus').removeClass('focus');
    $('.js-menu .js-menu-item > .fa-angle-right.hidden').removeClass('hidden');
    $('.js-menu .js-menu-item > .fa-angle-left:not(.hidden)').addClass('hidden');
  }
  function showHideMenuItens($this, show) {
    /* Função usada para mostrar o submenu dentro do submenu e para o menu mobile */
    if (show) {
      $this.find('> .fa-angle-left.hidden').removeClass('hidden'); // Mostra a seta da esquerda do item do menu clicado
      $this.find('> .fa-angle-right:not(hidden)').addClass('hidden'); // Oculta a seta da direita do item do menu clicado
      $this.siblings('.js-menu-item:not(#' + $this.attr('id') + ')').addClass('hidden'); // Oculta todos os itens irmãos que não foi clicado
    } else {
      $this.find('> .fa-angle-right.hidden').removeClass('hidden');
      $this.find('> .fa-angle-left:not(hidden)').addClass('hidden');
      $this.siblings('.js-menu-item.hidden').removeClass('hidden');
    }
  }
  $('.js-menu .js-menu-item[id]').on('click', function(event) {
    event.preventDefault();
    event.stopPropagation();
    var itemId = $(this).attr('id');
    if (widthViewport >= 1360) {
      onClickOut($('.js-menu-item'), null, closeMenu, null, true);
    }
    $('.js-menu .js-menu-item.focus').removeClass('focus'); // Remove todos os item em destaques
    if ($('.js-submenu').hasClass('active') && !$('.js-' + itemId).hasClass('hidden')) {
      resetMenu();
    } else {
      $('.js-submenu [class*=js-menu-]:not(.hidden)').addClass('hidden'); // Oculta todos os submenus
      $('.js-submenu .js-menu-item.hidden').removeClass('hidden'); // Mostra todos os itens do submenu
      $('.js-submenu .js-menu-item > .fa-angle-right.hidden').removeClass('hidden'); // Mostra a seta da direita do item do submenu
      $('.js-submenu .js-menu-item > .fa-angle-left:not(.hidden)').addClass('hidden'); // Oculta a seta da esquerda do item do submenu

      $(this).addClass('focus'); // Destaca o item clicado
      $('.js-submenu').addClass('active'); // Mostra o submenu
      $('.js-' + itemId).removeClass('hidden'); // Mostra o submenu clicado
    }
    if (widthViewport <= 1359) {
      if ($('.js-submenu').hasClass('active')) {
        showHideMenuItens($(this), true);
      } else {
        showHideMenuItens($(this), false);
      }
    }
  });
  $('.js-submenu .js-menu-item[id]').on('click', function(event) {
    event.preventDefault();
    event.stopPropagation();
    if ($('.js-' + $(this).attr('id')).hasClass('hidden')) {
      $('.js-' + $(this).attr('id')).removeClass('hidden');
      showHideMenuItens($(this), true);
    } else {
      $('.js-' + $(this).attr('id')).addClass('hidden');
      showHideMenuItens($(this), false);
    }
  });
  $('.js-menu-control').on('click', function(event) {
    event.preventDefault();
    event.stopPropagation();
    if ($('.js-menu').hasClass('active')) {
      closeMenu();
    } else {
      $('.js-menu').addClass('active');
      $('footer').append('<div class="js-menu-overlay"></div>');
      $('.js-menu-overlay').css({
        width: 'calc(100vw - 356px)',
        height: '100vh',
        position: 'fixed',
        top: '0',
        left: '0',
        'z-index': '15',
      });
    }
  });
  $('.js-menu-close').on('click', function(event) {
    event.preventDefault();
    event.stopPropagation();
    closeMenu();
  });
  $('footer').on('click', '.js-menu-overlay', function(event) {
    event.preventDefault();
    closeMenu();
  });
  /* Final - Menu */

  /* Inicio - Lateral suspensa */
  function closeSuspendedSide() {
    $('.js-suspended-side.active').removeClass('active');
    $('.js-suspended-side-overlay').remove();
  }
  $('.js-suspended-side-control').on('click', function(event) {
    event.preventDefault();
    event.stopPropagation();
    var suspendedSide = $('.js-' + $(this).attr('id'));
    if (suspendedSide.hasClass('active')) {
      closeSuspendedSide();
    } else {
      suspendedSide.addClass('active');
      $('footer').append('<div class="js-suspended-side-overlay"></div>');
      $('.js-suspended-side-overlay').css({
        width: '100vw',
        height: '100vh',
        position: 'fixed',
        top: '0',
        left: '0',
        'z-index': '9',
      });
    }
  });
  $('.js-suspended-side-close').on('click', function(event) {
    event.preventDefault();
    closeSuspendedSide();
  });
  $('footer').on('click', '.js-suspended-side-overlay', function(event) {
    event.preventDefault();
    closeSuspendedSide();
  });

  $('.js-control-manual').on('click', function(event) {
    $('.js-content-manual').empty();
    $.ajax({
      url: 'index.php?route=common/manual&token=' + token,
      dataType: 'html',
      beforeSend: function() {
        $('.js-content-manual').append(
          '<div class="flex between-xs"><img src="../assets/img/loading-black.svg" alt="" width="64" height="64" class="center-block" /></div>'
        );
      },
    }).done(function(html) {
      if (html) {
        $('.js-content-manual')
          .empty()
          .append(html);
      }
    });
  });

  /* Final - Lateral suspensa */

  $('[data-modal-id="change-password"]').on('click', function(event) {
    event.preventDefault();
    event.stopPropagation();
    var $this = $(this),
      $loading =
        '<div class="js-adm-modal-container"><img src="../assets/img/loading-black.svg" width="64" height="64" alt="" /></div>';
    $('#change-password').remove();
    $this.modalFutura({
      dataModalId: 'adm-modal-loading',
      appendModal: $loading,
    });
    $('#adm-modal-loading').addClass('js-adm-modal-overlay-no-close');
    $.ajax({
      url: $this.attr('href'),
      dataType: 'html',
    })
      .done(function(data) {
        $('#adm-modal-loading').remove();
        $this.modalFutura({
          dataModalId: 'change-password',
          appendModal: data,
        });

        $('#change-password-apply').on('click', function(event) {
          event.preventDefault();
          var $this = $(this);
          result = $('#change-password-form').serialize();
          $this.addClass('btn-loading');
          $('#change-password').addClass('js-adm-modal-overlay-no-close');
          $.ajax({
            url: 'index.php?route=user/trocasenha/verifica&token=' + token,
            type: 'POST',
            dataType: 'json',
            data: result,
          })
            .done(function(data) {
              if (data.error) {
                var $error =
                  '<div class="text-medium text-warning background-warning border-warning visible-block padding-small" id="change-password-error">' +
                  data.error +
                  '</div>';
                $('#change-password-error').remove();
                $('#notification').append($error);
              }
              if (data.success) {
                var $success = '<div class="js-adm-modal-container padding-x-large text-center">';
                $success += '<i class="fas fa-lock text-success bigger-text-x-large visible-block"></i>';
                $success +=
                  '<span class="text-dark text-medium visible-block top-margin-small"><b>Sua senha foi <br>trocada com sucesso!</b></span>';
                $success +=
                  '<button class="btn-default btn-medium btn-success top-margin-large horizontal-margin-x-large js-adm-modal-close" type="button">';
                $success += '<span>Concluir</span>';
                $success += '</button>';
                $success += '</div>';
                $this.modalFutura({
                  dataModalId: 'change-password-success',
                  appendModal: $success,
                });
              }
            })
            .fail(function(json) {
              alert(JSON.stringify(json));
            })
            .always(function() {
              $this.removeClass('btn-loading');
              $('#change-password').removeClass('js-adm-modal-overlay-no-close');
            });
        });
      })
      .fail(function() {
        //console.log("error");
      })
      .always(function() {
        // console.log("complete");
      });
  });

  maskAll();

  //================================= LIST BLOCKS ================================
  $('#sortable, .sortable').disableSelection();

  $('#sortable, .sortable').sortable({
    revert: true,
    axis: 'y',
    containment: 'body',
  });

  function error_clean() {
    if ($('.sortable .error').length > 0) {
      $('.sortable input, .sortable textarea').on('focus', function() {
        $(this).on('keyup', function() {
          if ($(this).val() != '') {
            $(this)
              .next('.error')
              .remove();
            $(this).off('keyup');
          }
        });
      });
    }
  }

  function validate_inputs($inputs) {
    $('.error').remove();
    var stop = 0;
    $inputs.each(function() {
      if ($(this).val() == '') {
        $(this).after('<span class="error">Preencha o campo acima!</span>');
        stop = 1;
      }
    });
    if (stop == 1) {
      error_clean();
    }

    return stop;
  }

  var row = [];
  $('.list-blocks').each(function() {
    row[$(this).attr('id')] = $(this).find('.block-item').length;
  });

  $('.js-add-block').live('click', function() {
    var stop = validate_inputs($('.sortable input[type=text], .sortable textarea'));

    if (stop) return;

    var htmlBlock = '';
    switch (
      $(this)
        .closest('.list-blocks')
        .attr('id')
    ) {
      case 'tracking_codes':
        htmlBlock += '<div class="block-item vertical-padding-medium border-custom-link-group">';
        htmlBlock += '  <div class="row x-small-space-xs top-xs">';
        htmlBlock += '    <div class="col-xs-6">';
        htmlBlock +=
          '      <input class="field-entry field-entry-medium text-small full-width" type="text" id="tracking_codes_title_' +
          row[
            $(this)
              .closest('.list-blocks')
              .attr('id')
          ] +
          '" name="tracking_codes_title[' +
          row[
            $(this)
              .closest('.list-blocks')
              .attr('id')
          ] +
          ']" value="" placeholder="Título">';
        htmlBlock += '    </div>';
        htmlBlock += '<div class="col-xs-2">';
        htmlBlock +=
          '  <select class="field-entry field-entry-medium text-small full-width" id="tracking_codes_position_' +
          row[
            $(this)
              .closest('.list-blocks')
              .attr('id')
          ] +
          '" name="tracking_codes_position[' +
          row[
            $(this)
              .closest('.list-blocks')
              .attr('id')
          ] +
          ']">';
        htmlBlock += '      <option value="1">Cabeçalho</option>';
        htmlBlock += '      <option value="2" selected="selected">Rodapé</option>';
        htmlBlock += '  </select>';
        htmlBlock += '</div>';
        htmlBlock += '<div class="col-xs-2">';
        htmlBlock +=
          '  <select class="field-entry field-entry-medium text-small full-width" id="tracking_codes_status_' +
          row[
            $(this)
              .closest('.list-blocks')
              .attr('id')
          ] +
          '" name="tracking_codes_status[' +
          row[
            $(this)
              .closest('.list-blocks')
              .attr('id')
          ] +
          ']">';
        htmlBlock += '      <option value="0">Desabilitado</option>';
        htmlBlock += '      <option value="1" selected="selected">Habilitado</option>';
        htmlBlock += '  </select>';
        htmlBlock += '</div>';
        htmlBlock += '    <div class="col-xs-1">';
        htmlBlock +=
          '      <button type="button" class="btn-default btn-medium btn-error btn-full text-small js-remove-block">';
        htmlBlock += '        <i class="fas fa-trash"></i>';
        htmlBlock += '      </button>';
        htmlBlock += '    </div>';
        htmlBlock += '    <div class="col-xs-1 text-center">';
        htmlBlock += '      <i class="fas fa-arrows-alt-v text-large padding-small full-width"></i>';
        htmlBlock += '    </div>';
        htmlBlock += '    <div class="col-xs-10">';
        htmlBlock +=
          '      <textarea class="field-entry field-entry-medium text-small full-width" type="text" id="tracking_codes_script_' +
          row[
            $(this)
              .closest('.list-blocks')
              .attr('id')
          ] +
          '" name="tracking_codes_script[' +
          row[
            $(this)
              .closest('.list-blocks')
              .attr('id')
          ] +
          ']" placeholder="Código"></textarea>';
        htmlBlock += '    </div>';
        htmlBlock += '  </div>';
        htmlBlock += '</div>';

        break;
    }

    row[
      $(this)
        .closest('.list-blocks')
        .attr('id')
    ]++;
    $('.container-block-items').append(htmlBlock);
  });

  $('.js-remove-block').live('click', function() {
    $(this)
      .closest('.block-item')
      .remove();
  });

  $("select[name='filter_integracao']").on('change', function() {
    // 0 é igual o valor mercado livre
    var $this = $(this);
    if ($this.val() == 0) {
      $("select[name='filter_marketplace']")
        .val(9)
        .attr('readonly', true);
    } else {
      $("select[name='filter_marketplace']")
        .val('*')
        .attr('readonly', false);
    }
  });

  if ($('.js-number').length > 0) $('.js-number').number();

  $('body').on('click', '.js-toggle-original-error', function() {
    $(this)
      .next('.hidden')
      .toggleClass('visible-block');
  });
}); // Fim document.ready

$(window).load(function() {
  window.handleDropdown = function(context) {
    context = context || $('body');
    var dropDowns = context.find('.js-new-dropdown');

    dropDowns.off('click', dropdownController);
    dropDowns.on('click', dropdownController);
  };
  window.handleDropdown();
});

function hideDropdown() {
  $('.js-new-dropdown').removeClass('active');
  $('.js-new-dropdown-mask').remove();
}

function dropdownController() {
  var content = $(this).find('.js-new-dropdown-content');
  var contentWith = content.width(); // Largura do dropdown
  var offset = content.offset().left; // Posição do dropdown
  /* Verifica se tem espaço para exibir o dropdown */
  if (contentWith + offset > $(window).width()) {
    content.removeClass('left').addClass('right');
  }
  if (offset < 0) {
    content.removeClass('right').addClass('left');
  }
  /* Ativar e desativar dropdown */
  if ($(this).hasClass('active')) {
    hideDropdown();
  } else {
    hideDropdown();
    $(this).addClass('active');
    var mask = $(
      '<div class="js-new-dropdown-mask" style="width:100vw;height:100vh;position:fixed;top:0;left:0;"></div>'
    );
    mask.on('click', hideDropdown);
    $('body').append(mask);
  }
}

function admAlert(msg, msgType, time) {
  var $div = $('<div>'),
    $span = $('<span>'),
    bottom = 32,
    time = time ? time : 3000;

  if (typeof msgType == 'undefined') {
    msgType = 'success';
  }

  $div.addClass(
    'adm-alert cursor-pointer padding-medium center-fixed shadow-small background-' + msgType + ' border-' + msgType
  );
  $div.css({ 'max-width': '600px', opacity: '0', 'min-width': '240px' });
  $span.addClass('text-medium text-' + msgType + '');
  $span.append(msg);
  $div.append($span);

  $('body').append($div);

  $('.adm-alert').each(function(index) {
    $(this).animate(
      {
        bottom: bottom,
        opacity: '1',
      },
      300
    );
    bottom += 8 + $(this).height() + 32 + 2; //margin + height + padding + border
  });

  function msgHide(element) {
    $(element).animate(
      {
        bottom: '-2rem',
        opacity: '0',
      },
      300,
      function() {
        $(element).remove();
      }
    );
  }

  setTimeout(function() {
    msgHide($div);
  }, time);

  $('.adm-alert').on('click', function(event) {
    event.preventDefault();
    msgHide(this);
  });
}

function getURLVar(key) {
  var value = [];

  var query = String(document.location).split('?');

  if (query[1]) {
    var part = query[1].split('&');

    for (i = 0; i < part.length; i++) {
      var data = part[i].split('=');

      if (data[0] && data[1]) {
        value[data[0]] = data[1];
      }
    }

    if (value[key]) {
      return value[key];
    } else {
      return '';
    }
  }
}

function getFontGoogle(token, fontepadrao, selectop) {
  $.ajax({
    url: 'https://www.googleapis.com/webfonts/v1/webfonts?key=AIzaSyBGSBS_pzdsUff3dah-mgL-AaHqTWJ8eQo',
    type: 'get',
    dataType: 'json',
    timeout: 3000,
    contentType: 'application/json; charset=utf-8',
    beforeSend: function() {
      $(selectop).append('<option value="carregando">Carregando...</option>');
    },
    complete: function() {
      $(selectop + " option[value='carregando']").remove();
    },
    error: function() {
      $(selectop).append('<option value="' + fontepadrao + '">O servidor não conseguiu processar o pedido</option>');
    },
    success: function(json) {
      var items = json.items;

      items.map(item => {
        $(selectop).append(
          $('<option>', {
            selected: item.family === fontepadrao ? true : false,
            value: item.family,
            text: item.family,
          })
        );
      });
    },
  });
}

$(document).ready(function() {
  route = getURLVar('route');

  if (!route) {
    $('#dashboard').addClass('selected');
  } else {
    part = route.split('/');

    url = part[0];

    if (part[1]) {
      url += '/' + part[1];
    }

    $("li a[href*='" + url + "&']")
      .parents('li[id]')
      .addClass('selected');
  }

  $('.btn-close').live('click', function() {
    $('.success, .warning, .attention, .information')
      .stop()
      .fadeOut('slow');
  });

  function habilitaLimite(inputPosition, inputGrid) {
    var thisInput = inputGrid.closest('tr,.row').find('.js-control-limit');
    // var thisInput = inputGrid.parent().next().find('.js-control-limit');
    if (inputGrid.val() == Type_DsimDnao.Tp_Sim) {
      thisInput.prop('disabled', false);
    } else {
      if (inputPosition.val() != Type_ModulePosition.Tp_ColumnLeft) {
        thisInput.prop('disabled', true).val(Type_DefaultValues.Tp_LimitModules24);
      } else {
        thisInput.prop('disabled', false);
      }
    }
  }

  $(document).on('change', '.js-control-position', function() {
    var thisInput = $(this)
      .closest('tr,.row')
      .find('.js-control-grid');
    // var thisInput = $(this).parent().next().find('.js-control-grid');
    if ($(this).val() == Type_ModulePosition.Tp_ColumnLeft) {
      thisInput.prop('disabled', true).val(Type_DsimDnao.Tp_Nao);
    } else {
      thisInput.prop('disabled', false);
    }

    habilitaLimite($(this), thisInput);
  });

  $(document).on('change', '.js-control-grid', function() {
    habilitaLimite(
      $(this)
        .closest('tr,.row')
        .find('.js-control-position'),
      $(this)
    );
  });
});

window.loadBeforeSend = function() {
  return '<div class="loadBeforeSend"><picture><source srcset="../assets/img/loading-white.svg" type="image/svg+xml"><img src="../assets/img/loading-white.svg" alt="MDN"></picture></div>';
};

window.addLoad = function() {
  window.removeLoad();
  document.body.insertAdjacentHTML('beforeend', window.loadBeforeSend());
};

window.removeLoad = function() {
  var loadings = document.body.querySelectorAll('.loadBeforeSend');
  for (var i = 0; i < loadings.length; i++) {
    var element = loadings[i];
    element.parentNode.removeChild(element);
  }
};

(function($) {
  $.fn.selectDisplayController = function() {
    return this.each(function() {
      var $this = $(this);

      $this.on('change', function() {
        $this
          .find('option')
          .not(':selected')
          .each(function() {
            $('.' + $(this).data('controlled')).hide();
          });
        $(
          '.' +
            $this
              .find('option')
              .filter(':selected')
              .data('controlled')
        ).show();
      });
    });
  };
})(jQuery);

function trocaCaracter(str) {
  var str = str.toLowerCase();

  str = str.replace(/^\s+|\s+$/g, '');

  var from = 'ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;';

  var to = 'aaaaaeeeeeiiiiooooouuuunc       ';

  for (var i = 0, l = from.length; i < l; i++) {
    str = str.replace(/from.charAt(i)/g, to.charAt(i));
  }

  str = str.replace(/[^a-z0-9 -]/g, '');

  return str;
}

function closestElement(classFind) {
  var element = this.parentElement;
  while (!element.classList.contains(classFind) && element.tagName != 'BODY') {
    element = element.parentElement;
  }

  if (element.tagName == 'BODY') {
    console.error('ERRO: Não foi encontrado nenhum elemento ancestral com a classe especificada.');
    return false;
  } else {
    return element;
  }
}

/**
 * Identifica o clique fora do elemento $parent
 *
 * @example
 *   function fora() {
 *     console.log('clicou fora');
 *   }
 *   function dentro() {
 *     console.log('clicou dentro');
 *   }
 *   onClickOut($('.quick-setup-container'), $('.overlay'), fora, dentro, false);
 *
 * @param  $parent        {element}  obrigatorio   elemento
 * @param  $removeElement {element|null}  [opcional]    elemento a ser removido
 * @param  functionTrue   {function|null} [opcional]    funcao excutada quando o clique for fora do elemento
 * @param  functionFalse  {function|null} [opcional]    funcao excutada quando o clique for dentro do elemento
 * @param  destroyEvent   {boolean}  [opcional]    parar de executar a funcao apos o primeiro click fora
 */
function onClickOut($parent, $removeElement, functionTrue, functionFalse, destroyEvent) {
  $('body').on('click', function(e) {
    if ($parent.find(e.target).length == 0 && $parent[0] != $(e.target)[0]) {
      if (typeof functionTrue != 'undefined' && functionTrue != null) {
        functionTrue();
      }
      if (typeof $removeElement != 'undefined' && $removeElement != null) {
        $removeElement.remove();
      }
      if (typeof destroyEvent == 'undefined' || destroyEvent == true) {
        $('body').off('click');
      }
    } else {
      if (typeof functionFalse != 'undefined' && functionFalse != null) {
        functionFalse();
      }
    }
  });
}
