/*
 * ImgRoller 0.3
 *
 * Licensed under the revised BSD License.
 * Copyright 2010 Ralf Bjarne Taraldset | www.rbt.no
 * All rights reserved.
 */

(function($){
	 $.fn.imgroller = function(options) {  
 
	  var defaults = {  
	   'images': null, // array (mandatory)
	   'behindCssClass': null,
	   'random': true, // TODO: implement me
	   'startIndex': 0, // TODO: implement me
	   'fadeInTime': 3000,
	   'fadeOut': true,
	   'fadeOutTime': 3000,
	   'waitTime': 12000,
	   'startTime': 6000
	  };
	  
	  if ($.isArray(options))
		  options = {'images': options};
	  
	  var options = $.extend(defaults, options); 
      
	  return this.each(function() {  
		  var over = $(this);
		  
		  // create a new object behind
		  var behind = over.clone(false);
		  behind.css('position', 'absolute');
		  behind.css('top', over.position.top);
		  behind.css('left', over.position.left);
		  behind.width(over.width());
		  behind.height(over.height());
		  behind.addClass(options.behindCssClass);
		  behind.hide();
		  behind.insertBefore(over);
		  		  
		  var roll = function() {
			  var newImg = over.attr('src');
			  while(newImg == over.attr('src')) {
			      newImg = options.images[Math.floor(Math.random()*options.images.length)];
			  }
			  
			  $.preload([newImg], {
				  onFinish: function() {
				  
				  	// set the image behind equal to the image over
				  	behind.attr("src",over.attr("src"));
				  	
				  	// show the image behind
				  	behind.show();
				
					// hide the image over
					over.hide();
					
					// set new image over
					over.attr("src",newImg);
					
					// fade out image behind (gives nice effect)
					if (options.fadeOut)
						behind.fadeOut(options.fadeOutTime);
					
					// fade in the image over and start over again
					over.fadeIn(options.fadeInTime, function() {setTimeout(function() { roll(); },options.waitTime); });
				}
			  });
		  };

		  // start the rolling
		  setTimeout(function() { roll(); },options.startTime);
		  
	  });
     };  
})(jQuery);