/* Code taken from http://www.ferretarmy.com/files/canvas/canvasParticle/canvasParticle2.html */
var ctx, canvasHeight, canvasWidth;
var ParticleArray = [];

$j=jQuery.noConflict();

$j(window).load(function() {
	SetupCanvas();
	if (ctx != null) {
		AddParticle();
		AddParticle();
		AddParticle();
		setInterval(Draw, 50);
	}
});

function SetupCanvas()
{
	var thisCanvas = $j('#canvas')[0];

	if (thisCanvas && thisCanvas.getContext)
	{
		canvasHeight = $j(thisCanvas).height();
		canvasWidth =  $j(thisCanvas).width();

		ctx = thisCanvas.getContext('2d');
		ctx.globalCompositeOperation = "lighter";

		$j(thisCanvas).click(function() {
			if (ParticleArray.length < 100) 
				AddParticle();
		});
	}
}

function Draw()
{
	ctx.clearRect(0, 0, canvasWidth, canvasHeight);

	$j(ParticleArray).each(function() {
		this.Draw();
	});
}


function AddParticle()
{
	ParticleArray.push(new Particle(Math.rand(0, canvasWidth), Math.rand(0, canvasHeight)));
}

function Particle(xCoord, yCoord)
{
	var particleRadius = Math.floor(Math.rand(12,16));
	var direction = Math.rand(0, 359);
	var speed = Math.rand(2,4);
	var startColor = "rgb(" + Math.rand(0, 255) + "," + Math.rand(0, 255) + "," + Math.rand(0, 255) + ")";
	var endColor = "rgba(" + Math.rand(0, 255) + "," + Math.rand(0, 255) + "," + Math.rand(0, 255) + ",0)";

	var x = xCoord;
	var y = yCoord;

	this.Draw = function()
	{
		// Move the particle.
		x += Math.sin(direction) * speed;
		y += Math.cos(direction) * speed;

		// If the particle position is outside the canvas, move it to the opposite side.
		if (x > canvasWidth)
			x = 0;
		else if (x < 0)
			x = canvasWidth;
		if (y >= canvasHeight)
			y = 0;
		else if (y < 0)
			y = canvasHeight;

		// Draw the particle.
		DrawGradient(x, y);

		// Add extra gradients temporarily so it appears the particle
		// is wrapping around the screen.
		if (x > canvasWidth - particleRadius)
			DrawGradient(x - canvasWidth, y);
		else if (x < particleRadius)
			DrawGradient(canvasWidth + x, y);

		if (y > canvasHeight - particleRadius)
			DrawGradient(x, y - canvasHeight);
		else if (y < particleRadius)
			DrawGradient(x, y + canvasHeight);
	};

	function DrawGradient(a, b)
	{
		var p = ctx.createRadialGradient(a, b, 0, a, b, particleRadius);

		p.addColorStop(0, startColor);
		p.addColorStop(1, endColor);

		ctx.fillStyle = p;
		ctx.fillRect(a - particleRadius, b - particleRadius, particleRadius * 2, particleRadius * 2);
	}
}

Math.rand = function(l,u)
{
	return Math.floor((Math.random() * (u-l+1))+l);
}



