(function()
{
	Common.Object.create('Typical.Chat.ScreenManager', {

		chat : null,
		isActive : null,
		
		focusElement : null,
		windowsBar : null,
		windows : null,
		windowsElement : null,
		focussedWindow : null,
		
		onNewWindow : null,
		onWindowFocus : null,
		
		ScreenManager : function(chat)
		{
			this.chat = chat;
			this.isActive = true;
			
			this.windows = [];
			
			this.onNewWindow = new Common.Dispatcher();
			this.onWindowFocus = new Common.Dispatcher();

			this.windowsBar = new Typical.Chat.WindowsBar(this);
			
			this.initGUI();
			this.initWindows();
			
			this.chat.onClose.add(this.handleClose, this);
		},
		
		initGUI : function()
		{
			// @todo Adjust size to resizing and minus scrollbar.
			this.focusElement = Builder.node('div', {'class' : 'chat focus'});
			{
				Event.observe(this.focusElement, 'mousedown', this.blur.bind(this));	
			}
			Element.insert(document.body, { top : this.focusElement});
		},
		
		initWindows : function()
		{
			this.handleWindowFocus(new Typical.Chat.RoomWindow(this));
			//new Typical.Chat.FriendsWindow(this);
		},
		
		registerWindow : function(window)
		{
			if(this.windows.indexOf(window) != -1)
				return;
			
			this.windows.push(window);
			
			window.onFocus.add(this.handleWindowFocus, this);
			window.onBlur.add(this.onWindowBlur, this);
			
			this.onNewWindow.dispatch(window);
		},
		
		unregisterWindow : function(window)
		{
			var windowIndex = this.windows.indexOf(window);
			
			if(windowIndex == -1)
				return;
			
			var windowElement = window.getElement();
			
			this.windows.splice(windowIndex, 1);
			
			Element.remove(windowElement);
		},
		
		handleWindowFocus : function(window)
		{
			if(this.focussedWindow)
				this.focussedWindow.blur();
			
			this.focussedWindow = null;
			
			this.focus();
			
			window.focus();
			
			this.focussedWindow = window;
			
			this.onWindowFocus.dispatch();
		},
		
		setWindowOverlap : function(window, overlap)
		{
			window.setOverlap(overlap);
		},
		
		onWindowBlur : function(window)
		{
			if(this.focussedWindow != window)
				return;
				
			this.focussedWindow = null;
			
			this.blur();
		},
		
		focus : function()
		{
			Element.setStyle(this.focusElement, {display : ''});
		},
		
		blur : function()
		{
			if(this.focussedWindow)
				this.focussedWindow.blur();
			
			Element.setStyle(this.focusElement, {display : 'none'});
		},
		
		userLoggedIn : function()
		{
			//this.barElement.innerHTML = 'Ingelogd, chat key: ' + this.chat.getChatKey();
		},
		
		userLoggedOut : function()
		{
			//this.barElement.innerHTML = 'Niet (meer) ingelogd.';
		},
		
		close : function()
		{
			if(!this.isActive)
				return;
				
			this.isActive = false;
			
			this.chat.close();
			
			this.hide();
		},
		
		hide : function()
		{
			this.windows.invoke('close');
			
			this.windowsBar.close();
		}
		
	});
})();
