/**
 * @class
 * @description	Creates a new slideshow
 * @author		Roberto Ortelli rortelli@gmail.com, nwolff@gmail.com
 * @return		{jQuery} chainable jQuery class
 * @param		o	Options of the slideshow
 * @param		o.elClass	The name of the container where the images are displayed
 * @param		o.path		The path to reach the folder on the server containing the images
 * @param		o.num		The number of images that can be displayed
 * @param		o.min_digit_count The number of digits that should be used to generate the filenames. 
 *              If for instance min_digit_count is 2, then the filenames will be 01.jpg, 02.jpg, etc.
 * @memberOf 	jQuery.fn
 * 
 * Notes: An elegant way to specify the path, digit_count, and image extension would be a single variable with tokens
 * inside. eg: image_spec = "http://mysite/images/image_##.jpg"
 */
jQuery.fn.slideShow = function(o){
	
	var defaults = {
		id: null,
		elClass: null,
		path: null,
		num: null,
		min_digit_count: 0
	};
	
	var settings = $.extend(defaults, o),
		el = (settings.id != null) ? $("#" + settings.id) : $("." + settings.elClass),
		i = 1;
	
	
	var elSizes = {
		width: el.width(),
		height: el.height()
	};
	
	$.image = function(src, f){ 
		var i = new Image(); 
		i.src = src; 
		i.onload = f;
	}
	
	setInterval(function() {
		
		i = (i < settings.num) ? i + 1 : 1;
		
		var digits = "" + i;
		while(digits.length < settings.min_digit_count) {
			digits = '0' + digits;
		}

		var image_name = settings.path + digits + ".jpg";
		
		$.image(image_name, function() {
			
			el.append("<div id='empty-element'></div>").ready(function() {

				$("#empty-element").css({

					"width": elSizes.width,
					"height": elSizes.height,
					"background-color": "#000",
					"opacity": "0",
				    "position": "absolute",
				    "top": 0,
					"z-index": 100

				}).show().animate({
					
					opacity: 1
					
				}, 1000, function() {

					el.css({
						backgroundImage: "url(" + image_name + ")"
					});
					
					$("#empty-element").animate({
						opacity: 0
					}, 1000, function() {
						$(this).remove();
					});
					
				});
			});
			
		})
		
		
		
		

		
	}, 10000);
}

/**
 * @author	rortelli
 * @class	Preload of a set of images
 * @param	{Array|String} arguments contains a list of images
 * @return {jQuery} chainable jQuery class
 * @memberOf jQuery
 */
jQuery.preloadImages = function() {
	for (var i = 0; i<arguments.length; i++) {
    	jQuery("<img>").attr("src", arguments[i]);
	}
}

/**
 * @description	Simplify the console.log command
 * @author	rortelli
 * @param	arguments contains a list of images
 * @function
 */
function log() {
  try {
    console.log.apply( console, arguments );
  } catch(e) {}
}
