$.fn.crossfade = function (opt) {
	return $(this).each(function() {
		
		function init() {
			children = 0;
			currentIndex = 0;
			container.children().each(function() {
				$(this).css({"position": "absolute", "display": !children ? "block" : "none"});
				if(options.preserveRatio) {
					ratio = $(this).outerHeight()/$(container).width();
					if(ratio > maxRatio) maxRatio = ratio;
				}
				children++;
			});

			if(options.preserveRatio) {
				setHeight();
				$(window).resize(setHeight);
			} else if(options.fillArea) {
				calculateFillSizes();
				$(window).resize(calculateFillSizes);
			}
			
			if(options.nextLink) {
				$(options.nextLink).click(showNext);
			}
			if(options.previousLink) {
				$(options.previousLink).click(showPrevious);
			}
			
			if(children && children > 1) {
				timer = setTimeout(function() {
					show(1, true);
				}, options.timeout);
			}
		}
		
		function show(index, timeout) {
			clearTimeout(timer);
			if(index < 0) index = container.children().length - 1;
			else if(container.children().length <= index) index = 0;
			currentIndex = index;
			container.children().filter(":visible").stop(true, true).fadeOut("slow");
			container.children().eq(index).stop(true, true).fadeIn("slow");
			if(timeout) {
				timer = setTimeout(function() {
					show(index+1, true);
				}, options.timeout);
			}
		}
		
		function showNext() {
			show(currentIndex+1, true);
		}
		
		function showPrevious() {
			show(currentIndex-1, true);
		}
		
		function setHeight() {
			$(container).height($(container).width()*maxRatio);
		}
		
		function calculateFillSizes() {
			containerWidth = $(container).width();
			containerHeight = $(container).height();
			containerRatio = containerWidth/containerHeight;
			$(container).children().each(function() {
				childWidth = $(this).width();
				childHeight = $(this).height();
				childRatio = childWidth/childHeight;
				if(containerRatio > childRatio) {
					$(this).width(containerWidth);
					$(this).height(containerWidth/childRatio);
				} else {
					$(this).height(containerHeight);
					$(this).width(containerHeight*childRatio);
				}
				if(!$(this).is("img")) $(this).children("img").css({"width": "100%", "height": "100%"});
			});
		}

		var options = $.extend({
	        method: "fade", //options: fade, slide_left, slide_right, slide_up, slide_down
	        timeout: "5000",
	        fillArea: false,
	        preserveRatio: false
        }, opt);
		
		var container = $(this);
		var maxRatio = 0;
		var timer;
		var currentIndex;
        
        init();
	});
};
