function swapImage(i){
	var currentIndex = $("#enlargement img").index( $('#enlargement img.selected') );
	// swap the image if it's different
	if (i != currentIndex){
		// current - fade out
		$('#enlargement img.selected').fadeOut(500, function(){
			$(this).removeClass('selected');
		});
		// next - fade in
		$('#enlargement img').eq(i).fadeIn(500, function(){					
			$(this).addClass('selected');
		});
	}
}

$(document).ready(function(){
	
	// display first image
	$('#enlargement img:first').fadeIn(1000, function(){
		$(this).addClass('selected');
	});
	
	// thumbnail links
    $('#thumbs a').each(function(index){
		$(this).click(function(){
			swapImage(index);
		});
    });
	
	// NEXT
	// next button
	$('#buttons a.next').click(function(){
		var next = $("#enlargement img").index( $('#enlargement img.selected') ) + 1;
		var thumbs = $("#thumbs li").size();
		if (next > (thumbs - 1)){
			next = 0; // loop forward to first
		}
		swapImage(next);
    });

	// next right arrow keyboard shortcut
	shortcut.add("Right",function() {
		$("#buttons a.next").addClass("click_down"); // button press effect
		var next = $("#enlargement img").index( $('#enlargement img.selected') ) + 1;
		var thumbs = $("#thumbs li").size();
		if (next > (thumbs - 1)){
			next = 0; // loop forward to first
		}
		swapImage(next);
		setTimeout(function() { $("#buttons a.next").removeClass("click_down"); }, 100); // remove button press effect
	});
	
	// PREVIOUS
	// previous button
	$('#buttons a.prev').click(function(){
		var previous = $("#enlargement img").index( $('#enlargement img.selected') ) - 1;
		var thumbs = $("#thumbs li").size();
		if (previous < 0){
			previous = (thumbs - 1); // loop back to last
		}
		swapImage(previous);
    });

	// previous right arrow keyboard shortcut
	shortcut.add("Left",function() {
		$("#buttons a.prev").addClass("click_down"); // button press effect
		var previous = $("#enlargement img").index( $('#enlargement img.selected') ) - 1;
		var thumbs = $("#thumbs li").size();
		if (previous < 0){
			previous = (thumbs - 1); // loop back to last
		}
		swapImage(previous);
		setTimeout(function() { $("#buttons a.prev").removeClass("click_down"); }, 100); // remove button press effect
    });
	
});