
var page_editor_controller = {
  toggleLink: {},
  pageToUpdate: {},
  editorElement: {},
  show: function() {
    console.log("showing editor");
    $(".page-edit-section").show();
    $(this.editorElement).tinymce().show();
  },
  hide: function() {
    console.log("hiding editor");
    $(".page-edit-section").hide();
    $(this.editorElement).height('auto');
    $(this.editorElement).tinymce().hide(); 
  },
  save: function(editor){
    console.log("saving to " + this.pageToUpdate + "...");

    var self = this;
    editor.setProgressState(1); // Show progress
    $.post(this.pageToUpdate,
      {
        "_method": "put",
        "authenticity_token": form_authenticity_token,
        "page[content]": editor.getContent() 
      },
      function(data, status) {
        editor.setProgressState(0); // Hide progress
        $(self.editorElement).data('original-value', editor.getContent()); //new save point
        console.log(status);
        if (or.admin.has_errors(data))
        {
          console.log(data);
        }
      }
    );
  },
  cancel: function(editor){
    console.log("cancel...");
    editor.setContent( $(this.editorElement).data('original-value') );

    // Need to revert changes here (save first version? download original from server?)
    this.hide();
    $(this.toggleLink).click();
  },
  load: function(attachToElement, linkElement){
    console.log("loading page editor...");
    $(".page-edit-section").show();

    this.toggleLink = linkElement;
    this.pageToUpdate = linkElement.attr('rev');
    this.editorElement = attachToElement;
    
    $(attachToElement).tinymce({
      relative_urls: false,     
      inline_styles: false,
      theme : "advanced",
      plugins : "safari,save,paste,inlinepopups,-obpimageselector,-obplinkselector",

      // Theme options
      theme_advanced_buttons1 : "savepage,cancelchanges,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,outdent,indent,blockquote,|,obp-link,obp-break-link",
      theme_advanced_buttons2 : ",formatselect,fontselect,fontsizeselect,|,bullist,numlist,|,obp-add-image", //code
      theme_advanced_buttons3 : "",
      theme_advanced_buttons4 : "",
      theme_advanced_toolbar_location : "top",
      theme_advanced_toolbar_align : "left",
      theme_advanced_statusbar_location : "none",
      theme_advanced_path : false,
      theme_advanced_resizing : false,
      theme_advanced_blockformats : "p,div,h1,h2,h3,h4,h5,h6",

      content_css : "/stylesheets/defaults.css,/stylesheet.css,/stylesheets/admin/content-editor.css",
      width: "100%",
      body_class: "content-editor-body",

      setup : function(editor) {
        console.log('loading plugins');
        tinymce.PluginManager.load('obpimageselector', '/javascripts/obp/tinymce/plugins/imageselector/editor_plugin_src.js');
        tinymce.PluginManager.load('obplinkselector', '/javascripts/obp/tinymce/plugins/linkselector/editor_plugin_src.js');

        console.log("setting custom buttons...");
        editor.addButton('savepage', {
          title : "Save changes to this Page",
          image : '/images/icons/disk.png',
          onclick : function(){ page_editor_controller.save(editor); }
        }),

        editor.addButton('cancelchanges', {
          title : "Throw out these changes",
          image : '/images/icons/delete.png',
          onclick : function(){ page_editor_controller.cancel(editor); }
        });

        editor.onPostRender.add(function(ed, cm){
          $('.mceExternalToolbar').css('display', 'block').css('top', '-54px');
          $('.content-editor-body').css('padding', '0');
        });
        editor.onLoadContent.add(function(ed, cm){
          $(attachToElement).data("original-value",$(attachToElement).html());
        });
      }
    });
  }
};

$(document).ready(function() {

  var div = $(".js-pages-content-editor");

  $("a.edit-page")
    .one('click', function(){
      console.log("Loading for first time");
      page_editor_controller.load(div, $(this));
      $(this).toggle(
        function(){ page_editor_controller.hide(); },
        function(){ page_editor_controller.show(); }
      );
      return false;
    });

  //div.height( div.parent().innerHeight() );
  
  $(".page-edit-section :input").change(function() {
    $.post($("form.edit_page").attr("action"), {
      "_method": "put",
      "authenticity_token": form_authenticity_token,
      "page[title]": $(".page-edit-section input#page_title").val(),
      "page[meta_description]": $(".page-edit-section textarea#page_meta_description").val(),
      "page[meta_keywords]": $(".page-edit-section textarea#page_meta_keywords").val()
    });
  });

  
});
