var chat = new Chat();

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function chat_init()
{
	chat.init();
}

addLoadEvent(chat_init);


var debug = false;

function Chat()
{
	this.debug = false;
	this.init = function()
	{
		//this.container = getElementById("chatbox");
		
		this.container = document.createElement("div");
		this.container.style.cssText = "border:1px solid black; padding:4px;";
		document.body.appendChild(this.container);
		
		if (!this.container)
		{
			document.write("Couldn't find chatbox.");
			return null;
		}
		
		this.container.innerHTML = "Comment Box";
		
		this.chatarea = document.createElement("pre");
		this.container.appendChild(this.chatarea);
		
		if (this.debug)
		{
			this.debugarea = document.createElement("pre");
			this.container.appendChild(this.debugarea);
			this.debugarea.innerHTML = "Debugging started...\r\n";
		}
		
		this.formarea = document.createElement("div");
		this.container.appendChild(this.formarea);
		
		this.formarea.innerHTML = 
			'<form id="nameform" onsubmit="return false;"> \
					Username: <input type="text" name="username"/><br/>\
					<input type="submit" value="OK" onClick="chat.setNameForm(this);"/>\
					</form>';
		
		this.username = "";
		
		var pathname = window.location.pathname;
		if (!pathname || pathname.length < 4)
			this.source = "/index.html.txt";
		else
			this.source = window.location.pathname + ".txt";
		
		this.refreshChat();
	}
	
	this.setNameForm = function(button) 
	{
		this.d("Name form click handler: "+button);
		this.d("Name form: "+button.form);
		this.d("Username: "+button.form.username.value);
		this.username = button.form.username.value;
		this.d("Set username: \""+this.username+"\"");
		this.formarea.innerHTML =
			'<form id="chatform" onsubmit="chat.submitChatForm(this); return false;"> \
					Comment: <input type="text" name="line" size="80"/> <br/>\
					<input type="submit" value="Send"/>\
					</form>';
		return false;
	}
	
	this.d = function(line)
	{
		if (this.debug)
			this.debugarea.innerHTML += line + '\n';
	}
	
	this.requestStateChange = function()
	{
		chat.d("Request state changed to "+chat.req.readyState+" (status: "+chat.req.status+")");
		if (chat.req.readyState == 4)
		{
			chat.d("Readystate 4...");
			if (chat.req.responseText && (chat.req.status == 0 || chat.req.status == 200 || debug))
			{
				chat.d("Updating chatarea...");
				chat.chatarea.innerHTML = chat.req.responseText.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;");
			}
		}
	}
	
	this.getRSCClosure = function(obj) { return function() { obj.requestStateChange(); } }
	
	this.refreshChat = function()
	{
		if (!this.chatarea)
		{
			this.d("No chatbox found.");
			return;
		}
		
		this.d("Creating request...");
		this.req = new XMLHttpRequest();
		this.d("Setting state change callback...");
		this.req.onreadystatechange = this.getRSCClosure(this);
		this.d("Opening request...");
		this.req.open("GET", this.source + "?avoidcache="+Math.random(), true);
		this.d("Sending request...");
		this.req.send();
	}
	
	this.submitRSC = function()
	{
		if (this.readyState == 4)
		{
			chat.d("Submit readystate == 4; refreshing chat...");
			chat.refreshChat();
		}
	}
	
	this.submitChatForm = function(form)
	{
		this.d("Submitting form...");
		var line = "<" + this.username + "> " + form.line.value;
		var params = "page="+this.source+"&line="+encodeURIComponent(line);
	
		this.d("Params = \""+params+"\"");
	
		var post = new XMLHttpRequest();
		post.open("POST", "/chat.php", true);
		post.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		post.setRequestHeader("Content-length", params.length);
		post.setRequestHeader("Connection", "close");
	
		post.onreadystatechange = this.submitRSC;
		this.chatarea.innerHTML += "                 &lt;" + this.username + "&gt; " + form.line.value + '\r\n';

		this.d("Sending...");
		post.send(params);
		
		form.line.value = "";
	}
}
