window.waitEvent('scripts_window', function() {
  $('.js-more-products').removeAttr('disabled');

  var page = 1,
    url,
    aviseme,
    countPage;

  function setVarValues() {
    aviseme = $('#data-selected-url').data('status_aviseme');
    url = JSON.parse(JSON.parse($('#data-selected-url').data('pagination'))); // Não remover os dois JSON.parse()

    if (url) {
      countPage = url.length;
      btnMoreProducts();
    } else {
      setTimeout(function() {
        setVarValues();
      }, 200);
    }
  }

  setVarValues();

  function loadMoreProducts() {
    $('.js-more-products').addClass('hidden');
    $('.products-view').append(
      '<div class="js-loading-products full-width text-center vertical-padding-large">' +
        '<img src="assets/img/loading-black.svg" width="40" height="40">' +
        '</div>'
    );

    $.ajax({
      url: url[page] + '&ajax=true',
      type: 'POST',
      dataType: 'html',
    })
      .done(function(html) {
        var $newHtml = $(html);
        $newHtml.find('.js-btn-cart').removeAttr('disabled');
        $('.products-view').append($newHtml);
        $('.js-more-products').removeClass('hidden');
        $('.js-loading-products').remove();
        window.gridFix();
        window.initActionProductBox($newHtml);
        window.initCountdown($newHtml);
        if (aviseme) {
          window.initAviseme();
        }
        page++;
        btnMoreProducts();
      })
      .fail(function(error) {
        console.log(error);
      });
  }

  function btnMoreProducts() {
    if (page === countPage) {
      $('.js-more-products').remove();
      $('.products-view').after(
        '<div class="full-width text-center padding-large text-medium top-margin-medium">Você chegou ao final desta listagem!</div>'
      );
    }
  }

  $('.js-more-products').on('click', function() {
    loadMoreProducts();
  });
});
