_get = function(id) { return document.getElementById(id); }
_new = function(type) { el = document.createElement(type); return el; }
_stop = function(e) { if (e.stopPropagation) e.stopPropagation(); if (e.preventDefault) e.preventDefault(); return false; }

root = _new("div");
document.documentElement.appendChild(root);

style = _new("link");
style.href = "/css/p957.css";
style.type = "text/css";
style.rel = "stylesheet";
root.appendChild(style);

pwd = "/";
PS1 = "p957 # ";
PS1x = /^p957 \# $/;

strings = {	
	badcmd: ": illegal command - type \"help\" for a list of commands",
	help: 	"\nCommands:\n" +
			"    gallery                view my gallery\n" +
			"    blog                   view my blog\n" +
			"    login <username>       attempts to login the specified user"
};

client = {
	request: (window.createRequest ? window.createRequest : new XMLHttpRequest()),
	run: function(cmd,args) {
		this.request.open("POST", "main.php", true);
		this.request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this.request.onreadystatechange = function() {
			if (client.request.readyState == 4)
				client.handleResponse(client.request.responseText);
		}
		this.request.send("pwd=" + pwd + "&c=" + cmd + "&a=" + args.join(","));
	},
	handleResponse: function(response) {
		if (response.length) io.print("\n" + response);
			else io.print();
	}
};

io = _new("textarea");
io.style.position = "absolute";
io.style.backgroundColor = "#1d1b19";
io.style.width = "100%";
io.style.height = "100%";
io.style.border = "0px";
io.style.color = "#f1edea";
io.style.fontFamily = "Incolota";
io.value = PS1;
io.get = function() { return io.value; }
io.print = function(s) { this.value += (s != undefined ? s : "") + "\n" + PS1; }
io.clear = function() { this.value = PS1; }
io.onblur = function() { this.focus(); }
io.onkeypress = function(e) {
	if (e.keyCode == 13) {
		main(io.get());
		return _stop(e);
	}
	else if (e.keyCode == 8) {
		if (PS1x.test(io.get())) {
			return _stop(e);
		}
	}
};
root.appendChild(io);

banner = _new("div");
banner.style.position = "absolute";
banner.style.right = "10px";
banner.style.top = "10px";
banner.style.color = "#0d0b09";
banner.style.fontFamily = "Helvetica,Arial";
banner.style.fontSize = "48px";
banner.style.fontWeight = "bold";
banner.innerHTML = "P957";
root.appendChild(banner);

main = function(stdin) {
	if (document.all) tmp = stdin.split("\r\n");
		else tmp = stdin.split("\n");
	args = tmp[tmp.length-1].replace(PS1,"").split(" ");
	cmd = args.splice(0,1);
	
	//if (cmd == "help") io.print(strings.help);
		if (cmd == "clear") io.clear();
		else if (cmd == "") io.print();
		else client.run(cmd,args);
}