(function($) {
$.fn.js_shell = function() {
	var t1 = ('<div id="shell_window" style="border: 0px solid black; position:absolute; top: 4px; right: 20px; height:400px; width:500px; z-index:900;"><div id="log" class="monotype" style=""></div><textarea id="sh_cmd" class="monotype"></textarea><input id="sh_do_it" name="shell_send" type="button" value="do it"><div style="clear:both"></div>');
	
	$(this).append(t1);
	
	
	JSShell();
	
	function shLog(logged) {
		$("#log").append("> "+logged+"<br>");
		$("#log").scrollTop(9000);
	}
	function dir(object)
	{
		methods = [];
		for (z in object) {
			if (typeof(z) != 'number') {
				methods.push(z);
			}
			return methods.join(', ');
		}
	}
	
	function JSShell() {
		var cmds	= new Array();
		cmds.push("");
		$l 			= $("#log");
		cmd_i		= 0;
		
		// Execute the code...
		$("#sh_do_it").click(function(e) { 
			var command = $("textarea#sh_cmd").val();
			// Log of commands, accessed with vertical arrows.
			cmds.pop();
			cmds.push(command);
			cmds.push("");
			cmd_i = cmds.length-1;
			if (true) { $("textarea#sh_cmd").val(''); }
			shLog('<span style="color:#33A;">'+command+'</span>');
			
			// Internal commands...
			if (command == ':close') { $('#shell_window').remove(); }
			else {			
				// Evaluate the expressioin
				$result = eval(command);
				
				shLog('<span style="color:#A33;">'+$result+'</span>');
			}
		});
		
		$('textarea#sh_cmd').keydown(function(e) {
			if (e.keyCode == 38 || e.keyCode == 40) {
				// If we're navigating commands and leave the most recent line, save any typed text
				if (cmd_i == cmds.length-1 && e.keyCode == 38 ) { cmds[cmd_i] = $("textarea#sh_cmd").val(); }
				// Traverse the command history
				cmd_i += (e.keyCode  == 40 ? (cmd_i < cmds.length ? 1: 0) : (cmd_i > 0 ? -1: 0));
				// Change the command text
				$("textarea#sh_cmd").val(cmds[cmd_i]);
				
				return false;
			}
			// Return key
			if (e.keyCode == 13) { $("#sh_do_it").click(); return false;}
		});
		
		window.onerror=errorPrinter;
		function errorPrinter(err, url, lineNum) { shLog('<span style="color:#D33;">'+err+'</span>'); return true;}
		
	}
};
})(jQuery);

