-initialized = false
+
 historyCache = []
-
+lastState = null
 visit = (url) ->
   if browserSupportsPushState? and document.location.href != url
-    rememberInitialPage()
-    saveScrollOffset()
+    rememberPage()
     reflectNewUrl url
     fetchReplacement url
   else
     document.location.href = url
 
-rememberInitialPage = ->
-  return if initialized
-  window.history.replaceState { turbolinks: true, position: window.history.length - 1}, "", document.location.href
-  historyCache[window.history.state.position] = url: document.location.href, body: document.body, title: document.title
-  initialized
-
-saveScrollOffset = ->
-  cache = historyCache[window.history.state.position]
-  cache.scrollTop = window.pageYOffset
-  cache.scrollLeft = window.pageXOffset
-
-
+rememberPage = ->
+  historyCache[lastState.position] = url: document.location.href, body: document.body, title: document.title, pageYOffset: window.pageYOffset, pageXOffset: window.pageXOffset
 
 fetchReplacement = (url) ->
   xhr = new XMLHttpRequest

  replaceDocument doc.body,title?.textContent, 'cache'


replaceDocument = (body,title,cache) ->
  originalBody = document.body
  document.documentElement.appendChild body, originalBody
  document.documentElement.removeChild originalBody
  document.title = title
  historyCache[window.history.state.position] = {url:document.location.href,body:body,title:title} if cache



extractLink = (event) ->

  xhr.send()

fetchHistory = (state) ->
  rememberPage()
  cache = historyCache[state.position]
  if cache
    replaceDocument cache.body, cache.title
    triggerPageChange
    window.scrollTo(cache.pageXOffset,cache.pageYOffset)
  else
    fetchReplacement document.location.href

