var Wick = Wick || {};
Wick.CardSlider = (function () {
  var $cardSliders = $('.card-slider');

  var getParameters = function (element, breakpoint) {
    var elemParent = $(element).parent(),
      count = $(element).find('.swiper-wrapper').children().length,
      slidesPerView = breakpoint === 'up-lg' ? element.dataset.slides : breakpoint === 'only-md' ? element.dataset.slidesMd : 1,
      isLocked = count <= slidesPerView;

    return {
      roundLengths: true,
      pagination: {
        el: elemParent.find('.card-slider__actions .btn__numbers')[0],
        type: 'custom',
        renderCustom: function (swiper, current, total) {
          return current + ' of ' + total;
        }
      },
      navigation: {
        nextEl: elemParent.find('.card-slider__btn-next')[0],
        prevEl: elemParent.find('.card-slider__btn-prev')[0]
      },
      slidesPerView: slidesPerView,
      spaceBetween: 30,
      watchOverflow: true,
      loop: !isLocked
    }
  };

  var bindShowMoreLess = function (slider) {
    var btn = '.card-slider__btn',
      frozenClass = 'card-slider_frozen',
      $wrapper = $(slider.el).parent('.card-slider__wrapper'),
      $btns = $wrapper.find(btn),
      $actions = $wrapper.find('.card-slider__actions');

    $actions.toggle(!slider.isLocked);
    $btns.off('click.showMoreLess').on('click.showMoreLess', function(){
      if ($wrapper.hasClass(frozenClass)){
        $('html, body').scrollTop($wrapper.offset().top - 30);
      }
      slider.params.virtualTranslate = !slider.params.virtualTranslate;
      $wrapper.toggleClass(frozenClass);
      $btns.toggle();
    });
  };

  var createSliders = function (bp) {
    $cardSliders.each(function(index, element){
      var slider = element.swiper;
      if (slider){
        slider.destroy();
      }
      slider = new Swiper(element, getParameters(element, bp));

      // listener for closing the cards which in "Read more" state
      slider.on('slideChange', function () {
        var x = $(this.$el).find('.clamp-full');
        if (x.length) {
          x.find('.clamp_btn').click();
        }
      });

      bindShowMoreLess(slider);
    });
  };

  var init = function () {
    createSliders(Wick.Responsive.getCurrentBreakpoint());
    Wick.Responsive.onBreakpoint(function () {
      createSliders('down-sm');
    }, 'down-sm');
    Wick.Responsive.onBreakpoint(function () {
      createSliders('only-md');
    }, 'only-md');
    Wick.Responsive.onBreakpoint(function () {
      createSliders('up-lg');
    }, 'up-lg');
  };

  $(document).ready(function () {
    $cardSliders.length && init();
  });
})();
