Ajax.InPlaceExternallyControlledEditor = Class.create(Ajax.InPlaceEditor, {
  initialize: function($super, element, url, options) {
    this._extraDefaultOptions = Ajax.InPlaceExternallyControlledEditor.DefaultOptions;
    $super(element, url, options);
  },
  getText: function() {
    return new String(this.element.innerHTML).unescapeHTML();
  }
});

Ajax.InPlaceExternallyControlledEditor.DefaultOptions = {
  ajaxOptions: {evalScripts: false},
  onComplete: null,
  onEnterHover: null,
  onLeaveHover: null,
  externalControlOnly: true,
  clickToEditText: ''
};

function replaceSelection (input, replaceString) {
  var selectionStart = input.selectionStart;
  var selectionEnd = input.selectionEnd;
  var contentBeforeSelection = input.value.substring(0, selectionStart);
  var contentAfterSelection = input.value.substring(selectionEnd);
  var codeRegExp = /[\r\n]+\{{3}[^\}{3}]*$/;
  
  if (codeRegExp.test(contentBeforeSelection)) {
    input.value = contentBeforeSelection + replaceString + contentAfterSelection;    
    if (selectionStart != selectionEnd){ 
      setSelectionRange(input, selectionStart, selectionStart + replaceString.length);
    } else {
      setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
    }
    return true;  
  }
  return false;    
}

function catchTab(item, e){
  if(e.which == 9 && item.setSelectionRange){
    scrollPos = item.scrollTop;
    if (replaceSelection(item, '  ')) {
      setTimeout("document.getElementById('"+item.id+"').focus();document.getElementById('"+item.id+"').scrollTop=scrollPos;",0);
      return false;
    }
    return true;	  
  }
}