 currentState = null
 initialized  = false
 referer = document.location.href
+historyState = null
 
 visit = (url) ->
   if browserSupportsPushState

  document.title = title
  document.documentElement.replaceChild body, document.body

  currentState = window.history.state
  triggerEvent 'page:change'


reflectNewUrl = (url) ->
  if url isnt document.location.href
    referer = document.location.href
    window.history.pushState { turbolinks: true, position: currentState.position + 1 }, '', url

rememberCurrentUrl = ->
  window.history.replaceState { turbolinks: true, position: window.history.length - 1 }, '', document.location.href

rememberCurrentState = ->
  currentState = window.history.state

rememberInitialPage = ->
  unless initialized

  nonHtmlLink(link)  or remoteLink(link)      or noTurbolink(link)  or
  newTabClick(event)

historyReplaceState = (state, title, url) ->
  window.history.replaceState state, title, url
  historyState = state

historyPushState = (state, title, url) ->
  window.history.pushState state, title, url
  historyState = state

browserSupportsPushState =
  window.history and window.history.pushState and window.history.replaceState

if browserSupportsPushState
  window.addEventListener 'popstate', (event) ->
    historyState = event.state
    fetchHistory event.state if event.state?.turbolinks

  document.addEventListener 'click', handleClick,true
