/*
	HTML5 Canvas bubbles by Jon Thornton (http://www.jonthornton.com)
*/

function Bubbles(opts)
{
	if (!opts.interval) opts.interval = 100;
	if (!opts.speed) opts.speed = 100;
	if (!opts.baseSize) opts.baseSize = 10;
	if (!opts.colors) opts.colors = ['black', 'white'];
	if (!opts.maxCircles) opts.maxCircles = 30;

	var wrapper = document.createElement('div');
	$(wrapper).css({ position: 'relative', zIndex: 2 });
	
	var canvas = document.createElement('canvas');
	$(canvas).css({ position: 'absolute', top:0, left:0, zIndex:1})
		.attr('height', $(document).height())
		.attr('width', $(document).width())
		.attr('id', 'bubblesBg');

	$('body').wrapInner(wrapper).append(canvas);
	
	var CAKECanvas = new Canvas(canvas);
	
	var mouse = {};
	var gInterval;
	$(window).bind('focus', function() {
		$('body').bind('mousemove', function(e) {
			mouse.x = e.pageX;
			mouse.y = e.pageY;
		});
		
		CAKECanvas.play();
		
		var lastX, lastY;
		gInterval = setInterval(function() {
			if (lastX && lastY) {
				var size = Math.sqrt(Math.pow(lastX - mouse.x, 2) + Math.pow(lastY - mouse.y, 2))/opts.interval;
				if (size > 0) {
					drawCircle(opts.baseSize*size, mouse.x, mouse.y);
				}
			}
		
			lastX = mouse.x;
			lastY = mouse.y;
		}, opts.interval);
	});
	
	$(window).bind('blur', function() {
		$('body').unbind('mousemove');
		clearTimeout(gInterval);
		CAKECanvas.stop();
	})
	$(window).focus();
	
	var colorIndex = 0;
	$('body').bind('click', function(e) {
		colorIndex = (colorIndex+1) % opts.colors.length;
	});
	
	var circles = [];
	var circleCount = 0;
	function drawCircle(size, x, y) {
		
		var start=0;
		var index = circleCount%opts.maxCircles;
		
		if (circles[index]) {
			circles[index].removeSelf();
		}
		
		circles[index] = new Circle(size, {
			x: x,  
			y: y, 
			fill: opts.colors[colorIndex],
			endAngle: Math.PI*2
		});
		circles[index].addFrameListener( function(t, dt) {
			if (!start) {
				start = t;
			}
			
			t2 = t-start;
			
			if (t2 > opts.speed) {
				this.removeFrameListener();
			}
			this.scale = .01+(t2 / opts.speed);
		});
		CAKECanvas.append(circles[index]);
		circleCount++;
	}
}	
