function ShoutBox(id) {
	this.element = $(id);
	this.curID = 0;
	this.windowTitle = document.title;
	this.timeout = 0;
	this.inputBox = $('shout_input_box');
	this.windowFocus = 0;
	this.blinkEnd = -1000;
	this.firstTime = 1;
	if (this.inputBox) {
		Event.observe(this.inputBox, 'blur', this.windowLostFocus.bind(this));
		Event.observe(this.inputBox, 'focus', this.windowGainFocus.bind(this));
	}
}

ShoutBox.prototype.update = function(xmlDoc) {
	var shoutList = getXMLNodeList(xmlDoc, "shout");
	
	var temp = getXMLNodeValue(xmlDoc, 'maxid');
	if (temp >= 0 && temp <= this.curID) return;
	var lastMsg = "", lastUsername = "";
	
	if (shoutList != null) {
		for (var i = shoutList.length-1; i >= 0; i--) {
			var username = getXMLNodeValue(shoutList[i], 'username');
			var content = getXMLNodeValue(shoutList[i], 'content');
			var id = getXMLNodeValue(shoutList[i], 'id');
			
			if (id <= this.curID && id >= 0) continue;	// id < 0 reserved for the announcement.
			
			lastMsg = content;
			lastUsername = username;
			
			var div = document.createElement('div');
			div.innerHTML = '<a href="user/profile/'+username+'"><b>'+username+'</b></a>:'+unescape(content);
			this.element.insertBefore(div, this.element.firstChild);
		}
	}
	
	if (temp*1 >= 0)
		this.curID = temp?temp:0;
	
	if (this.firstTime != 1 && !this.windowFocus && (lastMsg != "" || lastUsername != "")) {
		if (this.blinkEnd != -1000) window.clearTimeout(this.blinkEnd);
		this.blinkEnd = setTimeout(this.stopBlink.bind(this), 60*1000);
		this.blinkTitle(lastUsername+":"+lastMsg);
	}
	this.firstTime = 0;
}

ShoutBox.prototype.blinkTitle = function(msg, focus) {
	var oldTitle = document.title;
	document.title = msg;
	if (!this.windowFocus) {
		if (this.timeout) window.clearTimeout(this.timeout)
		this.timeout = setTimeout(this.blinkTitle.bind(this,oldTitle), 2000);
	}
	else document.title = this.windowTitle;
	//window.focus();
}

ShoutBox.prototype.stopBlink = function() {
	if (this.timeout) window.clearTimeout(this.timeout);
	window.clearTimeout(this.blinkEnd);
	document.title = this.windowTitle;
	this.blinkEnd = -1000;
}

ShoutBox.prototype.windowLostFocus = function() {
	this.windowFocus = 0;
}

ShoutBox.prototype.windowGainFocus = function() {
	this.windowFocus = 1;
	document.title = this.windowTitle;
	if (this.timeout) window.clearTimeout(this.timeout);
}
