       result = @results[index]
       @result_callback.apply(null, [result])
 
-  cloneModal: (selector) ->
-    new_modal_id = "quickjump"+new Date().getTime()
-    new_modal = $(selector).clone()
-    new_modal.attr("id", new_modal_id)
-    $("body").append(new_modal)
-    "##{new_modal_id}"
-
   getActiveResult: ->
     if @active_result?
       all = $(@selector+" .result")


  hide: ->
    $(@selector).modal("hide")

  highlight: (str, phrases) ->
    str.toString().replace(new RegExp('('+phrases.join('|')+')', 'gi'), '<strong>$1</strong>')

  markActiveResult: ->
    if @active_result?

    @old_query = query


class OUT.QuickJump.Renderer
  MAX_RESULTS: 10

  constructor: (@parent, selector) ->
    @selector = this.cloneModal(selector)
    self = this
    $(@selector).bind "hidden", ->
      $(self.selector).remove()

    $(@selector).bind "shown", ->
      $(self.selector+" input").select()

    $(@selector).modal().modal("show")

  cloneModal: (selector) ->
    new_modal_id = "quickjump"+new Date().getTime()
    new_modal = $(selector).clone()
    new_modal.attr("id", new_modal_id)
    $("body").append(new_modal)
    "##{new_modal_id}"

  highlight: (str, phrases) ->
    str.toString().replace(new RegExp('('+phrases.join('|')+')', 'gi'), '<strong>$1</strong>')

  renderResults: (query) ->
    out = ""
    index = 0
    phrases = query.replace(/^\s+|\s+$/g, '').split(' ')
    template = '<a class="result" data-result-index="%{index}" href="%{url}"><div class=title><i class="icon-%{type}"></i> <span>%{title}</span></div></a>'

    for result in @parent.results[0...@MAX_RESULTS]
      t = this.highlight(result.title, phrases)
      out += template.toString().replace("%{title}", t).replace("%{type}", result.type).replace("%{url}", result.url).replace("%{index}", index)
      index += 1

    $(@selector+" .results").html(out)
    self = this
    $(@selector+" .results a.result").bind "click", (event) ->
      self.parent.activateResult(this)
      event.preventDefault()
      false


class OUT.QuickJump.Base
  DELAY_BEFORE_SERVER_CALL: 300
  FETCHING_RESULTS: "fetching"
  DICTIONARY_KEY_LENGTH: 1

  constructor: (@result_callback, @data_url = "/quick_jump_targets.json", selector = "#quick-jump-template") ->
    @dictionary = new OUT.QuickJump.Dictionary(@DICTIONARY_KEY_LENGTH)
    @renderer = new OUT.QuickJump.Renderer(this, selector)
    @selector = @renderer.selector
    @controls = new OUT.QuickJump.Controls(this, @selector, @result_callback)
    this.setDefaultResults()

  activateResult: (anchor) ->
    anchor or= this.getActiveResult()
