// const $ = require('jquery');
const $ = require('jquery');
const ihk = require('../ihk');

ihk.Sidebar = function(sidebar) {
  const t = this;

  t.sidebar = sidebar.addClass('initiated');
  t.timer = null;

  t.sidebar.on('resize', function () {
    t.onResize();
  }).trigger('resize');

  $(window).on('resize', function () {
    t.onResize();
  })
}

ihk.Sidebar.prototype.onResize = function() {
  const t = this;

  if (t.timer) {
    clearTimeout(t.timer);
  }

  t.timer = setTimeout(function () {
    if (t.sidebar.outerHeight() < $(window).height() - 180) {
      t.sidebar.addClass('sticky');
    }
    else {
      t.sidebar.removeClass('sticky');
    }
  }, 250)
};

$('body').on('ihk-init dynamic-component-loaded', function () {
  $('.sidebar:not(.initiated)').each(function(i) {
    new ihk.Sidebar($(this));
  });
})
