/*
 * Run this when the Dom is ready
 */
jQuery(function(){
	// Call out setupImageSwap
	setupImageSwap('#animation-wrapper');
});

// Set a global variable here
var moving = false;
var timer = 0;

/**
 * Sets Up our Image Animations
 * 
 * 
 * @param parent	The item containing the items to be moved
 * @param distance	The width of a single item so we know how far to animate
 */
function setupImageSwap(parent){
	
	/* We need to find the first and last items to begin with 
	by using direct descenders and first and last sudo classes
	*/
	
	var firstItem 	= jQuery(parent).find('>:first');
	var lastItem 	= jQuery(parent).find('>:last');
	
	// Okay great now we have those...
	
	// First the move left (right arrow)
	jQuery('.arrow-forward').unbind('click').one('click',function(){
		// First clear the timer
		clearTimeout(timer);
		// ONLY ACTIVATE ONCE WE HAVE DONE MOVING
		if(moving == false){
			
			// We're moving, set it to true
			moving = true;
			
			// Animate the first item
			jQuery(lastItem).fadeOut('normal',
							 function(){
								 
								 // Okay animation complete set moving to false
								 moving = false;
								 
								 // Reset margin and detach
								 jQuery(lastItem).detach();
								 
								 // Now insert it after the last item
								 jQuery(lastItem).insertBefore(firstItem).show();
								 
								 // Recall ourselves
								 setupImageSwap(parent);
								 
							});
		} else {
			// DO NOTHING WE'RE STILL ANIMATING
		}
		
	});
	
	// Now the move right (left arrow)
	jQuery('.arrow-back').unbind('click').one('click',function(){
		// First clear the timer
		clearTimeout(timer);
		// ONLY ACTIVATE ONCE WE HAVE DONE MOVING
		if(moving == false){
			
			// We're moving set it to true
			moving = true;
			
			// We need to grab the last item first by setting it's margin to negative and detaching it
			jQuery(firstItem).hide().detach();
			
			// Copy it before the first item
			jQuery(firstItem).insertAfter(lastItem);
			
			// Right, now animate it
			jQuery(firstItem).fadeIn('normal',
							function(){
				
								// Okay we did all the moving around we need to, set moving to false
								moving = false;
								
								// Recall ourselves
								setupImageSwap(parent);
							});
		} else {
			// DO NOTHING WE'RE STILL ANIMATING
		}
	});
	// First clear the timer
	clearTimeout(timer);
	// Run a timer
	timer = setTimeout("jQuery('.arrow-forward').click()", 9000);
}
