$(function() {
	$('body').append($('<div class="contentContainer"></div>').css({display: 'none'}));
	$('.contentContainer').append('<div class="holding"></div>');
	
	var fetching = false,
		active = '';
		
	var switchContent = function (className) {
		
		$('.contentContainer').append($('#content .content'));
		$('#screenshot')
			.after($('.contentContainer .' + className))
			.removeClass()
			.addClass(className);
	}

	$('#nav a').click(function(e) {
	
		var target = e.target;
		var href = this.href.split('/').pop().split('.')[0];

		if(href!==active) {
			active = href;
		}
		else {
			e.stopPropagation();
			e.preventDefault();
			return;
		}
		
		if($('.contentContainer .'+href).length==0 && !fetching) 
		{
			fetching = true;
			$(' .holding').load(this.href + ' #content .content',null,function() {
				$('.contentContainer').append($('.contentContainer .holding .content'));
				switchContent(href);
				fetching = false;
			});
		}
		else {
			if (fetching) {
				e.stopPropagation();
				e.preventDefault();
				return;
			}
			switchContent(href);
		}

					
		$('#navigation .active').removeClass('active');
		$('#' + href + '-li').addClass('active');
		
		e.stopPropagation();
		e.preventDefault();
	
	});
	
	$('#navigation a').click(function(e) {
		var target = e.target;
		var href = this.href.split('/').pop().split('.')[0];
		if(href!==active) {
			active = href;
		}
		else {
			e.stopPropagation();
			e.preventDefault();
			return;
		}
		
		if($('.contentContainer .'+href).length==0 && !fetching) 
		{
			fetching = true;
			$(' .holding').load(this.href + ' #content .content',null,function() {
				$('.contentContainer').append($('.contentContainer .holding .content'));
				switchContent(href);
				fetching = false;
			});
		}
		else {
			if (fetching) {
				e.stopPropagation();
				e.preventDefault();
				return;
			}
			switchContent(href);
		}
				
		$('#navigation .active').removeClass('active');
		$(target).parents('li').addClass('active');
		e.stopPropagation();
		e.preventDefault();
	});
});