/**
 * отвечает за чат-лист
 */
var chatListEventsObserver = Class.create({
	initialize: function(observer) {
		
		this.chatListUpdatedAtHidden = $('chatListLastUpdateAt');
		this.chatListContainer = $('chat_list_container');
		this.chatBox = $('chadbox');
		this.tpl = {};
		
		this.observer = observer;
		this.activeChat = null;
		
		this.init();
	},
	
	init: function() {
		this.chatListUpdatedAtHidden.setValue(0);
		
		// шаблон для элемента чат-листа
		this.tpl.chatListItem = new Template(
			'<span class="talktabs #{jid}-js">' + 
				'<a href="#" class="cn-js">' + 
					'<img height="16" width="16" src="#{avatar}" alt="#{displayName}" title="#{displayName}" />' +
				'</a>' +
				'<b class="notif_bob msgc-js" id="msg-count-#{jid}" style="display: none;"></b>' +
			'</span>'
		);
		
		// слушаем событие по ресинку чат-листа
		this.observer.on('chatList.resyncList', this.resyncList.bind(this));
		
		// событие по обновлению числа сообщений чата
		this.observer.on('chatList.updateMessagesCount', this.updateChatsNewMessagesCount.bind(this));
		
		this.observer.on('chatList.activateChat', function(c) {
			this.activeChat = c;
		}.bind(this));
		
		this.observer.on('chatWindow.closeActiveChat', function() {
			this.activeChat = null;
		}.bind(this));
		
		// активация чата
		this.observer.on('chatList.activateChatWindow', this.activateChatWindow.bind(this));
	},
	
	/**
	 * ресинкает чат-лист, если он устарел
	 */
	resyncList: function(data) {
		// если страница обновлялась позже, чем произошло посл. измененме чат-листа 
		if (this.chatListUpdatedAtHidden.getValue() < data.time) {
			
			// почистим контейнер
			this.chatListContainer.update('');

			var avatars = $H(data.avatars);
			// обновим чат-контейнер
			data.cl.each(function(fullChatName) {
				var displayChatName = data.display_names.get(fullChatName);
				
				Element.insert(
					this.chatListContainer,
					// парсим шаблончег
					this.tpl.chatListItem.evaluate({
						'jid': Strophe.getNodeFromJid(fullChatName),
						'displayName': displayChatName,
						'avatar': avatars.get(fullChatName)
					})
				);
				
				var li = this.chatListContainer.select('.talktabs').last();
				
				// по клику на имя активируем окно чата
				// li.down('.cn-js').observe('click', this.openChat.bind(this, fullChatName));
				li.down('.cn-js').observe('click', function(e){
					this.observer.fire('chatContainer.show');
					this.openChat(fullChatName);
					Event.stop(e);
				}.bind(this));
				// по клику на крестик выходим из чата
				//li.down('.close-js').observe('click', this.removeChatFromList.bind(this, chatName));
			}.bind(this));
			
			// поставим последнее актуальное время в hidden
			this.chatListUpdatedAtHidden.setValue(data.time);
		}
	},
	
	/**
	 * рядом с именем чувачка в скобочках покажет число новых сообщений
	 */
	updateChatsNewMessagesCount: function(newMessages) {
		this.chatListContainer.select('.msgc-js').invoke('hide');
		newMessages.each(function(pair) {
			var s = $('msg-count-' + pair.key), n = pair.value;
			if (n > 0 && s) {
				s.show();
				s.update(n);
			}
		});
		//window.console.log(newMessages);
	},
	
	activateChatWindow: function(chatName) {
		this.observer.fire('chatList.activateChat', chatName);
		this.observer.fire('chatWindow.triggerSetWindowTitle', chatName);

		if (this.chatBox.offsetHeight == 0) {
			this.observer.fire('chatWindow.openChatWindow', chatName);
		}
		this.observer.fire('chatContainer.show');
	},
	
	openChat: function(chatName, e) {
		if (e) {
			e.preventDefault();
		}
		if (! this.activeChat || this.activeChat != chatName) {
			this.observer.fire('chatList.activateChat', chatName);
			this.observer.fire('chatWindow.triggerSetWindowTitle', chatName);
		}
	},
	
	removeChatFromList: function(chatName) {
		this.observer.fire('chatList.removeChatFromList', chatName);
		// удалим элемент из списка
		this.chatListContainer.down('li.' + Strophe.getNodeFromJid(chatName) + '-js').remove();
	}
	
});
