var tinymce_options = {
	mode : "textareas",
	theme : "advanced", 
	width : "540", 
	height : "360", 
	auto_resize : true, 
	content_css:"/stylesheets/application.css", 
	editor_selector : "mceEditor",
	browsers : "msie,gecko,safari",
	cleanup : true,
	cleanup_on_startup : true,
	convert_fonts_to_spans : true,
	convert_urls : false,
	editor_deselector : 'mceNoEditor',
	extended_valid_elements : 'img[class|src|flashvars|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|obj|param|embed|scale|wmode|salign|style],embed[src|quality|scale|salign|wmode|bgcolor|width|height|name|align|type|pluginspage|flashvars],object[align<bottom?left?middle?right?top|archive|border|class|classid|codebase|codetype|data|declare|dir<ltr?rtl|height|hspace|id|lang|name|style|tabindex|title|type|usemap|vspace|width],div[class|id]',
	plugin_preview_height : '650',
	plugin_preview_pageurl : '../../../../../posts/preview',
	plugin_preview_width : '950',
	plugins : "media,preview,curblyadvimage,inlinepopups,safari,paste,directionality,document,table,spellchecker",
	relative_urls : false,
	theme_advanced_buttons1 : "formatselect,fontsizeselect,fontselect,bold,italic,underline,strikethrough,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,indent,outdent,separator,code,charmap",
	theme_advanced_buttons2 : "forecolor,backcolor,sub,sup,separator,undo,redo,separator,cut,copy,paste,pastetext,pasteword,separator,link,unlink,anchor,image,media,document,separator,hr,removeformat,cleanup,visualaid,separator,ltr,rtl",
	theme_advanced_buttons3 : "tablecontrols,spellchecker",
	theme_advanced_layout_manager : 'SimpleLayout',
	theme_advanced_resize_horizontal : false,
	theme_advanced_resizing : true,
	theme_advanced_statusbar_location : 'bottom',
	theme_advanced_toolbar_align : 'left',
	theme_advanced_toolbar_location : 'top', 
	spellchecker_rpc_url: '/check_spellings'
};

var tinymce_sidebar_options = {
	mode : "textareas",
	theme : "advanced", 
	width : "75", 
	height : "200", 
	content_css:"/stylesheets/application.css",
	editor_selector : "smallMceEditor",
	browsers : "msie,gecko,safari",
	cleanup : true,
	cleanup_on_startup : true,
	convert_fonts_to_spans : true,
	convert_urls : false,
	editor_deselector : 'mceNoEditor',
	extended_valid_elements : 'img[class|src|flashvars|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name|obj|param|embed|scale|wmode|salign|style],embed[src|quality|scale|salign|wmode|bgcolor|width|height|name|align|type|pluginspage|flashvars],object[align<bottom?left?middle?right?top|archive|border|class|classid|codebase|codetype|data|declare|dir<ltr?rtl|height|hspace|id|lang|name|style|tabindex|title|type|usemap|vspace|width]',
	plugin_preview_height : '650',
	plugin_preview_pageurl : '../../../../../posts/preview',
	plugin_preview_width : '950',
	plugins : "media,preview,curblyadvimage,inlinepopups,safari,directionality",
	relative_urls : false,
	theme_advanced_buttons1 : "formatselect,fontsizeselect,fontselect,separator,charmap",
	theme_advanced_buttons2 : "bold,italic,underline,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,indent,outdent",
	theme_advanced_buttons3 : "forecolor,backcolor,separator,link,unlink,anchor,image,separator,hr,removeformat,cleanup,separator,ltr,rtl",
	theme_advanced_buttons4 : "",
	theme_advanced_layout_manager : 'SimpleLayout',
	theme_advanced_resize_horizontal : false,
	theme_advanced_resizing : true,
	theme_advanced_toolbar_align : 'left',
	theme_advanced_toolbar_location : 'bottom'
};

tinyMCE.init(tinymce_sidebar_options);
tinyMCE.init(tinymce_options);



// InPlaceRichEditor, version 1.3.1
// 
// Author: Sebastien Grosjean (http://www.zencocoon.com, http://seb.box.re)
//
// Contributor:
//   Neil Rickards, Robert Muzslai, Andrew Petersen, Brian Hansen, Brian French,
//   Dan Dalf, Anton Mostovoy, Hans-Peter, Filipe Pina, Min Kim, Rudi Boutinaud,
//   Joaquin Miguez, E. Vrolijk - RedAnt Solutions, Tony Cuny
//
// InPlaceRichEditor is freely distributable under the terms of an MIT-style license.
// For details, see the inPlaceRichEditor web site: http://inplacericheditor.box.re/

