$(document).ready(function () {
  Wick.OfferBanner = (function () {
    var offerBanner = $('.offer-banner')[0],
      offer;

    var stickyWrapper = $('.sticky-wrapper')[0];

    if (!offerBanner) {
      return;
    }

    Wick.applyBottomMarginIfBanner = function () {
      if (!Wick.isTradePro) {
        return;
      }

      if (!offerBanner) {
        return;
      }

      let bannerHeight = $(offerBanner).outerHeight();
      $(stickyWrapper).css('margin-bottom', bannerHeight + 'px');
    };

    var init = function () {
      offer = new Waypoint.Sticky({
        element: offerBanner
      });
    };

    var toggle = function () {
      if (offer) {
        offer.destroy();
        offer = null;
      } else {
        init();
      }
    };

    function handleResize() {
      if (!offer) {
        return;
      }
      var elHeight = offer.$element.outerHeight(true);
      if (elHeight !== offer.$wrapper.outerHeight(true)) {
        offer.$wrapper.height(elHeight);
      }

      Wick.applyBottomMarginIfBanner();
    }

    var bindEvents = function () {
      $(window).on('resize', handleResize);
      $(window).on('orientationchange', handleResize);
      $(document).on('mobileNav.toggle', toggle);
    };

    // Workaround for sticky banner functionality in IE
    function isIE() {
      var ua = navigator.userAgent;
      /* MSIE used to detect old browsers and Trident used to newer ones*/
      return ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;
    }

    if (isIE()) {
      init();
      bindEvents();
    }

    Wick.applyBottomMarginIfBanner();

    return offer;
  })();
});
