$(function() {
	// Animation flag. Prior to initial page load, don't animate.
	var animate = false;

	// Set active page
	var page = function(target) {
		if (!target.size() || target.is('.active')) return false;

		// Find targeted link and set active.
		var link = $('a[href=#' + target.attr('id') + ']');
		$('.navigation a.active').removeClass('active');
		$(link).addClass('active');

        // Set the image source so that it begins loading.
        if ($(target).attr('id') !== 'work' && $('img', target).size() > 0)
            $('img', target).attr('src', $('img', target).attr('original'));

		// Find targeted content and show.
		if (!animate) {
			$('.page.active').hide().removeClass('active');
			target.show().addClass('active');
			return;
		}
		$('.page.active').fadeOut(function() {
			$(this).removeClass('active');
			target.fadeIn(function() {
				target.addClass('active');
			});
		});
	};

	// Set active image
	var image = function(target) {
		if (!target.size() || target.is('.active')) return false;

		page($('#work'));

		// Find targeted link and set active.
		var link = $('a[href=#' + target.attr('id') + ']');
		$('.list a.active').removeClass('active');
		$(link).addClass('active');

        // Set the image source so that it begins loading.
        $('img', target).attr('src', $('img', target).attr('original'));

		// Find targeted image and show.
		if (!animate) {
			$('.image.active').hide().removeClass('active');
			target.show().addClass('active');
			return;
		}
		$('#work .images').height($('.image.active').height());
		$('.image.active').fadeOut(function() {
			$(this).removeClass('active');
			$('#work .images').animate({height: target.height()}, 500, function() {
				target.fadeIn(function() {
					target.addClass('active');
					$.scrollTo($('.page.active'), 500);
				});
			});
		});
	};

	// Next image
	$('a.next').click(function() {
		var target = $('.image.active').next('.image');
		if (target.size()) {
			window.location.hash = ('#' + target.attr('id'));
		}
		return false;
	});

	// Previous image
	$('a.prev').click(function() {
		var target = $('.image.active').prev('.image');
		if (target.size()) {
			window.location.hash = ('#' + target.attr('id'));
		}
		return false;
	});

	// Hash change event
	$(window).hashchange(function(ev) {
		var target = $(window.location.hash);
		if (target.is('.page')) {
			page(target);
		} else if (target.is('.image')) {
			image(target);
		}
	});
	$(window).hashchange();
	animate = true;
});


