Xmpp.Views.Tabbar ||= {}
 
class Xmpp.Views.Tabbar.TabView extends Backbone.View
  template: JST["backbone/templates/tabbar/tab"]
  tagName: 'div'
  className: 'tab'
 
  events:
    'click .js-close': 'fireCloseChatTrigger'
    'click a div': 'switchChatWindow'
 
  initialize: () ->
    _.bindAll(this)
    @active = false
 
    Backbone.Events.on('closeChat', (chat) =>
      if chat == @model
        @destroy()
    )
 
    @model.get('who').on('change:name', @render)
 
  fireCloseChatTrigger: ->
    Backbone.Events.trigger('closeChat', @model)
 
  setActive: ->
    $(@el).addClass('active')
    @active = true
    @render()
 
  setInactive: ->
    $(@el).removeClass('active')
    @active = false
    @render()
 
  render: ->
    if (@model.get('isMultiChat'))
      $(@el).html(@template(
        who:       @model.get('who').firstname(),
        multiChat: true
      ))
    else
      $(@el).html(@template(
        who:       @model.get('who').firstname(),
        withWhom:  @model.get('withWhom').firstname(),
        multiChat: false
      ))
    return this
 
  showChat: ->
    if !@chatWindow
      @chatWindow = new Xmpp.Views.Chat.WindowView(attributes: {tab: this})
      App.debug 'zobrazujem NOVY chat window'
    else
      App.debug 'zobrazujem EXISTUJUCI chat window'
 
    @chatWindow.render()
 
  destroy: ->
    App.debug 'destroy chatWindow and tab'
    if @active
      @chatWindow.remove()
    @remove()
 
  hideChat: ->
    if @chatWindow
      @chatWindow.hide();
 
  hasParticipants: (who, withWhom) ->
    @model && @model.get('who') == who && @model.get('withWhom') == withWhom
 
  switchChatWindow: ->
    Backbone.Events.trigger('openChat', @model)
 
  getOwner: ->
    @model.get('who')
 
  getChatId: ->
    @model.get('chatId')
 
  getAttendant: ->
    @model.get('withWhom')