let container = document.querySelector('.ftr-js-products-view'),
  page = 1,
  url,
  countPage;

function loadMoreProducts() {
  url = JSON.parse(JSON.parse($('.ftr-js-products-view').data('pagination'))),
  countPage = Object.keys(url).length;

  let windowInnerHeight = window.innerHeight;
  let contentOuterHeight = $('.ftr-main').outerHeight();
  let scrollEnd = contentOuterHeight - windowInnerHeight;
  let scrolled = window.scrollY + ((scrollEnd * 10)/100); //faz essa conta no final pra comecar carregar 10% antes de terminar a pagina

  if (
    scrolled >= scrollEnd &&
    url[page]
  ) {
    $.ajax({
      url: url[page] + '&ajax=true',
      type: 'POST',
      dataType: 'html',
      beforeSend: function() {
        $('.ftr-js-products-view').append(
          "<div class='ftr-js-loading-products ftr-h--full ftr-text--center ftr-in-space--v-l'><img src='assets/img/loading-black.svg'></div>"
        );
        $(window).off('scroll');
      },
      complete: function() {},
      success: function(html) {
        $('.ftr-js-products-view').append(html);
        $(window).on('scroll', loadMoreProducts);
        page++;
        $('.ftr-js-loading-products').remove();
        $('.ftr-js-image-load__image').imageLoad({ desconto: 500 });
        if (page >= countPage) {
          $('.ftr-js-products-view').append(
            '<div class="ftr-h--full ftr-text--center ftr-in-space--v-l">Você chegou ao final desta listagem!</div>'
          );
        }
      },
    });
  }
}

$(window).on('scroll', function(event) {
  loadMoreProducts();
});
