/*
	cdsFade(settings)

 Takes settings and fades images in wrapped set. Returns wrapped set.
Settings can have the following properties:

settings={
	srcPath: 'src/path/to/all/graphics/'
	fadingImages: ['array','of','image','names'],
	fadeInDuration: 2000,  // Time fade-in should last.
	fadeOutDuration: 1500, // Time fade-out should last.
	fadeInWait: 5000,      // Time to wait before fading out.
	fadeOutWait: 500       // Time to wait before fading in.
}

 If srcPath is omitted, each element of fadingImages must include its
own path. If fadingImages is omitted, each image is faded in and out
but the src is not changed.

 fadeInDuration and fadeOutDuration can each be a time in milliseconds,
or the jQuery times 'fast', 'normal' or 'slow'. Note that fadeInWait and
fadeOutWait must be millisecond times.

 Written by Joshua A. S. Allen of SlaphappyGeeks.com on 6/12/2009 for
CaptainDanielStone.com.

*/

(
	function($){
		// Add to jQuery functions.
		$.fn.cdsFade=function(settings){
			// Filter images and return wrapped set.
			return this.filter('img').each(
				function(){
					var fader={
						// Default settings.
						srcPath:'',
						fadingImages:[],
						fadeInDuration:2000,
						fadeOutDuration:1500,
						fadeInWait:5000,
						fadeOutWait:500
					};
					
					$.extend(fader,arguments.length?settings:{});
					// Set defaults.
					fader.imgRef=this;
					fader.fadeIndex=0;
					fader.onLoadSet=false;
					fader.srcPath=fader.fadingImages.length==0?'':fader.srcPath;
					fader.fadingImages=fader.fadingImages.length?fader.fadingImages:[this.src];

					fader.fade=function()
					{// Fade out image.
					$(fader.imgRef).fadeOut(fader.fadeOutDuration,fader.fadeOutDone);}

					fader.fadeOutDone=function()
					{// Set onload handler only once.
					if(!fader.onLoadSet){
						fader.onLoadSet=true;
						// Set onload handler for image.
						$(fader.imgRef).bind('load',
							function(){
								window.setTimeout(
									// Fade back onload after fadeOutWait time.
									function(){
										fader.fadeBack();},fader.fadeOutWait);});}
					// Set image src.
					fader.imgRef.src=(fader.srcPath.length?fader.srcPath+'/':'')+fader.fadingImages[fader.fadeIndex=(fader.fadeIndex+1)%fader.fadingImages.length];}

					fader.fadeBack=function()
					{// Fade image back.
					$(fader.imgRef).fadeIn(fader.fadeInDuration,fader.fadeBackDone);}

					fader.fadeBackDone=function()
					{// Set fading back after fadeInWait.
					window.setTimeout(fader.fade,fader.fadeInWait);}
					
					// Start fading.
					fader.fade();
			})
		}
	}
)(jQuery); // Force $ to mean jQuery in function.

