/**
 * отвечает за события в окне чата
 */
var chatWindowEventsObserver = Class.create({
	initialize: function(observer) {

		this.chatWindowHistoryContainer = $('chat_window_history_container');
		this.chatHistoryUpdatedAtHidden = $('chatHistoryLastUpdatedAt');
		this.chatUsersLastUpdatedAt = $('chatWindowUsersLastUpdatedAt');
		this.chatSendMessageButton = $('chat_send_message');
		this.closeActiveChatButton = $('close_active_chat');
		this.chatNameContainer = $('chat_name');
		this.chatHistoryList = $('chat_window_history');
		this.chatMessage = $('chat_window_input');
		this.chatUsersList = $('chat-window-users');
		this.chatBox = $('chadbox');
		this.chatIconImage = $('chatIconImage');
		this.chatTitle = $('chat_title');
		this.activeTitle = '';
		this.tpl = {};

		this.sendMessageContainer = $('send_message_container');
		this.showContacts = $('show_users_you_can_invite_button');
		this.actionsContainer = $('chat_actions_and_users_line');

		this.contactsContainer = $('chat_contacts_container');
		this.contactsTitle = $('chat_contacts_title');
		this.observer = observer;

		this.onlineUsers = [];
		
		this.init();
	},

	init: function() {
		// слушаем событие по синку истории чата
		this.observer.on('chatWindow.syncChatWindowHistory', this.syncChatWindowHistory.bind(this));

		// событие по активации окна чата
		this.observer.on('chatWindow.openChatWindow', this.openChatWindow.bind(this));

		// событие показать/спрятать окно чата
		this.observer.on('chatWindow.toggleChatWindow', this.toggleChatWindow.bind(this));

		// сменить название чата
		this.observer.on('chatWindow.setWindowTitle', this.setWindowTitle.bind(this));

		// засинкать пользоватлей беседы
		this.observer.on('chatWindow.syncGroupChatUsers', this.syncGroupChatUsers.bind(this));

		// почистить историю чата
		this.observer.on('chatWindow.clearMessageContainer', this.clearMessageContainer.bind(this));

		this.observer.on('chatWindow.hideChatList', this.hideChatList.bind(this));

		this.observer.on('contacts.syncOnline', this.syncOnlineUsers.bind(this));
		
		this.observer.on('notificationBar.chatListIsEmpty', this.showMyContacts.bind(this));

		this.observer.on('settings.onSuccess', function () {
			$('leave_active_chat_link').observe('click', function(e){
				e.preventDefault();
				this.closeActiveChat();
			}.bind(this));
		}.bind(this));

		
		this.observer.on('chatContainer.show', function() {
			this.chatWindowHistoryContainer.show();
			this.actionsContainer.show();
			this.sendMessageContainer.show();
			this.chatTitle.show();
			this.contactsContainer.hide();
			this.contactsTitle.hide();
		}.bind(this));
		
		// отправка сообщения по enter, перенос строки по ctrl+enter
		this.chatMessage.observe('keyup', function(e) {
			if (e.keyCode == 13 && e.ctrlKey) {
				this.chatMessage.value += "\n";
				return true;
			}
			if (e.keyCode == 13) {
				this.sendMessage();
				this.chatMessage.focus();
			}
		}.bind(this));

		// кнопка "свернуть чадбокс"
		this.closeActiveChatButton.observe('click', function(e) {
			e.preventDefault();
			this.observer.fire('notificationBar.toggleChatWindow');
		}.bind(this));

		this.showContacts.observe('click', this.showMyContacts.bind(this));

		/**
		 * Линки на старт чата
		 **/
		$A($('chat_contacts_container').getElementsByClassName('chat-start-link')).each(function(el){
			el.observe('click', function(e){
				e.preventDefault();
				this.observer.fire('chatList.activateChatWindow', el.previous('input').getValue());
			}.bind(this));
		}.bind(this));

		// отправить сообщение
		this.chatSendMessageButton.observe('click', this.sendMessage.bind(this));

		// шаблон для строки сообщения
		this.tpl.chatWindowMessage = new Template(
			'<li>' +
				'<p>' +
					'<img src="#{avatar}" alt="#{from}" title="#{from}" width="16" height="16"/> ' +
					'<a href="#"></a> [#{time}]' + 
				'</p>' +
				'#{message}' +
			'</li>'
		);

		// шаблон для юзера
		this.tpl.chatUser = new Template('<a href="#" onclick="return false;">#{userName}</a>');
	},

	showMyContacts: function () {
			/**
			 * Надо спрятать все окно чата (история, actions и т.д, оставить только title)
			 * и показать юзеров и клубы
			 *
			 **/
			this.chatWindowHistoryContainer.hide();
			this.actionsContainer.hide();
			this.sendMessageContainer.hide();
			this.chatTitle.hide();
			
			this.contactsTitle.show();
			this.contactsContainer.show();
			if (this.chatBox.offsetHeight == 0) {
				this.openChatWindow();
			}
	},
	/**
	 * активирует окно чата
	 */
	openChatWindow: function() {
		//if (! this.chatBox.visible() || toggle) {
			/*new Effect.Opacity(this.chatBox, {
				from: 0.0,
				to: 1.0,
				duration: 0.4
			});*/
			Effect.toggle(this.chatBox, 'slide', {
				duration: 0.4,
				afterFinish: function() {
					this.drainChatWindowScroll();
				}.bind(this)
			});
		//}
	},

	/**
	 * закрыть активный чат
	 */
	closeActiveChat: function() {
		this.observer.fire('chatWindow.closeActiveChat');
	},

	/**
	 * спускает скроллинг нашего чата вниз
	 */
	drainChatWindowScroll: function() {
		this.chatWindowHistoryContainer.scrollTop = this.chatWindowHistoryContainer.scrollHeight;
	},

	/**
	 * Перерисует онлайн юзеров - если конечно кто-то
	 * появился онлайн или кто-то ушел в оффлайн.
	 **/
	syncOnlineUsers: function (data) {
		$A($('chat_contacts_container').getElementsByClassName('userstate')).each(function(el){
			if (data.indexOf(el.previous('input').getValue()) == -1) {
				el.addClassName('userstate_off');
			} else {
				el.removeClassName('userstate_off');
			}
		});
		
		this.onlineUsers = data;
	},
	
	/**
	 * перепишет историю сообщений в окне
	 */
	syncChatWindowHistory: function(data) {
		var t = data.t;
			
		if (this.chatHistoryUpdatedAtHidden.getValue() < t || data.forceSync) {

			// очистим окно сообщений от прежнего чата
			this.chatHistoryList.update('');
			var prevDay = -1;
			
			data.history.each(function (item) {
				var date = new Date(item.time);

				// парсим шаблон сообщения
				if (prevDay != date.getDate()) {
					Element.insert(
						this.chatHistoryList,
						'<li><b>' +
						date.getFullYear() + ' ' +
						date.getMonthName() + ', ' + ' ' +
						date.getDate() + ' ' +
						date.getDayName() +
						'</b></li>'
					);

					var e = this.chatHistoryList.select('li');

					if (e.size() % 2 != 0) { // если нечетный ряд
						e.last().addClassName('big_popup_bg1');
					}
				}
				
				prevDay = date.getDate();

				var tpl = this.tpl.chatWindowMessage.evaluate({
					'time': date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds(),
					'from': item.from,
					'message': item.body.stripScripts().stripTags(),
					'avatar': item.avatar
				});

				// Parsing links
				var urlPattern = /((http|https|ftp)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?\/?([a-zA-Z0-9\-\._\?\,\'\/\\\+&amp;%\$#\=~])*)/g;
				tpl = tpl.replace(
					urlPattern,
					'<a href="$1">$1</a>'
				);

				// вставляем элемент в список
				Element.insert(this.chatHistoryList, tpl);

				var e = this.chatHistoryList.select('li');
				if (e.size() % 2 != 0) { // если нечетный ряд
					e.last().addClassName('big_popup_bg1');
				}
				
			}.bind(this));

			this.drainChatWindowScroll();
			this.chatHistoryUpdatedAtHidden.setValue(t);
		}
	},
	
	
	sendMessage: function() {
		var chatMessage = this.chatMessage.getValue();
		var notSpaceCharsCount = chatMessage.replace(/ /g, '').length;

		if (notSpaceCharsCount > 0) {
			this.observer.fire('chatWindow.sendMessage', chatMessage);
			this.observer.fire('sounds.onSentMessage');
			this.chatMessage.setValue('');
		}
	},
	
	setWindowTitle: function(data) {
		var title = data.chatName;
		//window.console.log(data);
		if (this.activeTitle != title) {
			this.chatIconImage.src = data.avatar;
			this.activeTitle = title;
			this.chatNameContainer.update(title);
		}
	},
	
	toggleChatWindow: function() {
		this.openChatWindow();
		/*if (this.chatBox.visible()) {
			this.chatBox.hide();
		}
		else {
			this.openChatWindow();
		}*/
	},
	
	syncGroupChatUsers: function(data) {
		if (this.chatUsersLastUpdatedAt.getValue() < data.t || data.forceSync) {
			// очистим окно сообщение от прежнего чата
			this.chatUsersList.update('');
			
			data.users.each(function (item) {
				// вставляем элемент в список
				Element.insert(
					this.chatUsersList,
					// парсим шаблон с юзером
					this.tpl.chatUser.evaluate({'userName': item.value})
				);
			}.bind(this));
			
			this.chatUsersList.show();

			this.chatUsersLastUpdatedAt.setValue(data.t);
		}
	},
	
	hideChatList: function() {
		this.chatUsersList.hide().update('');
	},
	
	clearMessageContainer: function() {
		this.chatHistoryList.update('');
	}
});
