/**
 * Jquery Plugin - Copyright 2008
 * Multicolor banner animation
 * by Diego Peroni
 * method:
 *  - .rainbow(opts)
 * opts:
 *  - colors: ['red', 'yellow', 'blue', 'green'], define number of partitions and colors (array)
 *  - easing: ['bounceout'], 'linear', 'backout', etc.
 *  - background: [ramdom] if not specified it's a random color
 *  - min: [3000] minimum animation duration
 *  - max: [6000] maximum animation duration
 */
$.fn.rainbow = function(opts) {
	
	/* default opts */
	opts.colors = ('colors' in opts) ? opts.colors : ['red', 'yellow', 'blue', 'green'];
	opts.easing = ('min' in opts) ? opts.easing : "bounceout";
	opts.min = ('min' in opts) ? opts.min : 3000;
	opts.max = ('max' in opts) ? opts.max : 6000;
	opts.background = ('background' in opts) ? opts.background : opts.colors[parseInt(Math.random()*opts.colors.length)];
	
	return this.each(function() {

		/* banner */
		$(this)
			.empty()
			.css('overflow', 'hidden')
			.css('cursor', 'pointer')
			.css('background', opts.background);

		var w = $(this).width()/opts.colors.length;
		var h = $(this).height();
		
		/* internal divs */
		for (var i=0; i<opts.colors.length; i++) {
			var c = parseInt(Math.random()*opts.colors.length);
			$(this).append($('<div></div>').css('position', 'absolute')
				.css('height', h+'px').css('top', '0px').css('left', (w*i)+'px')
				.css('width', w+'px').css('z-index', w-i).css('background', opts.colors[c]));
		}
		
		$(this).one( 'click', function(){$(this).rainbow(opts);} );
	
		$(this).find('div').each(function() {
			var c1 = parseInt(Math.random()*opts.colors.length);
			var c2 = parseInt(Math.random()*opts.colors.length);
			var w0 = $(this).width();
			var w1 = parseInt(Math.random()*opts.colors.length*20+opts.colors.length*5);
			var w2 = parseInt(Math.random()*opts.colors.length*20+opts.colors.length*5);
			if (w0>opts.colors.length*10 && (w2-w1)>0) w2=w2*2;
			
			/* bugfix per ie6 e 7 */
			if ($.browser.msie && w0+w1-w2<=((w0+w1)/100*10)) {w2=parseInt((w0+w1)/100*10);}
			
			var delta = parseInt((opts.max - opts.min)/2);
			var t1 = parseInt(Math.random()*delta+parseInt(opts.min/2));
			var t2 = parseInt(Math.random()*delta+parseInt(opts.min/2));

			$(this)
				.animate({
					width: "+="+w1+"px"
				}, t1, opts.easing)
				.animate({
					width: "-="+w2+"px",
					backgroundColor: opts.colors[c1]
				}, t2, opts.easing)
				.animate({
					backgroundColor: opts.colors[c2]
				}, parseInt(opts.min/3), opts.easing);
			
		});
		
	});
};