if(typeof Ajax.InPlaceEditor == 'undefined')
  throw("InPlaceRichEditor requires including script.aculo.us' controls.js library");
if(typeof tinyMCE == 'undefined')
  throw("InPlaceRichEditor requires including moxiecode' tiny_mce.js library and proper initialization");

tinymce.EditorManager.oldAdd = tinymce.EditorManager.add;
tinymce.EditorManager.add = function(ed) {
  ed.onInit.add(function(ed) {
    $(ed.id).fire('tinymce:onInit', ed);
  });
  return tinymce.EditorManager.oldAdd(ed);
}

Ajax.InPlaceRichEditor = Class.create(Ajax.InPlaceEditor, {
  // Dump form InPlaceEditor with only few changes
  // * Add support of formIdSuffix option
  // * Deletion of the Deprecation layer
  // * Add tinymce initialization
  initialize: function(element, url, options, tinymce_options) {
    this.url = url;
    this.element = element = $(element);
    this.prepareOptions();
    this.tinymceOptions = Object.clone(tinymce_options);
    this._controls = { };
    // Removed :: arguments.callee.dealWithDeprecatedOptions(options); // DEPRECATION LAYER!!!
    Object.extend(this.options, options || { });
    this.prepareTinymceSave();
    if (!this.options.formId && this.element.id) {
      this.options.formId = this.element.id + '-' + this.options.formIdSuffix;
      if ($(this.options.formId))
        this.options.formId = '';
    }
    if (this.options.externalControl)
      this.options.externalControl = $(this.options.externalControl);
    if (!this.options.externalControl)
      this.options.externalControlOnly = false;
    this._originalBackground = this.element.getStyle('background-color') || 'transparent';
    this.element.title = this.options.clickToEditText;
    this._boundCancelHandler = this.handleFormCancellation.bind(this);
    this._boundComplete = (this.options.onComplete || Prototype.emptyFunction).bind(this);
    this._boundFailureHandler = this.handleAJAXFailure.bind(this);
    this._boundSubmitHandler = this.handleFormSubmission.bind(this);
    this._boundWrapperHandler = this.wrapUp.bind(this);
    this.registerListeners();
    if (this.options.editOnBlank && this.getText().length == 0)
      this.enterEditMode();
  },
  createControl: function($super, mode, handler, extraClasses) {
    // if (!this.options.tinymceSave)
      $super(mode, handler, extraClasses);
  },
  createEditField: function() {
    var text = (this.options.loadTextURL ? this.options.loadingText : this.getText());
    var fld;
    fld = document.createElement('textarea');
    fld.id = this.element.id + '-' + this.options.textareaIdSuffix;
    fld.rows = 3;
    fld.cols = 40;
    fld.name = this.options.paramName;
    fld.value = text; // No HTML breaks conversion anymore
    fld.className = this.options.editorClassName;
	  // TODO: Check if onBlur can be supported
    // if (this.options.submitOnBlur)
    //   fld.onblur = this._boundSubmitHandler;
    this._controls.editor = fld;
    if (this.options.loadTextURL)
      this.loadExternalText();
    this._form.appendChild(this._controls.editor);
  },
  enterEditMode: function($super, e) {
    if (this.options.tinymceToElementSize)
      var elementDimensions = this.element.getDimensions();
	  $super(e);
    this.tinymce = new tinymce.Editor(this._controls.editor.id, this.tinymceOptions);
    this.tinymce.onInit.add(function(ed) {
      if (this._form.hasClassName(this.options.loadingClassName)) {
        this.tinymce.setProgressState(1);
      }
    }.bind(this));
    this.tinymce.inplacericheditor = this;
    if (this.options.tinymceToElementSize) {
      this.tinymce.settings.height = elementDimensions.height;
      this.tinymce.settings.width = elementDimensions.width;
    }
    this.tinymce.render();
  },
  getText: function() {
    return this.element.innerHTML;
  },
  handleAJAXFailure: function($super, transport) {
    $super(transport);
    this.tinymce.setContent(this.element.innerHTML);
  },
  handleFormSubmission: function($super, e) {
    this.tinymce.save();
    $super(e);
  },
  removeForm: function($super) {
    try {
      this.tinymce.remove();
    } catch(e) {}
	  $super();
  },
  // TODO: OPTIMIZATION: By adding the callback onLoadExternalText in the initial
  // InPlaceEditor would keep this code lighter and provide easier extentions
  loadExternalText: function() {
    this._form.addClassName(this.options.loadingClassName);
    this._controls.editor.disabled = true;
    var options = Object.extend({ method: 'get' }, this.options.ajaxOptions);
    Object.extend(options, {
      parameters: 'editorId=' + encodeURIComponent(this.element.id),
      onComplete: function() {
        this.tinymce.setProgressState(0);
      }.bind(this),
      onSuccess: function(transport) {
        this._form.removeClassName(this.options.loadingClassName);
        var text = transport.responseText;
        if (this.options.stripLoadedTextTags)
          text = text.stripTags();
        this._controls.editor.value = text;
        this.tinymce.setContent(text);
        this._controls.editor.disabled = false;
        this.postProcessEditField();
      }.bind(this),
      onFailure: this._boundFailureHandler
    });
    new Ajax.Request(this.options.loadTextURL, options);
  },
  postProcessEditField: function() {
	  var fpc = this.options.fieldPostCreation;
    $(this._controls.editor.id).observe('tinymce:onInit', function(event) {
      if (fpc) {
        if (fpc == 'focus') {
          event.memo.focus();
        } else if (fpc == 'activate') {
          event.memo.execCommand('SelectAll');
        }
      }
    });
  },
  prepareTinymceSave: function() {
    if (this.options.tinymceSave) {
      if (this.tinymceOptions.theme == 'simple') {
        this.options.tinymceSave = false;
        return;
      }
      if ((!(this.tinymceOptions.theme_advanced_buttons1 && this.tinymceOptions.theme_advanced_buttons1.match(/(^|,)save(,|$)/)) &&
           !(this.tinymceOptions.theme_advanced_buttons2 && this.tinymceOptions.theme_advanced_buttons2.match(/(^|,)save(,|$)/)) &&
           !(this.tinymceOptions.theme_advanced_buttons3 && this.tinymceOptions.theme_advanced_buttons3.match(/(^|,)save(,|$)/))) ||
          (this.tinymceOptions.plugins == undefined || !this.tinymceOptions.plugins.match(/(^|,)save(,|$)/))) {
        throw("InPlaceRichEditor' tinymceSave option require at least the save button and the save plugin in tinyMCE initialization.");
      }
      if (this.options.onTinymceSave)
        this.tinymceOptions.save_onsavecallback = this.options.onTinymceSave;
      if (this.options.onTinymceCancel)
        this.tinymceOptions.save_oncancelcallback = this.options.onTinymceCancel;
    }
  },
  prepareOptions: function() {
    this.options = Object.clone(Ajax.InPlaceRichEditor.DefaultOptions);
    Object.extend(this.options, Ajax.InPlaceRichEditor.DefaultCallbacks);
    [this._extraDefaultOptions].flatten().compact().each(function(defs) {
      Object.extend(this.options, defs);
    }.bind(this));
  }
});

