/* Copyright: Legion Digital, LLC 2010 */
Tree=function(canvas){this.setCanvas(canvas);this.x=this.canvasWidth/2;this.y=this.canvasHeight;this.radius=10;this.speed=2;this.angle=Math.PI/2;this.angleDiversion=this.fillStyle="#000000";this.shadowColor="#000000";this.shadowBlur=2;this.generation=0;this.lifespan=0;this.totalDistance=0;this.distance=0;};Tree.prototype={setCanvas:function(canvas){this.canvas=canvas;this.context=canvas.getContext("2d");this.$canvas=jQuery(canvas);this.canvasWidth=$canvas.width();this.canvasHeight=$canvas.height();},next:function(){this.draw();this.iterate();this.randomize();this.split();this.lifespan++;this.die();},draw:function(){var context=this.context;context.save();context.fillStyle=this.fillStyle;context.shadowColor=this.shadowColor;context.shadowBlur=this.shadowBlur;context.beginPath();context.moveTo(this.x,this.y);context.arc(this.x,this.y,this.radius,0,2*Math.PI,true);context.closePath();context.fill();context.restore();},iterate:function(){var lastX=this.x;var lastY=this.y;this.x+=this.speed*Math.cos(this.angle);this.y+=this.speed*-Math.sin(this.angle);this.radius*=(0.99-this.generation/250);var deltaDistance=Math.sqrt(Math.abs(lastX-this.x)+Math.abs(lastY-this.y));this.distance+=deltaDistance;this.totalDistance+=deltaDistance;if(this.speed>this.radius*2)
this.speed=this.radius*2;},randomize:function(){this.angle+=Math.random()/5-1/5/2;},reset:function(context){var $canvas=jQuery(context.canvas);var margin=30+this.radius;var width=$canvas.width();var height=$canvas.height();if(this.x<-margin||this.x>width+margin||this.y<-margin||this.y>height+margin){this.y=height;var grey=Math.floor(Math.random()*255).toString(16);this.fillStyle="#"+grey+grey+grey;this.shadowColor=this.fillStyle;}},split:function(){var splitChance=0;if(this.generation==0)
splitChance=(this.distance-this.canvasHeight/5)/100;else if(this.generation<3)
splitChance=(this.distance-this.canvasHeight/10)/100;if(Math.random()<splitChance){var n=2+Math.round(Math.random()*2);for(var i=0;i<n;i++){var tree=new Tree(this.canvas);tree.x=this.x;tree.y=this.y;tree.angle=this.angle;tree.speed=this.speed;tree.radius=this.radius*0.9;tree.generation=this.generation+1;tree.fillStyle=this.fillStyle;tree.shadowColor=this.shadowColor;tree.shadowBlur=this.shadowBlur;tree.totalDistance=this.totalDistance;this.collection.add(tree);}
this.collection.remove(this);}},die:function(){if(this.radius<0.2){this.collection.remove(this);}}}
TreeCollection=function(){this.canvas=canvas;this.trees=[];}
TreeCollection.prototype={next:function(){n=this.trees.length;var drawn=false;for(var s in this.trees){var tree=this.trees[s];if(this.trees[s]){this.trees[s].next();drawn=true;}}
return drawn;},add:function(tree){this.trees.push(tree);tree.collection=this;},remove:function(tree){for(var s in this.trees)
if(this.trees[s]===tree)
this.trees.splice(s,1);}}
