// JavaScript Document
(function($){
	$.fn.backgroundCycle = function( options ){
			
		// Settings list and the default values
		var defaults = {
			images : [],  			// Collection of images to cycle 
			delay : 5000,  	 		// The delay until the next image gets displayed
			initalDelay: 0,			// The inital delay for the first image until the next image gets displayed
			speed : 5000			// The speed of the image transition			
		};	
		
		// Set the default initalDelay to the delay setting if not specified
		if(!options.initalDelay && defaults.initalDelay == 0){ options.initalDelay = defaults.delay; }
		
		// Set the plugin options and defaults
		this.options = $.extend( defaults, options );
		
		// Cache the images for certain browsers
		var cache = [];
		
		// Store reference to current object
		var current = this;
		
		// Set current image index
		var currentImageIndex = 0;
		
		// Flag to indicate first run
		var isFirstRun = true;
		
		// Prepare the background image url
		for( var i = 0; i < this.options.images.length; i++ )
		{
			// Preload the image			
			var cacheImage = document.createElement('img');
			cacheImage.src = this.options.images[i];
			cache.push( cacheImage );
			
			// Add the image url string to the source
			this.options.images[i] = "url(" + this.options.images[i] + ")";	
		}					
						
		// Add the current background image into the array	
		this.options.images.unshift(current.css("background-image"));
		
		// Initalise the class
		function _initialise(){							
			if(!options.images.length){ return; }					
			_fadeOutBackground();	
		};				
						
		function _fadeInBackground(){
			// Loop the images in the array
			(currentImageIndex == current.options.images.length-1) ? currentImageIndex = 0 : currentImageIndex++;			
			current.css("background-image", current.options.images[ currentImageIndex ]);
			current.fadeTo( current.options.speed, 1, _fadeOutBackground );
		};
		
		function _fadeOutBackground(){					
			// On the first run use intial delay timming
			var delay = current.options.delay;	
			if(isFirstRun) { delay = current.options.initalDelay; isFirstRun = false; }			
			current.delay( delay ).fadeTo( current.options.speed, 0, _fadeInBackground );			
		};
		
		// Does not work in IE 6 when using transparent images
		if(($.browser.msie && $.browser.version < 7) == false)
		{
			_initialise();
		}
	};				
})(jQuery);
