(function()
{
	Common.Object.create('Typical.Chat.RoomWindow:Typical.Chat.Window', {

		usersData : null,

		onConnect : null,
		onUserOnline : null,
		onUserOffline : null,
		
		messagesView : null,
		usersView : null,
		
		channel : null,

		RoomWindow : function(mainBar)
		{
			this.usersData = {};
			
			this.onConnect = new Common.Dispatcher();
			this.onUserOnline = new Common.Dispatcher();
			this.onUserOffline = new Common.Dispatcher();
			
			this.parent(mainBar, {isPrimary : true, size : [700, 400], title : '<b>?</b> chatters', icon : 'roomwindow/icon.png', cssClass : 'roomwindow'});
			
			this.messagesView = new Typical.Chat.RoomWindow.Messages(this, this.elements.messages);
			this.usersView = new Typical.Chat.RoomWindow.Users(this, this.elements.users);
			
			this.getChat().onConnect.add(this.handleConnect, this);
		},
		
		initGUI : function()
		{
			this.parent();
			
			this.elements = { 	messages : Builder.node('div', {className : 'messagescontainer'}),
								users : Builder.node('div', {className : 'userscontainer'})
							};
							
			Element.insert(this.element, this.elements.messages);
			Element.insert(this.element, this.elements.users);
		},
		
		updateTitle : function()
		{
			var chatters = 0;
			
			for(var i in this.usersData)
			{
				if(this.usersData[i].isOnline)
					chatters++;
			}
			
			this.setTitle('<b>' + chatters + '</b> chatter' + (chatters != 1 ? 's' : ''));
		},
		
		getUserData : function(userId)
		{
			return this.usersData[userId];
		},
		
		getUsersData : function()
		{
			return this.usersData;
		},
		
		userLoggedIn : function(data)
		{	
			var userData = data.userData;
		
			if(!userData || this.usersData[userData.id] && this.usersData[userData.id].isOnline)
				return;
			
			if(this.usersData[userData.id])
				userData = this.usersData[userData.id];
			
			userData.isOnline = true;
			
			this.usersData[userData.id] = userData;
			
			this.updateTitle();
			
			this.onUserOnline.dispatch(userData);
		},
		
		userLoggedOut : function(data)
		{
			var userData = this.usersData[data.id];
			
			if(!userData || !userData.isOnline)
				return;
			
			userData.isOnline = false;
			
			this.updateTitle();
			
			this.onUserOffline.dispatch(userData);
		},
		
		handleConnect : function()
		{
			var connector = this.getChat().getConnector();
			
			connector.onCmd('userLoggedIn', this.userLoggedIn.bind(this));
			connector.onCmd('userLoggedOut', this.userLoggedOut.bind(this));
			
			connector.join('mainroom', { onJoin : this.handleJoin.bind(this) });
		},
	
		handleJoin : function(channel)
		{
			this.channel = channel;
			
			// Store users data.
			this.usersData = {};
			
			channel.users.each(function(userData)
			{
				userData.isOnline = true;
				
				this.usersData[userData.id] = userData;
			}.bind(this));
			
			// Update title.
			this.updateTitle();
			
			this.onConnect.dispatch();
		},
		
		getChannel : function()
		{
			return this.channel;
		}
		
	});
})();
