       command.setActive('wrapAsCode', e.nodeName == 'CODE')
     )
 
-  onSwitchEditor: (e)=>
+    @visualEditor = ed
+
+  onSwitchEditor: (e) =>
     e.preventDefault();
 
-    if not $(e.currentTarget).hasClass('current')
-      element = e.data.element
+    $currentTarget = $(e.currentTarget)
+    if not $currentTarget.hasClass('current')
+      $currentTarget.addClass('current')
+      @$mceToolbar.toggleClass(HTMLEditingDescriptor.isInactiveClass)
+      @$advancedEditorWrapper.toggleClass(HTMLEditingDescriptor.isInactiveClass)
 
-      $(e.currentTarget).addClass('current')
-      $(element).find('table.mceToolbar').toggleClass(HTMLEditingDescriptor.isInactiveClass)
-      $(@advanced_editor.getWrapperElement()).toggleClass(HTMLEditingDescriptor.isInactiveClass)
-
-      visualEditor = @getVisualEditor(element)
-      if $(e.currentTarget).attr('data-tab') is 'visual'
-        $(element).find('.html-tab').removeClass('current')
+      visualEditor = @getVisualEditor()
+      if $currentTarget.data('tab') is 'visual'
+        @$htmlTab.removeClass('current')
         @showVisualEditor(visualEditor)
       else
-        $(element).find('.visual-tab').removeClass('current')
+        @$visualTab.removeClass('current')
         @showAdvancedEditor(visualEditor)
 
   # Show the Advanced (codemirror) Editor. Pulled out as a helper method for unit testing.

    @focusVisualEditor(visualEditor)
    @showingVisualEditor = true

  focusVisualEditor: (visualEditor) ->
    visualEditor.focus()

  getVisualEditor: (element) ->
    ###
    Returns the instance of TinyMCE.
    This is different from the textarea that exists in the HTML template (@tiny_mce_textarea.
    ###
    return tinyMCE.get($(element).find('.tiny-mce').attr('id'))

  save: ->
    @element.off('click', '.editor-tabs .tab', @onSwitchEditor)
    text = @advanced_editor.getValue()
    visualEditor = @getVisualEditor(@element)
    if @showingVisualEditor and visualEditor.isDirty()
      text = visualEditor.getContent({no_events: 1})
    data: text

      theme_advanced_blockformats : "p,pre,h1,h2,h3",
      width: '100%',
      height: '400px',
      setup : @setupTinyMCE,
      # Cannot get access to tinyMCE Editor instance (for focusing) until after it is rendered.
      # The tinyMCE callback passes in the editor as a paramter.
      init_instance_callback: @focusVisualEditor
    })

    @showingVisualEditor = true
    # Doing these find operations within onSwitchEditor leads to sporadic failures on Chrome (version 20 and older).
    $element = $(element)
    @$htmlTab = $element.find('.html-tab')
    @$visualTab = $element.find('.visual-tab')

    @element.on('click', '.editor-tabs .tab', @onSwitchEditor)

  setupTinyMCE: (ed) =>
    ed.addButton('wrapAsCode', {
      title : 'Code',
      image : '/static/images/ico-tinymce-code.png',
