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

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

  var scroll_top = 0;
  var search_input_timeout;

  function open_search() {
    window.timetable_can_scroll = false;
    window.navigation_is_open = true;
    window.requestAnimationFrame(function() {
      scroll_top = $(window).scrollTop();
      $canvas.css({
        'top': scroll_top * -1,
        'position': 'fixed'
      });
      window.requestAnimationFrame(function() {
        $body.addClass('search_open');
        window.clearTimeout(search_input_timeout);
        search_input_timeout = window.setTimeout(function() {
          $body.find('#search__query').focus();
        }, 800);
      });
    });
  }

  function close_search() {
    window.clearTimeout(search_input_timeout);
    $body.find('#search__query').blur();
    window.requestAnimationFrame(function() {
      $body.removeClass('search_open');
      $canvas.removeAttr('style');
      $(window).scrollTop(scroll_top);
      window.navigation_is_open = false;
      window.timetable_can_scroll = true;
    });
  }
  window.close_search = close_search;

  $body.on('submit', '.search__form', function(event) {
    event.preventDefault();
    var $form = $(this);

    $body.find('#search__query').blur();

    var form_url = $form.attr('action');
    var serialized_form = $form.serialize();
    history.pushState({}, 'search', form_url + '?' + serialized_form);

    if (serialized_form !== 'q=') {
      var $search_content_main = $body.find('.search__content__main');
      $search_content_main.addClass('loading');

      $.ajax({
        type: $form.attr('method'),
        url: form_url,
        data: serialized_form,
        success: function(data) {
          $body.find('#canvas').remove();
          $body.addClass('_search');
          $search_content_main.removeClass('loading');
          $body.find('.search__results').replaceWith($(data).find('.search__results'));
          window.requestAnimationFrame(function() {
            $body.addClass('search_results');
          })
        }
      });
    } else {
      $body.removeClass('search_results');
    }
  });
});