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

  function luminiColor(element) {
    element.each(function() {
      var cor = $(this).css('background-color');
      cor = cor.replace('rgba(', '');
      cor = cor.replace('rgb(', '');
      cor = cor.replace(')', '');
      corRGB = cor.split(',');

      var lumini = corRGB[0] * 0.4 + corRGB[1] * 0.5 + corRGB[2] * 0.1;
      luminosidade = lumini / 255;

      if (luminosidade >= 0.4) {
        var classH = 'light';
      } else {
        var classH = 'dark';
      }

      $(this).addClass(classH);
    });
  }

  luminiColor($('.btn-default'));

  //================================ Menu mobile ===============================
  jQuery('.toggle, .menutop').click(function() {
    if (jQuery('.submenu').is(':hidden')) {
      jQuery('.submenu').slideDown('fast');
    } else {
      jQuery('.submenu').slideUp('fast');
    }
    return false;
  });

  $('.mask-date').mask('00/00/0000');
  $('.mask-date-card').mask('00/0000');
  $('.mask-time').mask('00:00:00');
  $('.mask-date-time').mask('00/00/0000 00:00:00');
  $('.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);
      },
    };
  $('.mask-celular').mask(SPMaskBehavior, spOptions);

  $('.mask-phone').mask('(00) 0000-0000');

  $('.mask-mixed').mask('AAA 000-S0S');
  $('.mask-cpf').mask('000.000.000-00', { reverse: true });
  $('.mask-cnpj').mask('00.000.000/0000-00', { reverse: true });
  $('.mask-money').mask('000.000.000.000.000,00', { reverse: true });
  $('.mask-money2').mask('#.##0,00', { reverse: true });
  $('.mask-percent').mask('##0,00%', { reverse: true });
  $('.mask-money-point').mask('##0.00%', { reverse: true });
  $('.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-int').mask('A', {
    translation: {
      A: { pattern: /[0-9]/, recursive: true },
    },
  });

  // if ($('.js-order-by-option').length > 0) {
  //   var script = document.createElement('script');
  //   script.setAttribute('src', 'catalog/view/theme/vista/js/order-list-async.js');
  //   document.body.appendChild(script);
  // }

  // =========================== estrutura HTML ============================
  // select.js-order-by-option
  //   option[value=data-name][data-type=text/number]
  //
  // radio.js-order-by-sequence[value=asc]
  // span.js-order-by-sequence-text-asc
  //
  // radio.js-order-by-sequence[value=desc]
  // span.js-order-by-sequence-text-desc
  //
  // div.js-order-by-list
  //   div.js-order-by-item[data-name=data-value]

  function formatStringOrFloat(n) {
    if (!isNaN(parseFloat(n)) && isFinite(n)) {
      return 'integer';
    } else {
      return 'string';
    }
  }

  // Esta função foi criada por causa dos navegadores da Microsoft
  function orderBySort(orderType, formatType, aSort, bSort, value) {
    switch (formatType) {
      case 'integer':
        if (orderType == 'asc') {
          return $(aSort).attr('data-' + value) - $(bSort).attr('data-' + value);
        } else {
          return $(bSort).attr('data-' + value) - $(aSort).attr('data-' + value);
        }
        break;
      case 'string':
        if (orderType == 'asc') {
          return $(aSort)
            .attr('data-' + value)
            .trim()
            .localeCompare($(bSort).attr('data-' + value));
        } else {
          return $(bSort)
            .attr('data-' + value)
            .trim()
            .localeCompare($(aSort).attr('data-' + value));
        }
        break;
    }
  }

  function orderBy() {
    $('.js-order-by-list').each(function() {
      var rowProduct = $(this).find('.js-order-by-item');
      var val = $('.js-order-by-option').val();
      var order = $('.js-order-by-sequence')
        .filter(':checked')
        .val();

      rowProduct.sort(function(a, b) {
        return orderBySort(order, formatStringOrFloat($(a).attr('data-' + val)), a, b, val);
      });

      $(this)
        .find('.js-order-by-item')
        .remove();
      for (var i = 0; i < rowProduct.length; i++) {
        $(this).append(rowProduct[i]);
      }
    });
  }

  orderBy();

  $('.js-order-by-option, .js-order-by-sequence').on('change', function(e) {
    if ($(this).hasClass('js-order-by-option')) {
      if (
        $(this)
          .find('option')
          .filter(':selected')
          .data('type') == 'text'
      ) {
        $('.js-order-by-sequence-text-asc').html('de A a Z');
        $('.js-order-by-sequence-text-desc').html('de Z a A');
      } else {
        $('.js-order-by-sequence-text-asc').html('Crescente');
        $('.js-order-by-sequence-text-desc').html('Decrescente');
      }
    }
    orderBy();
  });

  // if ($('.carousel-container').length > 0) {
  //   var sliderFuturaScript = document.createElement('script');
  //   sliderFuturaScript.src = 'view/theme/vista/js/slider-futura.js';
  //   document.body.appendChild(sliderFuturaScript);
  //
  //   $('.carousel-container').each(function(){
  //     $(this).carousel();
  //   });
  // }

  /**
   * Controla grupos de checkbox com dois níveis
   *
   * O id do controlador deve ser uma classe nos controlados
   * O data-parent-id dos controlados deve ser igual ao id do controlador
   *
   * <label>
   *   <input type="checkbox" name="213" id="213" class="js-check-control">
   *   <span>ANEIS</span>
   * </label>
   * <div>
   *   <label>
   *     <input type="checkbox" name="225" id="225" data-parent-id="213" class="js-check-controlled 213">
   *     <span>Solitario</span>
   *   </label>
   *   <label>
   *     <input type="checkbox" name="214" id="214" data-parent-id="213" class="js-check-controlled 213">
   *     <span>Zirconia</span>
   *   </label>
   * </div>
   */
  $('.js-check-control').live('change', function(e) {
    $('.js-check-controlled.' + $(this).attr('id')).prop('checked', $(this).prop('checked'));
  });
  $('.js-check-controlled').live('change', function() {
    if (
      $('.js-check-controlled.' + $(this).data('parent-id')).length ==
      $('.js-check-controlled.' + $(this).data('parent-id')).filter(':checked').length
    ) {
      $('.js-check-control#' + $(this).data('parent-id')).prop('checked', true);
    } else {
      $('.js-check-control#' + $(this).data('parent-id')).prop('checked', false);
    }
  });

  function accordionFooter() {
    if (getViewportWidth() < 768) {
      $('.js-footer-accordion').accordionFutura({ initFirstActive: false });
    } else {
      $('.js-footer-accordion').accordionFutura({ destructor: true });
    }
  }
  accordionFooter();
  $(window).resize(function() {
    accordionFooter();
  });

  if ($('.js-new-dropdown').length > 0) {
    function hideDropdown() {
      $('.js-new-dropdown').removeClass('active');
    }
    onClickOut($('.js-new-dropdown'), null, hideDropdown, null, false);
    $('.js-new-dropdown').on('click', function() {
      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');
      }
    });
  }

  function asideContent(index) {
    $(this)
      .find('.aside-content-icon')
      .css('top', index * 49 + 'px');

    $(this).on('click', function() {
      $(this).toggleClass('show');
      var icon = $(this).find('i');
      if (icon.data('class')) {
        icon.attr('class', icon.data('class')).data('class', '');
      } else {
        icon.data('class', icon.attr('class')).attr('class', 'fa fa-angle-right');
      }
    });
  }

  $('.js-aside-content.aside-content-right').each(asideContent);
  $('.js-aside-content.aside-content-left').each(asideContent);

  $('.js-close-smart-install-banner').on('click', function() {
    $(this)
      .closest('div')
      .addClass('hidden');
    function setCookie(cname, cvalue, exdays) {
      var d = new Date();
      d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
      var expires = 'expires=' + d.toUTCString();
      document.cookie = cname + '=' + cvalue + ';' + expires + ';path=/';
    }
    setCookie('closesmartinstallbanner', 'true', 10);
  });
}); // Fechamento document.ready