Object.extend(Ajax.InPlaceRichEditor, {
  // size, cols, rows and autoRows options are now unused
  DefaultOptions: Object.extend(Object.clone(Ajax.InPlaceEditor.DefaultOptions), {
	  editorClassName: 'editor_field',
	  fieldPostCreation: 'focus',
    formClassName: 'inplacericheditor-form',
	  formIdSuffix: 'inplacericheditor',
    loadingClassName: 'inplacericheditor-loading',
    savingClassName: 'inplacericheditor-saving',
	  textareaIdSuffix: 'textarea-inplacericheditor',
	  tinymceSave: false,
	  tinymceToElementSize: false
  }),
  DefaultCallbacks: Object.extend(Object.clone(Ajax.InPlaceEditor.DefaultCallbacks), {
    onTinymceSave: function(ed) { ed.inplacericheditor._boundSubmitHandler(); },
  	onTinymceCancel: function(ed) { ed.inplacericheditor._boundCancelHandler(); }
  })
});

tinyMCE.addI18n({en:{
common:{
edit_confirm:"Do you want to use the WYSIWYG mode for this textarea?",
apply:"Apply",
insert:"Insert",
update:"Update",
cancel:"Cancel",
close:"Close",
browse:"Browse",
class_name:"Class",
not_set:"-- Not set --",
clipboard_msg:"Copy/Cut/Paste is not available in Mozilla and Firefox.\nDo you want more information about this issue?",
clipboard_no_support:"Currently not supported by your browser, use keyboard shortcuts instead.",
popup_blocked:"Sorry, but we have noticed that your popup-blocker has disabled a window that provides application functionality. You will need to disable popup blocking on this site in order to fully utilize this tool.",
invalid_data:"Error: Invalid values entered, these are marked in red.",
more_colors:"More colors"
},
contextmenu:{
align:"Alignment",
left:"Left",
center:"Center",
right:"Right",
full:"Full"
},
insertdatetime:{
date_fmt:"%Y-%m-%d",
time_fmt:"%H:%M:%S",
insertdate_desc:"Insert date",
inserttime_desc:"Insert time",
months_long:"January,February,March,April,May,June,July,August,September,October,November,December",
months_short:"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec",
day_long:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",
day_short:"Sun,Mon,Tue,Wed,Thu,Fri,Sat,Sun"
},
print:{
print_desc:"Print"
},
preview:{
preview_desc:"Preview"
},
directionality:{
ltr_desc:"Direction left to right",
rtl_desc:"Direction right to left"
},
layer:{
insertlayer_desc:"Insert new layer",
forward_desc:"Move forward",
backward_desc:"Move backward",
absolute_desc:"Toggle absolute positioning",
content:"New layer..."
},
save:{
save_desc:"Save",
cancel_desc:"Cancel all changes"
},
nonbreaking:{
nonbreaking_desc:"Insert non-breaking space character"
},
iespell:{
iespell_desc:"Run spell checking",
download:"ieSpell not detected. Do you want to install it now?"
},
advhr:{
advhr_desc:"Horizontal rule"
},
emotions:{
emotions_desc:"Emotions"
},
searchreplace:{
search_desc:"Find",
replace_desc:"Find/Replace"
},
advimage:{
image_desc:"Insert/edit image"
},
advlink:{
link_desc:"Insert/edit link"
},
xhtmlxtras:{
cite_desc:"Citation",
abbr_desc:"Abbreviation",
acronym_desc:"Acronym",
del_desc:"Deletion",
ins_desc:"Insertion",
attribs_desc:"Insert/Edit Attributes"
},
style:{
desc:"Edit CSS Style"
},
paste:{
paste_text_desc:"Paste as Plain Text",
paste_word_desc:"Paste from Word",
selectall_desc:"Select All"
},
paste_dlg:{
text_title:"Use CTRL+V on your keyboard to paste the text into the window.",
text_linebreaks:"Keep linebreaks",
word_title:"Use CTRL+V on your keyboard to paste the text into the window."
},
table:{
desc:"Inserts a new table",
row_before_desc:"Insert row before",
row_after_desc:"Insert row after",
delete_row_desc:"Delete row",
col_before_desc:"Insert column before",
col_after_desc:"Insert column after",
delete_col_desc:"Remove column",
split_cells_desc:"Split merged table cells",
merge_cells_desc:"Merge table cells",
row_desc:"Table row properties",
cell_desc:"Table cell properties",
props_desc:"Table properties",
paste_row_before_desc:"Paste table row before",
paste_row_after_desc:"Paste table row after",
cut_row_desc:"Cut table row",
copy_row_desc:"Copy table row",
del:"Delete table",
row:"Row",
col:"Column",
cell:"Cell"
},
autosave:{
unload_msg:"The changes you made will be lost if you navigate away from this page."
},
fullscreen:{
desc:"Toggle fullscreen mode"
},
media:{
desc:"Insert / edit embedded media",
edit:"Edit embedded media"
},
fullpage:{
desc:"Document properties"
},
template:{
desc:"Insert predefined template content"
},
visualchars:{
desc:"Visual control characters on/off."
},
spellchecker:{
desc:"Toggle spellchecker",
menu:"Spellchecker settings",
ignore_word:"Ignore word",
ignore_words:"Ignore all",
langs:"Languages",
wait:"Please wait...",
sug:"Suggestions",
no_sug:"No suggestions",
no_mpell:"No misspellings found."
},
curblyadvimage:{
image_desc:"Insert / upload image"
},
document:{
desc:"Insert / upload document"	
},
pagebreak:{
desc:"Insert page break."
}}});