   'search-focused' if Session.get 'searchFocused'
 
 Template.searchInput.rendered = ->
-  if Session.get 'searchFocused'
+  # We make sure search input is focused if we know it should be focused (to make sure focus is retained between redraws)
+  # Additionally, HTML5 autofocus does not work properly when routing back to / after initial load, so we focus if we are displaying index header
+  if Session.get('searchFocused') or Template.header.indexHeader()
     $(@findAll '.search-input').focus()
 
 Template.searchInput.indexHeader = Template.header.indexHeader

Template.header.events =
  'click .top-menu .search': (e, template) ->
    Session.set 'searchActive', true
    Session.set 'searchFocused', true

  'click .search-input': (e, template) ->
    Session.set 'searchActive', true
    Session.set 'searchFocused', true

  # TODO: Parse search input and map to #title and others

  'click .search-button': (e, template) ->
    naturalQueryChange $(template.findAll '.search-input').val()

  'blur .search-input': (e, template) ->

    naturalQueryChange $(template.findAll '.search-input').val()

  'change .search-input': (e, template) ->
    Session.set 'searchActive', true
    Session.set 'searchFocused', true
    naturalQueryChange $(template.findAll '.search-input').val()

  'keyup .search-input': (e, template) ->
    val = $(template.findAll '.search-input').val()
    # If user focused with tab or pressed some other non-content key we don't want to activate the search
    Session.set 'searchActive', true if val
    Session.set 'searchFocused', true
    naturalQueryChange val

  'paste .search-input': (e, template) ->
    Session.set 'searchActive', true
    Session.set 'searchFocused', true
    naturalQueryChange $(template.findAll '.search-input').val()

  'cut .search-input': (e, template) ->
    Session.set 'searchActive', true
    Session.set 'searchFocused', true
    naturalQueryChange $(template.findAll '.search-input').val()

  'submit #search': (e, template) ->
    e.preventDefault()
    # If search is empty and user presses enter (submits the form), we should activate - maybe user wants structured query form
    Session.set 'searchActive', true
    Session.set 'searchFocused', true
    naturalQueryChange $(template.findAll '.search-input').val()

Template.header.development = ->
