CANVAS = function(id){
	this._canvas = $(id).get();
	this._ctx = this._canvas.getContext('2d');
	
	this._canvas.width = 750;
	this._canvas.height = 550;
	
	this._sprossachsen = [{'d':180,'l':4, 'a':0}];
	
	this.treeAge = 0;
	this.interval;
}
CANVAS.prototype = {
	start:function(img){
		var thisObj = this;
		setTimeout(function(){thisObj.boden();}, 1000);
		setTimeout(function(){
			var thisObjTemp = thisObj;
			thisObj.interval = window.setInterval(function(){thisObjTemp.refresh(350,500, 0);}, 100);
		}, 2000);
	},
	boden:function(){
		var thisObj = this;
		
		this._ctx.beginPath();
		this._ctx.fillStyle = "#12ff00"; 
		this._ctx.moveTo(150, 520);
		this._ctx.lineTo(350, 495);
		this._ctx.lineTo(500, 520);
		this._ctx.lineTo(355, 500);
		this._ctx.closePath();
		this._ctx.fill();
	},
	refresh:function(x, y, d){
		this._ctx.clearRect(0,0,this._canvas.width, this._canvas.height);
		
		this.boden();
		
		this.tree(this._sprossachsen, x, y, d);
		this.treeAge++;
		if(this.treeAge>7){
			window.clearInterval(this.interval);
		}
	},
	tree:function(achse, x, y, d){
		var thisObj = this;
		var faktor = 30;
		
		var curx = x;
		var cury = y;
		var curDir = d;
		this._ctx.beginPath();
		this._ctx.fillStyle = "#000000"; 
		for(var i=0;i<achse.length;i++){
			var tempDir = curDir+achse[i].d;
			var tempAge = achse[i].a/2;
			
			var botX1 = Math.sin((tempDir+90)*Math.PI/180)*tempAge+curx;
			var botY1 = Math.cos((tempDir+90)*Math.PI/180)*tempAge+cury;
			this._ctx.moveTo(botX1,botY1);
			
			var botX2 = Math.sin((tempDir+90)*Math.PI/180)*-tempAge+curx;
			var botY2 = Math.cos((tempDir+90)*Math.PI/180)*-tempAge+cury;
			this._ctx.lineTo(botX2,botY2);
			
			var tempx = Math.sin(tempDir*Math.PI/180)*(achse[i].l*faktor)+curx;
			var tempy = Math.cos(tempDir*Math.PI/180)*(achse[i].l*faktor)+cury;
			
			this._ctx.lineTo(tempx, tempy);
			this._ctx.closePath();
			this._ctx.fill();
			
			if(typeof achse[i].c!='undefined'){
				for(var j=0;j<achse[i].c.length;j++){
					var tempCx = Math.sin(tempDir*Math.PI/180)*(achse[i].l*achse[i].c[j].p*faktor)+curx;
					var tempCy = Math.cos(tempDir*Math.PI/180)*(achse[i].l*achse[i].c[j].p*faktor)+cury;
					
					this.tree(achse[i].c[j].c, tempCx, tempCy, tempDir);
				}
			}
			curx = tempx;
			cury = tempy;
			curDir = tempDir;
			achse[i].a = Math.min(achse[i].a+1, 10);
		}
		
		this.child(achse[achse.length-1]);
		this.grow(achse);
	},
	child:function(achse){
		var tempDir = (Math.random()-0.5)*25+25;
		
		achse.c = [{'p':.7, 'c':[{'d':tempDir,'l':3, 'a':0}]}, {'p':.7, 'c':[{'d':-tempDir,'l':3, 'a':0}]}];
	},
	grow:function(achse){
		var tempDir = (Math.random()-0.5)*20;
		achse.push({'d':tempDir,'l':2, 'a':0});
	}
}

var C, body;
function init(e){
	body = document.getElementsByTagName('body')[0];
	C = new CANVAS('tree');
	C.start();
}
