// Copyright (c) 2006 MapBuzz 

/*jsl:import ../../../client/src/base/js_extensions.js*/ 
/*jsl:import ../../../client/src/browser/browser.js*/ 


MapBuzz.UI.TextEditor = function MapBuzzTextEditor(elementId, options)
{
  this.elementId = elementId
  this.options = options || {}
  this.initialize()
}

MapBuzz.UI.TextEditor.LONG_BUTTONS = 'image,link,separator,bold,italic,underline,separator,bullist,numlist,separator,outdent,indent,separator,forecolor,backcolor,separator,styleprops,separator,code'
MapBuzz.UI.TextEditor.CONDENSED_BUTTONS = 'bold,italic,underline,separator,image,link,separator,bullist,numlist'


Object.extend(MapBuzz.UI.TextEditor,
{
  cleanup: function(type, value)
  {
    switch (type) {
      case "get_from_editor_dom":
        /* If the user pasted in code it will be embedded into a
           span tag with an id of redesign_default.  Often times
           that will result in invalid HTML, so remove the
           span tag. */
        var span = value.ownerDocument.getElementById('redesign_default')
        if (span && span.parentNode)
        {
          // Remove node may not be setup because span is from the
          // iframe so its document is not the same as the main one
          if (!span.removeNode)
            span.constructor.prototype.removeNode = Element.prototype.removeNode
            
          span.removeNode()
        }
        break         
          
      case "get_from_editor":
      /*  // First remove doctype from Opera
        if (Browser.instance.isOpera())
          value = value.replace(/<!DOCTYPE html PUBLIC "-\/\/W3C\/\/DTD XHTML 1.0 Strict\/\/EN" "http:\/\/www.w3.org\/TR\/xhtml1\/DTD\/xhtml1-strict.dtd">/, '')
      
        if (value.match(/^<html\s*\/>$/m)) // IE
          value = ''
        else if (value.match(/^<p>\s*<\/p>$/m)) // FF
          value = ''
        else
          value = value.replace(/&nbsp;/g," ")*/
          
        break
      case "insert_to_editor":
        value = value.replace(/&nbsp;/g," ")
        break
      default:
        break
    } 

    return value
  }
})

  
Object.extend(MapBuzz.UI.TextEditor.prototype,
{
  initialize: function()
  {
    this.element = $(this.elementId)
    var form = this.getForm()
    this.editor = this.createEditorCommand().execute()
  },
  
  release: function()
  {
    this.releaseEditorCommand().execute()      
  },
  
  isInitialized: function()
  {
    if (this.editor)
      return this.editor.initialized
    else
      return false
  },
  
  getOptions: function()
  { 
    var options = {
      // For some reason FF needs this.
      width: '100%',
      height: '12em',
      remove_trailing_nbsp: true,
      auto_reset_designmode: false,
      
      cleanup: true,
      add_form_submit_trigger: false,
      
      // Broken for xhtml
      add_unload_trigger: false,
      
      // By default turn this off because it breaks 
      // code that dynamically creates/deletes editors
      // like in comments
      add_form_submit_trigger: false,

      // Paste word options (override some defaults)
			paste_block_drop: true,
			paste_remove_spans: true,
			paste_remove_styles: false,
      paste_postprocess: function(pl, o)
      {
        // Nuke word height=0 values
        o.node.innerHTML = o.node.innerHTML .replace(/height=\d*/ig, '')
      },
      
      entity_encoding: 'raw',
      mode: 'none',
      strict_loading_mode: true, // Needed for IE and profile page
      cleanup_callback: 'MapBuzz.UI.TextEditor.cleanup',
      
      // URL handling - we *always* want absolute URIs
      convert_urls: true,
      relative_urls: false,
      remove_script_host: false,
      
      button_tile_map : true,

      theme: 'advanced',
      theme_advanced_layout_manager: 'SimpleLayout',
		  theme_advanced_toolbar_location : 'top',
		  theme_advanced_toolbar_align : 'left',
		  theme_advanced_resizing : true,
		  theme_advanced_buttons1: MapBuzz.UI.TextEditor.LONG_BUTTONS,
      theme_advanced_buttons2: '',
      theme_advanced_buttons3: '',
      /*theme_advanced_path_location: 'none',
      theme_advanced_statusbar_location: 'bottom',
      theme_advanced_resizing : true,
      theme_advanced_resize_horizontal: false,
      theme_advanced_resizing_use_cookie: true,*/
      
      plugins: 'paste,emotions,style',
      
      // Layout - increment the number each time you change it
      content_css: '/stylesheets/tinymce_content.css?3'
    }
    
    if (Browser.instance.isIE())
      options.doctype = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'
    else
      options.doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">'

    if (Browser.instance.isGecko())
      options.gecko_spellcheck = true

    Object.extend(options, this.options)
    return options
  },

  getForm: function()
  { 
    /* Can't use .form property that input elements
       have since we use a div tag instead. */
    var element = this.element.parentNode
    
    while (element)
    {
      if (element === document) break
      
      if (element.tagName.toLowerCase() == 'form')
        return element
      else
        element = element.parentNode
    }
    return null
  },
  
  getContainer: function()
  {
    return this.editor.getContainer()
  },
  
  getContent: function()
  {
    return this.editor.getContent()
  },
  
  setContent: function(value)
  {
    return this.editor.setContent(value)
  },
  
  save: function()
  {
    this.editor.save()
  },

  createEditorCommand: function tinyMceCreateCommand()
  {
    var command = new MapBuzz.Command.Functor('Initialize Tiny Mce',
    {
      execute: function()
      {
        this.editor = new tinymce.Editor(this.element.id,
                                         this.getOptions())
        this.editor.render()
        return this.editor
      }.bind(this)
    })
      
    return command    
  },

  releaseEditorCommand: function()
  {
    var command = new MapBuzz.Command.Functor('Release Tiny Mce',
    {
      execute: function()
      {
        this.editor.remove()
        this.editor = null
      }.bind(this)
    })
    
    return command    
  },

  cancelCommand: function()
  {
    var cancelCommand = new MapBuzz.Command.Functor('Cancel Edit',
    {
      execute: function()
      {
        this.editor.setContent(this.editor.startContent)
      }.bind(this)
    })
    
    return cancelCommand
  }
})
