/**
 * отвечает за нотификейшн бар
 */
var notificationBarEventsObserver = Class.create({
	initialize: function(observer, settings) {
		
		this.chatWithNewMessages = $('chats_with_new_messages');
		this.chatWindowOpenButton = $('chadbox_a');
		this.listContainer = $('user_you_can_invite'); 
		
		this.observer = observer;
		
		// unnoticeable chats
		this.unnoChats = settings.unnoticeableChats.toArray();
		
		this.init();
	},
	
	init: function() {
		// слушаем событие по обновлению числа чатов с новыми сообщениями
		this.observer.on('notificationBar.updateCounter', this.updateCounter.bind(this));
		
		//this.observer.on('notificationBar.chatListIsEmpty', this.showUsersOnEmptyList.bind(this));
		
		this.observer.on('notificationBar.makeChatUnnoticeable', function(data) {
			var v = data[1], chatName = data[0];
			if (v == 0) { // включить нотифы
				if (this.unnoChats.indexOf(chatName) == -1) {
					this.unnoChats.push(chatName);
				}
			}
			else { // выключить нотифы
				this.unnoChats = this.unnoChats.without(chatName);
			}

		}.bind(this));

		// откроем окно с последним активным чатом
		this.chatWindowOpenButton.observe('click', this.toggleChatWindow.bind(this));
	},
	
	/**
	 * обновить число чатов с новыми сообщениями
	 */
	updateCounter: function(cc) {
		n = cc.size();
		// исключим чаты с вырубленными нотификациями
		cc.each(function(chatName) {
			if (this.unnoChats.indexOf(chatName) != -1) {
				n --;
			}
		}.bind(this));
		if (n <= 0) {
			this.chatWithNewMessages.hide();
		}
		else {
			this.chatWithNewMessages.show();
		}
		this.chatWithNewMessages.update(n <= 0 ? '' : n);
		this.observer.fire('document.newChats', n);
	},
	
	toggleChatWindow: function(e) {
		e.preventDefault();
		this.observer.fire('notificationBar.toggleChatWindow');
	},
	
	showUsersOnEmptyList: function() {
		if (this.listContainer.offsetHeight == 0) {
			if (this.listContainer.innerHTML.strip().length > 0) {
				this.toggleUserYouCanInvite();
			}
			else {				
				new Ajax.Request('/jabber/getUsersYouCanInvite/', {
					onSuccess: function(r) {
						this.listContainer.update(r.responseText);
						this.listContainer.select(".chat-invite-link").each(function(el) {
							el.observe('click', function(e) {
								e.preventDefault();
								this.observer.fire('chatList.activateChatWindow', el.previous().getValue());
								this.toggleUserYouCanInvite();
							}.bind(this))
						}.bind(this));
						this.toggleUserYouCanInvite();
					}.bind(this)
				});
			}
		} else {
			this.toggleUserYouCanInvite();
		}
	},
	
	toggleUserYouCanInvite: function() {
		Effect.toggle(this.listContainer, 'slide', {
			duration: 0.4
		});
	}
});
