 
   classDelay: 0
 
+  eventId: NaN
+
   constructor: (params = {}) ->
     @[key] = value for own key, value of params when key of @
-    log params
+    @eventId = Math.random().toString(36)[2...]
 
     @el.on 'click', @onClick
 
     @popup.addClass 'hidden'
     @popup.remove()
+    @popup.prepend '<button name="close">&times;</button>'
 
-    $(document).on 'click', @onDocumentClick
-
-  onClick: (e) =>
+  onClick: =>
     @toggle()
 
+  onClickClose: =>
+    @close()
+
   onDocumentClick: ({target}) =>
-    @close() unless $(target).parents().andSelf().is @el
+    @close() unless $(target).parents().andSelf().is @el.add @popup
 
   toggle: ->
     if @el.hasClass 'open' then @close() else @open()

attach = require 'zootorial/lib/attach'
$ = require 'jqueryify'

log = -> console?.log? arguments...

class PopupButton
  @fromDOM: (el) ->

    attach @popup, @attachAt.split(/\s/), @el, @attachTo.split(/\s/), margin: @attachMargin
    setTimeout $.proxy(@popup, 'removeClass', 'hidden'), @classDelay

    @popup.on 'click', 'button[name="close"]', @onClickClose
    $(document).on "click.#{@eventId}", @onDocumentClick

  close: ->
    @el.removeClass 'open'
    @popup.addClass 'hidden'
    setTimeout $.proxy(@popup, 'remove'), @classDelay

    @popup.off 'click'
    $(document).off "click.#{@eventId}"

module.exports = PopupButton
