       @checkAutocomplete()
 
     # @input.on "blur", (event) =>
-    #   console.log $(event.target)
-    #   @closeAutocomplete()
+    #   setTimeout( =>
+    #     @closeAutocomplete()
+    #   , 100)
 
   checkAutocomplete: ->
     # Open autocomplete menu if it's a word.

          @element.addClass "invalid"
          @errorMsg.show()

  existingNames: ->
    @element.find(".token-text-area-results li")
      .map (index, element) ->
        $(element).html()
      .get()
      
  existingIds: ->
    @element.find(".token-text-area-results li")
      .map (index, element) ->
        $(element).attr("data-id")
      .get()

  isArrow: (code) ->
    $.inArray(code, [37, 38, 39, 40]) != -1

  getCaretPos: ->
    if window.getSelection and window.getSelection().rangeCount > 0
      range = window.getSelection().getRangeAt(0).cloneRange()
    else
      range = document.selection.createRange()
    range.collapse(true)
    range.setStart(@element[0], 0)
    range.toString().length

  getSelection: ->
    caretPos = @getCaretPos()

    # Remove each token in range and remove them from the caret position.
    # Otherwise, autocomplete suggestions will include existing tokens.
    html = $('<p>' + @input.html() + '</p>')



    # Close menu and reset.
    @closeAutocomplete()
    @range = null
    @word = null
    @resultList.html ''
    @checkEquation()
