$(function() {
  var $body = $('body');
  var $canvas = $('#canvas');
  var $navigation = $('#navigation');

  window.onpageshow = function(event) {
    if (event.persisted) {
      window.location.reload();
    }
  };

  $body.on('click', 'a', function(event) {
    var href = $(this).attr('href');
    var target = $(this).attr('target');
    if (href.indexOf('/') === 0 && !target && !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey && !$('html').hasClass('cms-ready')) {
      event.preventDefault();
      $body.addClass('unload loading');
      window.setTimeout(function() {
        window.location = href;
      }, 50);
    }
  });

  $body.on('click', '.header__button--navigation', function(event) {
    event.preventDefault();
    open_navigation();
  });

  $body.on('click', '.navigation__close', function(event) {
    event.preventDefault();
    close_navigation();
  });

  var scroll_top = 0;

  function open_navigation() {
    window.timetable_can_scroll = false;
    window.navigation_is_open = true;

    $navigation.one(window.transitionend, function() {
      window.requestAnimationFrame(function() {
        $navigation.css('position', 'relative');
        $navigation.off(window.transitionend);
      });
    });

    window.requestAnimationFrame(function() {
      scroll_top = $(window).scrollTop();
      $canvas.css({
        'top': scroll_top * -1,
        'position': 'fixed'
      });
      window.requestAnimationFrame(function() {
        $body.addClass('navigation_open');
      });
    });
  }

  function close_navigation() {
    $navigation.removeAttr('style');
    $body.removeClass('navigation_open');
    window.requestAnimationFrame(function() {
      $canvas.removeAttr('style');
      $(window).scrollTop(scroll_top);
      window.navigation_is_open = false;
      window.timetable_can_scroll = true;
    });
  }
});