/*--------------------------------------------------------------------------  
 * ChatManager
 * 
 * Use the Mootools Javascript framework
 * 
 * (c) 2008 Unikity (www.unikity.fr)
 *--------------------------------------------------------------------------*/

var ChatManager = new Class(
{	
	Implements: [Event],
	
	rate: 2000, // in mseconds
	msgIndex: 0,
	arrMsg: [],
	isFocus: true,
	isActive: false,
	pe: null,
	DEFAULT_TITLE: 'Unikity, le chat qui vous unit.',
	END_TITLE: '...',
	MAX_TITLE_LENGTH: 10,

	initialize: function()
	{
		window.addEvent('blur', this.onWindowBlur.bindWithEvent(this));
		window.addEvent('focus', this.onWindowFocus.bindWithEvent(this));
	}, 
	
	updateTitleStart: function(nickname, msg)
	{
		if(this.pe != null)
			this.pe = $clear(this.pe);
		
		this.setTitleMessages(nickname, msg);
		this.pe = this.periodicalChangeTitleFunction.periodical(this.rate, this);
		this.isActive = true;
	},
	
	periodicalChangeTitleFunction: function() 
	{
		if (!this.isFocus && this.isActive)
		{
			this.msgIndex += 1;
			if (this.msgIndex == this.arrMsg.length)
				this.msgIndex = 0;
			
			document.title = this.arrMsg[this.msgIndex];
		}
	},
	
	updateTitleStop: function()
	{
		document.title = this.DEFAULT_TITLE;
		
		if (this.isActive)
		{
			this.pe = $clear(this.pe);
			this.isActive = false;
		}
	},
	
	setTitleMessages: function(nickname, msg)
	{
		this.arrMsg[0] = nickname;
		if (msg.length > this.MAX_TITLE_LENGTH)
			this.arrMsg[1] = msg.substr(0, this.MAX_TITLE_LENGTH) + this.END_TITLE;
		else
			this.arrMsg[1] = msg;
	},
		
	onWindowBlur: function()
	{
		this.isFocus = false;
		
		if (this.isActive)
		{
			this.pe = $clear(this.pe);
			this.pe = this.periodicalChangeTitleFunction.periodical(this.rate, this);
		}
	},
	
	onWindowFocus: function() 
	{
		this.isFocus = true;
		if (this.isActive)
		{
			this.pe = $clear(this.pe);
			document.title = this.DEFAULT_TITLE;
		}
	}
});