 Template.header.events =
   'click .top-menu .search': (e, template) ->
-    Session.set 'searchActive', true
-    Session.set 'searchFocused', true
+    # Only if focused on no-index header
+    if Template.header.noIndexHeader()
+      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
+    # Only if focused on no-index header
+    if Template.header.noIndexHeader()
+      Session.set 'searchFocused', true
 
   'click .search-button': (e, template) ->
+    Session.set 'searchActive', true
     naturalQueryChange $(template.findAll '.search-input').val()
 
   'blur .search-input': (e, template) ->

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

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

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

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

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

  'submit #search': (e, template) ->
    e.preventDefault()
    naturalQueryChange $(template.findAll '.search-input').val()

Template.header.development = ->

  'search-focused' if Session.get 'searchFocused'

Template.searchInput.rendered = ->
  # 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
