/**
 * @name Crossfade
 * @desc Image Cross Fade Transition
 * @date February 2009
 * @author Remy Sharp - jqueryfordesigners.com/image-cross-fade-transition/
 * @author Trevor Morris - www.trovster.com
 * @version 1.0 by Remy Sharp, modified by Trevor Morris
 */
if(typeof jQuery != 'undefined') {
	(function($) {		
		$.fn.extend({
			crossfade: function(options) {
				return this.each(function() {
					var s, o, $$, $wrap, $target, $loader, wrapCss;
				
					$$ = $(this).children('img');
					s = $.extend({}, $.fn.crossfade.defaults, options);
					o = $.metadata ? $.extend({}, s, $$.metadata()) : s;
					
					// if animation is turned off, set the duration to 0
					if(o.animated === false) {
						o.duration = 0;
					}
				
					// Wrapped div with the target image path
					if(typeof o.wrapCss === 'undefined') {
						wrapCss = {
							height: 	parseInt($$.height(), 10),
							width:		parseInt($$.width(), 10)
						};
					}
					else {
						wrapCss = o.wrapCss;
					}
					
					if(o.wrap === null) {
						$wrap = $(this);
					}
					else {
						$wrap = $$.wrap(o.wrap).parent();
					}
					$wrap.css(wrapCss);
					
					// Fade out the current image
					$target = $('<img/>').appendTo($wrap);
					$target.css({position: 'absolute', left: 0, top: 0, opacity: 0, height: $$.height(), width: $$.width(), marginTop: $$.css('margin-top'), marginLeft: $$.css('margin-left')});
					$loader = $('div.load', $wrap);
					if($loader.length > 0) {
						$loader.remove();
					}
					$loader = $(o.loader).appendTo($wrap).hide();
					$$.animate({opacity: 0}, {duration: o.duration / 2, complete: function(){
						$loader.show();
					}});
					$$.css({position: 'absolute', left: 0, top: 0});
					
					// Load the new image
					$(document).trigger('crossfadeStart');
					$target.one('load', function(){
						$loader.remove();
						$('div.loader').remove();
						$target.animate({opacity: 1}, {duration: o.duration / 2, complete: function(){
							$target.attr('id', $$.attr('id')).attr('alt', $$.attr('alt')).attr('height', $$.attr('height')).attr('width', $$.attr('width'));
							$target.css('position', 'relative');
							if(o.wrap === null) {
								$$.remove();
							}
							else {
								$wrap.replaceWith($target);
							}
							$(document).trigger('crossfadeEnd');
							o.callback.call(this, o);
						}});
					}).attr({src: o.target});
				});
			}
		});
		
		// Defaults…
		$.fn.crossfade.defaults = {
			duration : 1200,
			target	 : null,
			center	 : false,
			callback : function() {},
			wrap	 : '<div class="crossfade" />',
			loader	 : '<div class="loader" />',
			animated : false
		};
	})(jQuery);
}
