/*
 * Draak is not a function itself, but rather the return value of the 
 * function that is executed during Draak's definition: in this case
 * the return value is a sort of API.
 * The effect is encapsulation. Only the API functions are accessible.
 * Apart from that it avoids global functions (think of it as namespacing).
 * Also note you don't need 'this' at all.
 * 
 * If you need just 1 function (e.g. initialize), you can also assign this
 * function to Draak
 */
var Draak = ( function(){ 
	var circles,
		s = 400,//scale	
		speed,
		tr = .94,	//tranparency
		ctx,
		t0,	total // timing 
		; // parameter for change in the animation
	
	function initialize( n, v ) {
		circles = n;
		speed = v/10000;
		var el = document.getElementById('canvas');
		// A little interactivity
		// What is it like to crash a spacecraft?
		el.onmouseover = function() {
			speed *= 100;
		}
		el.onmouseout = function() {
			speed /= 100;
		}
		ctx = el.getContext('2d');
		ctx.translate(298,180);
	    ctx.scale(s,s);
		t0 = new Date().getTime();
		
		// Start it up:
		update();
	};
	var draw = function () {
	    ctx.save();
	    ctx.rotate(total * speed);
	    for (var i = 0; i < circles; i++) {
	        ctx.save();
	        ctx.scale(1 - i / circles, 1 - i / circles);
	        sign = ( i%2 == 0 ) ? 1 : -1;
	        var x = total * speed * 3 + 120;
	        ctx.translate(sign/3 * Math.sin(x/8), Math.cos(x)*Math.sin(x/16)/2);
	        ctx.fillStyle = i % 2 === 0 ? 'rgba(0,0,0,'+tr+')' : 'rgba(155,155,155,'+tr+')';
	        ctx.lineWidth = 1 / 100;
	        ctx.beginPath();
	    	ctx.arc(0, 0, 1, 0, Math.PI * 2, true);	// draw circle
	        ctx.fill();
	        ctx.restore();
	        ctx.rotate(Math.sin(x));
	    }
	    ctx.restore();
	};
	
	function update() {
		var t = new Date().getTime();
		total = t - t0;
		draw();
		requestAnimFrame ( update );
	}

	// declare an API
	return {
		go: initialize
	};	
})();

window.onload = function() {
	Draak.go ( 18, 1 );
};

window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();
