
function Chat(textbox, inputbox, submitbtn, url) {
	this.textBox = textbox;
	this.inputBox = inputbox;
	this.button = submitbtn;
	this.url = url;
	this.known = 0;
	this.timer = null;
	this.shown = 0;

	/* Setup callback for message button */
	var buttonclosure = function(me) {
		return function() {me.postMessage();};
	}
	this.button.onclick = buttonclosure(this);

	var inputclosure = function(me) {
		return function(e) {if ((e.keyCode || e.which) == 13) {me.postMessage();}};
	}
	this.inputBox.onkeypress = inputclosure(this);

	/* Start periodic updates */
	this.update();
}

Chat.prototype.update = function() {
	this.doUpdate();
	var me = this;
	this.timer = window.setTimeout(function() {me.update();}, 8000);
}

Chat.prototype.postMessage = function() {
	window.clearTimeout(this.timer);

	this.doUpdate(this.inputBox.value);
	this.inputBox.value = '';

	var me = this;
	this.timer = window.setTimeout(function() {me.update();}, 8000);
}

Chat.prototype.doUpdate = function (post) {

	var httpRequest = getXMLHTTPRequest();
	/* Setup xmlhttprequest objet */
	var readystateclosure = function(me) {
		return function () {
			if (httpRequest.readyState == 4) {
				if (httpRequest.status == 200) {
					eval("var result = " + httpRequest.responseText);
					for(var i = result.length-1; i >= 0; i--)
					{
						var msg = document.createElement('div');
						var obj = document.createElement('span'); obj.className = 'chattime';
						obj.appendChild(document.createTextNode('[' + result[i].time + ']'));
						msg.appendChild(obj);
						msg.appendChild(document.createTextNode(' '));
						var obj = document.createElement('span'); obj.className = 'chatposter';
						obj.appendChild(document.createTextNode(result[i].poster));
						msg.appendChild(obj);
						msg.appendChild(document.createTextNode('> '));
						var obj = document.createElement('span'); obj.className = 'chatmessage';
						obj.innerHTML = result[i].message;
						msg.appendChild(obj);
						me.textBox.insertBefore(msg, me.textBox.firstChild);
						me.known = result[i].dbid;

						if (me.shown == 20) {
							me.textBox.removeChild(me.textBox.lastChild);
						} else {
							me.shown++;
						}
					}
				}
			}
		}
	}
	httpRequest.onreadystatechange = readystateclosure(this);

	httpRequest.open("GET",
			this.url + '?limit=20&known=' + this.known + (post ? '&msg=' + escape(post) : ''), true);
	httpRequest.send("");
}

