String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g, "");
}

var lightningBlog = {

  /* ******************************************************************
   * Add Javascript goodies to posts
   *
   */
  garnishPost: function() {

    // Add "Select all" icon to code sections
    var pres = document.getElementsByTagName('pre');
    for (var x = 0, elem; elem = pres[x++];) {
      var img = document.createElement('img');
          img.src = "img/png/icon.hand.png";
          img.alt = img.title = "Select all";
          img.onclick = function() {
            if (window.getSelection) {
              var s = window.getSelection(), r = document.createRange();
              r.setStartBefore(this.nextSibling);
              r.setEndAfter(this.parentNode.lastChild);
              s.removeAllRanges();
              s.addRange(r);
            } else if (document.selection) {
              var parent = this.parentNode, r = document.body.createTextRange();
              var img = parent.removeChild(this);
              r.moveToElementText(parent);
              r.select();
              parent.insertBefore(img, parent.firstChild);
            }
          };
        elem.insertBefore(img, elem.firstChild);
    }
  },


  /* ******************************************************************
   * Fetch a post via Ajax by id
   *
   */
  fetchPost: function(id, action, callback, errorback, timeout) {
    var http = getHTTPObject();
    http.open("GET", window.location.pathname + "?action=" + action + "&id=" + id + "&ajax&" + (new Date()).getTime(), true);
    http.onreadystatechange = function() {
      if (http.readyState == 4) {
        clearTimeout(http.timeout);
        if (http.responseText.indexOf('Error:') === 0) {
          errorback(http.responseText);
        } else callback(http.responseText, http.responseXML);
      }
    };
    http.send(null);
    http.timeout = setTimeout(function() {
      http.abort();
      timeout();
    }, 3000);
  },


  /* ******************************************************************
   * Wrap a fetched message in quote bbcode and paste into the form
   *
   */
  quotePost: function(parentid, commentid, author) {
    var bp_message = document.getElementById('bp_message');

    if (bp_message) {
      this.fetchPost(commentid, "Fetch",
        function(text, data) {
          if (data) {
            var original = data.document.getElementsByTagName('original')[0];
            if (original && original.firstChild) {
              var message = original.firstChild.nodeValue.replace(/\[QUOTE[\S\s]+\[\/QUOTE\]/ig, "").trim();
              bp_message.value = "[QUOTE=" + author + ";" + commentid + "]" + message + "[/QUOTE]";
              bp_message.form.scrollIntoView();
            }
          }
        },
        function(error) { alert(error); },
        function() { window.location.href = window.location.pathname + "?post=" + parentid + "&quote=" + commentid + "#blogPost"; }
      );
      return false;
    } else return true;
  },


  /* ******************************************************************
   * Delete a comment or post
   *
   */
  deletePost: function(postid, parent) {
    if (confirm('Really delete this post?')) {
      this.fetchPost(postid, "Delete",
        function(text, data) {
          if (parent) { // This is a comment
            var li = document.getElementById('comment' + postid);
            if (li) {
              li.style.overflow = "hidden";
              li.size = [li.offsetHeight, li.offsetHeight - 1];
              li.opacity = [1.0, 0.99];
              li.rollUp = function() {
                if (this.style.height != "1px") {
                  this.style.height = Math.max(1, li.size[1] -= li.size[0] - li.size[1]) + "px";
                  this.style.opacity = Math.max(0, li.opacity[1] -= li.opacity[0] - li.opacity[1]);
                } else {
                  clearInterval(this.interval);
                  this.parentNode.removeChild(this);
                }
              };
              li.interval = setInterval((function(li) { return function() { li.rollUp(); }})(li), 30);

              var list = li.parentNode.getElementsByTagName('li');
              if (list.length == 1) { // We are removing the last comment
                var heading = document.getElementById('comments_heading');
                if (heading && heading.className.indexOf('closed') === -1)
                  heading.firstChild.nodeValue = "No Comments";
              }
            }
          } else window.location.href = "/";
        },
        function(error) { alert(error); },
        function() { window.location.href = window.location.pathname + "?action=Delete&id=" + postid; }
      );
    } return false;
  },


  /* ******************************************************************
   * Approve a comment or post
   *
   */
  approvePost: function(postid, parent, link) {
    this.fetchPost(postid, "Approve",
      function(text, data) {
        if (parent) { // This is a comment
          var li = document.getElementById('comment' + postid);
          if (li) {
            li.className = li.className.replace(/ ?ghosted ?/i, "");
            link.parentNode.removeChild(link);
            for (var x = 0, div = li.getElementsByTagName('div'), d; d = div[x++];)
              if (d.className == "commentOptions") d.style.display = "block";
          }
        } else window.location.href = window.location.pathname + "?post=" + postid;
      },
      function(error) { alert(error); },
      function() { window.location.href = window.location.pathname + "?action=Approve&id=" + parentid; }
    );
    return false;
  }
};



if (window.addEventListener) {
  window.addEventListener('load', lightningBlog.garnishPost, false);
} else if (window.attachEvent)
  window.attachEvent('onload', lightningBlog.garnishPost);