var play;

$(document).ready(function() {
	var $els = $('.slider-wrap .image_reel a');
	$els.filter(':lt(' + (Math.floor(Math.random()* ($els.length)) + 1) + ')').appendTo($(".slider-wrap .image_reel"));
});

$(window).load(function() {
	//Set Default State of each portfolio piece
	$(".slider-wrap .paging-wrap").show();
	$(".slider-wrap .paging a:first").addClass("page-active");
		
	//Get size of images, how many there are, then determin the size of the image reel.
	var imageWidth = $(".slider-wrap .window").width();
	var imageSum = $(".slider-wrap .image_reel a").length;
	var imageReelWidth = imageWidth * imageSum;
	
	//Adjust the image reel to its new size
	$(".slider-wrap .image_reel").css({
		'width' : imageReelWidth + 20
	});
	
	//Paging + Slider Function
	var rotate = function($active) {
		var triggerID = $active.attr("rel") - 1; //Get number of times to slide
		var image_reelPosition = triggerID * imageWidth; //Determines the distance the image reel needs to slide

		$(".slider-wrap .paging a").removeClass('page-active'); //Remove all active class
		$active.addClass('page-active'); //Add active class (the $active is declared in the rotateSwitch function)
		$active.parent().css('display', 'none').css('display', 'block');
		
		//Slider Animation
		$(".slider-wrap .image_reel").animate({ 
			left: -image_reelPosition
		}, 500 );
	}; 
	
	//Rotation + Timing Event
	var rotateSwitch = function() {
		//play = setInterval(function() {
		play = setTimeout(function() {
			var $active = $('.slider-wrap .paging .page-active').next();
			if ($active.length == 0) { //If paging reaches the end...
				$active = $('.slider-wrap .paging a:first'); //go back to first
			}
			rotate($active); //Trigger the paging and slider function

			rotateSwitch();

		}, 7000); //Timer speed in milliseconds (3 seconds)
	};
	
	rotateSwitch(); //Run function on launch
	
	//On Hover
	$(".slider-wrap .image_reel a").hover(function() {
		//clearInterval(play); //Stop the rotation
		clearTimeout(play);
	}, function() {
		rotateSwitch(); //Resume rotation
	});	
	
	//On Click
	$(".slider-wrap .paging a").click(function() {
		//Reset Timer
		//clearInterval(play); //Stop the rotation

		clearTimeout(play);
		rotate($(this)); //Trigger rotation immediately
		rotateSwitch(); // Resume rotation
		return false; //Prevent browser jump to link anchor
	});	
	
});

