/**
 * jQuery Crossfade - A jQuery image crossfading plugin
 * 
 * @version 1.0
 * @date    2008-05-11
 * 
 * Copyright (c) 2008 Trey Shugart (shugartweb.com/jquery/)
 * 
 * Dual licensed under: 
 *  MIT - (http://www.opensource.org/licenses/mit-license.php) 
 *  GPL - (http://www.gnu.org/licenses/gpl.txt)
 * 
 *	Optional: jquery.hoverIntent
 */
;(function($) {
	
	$.fn.crossfade = function(options) {
		var options = typeof options === 'object' ? options : {startDelay: options, endDelay: options};
		
		options = $.extend({
			startDelay: 1000, // amount of time it takes to fade from the first image to the second image (in milliseconds)
			endDelay: 1000, // amount of time it takes to fade from the second image back to the first image (in milliseconds)
			startCallback: blank, // function to call when the crossfading begins
			endCallback: blank, // function to call when the second image is transitioning back to the first image
			startCondition: blank, // condition to evaluate/return true if the crossfading is to start
			endCondition: blank, // condition to evaluate/return true if the crossfading is to complete
			useAttr: 'style', // the attribute to pull the second image source path from
			regex: 'background(-image)?:.*url\\((.+)\\)', // the regex used to find the value/src of the second image
			image: false
		}, options);
		
		return $(this).each(function() {
			var $$    = $(this);
			var img   = $('<img />');
			var regex = options.image ? null : new RegExp(options.regex, 'i');
			var src   = options.image || $$.attr(options.useAttr).match(regex)[2].replace(/'|"/g, '');
			
			// replace the part of the attribute that we used with nothing and apply necessary styles to the original image
			if (!options.image)
				$$.attr(options.useAttr, $$.attr(options.useAttr).replace(regex, '')).css({
					position: 'relative',
					zIndex: 10001
				});
			
			// create the crossfading image
			img.attr('src', src).css({
				position: 'absolute',
				zIndex: 10000,
				opacity: 0
			}).insertBefore($$);
			
			// if jquery.hoverIntent is available, use it
			if ($.isFunction($.fn.hoverIntent))
				$$.hoverIntent(over, out);
			// otherwise use the regular hover event
			else
				$$.hover(over, out);
			
			/**
			*	Function that is called on the hover (over) event
			*/
			function over() {
				if (options.startCondition($$)) {
					$$.fadeTo(options.startDelay, 0);
					img.fadeTo(options.startDelay, 1);
					options.startCallback($$, img);
				}
			}
			
			/**
			*	Function that is called on the hover (out) event
			*/
			function out() {
				if (options.endCondition($$)) {
					$$.fadeTo(options.endDelay, 1);
					img.fadeTo(options.startDelay, 0);
					options.endCallback($$, img);
				}
			}
		});
		
		/**
		*	A function that simply returns true so I didn't have to type: function() { return true; }, four times above.
		*/
		function blank() {
			return true;
		}
	};
	
})(jQuery);