jQuery(document).ready(function () {
  var shouldNotBeActioned = false;

  jQuery('#fullpage').fullpage({
    autoScrolling: true,
    licenseKey: 'OPEN-SOURCE-GPLV3-LICENSE',
    slidesNavigation: true,
    fixedElements: '.nt-timeline-return-button, .timeline-controls',
    navigationPosition: 'left',
    onLeave: function (section, origin, direction) {

      if (shouldNotBeActioned) {
        return;
      }

      colourControls(origin);

      var ttl = jQuery.fn.fullpage.getFullpageData.navigationTooltips.length + 1;

      if (direction == 'down') {
        jQuery('.slider-control').slider('option', 'value', ttl - (jQuery.fn.fullpage.getActiveSection().index + 1))
      } else {
        jQuery('.slider-control').slider('option', 'value', ttl - (jQuery.fn.fullpage.getActiveSection().index - 1))
      }

    }
  });

  jQuery('.fp-tooltip').each(function () {
    this.parentElement.classList.add('year-divider');
  });

  var slider = jQuery(".slider-control").slider(
    {
      min: 1,
      step: 1,
      orientation: "vertical"
    }
  );

  jQuery('.slider-control').slider('option', 'max', jQuery.fn.fullpage.getFullpageData.navigationTooltips.length + 1);
  jQuery('.slider-control').slider('option', 'value', jQuery.fn.fullpage.getFullpageData.navigationTooltips.length + 1);

  jQuery(".slider-control").on("slidechange", function (event, ui) {

    if (event.originalEvent) {
      shouldNotBeActioned = true;
      jQuery.fn.fullpage.moveTo(jQuery('.slider-control').slider('option', 'max') - ui.value + 1);
      console.log(jQuery.fn.fullpage.getFullpageData.navigationTooltips.length - ui.value + 1);
      shouldNotBeActioned = false;
    } else {
      shouldNotBeActioned = false;
    }
    colourControls(jQuery.fn.fullpage.getActiveSection());
  });

  var jQueryslider = jQuery('.slider-control');
  var max = jQueryslider.slider("option", "max");
  var spacing = 100 / (max - 1);

  jQueryslider.find('.ui-slider-tick-mark').remove();

  for (var i = 0; i < max; i++) {
    jQuery('<span class="ui-slider-tick-mark"></span>').css('top', (spacing * i) + '%').appendTo(jQueryslider);
  }

  var foundTicks = jQuery('.ui-slider-tick-mark');

  jQuery('#fullpage > .image-container').each(function (index) {
    if (!!jQuery(this).data('tooltip')) {
      var year = jQuery('.image-container')[index];

      jQuery(foundTicks[index]).addClass('ui-slider-tick-mark--year');
      jQuery(foundTicks[index]).append('<p>' + jQuery(year).data('tooltip') + '</p>')
    }
  });

  function colourControls() {

    setTimeout(function () {
      if(!jQuery(jQuery.fn.fullpage.getActiveSection().item).data('colour')) {
        jQuery('.slider-control-white').removeClass('slider-control-white');
        return;
      }
      jQuery('.slider-control').addClass('slider-control-white');
    }, 400);
  }
});
