 # make it accessible
 window.selection = 0
 selected_menu = false
+window.current_editor = null
 
 class Editor.MainEditor extends Backbone.View
   el: "#editor"

    @editor_menu.render()
    @editor_menu.show()

  #get text of selected and displays menu
  handleTextSelection: (ev)->
    @editor_menu.hide()
    text = @getSelectedText()
    @.displayMenu() unless _.isEmpty text

  handleCaret: ()->
    @resetOffset($(@el));

  handleArrow: (ev)=>
    console.log("ENTER ARROWS")
    console.log @getNode()
    #range = @selection().getRangeAt(0)
    #debugger
    current_node = $(@getNode())

    @displayTooltipAt( current_node )
    @markAsSelected( current_node )

  resetOffset: ($textField)=>
    offset = $textField.caret('offset');
    position = $textField.caret('position');

      selection = window.getSelection()
    else if (document.selection && document.selection.type != "Control")
      selection = document.selection

  getRange: () ->
    editor = $(@el)[0]
    range = selection.rangeCount && selection.getRangeAt(0)
    range = document.createRange() if (!range)
    if !editor.contains(range.commonAncestorContainer)
      range.selectNodeContents(editor)
      range.collapse(false)
    range

  setRange: (range)->
    range = range || this.current_range
    if !range
      range = this.getRange()
      range.collapse(false); # set to end

    @selection().removeAllRanges()
    @selection().addRange(range)
    @

  #set focus and caret position on element
  setRangeAt: (element)->
    range = document.createRange()
    sel = window.getSelection()

    range.setStart(element, 0);
    range.collapse(true)
    sel.removeAllRanges()
    sel.addRange(range)
    @el.focus()

  focus: (focusStart) ->
    @.setRange() if (!focusStart)
    $(@el).focus()
    @

  #NOT USED
  focusNode: (node, range)->
    range.setStartAfter(node)
    range.setEndBefore(node)
    range.collapse(false)
    @.setRange(range)

  #get the element that wraps Caret position
  getNode: ()->
