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))
    $('.inactive-layer').fadeIn(50)

  close: (e) ->
    e.preventDefault()
    @remove(e)
    $('.inactive-layer').fadeOut(50)

  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()