/* eslint-disable prettier/prettier */
/*
Responsavel pelo carregamento dinamico das imagens.
*/
;(function($) {
  $.fn.imageLoad = function(options) {
    var settings = $.extend(
      {
        desconto: 0,
      },
      options
    );

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

      function image_load() {
        if ($this.prop('tagName') == 'SOURCE') {
          $this.attr('srcset', $this.data('src'));
        } else {
          $this.attr('src', $this.data('src'));
        }

        $this.removeClass('load-image');

        $this[0].onload = function() {
          var ua = window.navigator.userAgent;
          var msie = ua.indexOf('MSIE ');

          if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) {
            $this
              .closest('.image-loading-in-background')
              .css({ height: 'auto', 'padding-bottom': 0 })
              .removeClass('image-loading-in-background');
          } else {
            $this
              .closest('.image-loading-in-background')
              .css({ height: 'initial', 'padding-bottom': 0 })
              .removeClass('image-loading-in-background');
          }
        };
        $this[0].onerror = function() {
          $this.closest('.image-loading-in-background').removeClass('image-loading-in-background');
        };
      }

      if ($this.parent().offset().top < $(window).scrollTop() + $(window).height() + settings.desconto) {
        image_load();
      }

      $this.one('image_load', function() {
        image_load();
      });

      $(window).on('scroll', function() {
        if ($this.parent().offset().top < $(window).scrollTop() + $(window).height() + settings.desconto) {
          $this.trigger('image_load');
        }
      });
    });
  };

  $(window).on('load', function() {
    $('.load-image').each(function() { 
      $(this).trigger('image_load'); 
    });
  });

})(jQuery);