$(function() {

	var index = 0; // current photo

	// Build arrow elements
	$('#content #images')
		.append('<span class="arrow left"></span>')
		.append('<span class="arrow right"></span>');

	// Hide all images after the first one
	$('#images img')
		.hide()
		.eq(0).show().css('z-index', 1);

	// Hide arrows
	$('#content .arrow').hide();
	
	// Left arrow functionality
	$('#content .arrow.left').click(function() {
		nextPhoto(this);
	});
	
	// Right arrow functionality
	$('#content .arrow.right').click(function() {
		nextPhoto(this);
	});

	// Setup arrow mouseovers
	$('#images').bind({
		mouseenter: function(e) {
			e.stopPropagation();
			$('#content .arrow').stop().fadeIn(250);
		},
		mouseleave: function(e) {
			e.stopPropagation();
			$('#content .arrow').stop().fadeOut(250);
		}
	});

	// Generate thumbnail elements
	$('#images img').each(function() {
		$('<ul id="thumbs">').appendTo('#content');
		$('<li><img src="' + $(this).attr('src').replace(/\.\w+$/, '_thumb.jpg') + '" width="49" height="40"></li>').appendTo('#thumbs');
	});

	// Hide all thumbnails except for the first one
	$('#thumbs img')
		.css('opacity', 0.5)
		.eq(0).css('opacity', 1).data('active', true);

	// Setup thumbnail behaviors
	$('#thumbs img').bind({

		mouseover: function(e) {
			$(this).clearQueue().fadeTo(250, 1);
		},

		mouseout: function(e) {
			if(!$(this).data('active')) {
				$(this).clearQueue().fadeTo(250, 0.5);
			}
		},

		click: function(e) {
			nextPhoto(this);
		}

	});

	function nextPhoto(context) {
		
		if($(context).hasClass('left')) {
			index--;
		} else if($(context).hasClass('right')) {
			index++;
		} else {
			index = $(context).parent().index(); // when a thumbnail is clicked
		}
		
		if(index >= $('#images img').length) {
			index = 0;
		} else if(index < 0) {
			index = $('#images img').length - 1;
		}

		$('#thumbs img')
			.data('active', false)
			.fadeTo(250, 0.5)
			.eq(index)
				.clearQueue()
				.data('active', true)
				.fadeTo(250, 1);

		$('#images img')
			.stop()
			.css('z-index', 0)
			.eq(index)
				.css('z-index', 1)
				.fadeIn(1000, function() {
					$('#images img').css('z-index', 0).hide();
					$(this).css('z-index', 1).show();
				});
	}

});
