﻿function SetupSlideshow(nRows, nColumns, aSpeed) {
    $(document).ready(function(){
	    var groups = $('.slideshowGroup').length;
	    if (groups == 0) {
	        $('.iwkSlideshow').iwkSlideshow({
		        rows:nRows,
  		        columns:nColumns,
  		        timeout:aSpeed
	        });
	    }
    });
}


(function($){  
	$.fn.iwkSlideshow = function(options) {  

  		//Options Class
  		var defaults = {
  			rows:1,
  			columns:3,
  			timeout:2000
  		};		
  		//... extending options object with defaults values
  		var options = $.extend(defaults, options);
  
    	return this.each(function() {  

 			var slideshowTimer;
 			
 			$('.slideshowItem', $(this)).css('float','left');
 			
 			
 			var columnCounter = 0;
 			
 			var itemsCounter = 0;
 			var groupCounter = 0;
 			
 			$('.slideshowItem', $(this)).each(function(){
 				
 				$(this).addClass('g' + groupCounter);
 				
 				columnCounter++;
 				if(columnCounter == options.columns) {
 					$(this).after('<div class="g'+groupCounter+'" style="clear:both;">');
 					columnCounter = 0;
 				}
 				
 				itemsCounter++;
 				if (itemsCounter == options.columns*options.rows) {
 					itemsCounter = 0;
 					columnCounter = 0;
 					groupCounter++;
 				}
 				
 			});
 			
 			
 			for(var i=0; i<groupCounter + 1; i++) {
 				$('.g' + i).wrapAll('<div class="slideshowGroup">');
 			}
 			
 			var totalItems = $('.slideshowItem', $(this)).length;		
 			var pageSize = options.columns*options.rows;
 			
			if (totalItems > pageSize) { 			 			
 				
 				slideshowTimer = setInterval("slideSwitch()", options.timeout);

 				/* mouseOvering */
 				$('.slideshowItem', $(this)).hover(
 				    function(){
 				    	clearInterval(slideshowTimer);
 				    },
 				    function(){
 				    	slideshowTimer = setInterval("slideSwitch()", options.timeout);
 				    }
 				);
				
 			}
 			

 			
    	});
    	
 	};  
})(jQuery); 

function slideSwitch() {
	
	var $active = $(".iwkSlideshow .active");
	
	if($active.length == 0)
    	$active = $(".iwkSlideshow .slideshowGroup:last");
	
	var $next = $active.next().length ? $active.next() : $('.iwkSlideshow .slideshowGroup:first');
	
	$active.addClass('lastActive');
	
	$next.css({opacity:0.0});
	$next.addClass('active');
	$next.animate({opacity:1.0}, 1000, function(){
		$active.removeClass('active lastActive');
	});
	
};

