const $ = require('jquery');
import 'jquery.easing';

class SearchTiles {
  constructor(tileWrapper) {
    this.tiles = tileWrapper.find('.tile a');

    this.tiles.each((i, el) => {
      const tile = $(el);
      if (tile.text().length > 48) {
        tile.text( tile.text().substr(0, 48) + '…' );
      }
    })
  }
}

class ExtendedSearch {
  constructor(section) {
    this.section = section.addClass('initiated');

    $('#search-expand-collapse').on('click', (e) => {
      e.preventDefault();
      $(e.currentTarget).toggleClass('open');
      this.section.stop().slideToggle(500, 'swing');
    });

    section.find('.ev-search-btn').on('click', (e) => {
      e.preventDefault();
      $(e.currentTarget).toggleClass('open').next('.ev-filter').stop().slideToggle(400, 'easeOutQuad');
    });

    section.find('label.acc a').each((i, el) => {
      new FormAccordion($(el));
    });

    section.find('.reset').on('click', (e) => {
      e.preventDefault();

      const form = $(e.currentTarget).closest('form');

      form[0].reset();
      form.find('.half-checked').removeClass('half-checked');

      $('html, body').animate({
        scrollTop: form.offset().top - 120
      }, 500, 'easeOutQuad');
    });

    $('.datepicker').each((i, el) => {
      $(el).datepicker({ changeYear: true, changeMonth: true});
    });
  }
}

class FormAccordion{
  constructor(toggle) {
    const t = this;

    this.toggle = toggle;
    this.label = this.toggle.parent('label');
    this.checkbox = this.label.prev('input[type="checkbox"]');
    this.subs = this.label.next('.ev-filter');

    this.toggle.on('click', (e) => {
      e.preventDefault();
      e.stopPropagation();
      this.label.toggleClass('open');
      this.subs.stop().slideToggle(400, 'swing');
    })

    this.subs.find('input[type="checkbox"]').on('change', () => {
      this.checkSelection();
    })

    this.checkbox.on('change', (e) => {
      const isChecked = $(e.currentTarget).removeClass('half-checked').prop('checked');
      this.subs.find('input[type="checkbox"]').prop('checked', isChecked);
    })

    this.checkSelection();
  }

  checkSelection() {
    const checked = this.subs.find('input[type="checkbox"]:checked').length;
    const unchecked = this.subs.find('input[type="checkbox"]:not(:checked)').length;

    if (checked === 0) {
      this.checkbox.prop('checked', false).removeClass('half-checked');
    }
    else if (unchecked === 0) {
      this.checkbox.prop('checked', true).removeClass('half-checked');
    }
    else {
      this.checkbox.prop('checked', false).addClass('half-checked');
    }
  }
}


$('body').on('ihk-init dynamic-component-loaded', function () {
  $('.extended-search:not(.initiated)').each(function(i) {
    new ExtendedSearch($(this));
  });
  $('.search:not(.initiated) .tiles').each(function () {
    new SearchTiles($(this));
  })
})
