$("#shell").ready(function(){
	
	var shell, input, output, history, historyIdx, inputText;
	
	shell = $("#shell");
	
	shell.append("<section class=\"output\"></section>");
	shell.append("<section class=\"input\"><div class=\"label\">&gt;</div><input class=\"text\" type=\"text\" value=\"\"/></section>");
	
	output = $("#shell > .output");
	input = $("#shell > .input");
	inputText = $("#shell > .input > .text");
	history = [];
	historyIdx = 0;
	
	function recordOutput(value) {
		output.append("<div class=\"line\"><div class=\"text\">"+value+"</div></div>");
	}
	
	function recordInput(value) {
		history.push(value);
		output.append("<div class=\"line\"><div class=\"label\">&gt;</div><div class=\"text\">"+value+"</div></div>");
	}
	
	
	var commands = {
		"help": function() {
			recordOutput(
				"Commands:\n"+
				"    help       display this message\n"+
				"    contact    display contact information\n"+
				"    clear      clear the screen\n"
				);
		},
		"contact": function() {
			recordOutput(
				"  - <a href=\"http://www.facebook.com/cstivers\">Facebook</a>\n"+
				"  - <a href=\"http://www.twitter.com/cstivers78\">Twitter</a>\n"+
				"  - <a href=\"http://blog.stivers.us\">Tumblr</a>\n"+
				"  - <a href=\"http://www.linkedin.com/pub/chris-stivers/1/87a/863\">LinkedIn</a>\n"+
				"  - <a href=\"mailto:chris@stivers.us\">E-mail</a>\n"
				);
		},
		"history": function() {
			for(var i=0; i<history.length; i++) {
				recordOutput(
					history[i]
					);
			}
		},
		"clear": function() {
			output.empty();
		}
	};
	
	function invokeCommand() {
		var args = Array.prototype.slice.call(arguments);
		var cmd = args.shift();
		
		if ( commands[cmd] ) {
			commands[cmd].apply({},args);
		}
	}
	
	function evaluateInput(value) {
		recordInput(value);
		invokeCommand.apply({},value.split(" "));
		historyIdx=0;
	}
	
	input.keypress(function(event){
		switch( event.which ) {
			case 13:
				return (function(){
					var value = inputText.val();
					inputText.val("");
					evaluateInput(value);
					inputText.focus();
				})();
		}
	});

	// input.keydown(function(event){
	// 	switch( event.which ) {
	// 		case 38: // UP
	// 			return (function(){
	// 				if ( historyIdx < history.length ) {
	// 					historyIdx++;
	// 					inputText.val(history[history.length-historyIdx]);
	// 				}
	// 			})();
	// 		case 40: // DOWN
	// 			return (function(){
	// 				if ( historyIdx >= 0 ) {
	// 					historyIdx--;
	// 					inputText.val(history[history.length-historyIdx]);
	// 				}
	// 			})();
	// 	}
	// });
	
	inputText.focus();
});
