       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: ()->

    if _.contains([37,38,39,40], e.which)
      @handleArrow(e)



class Editor.Menu extends Backbone.View
  el: "#editor-menu"

  events:
    "click .editor-icon" : "handleClick"
    "mouseenter" : "handleOver"
    "mouseleave" : "handleOut"

  initialize: (opts={})=>
    @config = opts.buttons || @default_config()

  default_config: ()->
    buttons: ["blockquote", "h2", "h3", "code", "bold", "italic", "underline", "createlink"]

  template: ()=>
    html = ""

    top =  offset.top - offset.height - 16
    @editor_menu.$el.offset({left: offset.left - padd, top: top })


  handleBlur: (ev)=>
    #console.log(ev)
    #hide menu only if is not in use
    setTimeout ()=>
      @editor_menu.hide() unless selected_menu
    , 200

    @tooltip_view.hide()
    false

  handleFocus: (ev)=>
    console.log("Handle focus #{ev}")

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

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

  handleArrow: (ev)=>
    console.log("ENTER ARROWS")
    #console.log @getNode()
    current_node = $(@getNode())
    @displayTooltipAt( current_node )
    @markAsSelected( current_node )

  #overrides default behavior
  handleKeyDown: (e)->
    e.preventDefault() if _.contains([13], e.which)

  handleCarriageReturn: (e)->
    @editor_menu.hide() #hides menu just in case
