jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("top", ( $(window).height() - this.height() )+$(window).scrollTop() + "px");
    this.css("left", ( ($(window).width() - this.width() ) / 2+$(window).scrollLeft()) - 1 + "px");
    return this;
}

$(document).ready(function() {
	$(".console").center();
	var commands = [];
	var count = 0;
	$(window).scroll(function() {
		$(".console").center();
	});
	$(".console input").focus();
	$("em").live("click", function(){
		if($(".console input").attr("value") != "") {
			$(".console input").attr("value", $(".console input").attr("value") + " " + $(this).html());
		} else {
			$(".console input").attr("value", $(this).html());
		}
		$(".console input").focus();
	});
	$(".console input").live("keyup", function(event) {
		var val = $(".console input").attr("value");
		if(event.keyCode == '13') {
			commands.push(val);
			count = commands.length;
			
			// Run Ajax
			$.ajax({
				type: "POST",
				url: "s8n.php",
				data: "command="+val,
				success: function(msg){
					// Show Result
					$("body").append(msg);

					// Clear Command Line
					$(".console input").attr("value","");
					$(".console input").focus();

					// Scroll to the bottom of the page
					$('html, body').animate({
						scrollTop: $(document).height()
					}, 0);
					$(".console").center();
				}
			});
		}
		
		if(event.keyCode == '38') {
			count--;
			if(count < 0) { count = 0;}
			$(".console input").attr("value",commands[count]);
			$(".console input").focus();
		}
		
		if(event.keyCode == '40') {
			count++;
			if(count > commands.length - 1) { count = commands.length - 1;}
			$(".console input").attr("value",commands[count]);
			$(".console input").focus();
		}
	});
	
});
