$(document).ready(function() {
	var z = 0; //for setting the initial z-index's
	var inAnimation = false; //flag for testing if we are in a animation
	var imgLoaded = 0; //for checking if all images are loaded
	
	$('#pictures img').each(function() { //set the initial z-index's
		z++; //at the end we have the highest z-index value stored in the z variable
		$(this).css('z-index', z); //apply increase z-index to <img>
		
		$(new Image()).attr('src', $(this).attr('src')).load(function() { //create new image object and have a callback when it's loaded
			imgLoaded++;
			
			if(imgLoaded == z) { //Do we have all pictures loaded?
				$('#loader').fadeOut('slow'); //if so fade out the loader div
			}
		});
	});
	
	function swapFirstLast(isFirst) {
		if(inAnimation) { //if already swapping pictures just return
			return false; 
		}
		else { //set the flag that we process a image
			inAnimation = true;
		}
		
		var processZindex, direction, newZindex, inDeCrease; //change for previous or next image
		
		if(isFirst) { //set variables for "next" action
			processZindex = z;
			direction = '-';
			newZindex = 1;
			inDeCrease = 1;
		}
		else { //set variable for "previous" action
			processZindex = 1;
			direction = '';
			newZindex = z;
			inDeCrease = -1;
		}
		
		$('#pictures img').each(function() { 
			if($(this).css('z-index') == processZindex) { //process each image
				$(this).animate({ 'top' : direction + $(this).height() + 'px' }, 'slow', function() {
					$(this).css('z-index', newZindex) //set new z-index
						.animate({ 'top' : '0' }, 'slow', function() { //animate the image back to its original postion
							inAnimation = false; //reset the flag
						});
				});
			}
			else { //not the image we need to process, only id/de-crease z-index
				$(this).animate({ 'top' : '0' }, 'slow', function() { //make sure to wait swapping the z-index when image is above/under the gallery
					$(this).css('z-index', parseInt($(this).css('z-index')) + inDeCrease); //in/de-crease the z-index by one
				});
			}
		});
		
		return false;
	}
	
	$('#next').click(function() {
		return swapFirstLast(true);
	});
	
	$('#prev').click(function() {
		return swapFirstLast(false);
	});
});
