Xmpp.Views.Popup ||= {}

class Xmpp.Views.Popup.PopupView extends Backbone.View
  superTemplate: JST["backbone/templates/popup/popup"]
  el: $('#js-popups')

  @popups = {}

  constructor: ->
    super
    PopupView.popups[@cid] = this

  superEvents: ->
    result = {}
    result["click .#{@className} .close"] = 'close'
    result

  render: (childHtml) ->
    $(@el).find('.popup').hide()
    _.each(PopupView.popups, (view) ->
      view.undelegateEvents()
    )

    thisView = PopupView.popups[@cid]
    thisView.delegateEvents()

    $(@el).append(@superTemplate(inside: childHtml, class: @className))

  close: (e) ->
    e.preventDefault()
    @remove(e)

  remove: (e) ->
    @stopListening()
    @undelegateEvents()
    $(e.currentTarget).closest('.popup').remove()

    delete PopupView.popups[@cid]

    firstFoundView = _.find(PopupView.popups, (view) -> view) # najde prvy view
    if firstFoundView
      $(@el).find('.popup').first().show()
      firstFoundView.delegateEvents()