jQuery(function($) {
	var cache = {
		'':$('#content-default') // display the default-content div if we haven't loaded anything else
	};

	var subcache = {
	};

	var transTimeout = null;

	var bgTimeout = false;




	/**
	 * Updates content areas. Relies on a cache to reduce ajax requests.
	 */
	function onHashChange() {
		if($.param.fragment().charAt(0) != '!') return; // don't do internal links
		var frag = $.param.fragment().replace('!', '');
		var url = frag.split('/')[0]; // gets the url fragment from bbq
		
		// skip loading main content if only sub content has changed
		if(cache[url] && cache[url].hasClass('content-current')) {
			if(subcache[frag] !== $('.subcontent-current')) updateSub(frag, url);
		}
		else {
			updateMain(frag, url);
		}
	}



	function updateMain(frag, url) {
		$('a.current').removeClass('current'); // clean up old "current" links
		url && $('a[href="#!'+url+'"]').addClass('.current'); // update nav links if url isn't empty

		if(cache[url]) { // keep a cache, let's not do ajax loads when we don't need to
			swap(frag, url);
		} // end if(cache)
		else {
			// create a new container for the upcoming content
			$.ajax({
				url:url+".html",
				dataType:'html',
				success:function(res) {
					cache[url] = $('<div class="content-item" id="'+url+'"/>').html(res);
					swap(frag, url);
				}
			});
		} // end else if(cache)
	}


	/**
	 * These variables are all related to the swap() function so defined here.
	 */
	var curSwapFrag = null;
	var curSwapUrl = null;
	var curSwapTimeout = null;
	function swap(frag, url) {
		var current = $('.content-current');
		current.stop().removeClass('content-current').css({opacity:1}).animate({opacity:0}, 1000, function() {
			$(this).children().css({opacity:1}).animate({opacity:0}, 1000, function() {$(this).hide()});
		});
		$(cache[url]).addClass('content-current').stop();
		curSwapFrag = frag;
		curSwapUrl = url;
		curSwapTimeout = setTimeout(function() {
			$(cache[curSwapUrl]).hide()
				.prependTo('.content').css({opacity:0})
				.show().animate({opacity:1}, 1000)
				.children().css({opacity:0}).show().animate({opacity:1}, 1000);
			url = curSwapUrl || 'home';
			$('body').attr('class', url);
			if($('#audio-play').css('display') == 'none') $('#audio-player-widget').jPlayer('play');
			updateBGs();
			updateSub(curSwapFrag, url);	
			$(window).trigger('bbq.load');
		}, 1000);
	}




	/**
	 * Updates subcontent areas.
	 */
	function updateSub(frag, url) {
		if($('.anim-helper').size()) {
			$('.anim-helper').stop().trigger('complete').children().unwrap();
		}
		var sub = frag.split('/')[1];
		sub = sub || 'default';
		frag = url+'-'+sub;
		if($('#'+frag) && !subcache[frag]) subcache[frag] = $('#'+frag);
		if(subcache[frag] && subcache[frag].hasClass('subcontent-current')) return;
		if(subcache[frag].size()) {
			$('.content-current .subcontent').children(":visible").not('.subcontent-current').hide();
			var el = $('.content-current .subcontent-current');
			el.removeClass('subcontent-current');
			var width = el.outerWidth();
			el.css('width', width).wrap('<div class="anim-helper" />');
			$('.anim-helper').animate({width:0}, 500, function() {
				$(el).css('width', '').hide().unwrap();
				var height = subcache[frag].addClass('subcontent-current').show().height();
				subcache[frag].css('width', width).wrap('<div class="anim-helper" style="width:0">');
				$('.anim-helper').css('width', 0).stop().animate({width:width}, {
					duration:250,
					step:function() {/*updateBGs()*/},
					complete:function() {
						subcache[frag].css('width', '').unwrap(); 
						if($(window).width() < 480) $(window).scrollTop($(this).offset().top-10);
						updateBGs();
					}
				});
			});
		}
	}




	/**
	 * If the window is wider than the image proportionally, scale it horizontally.
	 * If the window is taller, scale the image vertically.
	 */
	function updateBGs() {
		clearTimeout(bgTimeout);

		// go update the scale properties on each bg item to make sure it's scaling appropriately
		var bg = $('.content-current .body-bg');
		var tmp = false;
		if(bg.size() && (bg[0].complete || bg[0].readyState === 4)) {
			bg.css({width:'', height:''});
			if(bg.width()/bg.height() > $(window).width()/$(window).height()) {
				$('body .content-current .body-bg').css({width:'auto', height:'100%'});
			}
			else {
				$('body .content-current .body-bg').css({width:'100%', height:'auto'});
			}
			$('#header-bg').css({width:bg.width(), height:bg.height()});
		}
	 	// if the image hasn't finished loading, try again in 1 second	
		else bgTimeout = setTimeout(updateBGs, 1000);

		if($('#about.content-current').size()) {
			// Let's also center the content blurb here if it exists 
			var content = $('#about.content-current div.section-content');
			// we don't want to overlap about, so limit the centering effect
			var limit = $('#about.content-current').offset().top+$('#about.content-current').height();
			var newMargin = $(window).height()/2-content.height()/2;
			newMargin = Math.max(limit, newMargin);
			content.css({'margin-top':newMargin+"px"});
		}
	} // end updateBGs

	$(window).bind('hashchange', onHashChange); // updates content when the hash changes

	$(window).bind('resize', updateBGs); // updates background image scaling so that it stretches the right direction

	$(window).trigger('hashchange'); // Since the event is only triggered when the hash changes let's trigger it now to handle any existing hash
	
	$('a.lightbox').live('click', function(e) {
		e.preventDefault();
		var el = $(this).attr('href').match(/#.*$/)[0];
		try {
			var html = $(el)[0].outerHTML;
			if(!html) throw new Error();
		}
		catch(e) { // if it doesn't have outerHTML, it's not Internet Explorer and thus can handle this:
			var html = $(el).clone().wrap('<div />').parent().html();
		}
		$.fancybox(html, {overlayShow:false, padding:0, autoDimensions:false}); // ugliest hack evar, thanks IE7
	});
	updateBGs();
	// catch all for occasional race condition bug
	setTimeout(updateBGs, 1000);
}); // end jQuery()

