jQuery(document).ready(function($) {
  //* FacetWP Isotope
  var fwpScrollToBtn = false;
  var $grid = $('.fwpl-layout');
  $grid.imagesLoaded(function() {
    //* Wrapped in a short timeout function because $grid.imagesLoaded doesn't reliably lay out correctly
    setTimeout(function(){
      $grid.isotope({
        itemSelector: '.fwpl-result',
      });
    }, 250);
  });

  $(document).on('facetwp-loaded', function() {
    if (FWP.loaded) {
      $grid = $('.fwpl-layout');
      $grid.isotope('destroy');
      $grid.isotope({
        itemSelector: '.fwpl-result',
      });

      //* Scroll to the button of the results on click of load more since we're destroying the listing
      if(fwpScrollToBtn === true){
        var $loadMoreBtn = $('.facetwp-load-more');
        if($loadMoreBtn.length){
          $([document.documentElement, document.body]).animate({
            scrollTop:
              $loadMoreBtn.offset().top // button scrolled distance from the top of the screen
              - window.innerHeight // window height (to get it scrolled where the button is at the bottom of the screen vs top)
              + $loadMoreBtn.outerHeight() // height of the btn
              + 20 // padding from the bottom of the screen
          }, 250);
        }
      }
    }
  });
  
  $(document).on('click', '.facetwp-load-more', function () {
    fwpScrollToBtn = true;
  });
});