var textarea    = document.getElementsByName('document[source]')[0],
    preview     = document.getElementById('preview'),
    previewLink = document.getElementById('preview-link'),
    pos         = textarea.value.length * 2,
    dirty       = true

textarea.focus()
textarea.setSelectionRange(pos, pos)
textarea.addEventListener('keyup', function(ev) {
  dirty = true
}, false)

updatePreview = function() {
  if (!dirty) return;
  var xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      preview.innerHTML = xhr.responseText
      dirty = false
    }
  }
  xhr.open('POST', '/render', true)
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  xhr.send('source=' + encodeURIComponent(textarea.value))
}

togglePreview = function() {
  if (window.location.hash == '#preview') {
    window.location.hash = ''
    previewLink.textContent = 'P'
    previewLink.setAttribute('title', 'Preview changes (Alt-P)')
    textarea.focus()
  } else {
    window.location.hash = '#preview'
    previewLink.textContent = 'E'
    previewLink.setAttribute('title', 'Edit document (Alt-P)')
  }
}

scrollPreview = function() {
  var editorHeight  = textarea.scrollHeight - textarea.clientHeight,
      previewHeight = preview.scrollHeight - preview.clientHeight,
      scrollRatio   = textarea.scrollTop / editorHeight

  preview.scrollTop = previewHeight * scrollRatio;
}

window.setTimeout(function() {
  updatePreview()
  window.setTimeout(arguments.callee, 1000)
}, 0)

textarea.addEventListener('scroll', scrollPreview);

previewLink.addEventListener('click', function(ev) {
  togglePreview()
  ev.preventDefault()
})

keymage('alt-p', togglePreview, {preventDefault: true})

var saveButton = document.querySelector('a[href="#save"]')
saveButton.addEventListener('click', function(ev) {
  document.forms[0].submit()
  ev.preventDefault()
}, false)

@@ -171,24 +171,85 @@
 iew-link'),%0A
+    saveButton  = document.querySelector('a%5Bhref=%22#save%22%5D'),%0A
     pos     
@@ -363,82 +363,36 @@
 os)%0A
-textarea.addEventListener('keyup', function(ev) %7B%0A  dirty = true%0A%7D, false)
+%0A// Preview-related function
 %0A%0Aup
@@ -1464,16 +1464,35 @@
 tio;%0A%7D%0A%0A
+// Event handling%0A%0A
 window.s
@@ -1634,16 +1634,91 @@
 review);
+%0Atextarea.addEventListener('keyup', function(ev) %7B%0A  dirty = true%0A%7D, false)
 %0A%0Aprevie
@@ -1812,124 +1812,8 @@
 %7D)%0A%0A
-keymage('alt-p', togglePreview, %7BpreventDefault: true%7D)%0A%0Avar saveButton = document.querySelector('a%5Bhref=%22#save%22%5D')%0A
 save
@@ -1911,16 +1911,16 @@
 fault()%0A
-
 %7D, false
@@ -1913,16 +1913,73 @@
 ult()%0A%7D, false)%0A
+%0Akeymage('alt-p', togglePreview, %7BpreventDefault: true%7D)%0A

Reorganize editor code