var directoryPrefix = "";

$(document).ready(function(){
	$("#nav a").bind("click", function(event) {
		loadCategory(this, $(this).attr('href'));
		event.preventDefault();
	});

	bindLoadedContent();
});

function bindLoadedContent() {
	$("#content a").bind("click", function(event) {
		loadQuestion($(this).attr('href'));
		event.preventDefault();
	});
	$("#content").parent().css("height", $("#content").css("height"));
	handleContentVisiblity("show", "");
}
function loadCategory(clickedObject, url) {
	$("#nav a").removeClass("current");
	$(clickedObject).addClass("current");
	handleContentVisiblity("hide", url, "cat");
}

function loadQuestion(url) {	
	handleContentVisiblity("hide", url, "q");	
}

function doLoadAction(url, catOrQ) {
	if (typeof directoryPrefix == 'undefined' || directoryPrefix == '') {
		directoryPrefix = "";
	} else {
		directoryPrefix = directoryPrefix + "/";
	}
	
	if (url.substr(0, 3) == "http" || catOrQ == "cat") {
		// Using absolute links, dir prefix will cause problems.
		// No prefix for categories.
		directoryPrefix = "";
	}
	
	$("#content").empty();
	$("#content").load(directoryPrefix + url + " #content", '', bindLoadedContent);
	
	var urlElements = url.split("/");
	urlElements.pop(); // Removes index.html
	directoryPrefix = urlElements[urlElements.length-1]; // set directory to last element
}

function handleContentVisiblity(targetVis, url, catOrQ) {
	if (doAnimations) {
		if (targetVis == "show") {
			$("#content").fadeIn(400);
		} else if (targetVis == "hide") {
			$("#content").fadeOut(200, function() {
				doLoadAction(url, catOrQ);
			});
		}
		
	} else {
		if (targetVis == "show") {
			$("#content").show();
		} else if (targetVis == "hide") {
			$("#content").hide();
			doLoadAction(url, catOrQ);
		}
	}
}