/*
	jquery.imageFading.js (1.0), Copyright (C) 2010 Max Kiusso
	Author:		Max Kiusso - mc AT mkitec DOT it										
	Date:		2010 04 30																
	
	REQUIRES jQuery 1.X <http://jquery.com/>
	
	Features:	This software create an images slideshow with
				fading effects.
				
	Configuration:	$( "#div" ).imageFading( {options} )
	
					options:	showtime (milliseconds) - image showing time - default 3000 (3 seconds)
								loading (string) - text on preloading images
								fadetime (milliseconds) - fading time - default 3000 (3 seconds)

*/

( function( $ ) {
	$.fn.imageFading = function ( options ) {
		return this.each( function() {
			var $this = $( this );
			// set parameters
			var opt = $.extend( 
				{ 
					  showtime: 3000
					, loading: "Loading images..." 
					, fadetime: 3000
				}
				, options || {}
			);
			
			// hide all images
			$this.children().css({ position: "absolute" }).hide();
			
			// print loading
			$this.append(
				"<div style='clear:both; padding: 0px; margin: 0px;' id='loading'>" + opt.loading + "</div>"
			);
			
			// preload images
			var loadImgs = 0;
			$( "img" , $this ).each(
				function () {
					var img = new Image();
					var soc = $( this ).attr( 'src' );
					
					$( img ).load(
						function () {
							loadImgs++;
						}
					).attr( "src" , soc );
				}
			);
			
			var totImgs = $( "img" , $this ).length;
			var intVal = window.setInterval(
				function () {
					if ( loadImgs == totImgs ) {
						window.clearInterval( intVal );
						$( "#loading" ).remove();
						$this.children( ":eq(0)" ).fadeIn( parseInt ( opt.fadetime ) );
						if ( totImgs > 1 ) { fadeStart( $this , opt , totImgs ); }
					}
				}
				, 100
			);
			
			function fadeStart ( $this , opt , totImgs ) {
				var cnt = 0;
				var intVal = window.setInterval(
					function () {
						$( $this ).children( ":eq(" + cnt + ")" ).fadeOut( parseInt ( opt.fadetime ) );
						
						if ( ( cnt + 1 ) == totImgs ) {
							cnt = 0;
						} else {
							cnt++;
						}
						
						$( $this ).children( ":eq(" + cnt + ")" ).fadeIn( parseInt ( opt.fadetime ) );
					}
					, parseInt ( opt.showtime ) + parseInt ( opt.fadetime )
				);
			}
		});
	};
})(jQuery);
