var canvas;
var canvasHeight;
var canvasWidth;
var canvasLeft;
var canvasTop;
var ctx;
var stage;
//var graphics;
var world;
var iconImages;
var icons = [];
var iconN = 15;


var Icon = Class.create
({
	initialize: function(x,y)
	{
		var n = Math.floor(Math.random()*iconImages.length);
		
		this.skin = new Bitmap(iconImages[n]);
		this.width = iconImages[n].width;
		this.height = iconImages[n].height;
//		console.log( "GENERATED ICON " + this.width + ":" + this.height );
		this.skin.regX = this.width/2;
		this.skin.regY = this.height/2;
		stage.addChild(this.skin);
		
		this.createBody();
		this.setPosition( x,y );
	},
	
	createBody: function()
	{
		var overlap = 5;
		var shape;
		var r = Math.random();
		if (r > 0.5) {
			shape = new b2BoxDef();
			shape.extents = new b2Vec2(this.width / 2 - overlap, this.height / 2 - overlap);
		}
		else
		{		
			shape = new b2CircleDef();
			if( this.height>this.width ) shape.radius = this.width/2;
			else shape.radius = this.height/2;
		}
		shape.density = 1.0;
		shape.restitution = 0.05;
		shape.friction = 0.9;
		var def = new b2BodyDef();
		def.AddShape(shape);
//		def.position.Set(0,0);
		this.body = world.CreateBody(def);		
	},
	
	update: function()
	{
		this.skin.x = this.body.m_position.x;
		this.skin.y = this.body.m_position.y;
		this.skin.rotation = this.body.GetRotation()*180/Math.PI;
	},
	
	setPosition: function( x,y )
	{
		this.skin.x = x;
		this.skin.y = y;
		this.body.m_position = new b2Vec2(x,y);
	},
	
	kill: function()
	{
		stage.removeChild(this.skin);
		world.DestroyBody(this.body);
	}
});

function init()
{
	canvas = document.getElementById("canvas");
	stage = new Stage(canvas);
	stage.autoClear = true;
//	stage.autoClear = false;
	
	ctx = $('canvas').getContext('2d');
	var canvasElm = $('canvas');
	canvasWidth = parseInt(canvasElm.width);
	canvasHeight = parseInt(canvasElm.height);
	canvasTop = parseInt(canvasElm.style.top);
	canvasLeft = parseInt(canvasElm.style.left);	
	
	var worldAABB = new b2AABB();
	worldAABB.minVertex.Set(-1000, -1000);
	worldAABB.maxVertex.Set(1000, 1000);
	var gravity = new b2Vec2(0, 300);
	var doSleep = true;
	world = new b2World(worldAABB, gravity, doSleep);

	// create walls
	var wallW = 5; // half
//	createBox(world, 5, canvasHeight/2, wallW, canvasHeight/2);
	createBox(world, canvasWidth/2-70, canvasHeight, canvasWidth/2-170, wallW);
//	createBox(world, canvasWidth-wallW, canvasHeight/2, wallW, canvasHeight/2);
	
	iconImages = document.getElementsByClassName("iconImage");
	
	update();
	generate();
}

function createBox(world, x, y, width, height, fixed) {
	if (typeof(fixed) == 'undefined') fixed = true;
	var boxSd = new b2BoxDef();
	if (!fixed) boxSd.density = 1.0;
	boxSd.extents.Set(width, height);
	var boxBd = new b2BodyDef();
	boxBd.AddShape(boxSd);
	boxBd.position.Set(x,y);
	return world.CreateBody(boxBd)
}

function update(cnt)
{
	var stepping = false;
	var timeStep = 1.0/60;
	var iteration = 1;
	
	world.Step(timeStep, iteration);
//	ctx.clearRect(0, 0, canvasWidth, canvasHeight);
//	drawWorld(world, ctx);
	
	for( var i=0; i<icons.length; i++ ) {
		icons[i].update();
	}
	
	stage.update();
	setTimeout('update(' + (cnt || 0) + ')', 10);
}

function generate()
{
//	console.log( "GENERATE" );
	if( icons.length>=iconN) pop();

	var delay = Math.random()*5000;	
	var dx = Math.random() * 20;
	var icon = new Icon(395 + dx, -80);
	icons.push(icon);

	setTimeout('generate()', delay);
}

function pop()
{
	var icon = icons.shift();
	icon.kill();
}

// for debug drawing box2d world objects

function drawWorld(world, context)
{
	for (var b = world.m_bodyList; b; b = b.m_next) {
		for (var s = b.GetShapeList(); s != null; s = s.GetNext()) {
			drawShape(s, context);
		}
	}
}

function drawShape(shape, context)
{
	context.strokeStyle = '#000000';
	context.beginPath();
	switch (shape.m_type) {
	case b2Shape.e_circleShape:
		{
			var circle = shape;
			var pos = circle.m_position;
			var r = circle.m_radius;
			var segments = 16.0;
			var theta = 0.0;
			var dtheta = 2.0 * Math.PI / segments;
			// draw circle
			context.moveTo(pos.x + r, pos.y);
			for (var i = 0; i < segments; i++) {
				var d = new b2Vec2(r * Math.cos(theta), r * Math.sin(theta));
				var v = b2Math.AddVV(pos, d);
				context.lineTo(v.x, v.y);
				theta += dtheta;
			}
			context.lineTo(pos.x + r, pos.y);
	
			// draw radius
			context.moveTo(pos.x, pos.y);
			var ax = circle.m_R.col1;
			var pos2 = new b2Vec2(pos.x + r * ax.x, pos.y + r * ax.y);
			context.lineTo(pos2.x, pos2.y);
		}
		break;
	case b2Shape.e_polyShape:
		{
			var poly = shape;
			var tV = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[0]));
			context.moveTo(tV.x, tV.y);
			for (var i = 0; i < poly.m_vertexCount; i++) {
				var v = b2Math.AddVV(poly.m_position, b2Math.b2MulMV(poly.m_R, poly.m_vertices[i]));
				context.lineTo(v.x, v.y);
			}
			context.lineTo(tV.x, tV.y);
		}
		break;
	}
	context.stroke();
}

