document.observe("dom:loaded", function() {
  $("page_form").observe("submit", function() {
    saveEditorContents(tinymce.EditorManager.get("editable_page_body"));
  });
});

var saveEditorContents = function(editor) {
  $("page_body").value = editor.getContent();
}

var onMCESave = function(editor) {
  saveEditorContents(tinymce.EditorManager.get("editable_page_body"));
  $("page_form").submit();
}

var configureEditor = function(editor) {
  var cell = $(editor.contentAreaContainer).up("table").select("tr.mceLast").first();
  var h    = document.viewport.getHeight() - 20 - cell.cumulativeOffset().top;
  var w    = $("page_body_form").getWidth();
  $(editor.contentAreaContainer).down("iframe").setStyle({ width : w + "px", height: h + "px" });

  $$("a.mce_save").first().setStyle({ marginRight: "10px" });
  $$("a.mce_table").first().setStyle({ marginLeft: ($$("a.mce_table").first().getWidth() + 10) + "px" });
}

tinyMCE.init({
  "editor_selector"                : "wysiwyg_editable",
  "theme"                          : "advanced",
  "mode"                           : "specific_textareas",
  //"plugins"                        : "imagepicker,linkpicker,filepicker,paste,save,table",
  "plugins"                        : "cctslink,imagepicker,paste,save,table",
  "content_css"                    : "/stylesheets/reset.css,/stylesheets/body.css",
  "body_id"                        : "content",
  "visual"                         : true,
  "visual_table_class"             : "borderless",
  "theme_advanced_toolbar_location": "top",
  "theme_advanced_toolbar_align"   : "left",
  "theme_advanced_buttons1"        : "save,formatselect,bold,italic,underline,bullist,numlist,|,imagepicker,|,link,unlink,|,pasteword,|,code",
  "theme_advanced_buttons2"        : "tablecontrols",
  "theme_advanced_buttons3"        : "",
  "theme_advanced_styles"          : "Fancyblock=fancy",
  "theme_advanced_blockformats"    : "h1,h2,h3,p",
  "extended_valid_elements"        : "foo",
  "custom_elements"                : "foo",
  "init_instance_callback"         : configureEditor,
  "save_onsavecallback"            : onMCESave
});
