//= require content/markdown_editor/jquery.markdown-0.2
//= require content/markdown_editor/textselector
//= require content/markdown_editor/jquery.griffin.editor
//= require content/markdown_editor/jquery.griffin.editor.markdown

(function($){
  // plugin the image dialog
  $.extend($.griffinEditorExtension, {
    imageDialog: function(options){
      $('#image-dialog').attachmentsDialog("show").off("insert.attachmentsDialog").on("insert.attachmentsDialog", function(e){
        options.success({title: e.title, url: e.url});
      });
    }
  });

  var MarkdownEditor = function(element, options){
    var $element = $(element),
        $editor = $element.griffinEditor({autoSize:false}),
        self = this;

    this.element = $element;
    this.layout(false);

    // handle toolbar actions
    $element.on("click", '[data-action]', function(e){
      var data = $(this).data();
      e.preventDefault();
      self[data["action"]]();
    });

    // preview tab
    $element.on("shown", ".nav-tabs a[href='#preview']", function(e){
      self.preview();
    });
  }

  MarkdownEditor.prototype={
    layout: function(toggle_help){
      var $title_field = $("input[type='text']", this.element),
          $main_content = $("#editor .main-content", this.element),
          $help = $(".help", $main_content),
          $textarea = $("textarea", $main_content),
          field_padding = 6,
          content_padding=10,
          help_width= 300,
          width = this.element.width();
          

      $title_field.css("width", width - field_padding*2 -2);
      if(toggle_help){
        width -= help_width;
        $help.css("width", help_width - 40).show();
      }else{
        $help.hide();
      }
      $textarea.css("width", width - field_padding*2 - content_padding*2 - 4 );
    },

    preview: function(){
      var previewPath = this.element.attr("data-preview-url"),
          griffinEditor = this.element.data("griffinEditor"),
          html_content_el = $("#preview .html-content", this.element);

      $.post(previewPath, {content: griffinEditor.editor.val()}, function(results){
        html_content_el.html(results);
      });
    },

    save: function(){
      this.element.parent("form").submit();
    },

    toggleHelp: function(){
      var helpBtn = $("[data-action=toggleHelp]", this.element)
      this.layout(helpBtn.toggleClass("active").hasClass("active"));
    }
  }

  $.fn.markdownEditor = function(options){
    return this.each(function(){
      var $this = $(this),
          data = $this.data("markdown-editor");

      if (!data){
        $this.data("markdown-editor", (data = new MarkdownEditor(this, options)));
      }
    });
  }

  $(function() {
    $('[data-trigger="markdownEditor"]').markdownEditor();
  });

})(jQuery);