(function($) {
    $.fn.random_carousel = function(url, delay) {
		var container = $(this);
		var i = 0;
		$('<div id="'+ container.attr('id') + '_1' +'" style="position: relative;"></div><div id="'+ container.attr('id') + '_2' +'" style="position: relative;"></div>').appendTo(container);
		var containers = new Array($('#' + container.attr('id') + '_1'), $('#' + container.attr('id') + '_2'));
		var stack = {
		    delay: 7000,
		    actions:[],
		    prev: false,
		    cur: false,
		    run: function() {
		        if (stack.actions.length) {
		        	stack.cur = stack.actions.shift();
		        	container.height(stack.cur.outerHeight(true));
		        	if (stack.prev)
		        		stack.prev.fadeOut(1000);
		            stack.cur.fadeIn(2000);
		        	stack.prev = stack.cur;
		            setTimeout(stack.run, stack.delay + delay);
		            delay = 0;
		        }
		        else {
		        	i = (i + 1)  % 2;
			        containers[i].load(url, '', switchDivs);
		        }
		    }
		};
		
		function switchDivs() {  
			containers[i].children().hide().css('position', 'absolute');	
			containers[i].children().each(function(){
			    stack.actions.push($(this));
			});
			
			stack.run();
		};
		
		
		$(document).ready(function() {
			if (delay == undefined) {
				delay = 0;
			}
			containers[i].load(url, '', switchDivs);
		});
    };
})(jQuery);
