function $ (id)
{
  return document.getElementById(id);
}

function makeCommentable ()
{
  $("msg").addEventListener("mousedown", ifLink(followLink, makeEditable), false);
}

function ifLink (f, falt)
{
  return function (e)
  {
    var link = e.target;
    if (link && link.nodeName == "A" && link.href)
      return f(link);
    else if (falt)
      return falt(e);
  }
}

function followLink (link)
{
  if ($("msg").contentEditable)
  {
    location.href = link.href;
  }
  else
  {
    link.click();
  }
  $("msg").blur();
}

function makeEditable ()
{
  var c = $("msg");
  if (c.contentEditable != "true")
  {
    c.contentEditable = true;
    monitorChanges.baseContent = c.innerHTML;

	  // Disable spellchecking on Gecko's.
	  document.body.spellcheck = false;

    // Make sure links always work onclick.
    c.addEventListener("click", ifLink(followLink), false);

    // Monitor changes. This isn't perfect but good enough for this gimmick.
    c.addEventListener("keyup", monitorChanges, false);
    c.addEventListener("mouseup", monitorChanges, false);
  }
}

function monitorChanges (e)
{
  var c = $("msg");
  if (c.innerHTML != monitorChanges.baseContent)
  {
    // Show edit
    $("editor").className = $("instruction").className = "secretVisible";
    
    // Enable Send button
    $("send").addEventListener("click", postMsg, false);
    
    // No need for this method any more.
    c.removeEventListener("keyup", monitorChanges, false);
    c.removeEventListener("mouseup", monitorChanges, false);
    
    trackEvent("/events/edit-discovered");
  }
}

function monitorSize ()
{
  recalcBodyState();
  window.onresize = recalcBodyState;
}

function recalcBodyState ()
{
  document.body.className = document.documentElement.clientWidth < 990 ? "narrow" : "wide";
  // Hack for Safari. Does no harm on other browsers.
  document.getElementsByTagName("footer")[0].style.paddingTop = "1px";
}

function postMsg ()
{
  var req = new XMLHttpRequest();
  req.open("POST", "/feedback", true);
  req.onreadystatechange = postDone;
  req.send($("msg").innerHTML);
  trackEvent("/events/edit-posted");
}

function postDone ()
{
  $("instruction").innerHTML = "Thank you!";
  $("editor").className = "secret";
  $("msg").contentEditable = false;
}

function trackLinks ()
{
  document.body.addEventListener("click", trackLink, false);
}

function trackLink (e)
{
  if (e.target && e.target.href)
    trackEvent("/out/" + e.target.href);
}

function trackEvent (uri)
{
  if (pageTracker)
    pageTracker._trackPageview(uri.replace("https://", "").replace("http://", "").replace(":", "/").replace("www.typlab.com/", ""));
}

(function init ()
{
  if (!document.body.addEventListener)
    return; // No script for you!
  
  trackLinks();
  monitorSize();
})();
