/**
 * отвечает за нотификейшн бар
 */
var windowTitleEventsObserver = Class.create({
	initialize: function(observer, o) {
		this.observer = observer;
		
		this.options = o;
		
		this.isActive = true;
		this.origTitle = document.title;
		this.periodical = null;
		this.counter = 0;
		this.activeNumber = 0;
		this.sign = 1;
		
		this.directionOffset = 10; // число симоволов смещения надписи
		
		this.init();
	},
	
	init: function() {
		
		Event.observe(window, 'blur', function() {
			this.isActive = false;
		}.bind(this));
		
		Event.observe(window, 'focus', function() {
			this.isActive = true;
			this.stopPeriodical();
			this.setTitle(this.origTitle);
		}.bind(this));
		
		// слушаем событие по натравливанию на название страницы спец. функции
		this.observer.on('document.newChats', this.initPeriodical.bind(this));
		
//		// слушаем событие по обновлению числа чатов с новыми сообщениями
//		this.observer.on('notificationBar.updateCounter', this.updateCounter.bind(this));
//		
//		this.observer.on('notificationBar.chatListIsEmpty', function() {
//			//TODO: временно
//			alert('chat list is empty!!')
//		}.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));
	},
	
	setTitle: function(title) {
		document.title = title;
	},
	
	initPeriodical: function(n) {
		if (! this.isActive && n > 0) { // только если окно неактивно
			//startPeriodical
			if (! this.periodical) {
				this.activeNumber = n;
				this.startPeriodical(n);
			}
			else if (this.activeNumber != n) {
				this.activeNumber = n;
				this.stopPeriodical();
				this.startPeriodical(n);
			}
		}
	},
	
	startPeriodical: function(n) {
		if (! this.periodical) {
			this.periodical = new PeriodicalExecuter(this.doShakyTitle.bind(this, n), 0.3);
		}
	},
	
	stopPeriodical: function() {
		if (this.periodical) {
			this.periodical.stop();
			this.periodical = null;
			this.counter = 0;
			this.sign = 1;
		}
	},
	
	doShakyTitle: function(n) {
		if (this.counter == this.directionOffset) {
			this.sign = 0;
		}
		else if (this.counter == 0) {
			this.sign = 1;
		}

		this.sign ? this.counter ++ : this.counter --; 

		var suffix = ' ';
		for (var i = 0; i < this.counter; i++) {
			suffix = suffix + ' · ';
		}
		//alert(this.options.msgTpl.replace('%d', n))
		this.setTitle(this.origTitle + suffix + this.options.msgTpl.replace('%d', n));
	},
	
	log: function(m) {
		window.console.log(m)
	}

});
