var WikiBit = function(elem, options) {
    this.element = jQuery(elem);
    this.tb_elem = jQuery("<div></div>").appendTo(jQuery('<div class="wikibit-textbox"></div>"').appendTo(this.element));

    this.options = jQuery.extend({
        load: AXIS.F,      // executed after wikibit is loaded
        textboxOptions: {}
    }, options)

    this.id = this.element[0].id;
    if (this.id.charAt(0) == "/") {
        this.url = this.id;
    }
    else {
        this.url = AXIS.Util.uri.getFolder(location.pathname) + this.id;
    }
    this.load();
};
  
WikiBit.prototype = {
  load: function() {
      var self = this;
      this.tb_elem.textbox(this.url, jQuery.extend(this.options.textboxOptions, { 
          versioned: true,
          load: function() {
              self.init();
              self.options.load();
          },
          save: jQuery.context(self, self.init),
          cancel: jQuery.context(self, self.init)
      }));
      this.textbox = this.tb_elem.data("textbox");
  },

  init: function() {
      var history_link = jQuery("<a href='#' class='history-button button'>History</a>");
      history_link.appendTo(this.textbox.toolbar)
        .bind("click", jQuery.context(this, this.history));

      if (this.textbox.isCheckedOut(this.url)) {
        history_link.removeClass("disabled");
      }
      else {
        history_link.addClass("disabled");
      }
  },

  diff: function(v) {
      var current = AXIS.WebDAV.GET({ asynch: false, url: this.url }).responseText;
      var newSide = this.textbox.processResult(current);
      var oldSide = this.textbox.processResult(this.getVersion(v));

      var diff = diffString(oldSide, newSide);
      jQuery("#" + AXIS.escapeCSS(this.id) + "-diff > .diff-left").html(diff.replace(/ins>/, 'ins-inv>'));
      jQuery("#" + AXIS.escapeCSS(this.id) + "-diff > .diff-right").html(diff.replace(/del>/, 'del-inv>'));
  },

  leaveHistory: function(e) {
      jQuery(this.element).removeClass("history");
      this.history_div.remove();
      this.load();
      if (e) {
          e.preventDefault();
          e.stopPropagation();
      }
  },

  updateSaveAsNew: function(v) {
      var self = this;
      var elem = jQuery('#' + AXIS.escapeCSS(this.id) + '-save_as_new')
      elem.unbind('click'); // clear existing handlers.
      elem.click(function(e) {
          self.saveAsNewVersion(v);
          if (e) {
              e.preventDefault();
              e.stopPropagation();
          }
      });
  },

  saveAsNewVersion: function(v) {
      var version_url = this.getVersionURL(v);
      if (!this.textbox.isCheckedOut()) {
        this.textbox.checkout(this.url);
      }

      AXIS.WebDAV.COPY({
          url: version_url,
          destination: this.url,
          async: false,
          overwrite: true
      });

      AXIS.WebDAV.CHECKIN({ url: this.url });
      this.textbox.checkout(this.url);
      this.diff(v);
  },

  history: function() {
      jQuery(this.element).addClass("history");
      this.textbox.content.remove();
      this.textbox.toolbar.remove(); // cleanup the toolbar events

      // initialize versioning info 
      var checked_in_url = this.getCheckedInUrl();
      var current_version = AXIS.Util.uri.basename(checked_in_url);
      var version_collection = "/!lime/root" + AXIS.Util.uri.getFolder(checked_in_url);

      // initialize the various div's 
      this.history_div = jQuery('<div class="wikibit-history"></div>').appendTo(jQuery(this.element));

      var diff_div = jQuery('<div id="' + this.id + '-diff" class="diff">' + 
                                '<div class="diff-left"></div>' + 
                                '<div class="diff-right"></div>' + 
                            '</div>').appendTo(this.history_div);

      // display diff 
      this.diff(current_version - 1);

      jQuery('<div id="' + this.id + '-history" class="history-list"></div>').prependTo(diff_div);

      var history_toolbar = jQuery("<div class='history-toolbar'></div>").prependTo(this.history_div);
      var done_link = jQuery("<a href='#' class='history_control button'>Done</a>").appendTo(history_toolbar);

      done_link.click(jQuery.context(this, this.leaveHistory));

      var side_by_side_toolbar = jQuery("<div class='revision-header'>" +
          "<div class='previous-revision-header'>" + 
              "<div style='float: left'>Previous revision</div> " + 
              "<a href='#' id='" + this.id + "-save_as_new' class='save_as_new button'>Save as newest version</a>" +
          "</div>" +
          "<div class='current-revision-header'>" + "<div style='float: left'>Current revision</div> " + "</div>" +
          "</div>"
      ).prependTo(this.history_div);

      this.updateSaveAsNew(current_version - 1);

      // attach history_browser 
      var responses = AXIS.WebDAV.getVersionTreeReport({
          url: this.url,
          asynch: false
      }).responseXMLObject().multistatus.response;

      var timestamps = [];
      var items = [];

      for(var i=0; i<responses.length; i++) {
          var response = responses[i];
          var props = response.propstat.prop;
          var d = new Date(props['getlastmodified']);
          timestamps.push(d.getTime());
          items.push(
              props['version-name'] + " " + props['creator-displayname'] + " " + d.toLocaleString()
          );
      };
      var self = this;
      var history_browser = new HistoryBrowser(timestamps, items, self.id + "-history", { 
          onItemClick: jQuery.context(self, function(e) {
              jQuery('history-river').hide();
              var i = e.target.id.replace(/.*-/,'');
              this.diff(i);
              this.updateSaveAsNew(i);
          })
      });

      history_browser.river.hide();
      history_browser.timeline.element.click(function() {
          history_browser.river.toggle();
      });
  },

  getCheckedInUrl: function() {
      var checked_in_url = this.textbox['checked-in'] || this.textbox.getProperty(this.url, ["checked-out"]);
      if (!checked_in_url || !checked_in_url["checked-out"]) {
          return null;
      }

      this.textbox["checked-in"] = checked_in_url;
      return "/!lime/root" + checked_in_url["checked-out"].href;
  },

  getVersion: function(n) {
      return AXIS.WebDAV.GET({ asynch: false, url: this.getVersionURL(n) }).responseText;
  },

  getVersionURL: function(v) {
      var checked_in_url = this.getCheckedInUrl();
      var version_url;

      if (checked_in_url && v) {
          version_url = checked_in_url.replace(/\d+$/, v);
      }
      else {
          version_url = this.url;
      }

      return version_url;
  }
}
