var Wick = Wick || {};

Wick.ScrollDisable = {
  el: {
    $body: $('body')
  },
  currentPosition: 0,
  disableScroll: function () {
    Wick.ScrollDisable.el.$body
      .addClass('scroll-disable')
      .css('margin-top', -Wick.ScrollDisable.currentPosition + 'px');
  },
  enableScroll: function () {
    Wick.ScrollDisable.el.$body
      .removeClass('scroll-disable')
      .css('margin-top', '');
    window.scrollTo(0, Wick.ScrollDisable.currentPosition);
  },
  initializeShowModalEvents: function (modal) {
    const $modal = $(modal);
    Wick.ScrollDisable.currentPosition = $(window).scrollTop();

    Wick.ScrollDisable.disableScroll();
    Wick.ScrollDisable.initializeHideModalEvents($modal);
  },
  initializeHideModalEvents: function (modal) {
    modal.on('hidden.bs.modal', function() {
      Wick.ScrollDisable.enableScroll();
    });
  },
  handleTagAdded: function () {
    Wick.ScrollDisable.currentPosition = $(window).scrollTop();
    Wick.ScrollDisable.disableScroll(Wick.ScrollDisable.currentPosition);
  },
  handleTagRemoved: function () {
    Wick.ScrollDisable.enableScroll(Wick.ScrollDisable.currentPosition);
  },
  init: function () {
    if (!Wick.Responsive.isTouchDevice()) {
      return;
    }

    $(document).on('show.bs.modal', '.modal', function (event) {
      Wick.ScrollDisable.initializeShowModalEvents(event.currentTarget);
    });

    Wick.ScrollDisable.el.$body.on("tagKlarnaModalAdded", Wick.ScrollDisable.handleTagAdded);
    Wick.ScrollDisable.el.$body.on("tagKlarnaModalRemoved", Wick.ScrollDisable.handleTagRemoved);
  }
};

$(document).ready(function () {
  Wick.ScrollDisable.init();
});
