$(function() {
  var $body = $('body');

  var $content_navigation = $('.content__navigation');
  var $content = $('.content');
  var content_navigation_class = 'content__navigation__anchor';

  if ($content_navigation.length === 0) {
    return false;
  }

  $content.find('.section').each(function() {
    var $this = $(this);
    var id = $this.attr('id');
    var text = $this.find('h2').text();
    var content_navigation_link = '<a class="' + content_navigation_class + '" href="#' + id + '">' + text + '</a>';
    $content_navigation.find('ul').append('<li>' + content_navigation_link + '</li>');
    $this.find('.section__title__content').html(text);
  });

  if (window.location.hash) {
    var hash = window.location.hash;
    window.requestAnimationFrame(function() {
      window.location.hash = hash;
    });
  }

  $body.on('click', '.' + content_navigation_class, function(event) {
    event.preventDefault();
    var $this = $(this);
    $content_navigation.find('.active').removeClass('active');
    $this.addClass('active');
    TweenLite.to(window, 0.5, {
      scrollTo: $this.attr('href')
    });
  });

  var $navigation_watchers = $content.find('.section');
  $navigation_watchers.each(function() {
    var element = this;
    var elementWatcher = scrollMonitor.create(element);
    elementWatcher.fullyEnterViewport(function() {
      $content_navigation.find('.active').removeClass('active');
      $content_navigation.find('a[href="#' + $(element).attr('id') + '"]').addClass('active');
    });
  });

  var content_navigation_offset_top = $content_navigation.offset().top;
  $(window).on('resize', function() {
    content_navigation_offset_top = $content_navigation.offset().top;
  });

  var $content_navigation_progress_fill = $('.content__navigation__progress__fill');

  function content_navigation_scroll() {
    var progress = Math.round(100 / window.document_height * (window.scroll_top + window.window_height));
    $content_navigation_progress_fill.height(progress + '%');

    if (content_navigation_offset_top && window.scroll_top >= content_navigation_offset_top) {
      $content_navigation.addClass('fixed');
    } else {
      $content_navigation.removeClass('fixed');
    }
  }

  function watch_content_navigation_scroll() {
    if (!window.navigation_is_open) {
      content_navigation_scroll();
    }
    window.requestAnimationFrame(watch_content_navigation_scroll);
  }

  watch_content_navigation_scroll();
});