// Simple templating engine

var engine = new function() {
	var that = this;
	var pageLoadCallbacks = [];
	var loadingCount = 1;
	
	this.getVars = getVars();
	
	this.pageLoad = function(callback) {
		pageLoadCallbacks.push(callback);
	};

	this.change = function(id, contentName) {

		loadingCount++;
		
		if(typeof(contentName) == "undefined" || contentName == null) {
			contentName = id;
		}

		jQuery("#" + id).load(
			"content/" + contentName + ".html",
			function() {
				//See if there's any js
				jQuery.getScript("content/" + contentName + ".js");

				//Now load children if there are any
				jQuery("#" + id).ready(function() {
					if(jQuery("#" + id ).children().size() > 0) {
						autoLoad("#" + id);
					}
					
					loadingCount--;
					
					if(loadingCount == 1) {
						pageLoaded();
					}
				});

				updateLinks();
			}
		);
	}

	function autoLoad(contentParent) {
		var selector = "div";
		if(typeof(contentParent) != "undefined" && contentParent != null) {
			selector = contentParent + " " + selector;
		}

		jQuery(selector).each(function() {
			var id = jQuery(this).attr("id");

			if(jQuery(this).html() == "") {
				that.change(id);
			}
		});
	}

	function updateLinks() {
		jQuery("a.magicLink").each(function() {
			var location = jQuery(this).attr("href");
			var title = jQuery(this).attr("name");

			jQuery(this).attr("href", "#");
			jQuery(this).removeAttr("name");
			jQuery(this).click(function() {
				that.change('content', location);
				if(title != "") {
					jQuery("title").text(title)
				}
			});

			jQuery(this).removeClass("magicLink")
		});
	}
	
	function pageLoaded() {
		while(pageLoadCallbacks.length > 0) {
			var callback = pageLoadCallbacks.pop();
			callback();
		}
	}
	
	function getVars() {
		var getVars = [];
		var hashes = window.location.href.substr(window.location.href.indexOf('?') + 1).split('&');
		for(var i=0; i<hashes.length; i++) {
			var hash = hashes[i].split('=');
			getVars[hash[0]] = hash[1];
		}
		return getVars;
	}

	jQuery(document).ready(function() {
		autoLoad();
	});
}
