 define (require) ->
+  $ = require('jquery')
   BaseView = require('cs!helpers/backbone/views/base')
   template = require('hbs!helpers/backbone/views/attached/tooltip/tooltip-template')
   require('less!helpers/backbone/views/attached/tooltip/tooltip')
+
+  # Close tooltips and popovers when clicking outside of them
+  $(document).click () ->
+    $('.popover, .tooltip').hide().removeClass('in')
 
   return class Tooltip extends BaseView
     containerTemplate: template

      super()
      @$owner = $(options.owner)

    onShow: () ->
      switch @trigger
        when 'click'
          @$owner.on "click.#{@type}.#{@cid}", () => @toggle()
        when 'hover'
          @$owner.on "mouseenter.#{@type}.#{@cid}", () => @show()
          @$owner.on "mouseleave.#{@type}.#{@cid}", () => @hide()

    show: () ->
      @reposition()
      @$el.children(".#{@type}").show().addClass('in')

    hide: () ->
      @reposition()
      @$el.children(".#{@type}").hide().removeClass('in')

    toggle: () ->
      @reposition()
      @$el.children(".#{@type}").toggle().toggleClass('in')


            'right': Math.floor($(document).outerWidth(true) - @$owner.offset().left)

    onBeforeClose: () ->
      @$el.off "click.#{@type}.#{@cid}"
      @$owner.off "click.#{@type}.#{@cid}"
      @$owner.off "mouseenter.#{@type}.#{@cid}"
      @$owner.off "mouseleave.#{@type}.#{@cid}"
