jQuery(function($) {
	
	var ContentLoader = {
	
		defaultContentID: 'welcome',
		storage: $('#storage'),
		target: $('#content'),
		cookieName: 'nerd_current_content',
		
		load: function(contentID) {

			contentID = contentID || $.cookie(this.cookieName) || this.defaultContentID;
			
			var contentSelector = '#' + contentID;
			var content = this.storage.find(contentSelector);
			if (!content.length) return;
			
			// reset scrolling
			$('body').scrollTo('0px','0px');
			
			// remove existing content
			this.target.children().fadeOut().appendTo(this.storage);
		
			// show requested content
			content.hide().appendTo(this.target).fadeIn();
			
			// mark last location in the cookie
			$.cookie(this.cookieName, contentID, {expires: 7});
			
			// update navigation link appearance
			$('a').closest('li').removeClass('selected');
			$('a[href=#!'+contentID+']').closest('li').addClass('selected');
			
			// draw submenu
			// this.drawSubMenu(content);
			
		},

		// drawSubMenu function constants
		submenuContainer: $('#sub_navigation'),
		submenuTemplate: tmpl('template_submenu_links'),
	
		drawSubMenu: function(content) {

			var html = "";
			var self = this;
			var ommittedLinks = '.inset, .external';
			
			$(content).find('a:not([href^=mailto]):not('+ommittedLinks+')').each(function() {
				var link = $(this);
				html += self.submenuTemplate({
					label: link.text().truncate(20, "...") + " &raquo;", 
					href: link.attr('href'),
					target: link.attr('target')
				});
			});
			
			this.submenuContainer
				.empty()
				.hide()
				.html(html)
				.fadeIn();
		}
	
	};
	
	// Ajax content Links
	$.address.change(function(e) {
		var pathValue = e.value != "/" ? e.value : null;
		ContentLoader.load(pathValue);
	});

});
