// http://www.sohtanaka.com/web-design/automatic-image-slider-w-css-jquery/
(function($){

$(".main_view .window, .main_view-centered .window").available(function(){
 $(this).append('<div class="loading"><img src="images/loading.gif" alt="◯" /></div>');
 var _this = $(this);
 $(document).ready(function(){
	_this.find(".image_reel img:first-child").bind('imgload', function(){
		_this.find('.loading').hide();
	});
 });
}, true);

$(document).ready(function(){
 //Set Default State of each portfolio piece
 $(".paging").show();
 $(".paging a:first").addClass("active");

 //Get size of images, how many there are, then determin the size of the image reel.
 var imageWidth = $(".window").width();
 var imageSum = $(".image_reel img").length;
 var imageReelWidth = imageWidth * imageSum;

 //Adjust the image reel to its new size
 $(".image_reel").css({'width' : imageReelWidth});

 var delay = 5000;//Timer speed in milliseconds
 var slide_speed = (500 >= delay ? parseInt(delay / 10) : 500);

 //Paging + Slider Function
 var rotate = function(){
 	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

 	$(".paging a").removeClass('active'); //Remove all active class
 	$active.addClass('active'); //Add active class (the $active is declared in the rotateSwitch function)

 	//Slider Animation
 	$(".image_reel").animate({ left: -image_reelPosition }, slide_speed);

	play = null;
	rotateSwitch();// set up next slide
 };

 //Rotation + Timing Event
 var play;
 var rotateSwitch = function(){
	before = new Date();
	if (!play) play = setTimeout(function(){// only rotate if play not set
		$active = $('.paging a.active').next();
 		if ($active.length === 0) //If paging reaches the end...
 			$active = $('.paging a:first'); //go back to first
 		rotate(); //Trigger the paging and slider function
 	}, delay); //Timer speed in milliseconds (3 seconds)
 };

 rotateSwitch(); //Run function on launch
 
 $(window).focus(function(){
	rotateSwitch();// entering tab, restart slider
 }).blur(function(){
	clearTimeout(play);// leaving tab, suspend slider
	play = null;
 });

 //On Hover
 $(".image_reel a").hover(function(){ clearTimeout(play) }, //Stop the rotation
                          function(){ rotateSwitch() }); //Resume rotation

 //On Click
 $(".paging a").click(function(){	
 	$active = $(this); //Activate the clicked paging
 	//Reset Timer
 	clearTimeout(play); //Stop the rotation
	play = null;
 	rotate(); //Trigger rotation immediately
 	return false; //Prevent browser jump to link anchor
 });

});
})(jQuery);

