// this code is awful

var commands = [
    { cmd: 'shutdown -h now', html: 'Permission denied<br />This is a web page.' },
    { cmd: 'ls -A ~', html: '.bashrc<br />.profile<br />src/<br />test.cpp' },
    { cmd: 'make oldconfig && make all modules_install install' },
    { cmd: 'rm -rf /', html: 'Permission denied<br />you cannot be serious' },
    { cmd: '(cd /; touch this)', html: 'touch: cannot touch `this\': Permission denied' },
    { cmd: 'make love', html: 'Don\'t know how to make love.' },
    { cmd: 'man woman', html: 'No manual entry for woman.' },
    { cmd: 'make me a sandwich', html: 'What? Make it yourself.' },
    { cmd: 'sudo make me a sandwich', html: 'Okay.' }
];
var command_num = null;

function prompt_element()
{
	return document.getElementById('prompt_span');
}
function prompt_clear()
{
	prompt_set('');
}
function prompt_set(value)
{
	prompt_element().firstChild.data = value + '_';
}
function prompt_append(value)
{
	var node = prompt_element().firstChild;
	node.data = node.data.substring(0, node.data.length - 1) +
	    value + '_';
}
function prompt_finish()
{
	var node = prompt_element().firstChild;
	node.data = node.data.substring(0, node.data.length - 1);
}

function result_element()
{
	return document.getElementById('result_span');
}
function result_clear()
{
	result_set('');
}
function result_set(value)
{
	var n = result_element();
	n.innerHTML = value + (value.length ? '<br />' : '') + '_';
}
function result_blank()
{
	var n = result_element();
	n.innerHTML = '';
}
function result_type(cmd, also_this)
{
	result_set(cmd.html);
	also_this();
}

function prompt_type(cmd, pos, also_this)
{
	var next;
	if (arguments.length == 3) {
		result_blank();
		prompt_clear();
	}
	if (pos == cmd.cmd.length) {
		result_clear();
		prompt_finish();

		next = function () {
			result_type(cmd, also_this);
		}
		if (cmd.html)
			setTimeout(next, 1000);
		else
			also_this();
		return;
	}
	prompt_append(cmd.cmd.charAt(pos));
	next = function () {
		prompt_type(cmd, pos + 1, also_this, true);
	}
	setTimeout(next, 50);
}

function prompt_cycle()
{
	if (command_num == null)
		command_num = 0;
	else {
		command_num++;
		command_num %= commands.length;
	}
	var next = function () {
		prompt_type(commands[command_num], 0, prompt_cycle);
	}
	setTimeout(next, 3000);
}
