$(document).ready(function() {
	
	// Used to access the values in the consoles in order	
	var currentConsole = 0;
	
    // Header hover effects
	$("div#header > a#lnk").hover(function() {
		$("div#header").css("background-position", "top center");
    }, function() {
		$("div#header").css("background-position", "bottom center");
    });
    
	$(".console:last").livequery("keyup", function(e) {	
		if(e.keyCode == 13 || e.keyCode == 10)	// Enter key
			submitForm();
	});
	
	// EXPERIMENTAL: Re-gain console input focus right when it is
	// lost? This makes it near-impossible to "lose track" of where to type.
	// WORKING ON THIS; IT DOESN'T WORK.
	/*
	var hasFocus = $(".console:last").focus();
	$(document).bind("click", function(event) {
		var ev = $(event.target);
		if(ev != hasFocus){
			if (ev.is('.console:last')){
				hasFocus = ev;
			}
			hasFocus.focus();
		}
	});
	$('.console:last').bind("focus", function() {
    	hasFocus = $(this);
  	});
  	*/
	
	// Make it easy to execute previous commands (up/down keys)
	$(document).livequery("keyup", function(event) {
		// Put in the text we need
		if (event.keyCode == 38 || event.keyCode == 40)
		$(".console:last").val($(".console").eq(currentConsole).val());
		
		if (event.keyCode == 38)
		{
			// Up arrow key
			if (currentConsole > 0)
				currentConsole --;
			else
				currentConsole = $(".console").size() - 2;
		}
		else if (event.keyCode == 40)
		{
			// Down arrow key
			// We use minus two here for the same reason we do
			// up at the end of the submit code... it's the last
			// console we're interested in reading from.
			if ($(".console").size() - 2 > currentConsole)
				currentConsole ++;
			else
				currentConsole = 0;
		}
	});
	// Set focus to the initial input line when the site first loads.
	$(".console:last").focus();
});

// Function called when the console form is submitted.
// No form actually exists, we just capture the Enter key.
// I use the jQuery plugin "LiveQuery" to keep JQuery up-to-date
// with new DOM elements such as the newest input textbox, etc.
var submitForm = function() {
	// At some point, we want to update the URL without
	// reloading the page... shouldn't be too difficult.
	// Just add a # after it. We'll have to be able to parse
	// those then too.
	
	// Get the user's input
	var userInput = $(".console:last").val();

	// Make sure they typed something
	if (!userInput)
		return false;
 	
	// Show the loading animation
	var lastLoadingIcon = "div.loading:last";
	$(lastLoadingIcon).css("display", "block");

	// If they want to reset/reload the page....
	if (userInput == "clear" || userInput == "cls")
	{
		location = location;	// true "refreshing" has weird effects
		return false;
	}
	
	// POST the request to the hypertext preprocessor
	$.post("./process.php", { request: userInput }, function(data) {
	
	 // Hide the loading thing
	 $(lastLoadingIcon).css("display", "none");

	 // Check for debug info
	 if (data == "force-do-reset")
	 {
	 	location = location;
	 	return;
	 }
	 
	 // Check for redirect commands
	 if (data.substring(0, 9) == "redirect:")
	 {
	 	location = data.substring(9, data.length);
	 	return;
	 }
	 
// Add results to the content div
$("div#content").append(data);

var newestInput = ".console:last";

// Focus on the newest console input line
$(newestInput).focus();

// Disable all other console lines -- BUG IN JQUERY OR WEBKIT HERE.
// BUG REPORT: http://dev.jquery.com/ticket/4587
$(".console:not(:last)").attr("readonly", "readonly");

// Until the bug is fixed, this will work around it and undo
// the readonly for the last textbox too.
$(".console:last").attr("readonly", "");

// Scroll to the bottom-most console input if necessary
$('html, body').animate({
	scrollTop: $(newestInput).offset().top - 100
}, 500);
		
	// Update the $currentConsole jQuery object because
	// we need to access the most recently typed command.
	// We minus two because that's the last textbox
	// we're interested in. Minus 1 gives us the current, empty
	// console, and minus 0 gives us... an off-by-one error.
	currentConsole = $(document).find(".console").length - 2;
});

// Don't let the form actually submit which would reload the page
return false;
};

// Here's a function that we can call to show a certain page.
// like: href="javascript:load('request here');"
var load = function(request) {
	jQuery(".console:last").val(request);
	submitForm();
}