function $(id) { return document.getElementById(id); }

setInterval(check, 1000);

var oldHtml = "";

function load() {
  oldHtml = $("html").innerHTML;
  if (navigator.userAgent.toLowerCase().indexOf('chrome') == -1)
    $("html").focus();
  document.onkeydown = keydown;
  try {
    document.execCommand("styleWithCSS", null, false);
    document.execCommand("insertBrOnReturn", null, false);
  } catch (e) { };
}

function check() {
  var html = $("html").innerHTML;
  if (html != oldHtml) {
    oldHtml = html;
    $("area").value = html;
    Ajax.form("form", document.location.href).submit();
  }
}

function keydown(evt) {
  var evt = Ajax.IE ? event : evt;
  if (evt.ctrlKey) {
    var key = String.fromCharCode(evt.keyCode);
    switch (key) {
      case "B":
        eat(evt);
        document.execCommand("bold", 0, 0);
        break;
      case "I":
        eat(evt);
        document.execCommand("italic", 0, 0);
        break;
      case "U":
        eat(evt);
        document.execCommand("underline", 0, 0);
        break;
      case "K":
        eat(evt);
        var url = prompt("Please enter the link URL:", "http://");
        document.execCommand("createLink", 0, url);
        break;
      case "M":
        eat(evt);
        var url = prompt("Please enter the image URL:", "http://");
        document.execCommand("insertimage", 0, url);
        break;
    }
  }
  return;
}

function eat(evt) {  
  if (Ajax.IE) {
    evt.returnValue = false;
    evt.cancelBubble = true;
  }
  else {
    evt.preventDefault();
    evt.stopPropagation();
  }
}

//  Ajax.js | A lightweight ajax api written by Martin Kool | (c)copyright 2008 Q42 Internet B.V. 
var Ajax =
{   
  IE: (navigator.appName == "Microsoft Internet Explorer"),
  
  calls: {},
  
  // api for xhr gets
  get: function(url, handler, loadingId)
  {
    if (!handler)
      handler = Ajax.scatter;
    Ajax.httpRequest(url, "GET", handler, loadingId?document.getElementById(loadingId.replace(/^#/,"")):document.body);
  },
  // generic xhr call
  httpRequest: function(url, httpMethod, handler, loadingEl)
  {
    // generate the xhr and set the readystatechange handler
    var xhr = Ajax.IE? new ActiveXObject("Microsoft.XmlHttp") : new XMLHttpRequest();

    // cancel previous calls to the same url
    if (Ajax.calls[url])
    {
      Ajax.calls[url].abort();
      delete Ajax.calls[url];
    }

    Ajax.calls[this.url] = xhr;
    xhr.open(httpMethod, url, true);
    xhr.setRequestHeader("ajax", 1);
    xhr.onreadystatechange = function()
    {
      if (xhr.readyState == 4)
        handler(xhr, loadingEl);
    }
    xhr.send(null);    
  },
  // filters script and executes it after scattering one or elements in xhr's contents
  scatter: function(xhr, loadingEl)
  {     
    var script = "", 
        els = [],
        html = xhr.responseText.replace(/<script[^>]*?>([^<]*?)<\/script>/gim, 
               function(a,b,c){script+=b; return "";}),    
        temp = document.createElement("div");        
    
    temp.innerHTML = html;
    for (var i=0, l=temp.childNodes.length; i<l; i++)
      els.push(temp.childNodes[i]);
    for (i=0; i<l; i++)
    {
      var child = els[i];
      if (child.nodeType == 1 && child.id)
      {         
        var targetEl = document.getElementById(child.id);
        if (targetEl)
          Ajax.replaceElement(targetEl, child);
      }
    }
    eval(script);
  },  
  // replaces one element with the other
  replaceElement: function(el, newEl)
  {
    el.style.display = "none";
    el.parentNode.insertBefore(newEl, el);
    el.parentNode.removeChild(el);
  },
  // retrieve a Ajax.Form object by id or by element
  form: function(idOrElement, url)
  {
    var formEl = idOrElement;
    if (typeof(idOrElement) == "string")
      formEl = document.getElementById(formEl);
    return new Ajax.Form(formEl, url);
  }
};

// The form object has a submit method to submit by xmlhttp
Ajax.Form = function(formEl, url)
{
  this.formEl = formEl;
  this.url = url;
}
Ajax.Form.prototype =
{
  // Its only argument is the Ajax.Form instance, which exposes the xhr and formEl.
  submit: function(loadingId)
  {
    var loadingEl = loadingId?document.getElementById(loadingId.replace(/^#/,"")):document.body;
    var h = this.defaultResponseHandler;
    var xhr = Ajax.IE? new ActiveXObject("Microsoft.XmlHttp") : new XMLHttpRequest();
    var ps = this.getParameterString();
    var attrs = this.formEl.attributes;
    var method = attrs.method ? attrs.method.nodeValue.toLowerCase() : "get";
    if (!this.url)
      this.url = attrs.action.nodeValue;

    if (Ajax.calls[this.url])
    {
      Ajax.calls[this.url].abort();
      delete Ajax.calls[this.url];
    }
    Ajax.calls[this.url] = xhr;

    if (method == "get")
      this.url += (this.url.indexOf('?')==-1?'?':'&') + ps;
    xhr.open(method, this.url, true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.setRequestHeader("Content-length", ps.length);
    xhr.setRequestHeader("ajax", 1);
    xhr.onreadystatechange = function() { h(xhr); };
    xhr.send(method == 'get' ? null : ps);
  },
  // builds up the parameterstring from the form elements
  getParameterString: function()
  {
    var ps = "";
    for (var i=0, el; el = this.formEl.elements[i++];)
    {
      if (!el.name)
        continue;
      var name = el.name;
      var value = escape(el.value);
      switch(true)
      {
        case el.type == "submit" && !el.clicked:
          el.clicked = undefined;
        case el.type == "radio" && !el.checked:
        case el.type == "checkbox" && !el.checked:
          continue;
        case el.type == "submit":
          el.clicked = undefined;
        default:
          ps += ((ps == "")? "" : "&") + name + "=" + value;
      }  
    }
    return ps;
  },
  // the default handler for the readyStateChange event
  defaultResponseHandler: function(xhr)
  {
    if (xhr.readyState == 4)
      Ajax.scatter(xhr);
  }
};
