/**
Copyright (c) 2009 Selim Arsever, http://www.onaluf.org/

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/

aForest = {
    seedsNumber:   10,
    plantDepth:    60,
    plants:        [],
    maxFall:       0.25,
    plantMaxWidth: 15,
    tenser:        0.5,
    maxFlowerNb:   200,
    flowerSize:    5,
    
    init: function(context){
        this.context = context;
        this.screenWidth      = $("canvas")[0].width;
        this.screenHeight     = $("canvas")[0].height;
        this.maxSegmentLength = this.screenHeight/this.plantDepth;
        this.shortening       = this.maxSegmentLength/this.plantDepth;
        
        // Array for plant growth history
        for(var i=0; i < this.seedsNumber; i++){
            this.plants[i] = [];
        }
        
        // Define constant style
        this.context.lineCap = 'round';
    },
    
    loop: function(){
        // Grow and Draw plants
        aForest.growTree();
        
        for(var i=0; i < aForest.seedsNumber; i++){
            if(aForest.plants[i].length > 0){
                if(aForest.plants[i][0].age < aForest.plantDepth){
                    // draw plant
                    aForest.drawSegment(aForest.plants[i], 0);
                } else {
                    //draw flower
                    aForest.drawFlowers(aForest.plants[i])
                }
            }
        }
    },
    
    growTree: function () {
        for(var i=0; i < this.seedsNumber; i++){
            // Does the seed has beging its germination ?
            if(this.plants[i].length == 0){
                // if not there is a 4% to do so:
                if(Math.random() > 0.96){
                    this.plants[i][0] = this.growSegment(Math.random()*this.screenWidth, this.screenHeight, -Math.PI/2, this.plantDepth);
                    this.plants[i][0].age = 1;
                }
            } else {
                // if so we grow it one step further
                if(this.plants[i][0].age < aForest.plantDepth){
                this.plants[i][0].age++;
                    for(var j=this.plants[i].length-1; j >= 0; j--){ 
                        //find the end of each branch:
                        if(this.plants[i][j].nexts.length == 0){
                            var newSegmentIndex = this.plants[i].length;
                            this.plants[i][newSegmentIndex] = this.growSegment(this.plants[i][j].endX, this.plants[i][j].endY, this.plants[i][j].orientation, this.plants[i][j].depth-1);
                            this.plants[i][j].nexts[0] = newSegmentIndex;
                            
                            // 10% chance of forking the branch
                            if (Math.random() > 0.95){
                                newSegmentIndex = this.plants[i].length;
                                this.plants[i][newSegmentIndex] = this.growSegment(this.plants[i][j].endX, this.plants[i][j].endY, this.plants[i][j].orientation, this.plants[i][j].depth-1);
                                this.plants[i][j].nexts[1] = newSegmentIndex;
                            }
                        }
                    }
                }
            }
        }
    },
    
    growSegment: function (startX, startY, orientation, depth) {
        var fall          = (Math.random()*2-1)*this.maxFall;
        var segmentLength = 2*Math.random()*(this.maxSegmentLength - ((this.plantDepth/depth-1)*this.shortening));
        
        
        var endX    = startX + Math.cos(orientation-fall)*segmentLength;
        var endY    = startY + Math.sin(orientation-fall)*segmentLength;
        
        return {
                    orientation: orientation-fall,
                    depth:       depth,
                    startX:      startX,
                    startY:      startY,
                    endX:        endX,
                    endY:        endY,
                    control1x:   startX + Math.cos(orientation)*segmentLength*this.tenser,
                    control1y:   startY + Math.sin(orientation)*segmentLength*this.tenser,
                    control2x:   endX + Math.cos(orientation-fall+Math.PI)*segmentLength*this.tenser,
                    control2y:   endY + Math.sin(orientation-fall+Math.PI)*segmentLength*this.tenser,
                    nexts:       []
                };
    },
    
    drawSegment: function (plant, segmentIndex) {
        var lineWidth = this.plantMaxWidth*((plant[0].age-this.plantDepth+plant[segmentIndex].depth)/this.plantDepth);
    
        this.context.strokeStyle = "black";
        this.context.lineWidth = lineWidth;
        this.context.beginPath();
        this.context.moveTo(plant[segmentIndex].startX, plant[segmentIndex].startY);
        this.context.bezierCurveTo(plant[segmentIndex].control1x, plant[segmentIndex].control1y, plant[segmentIndex].control2x, plant[segmentIndex].control2y, plant[segmentIndex].endX, plant[segmentIndex].endY);
        this.context.stroke();
        for(var i=0; i < plant[segmentIndex].nexts.length; i++){
            this.drawSegment(plant, plant[segmentIndex].nexts[i]);
        }
    },
    
    drawFlowers: function(plant) {
        if(!plant[0].flowers){
            plant[0].flowers = 1;
        }
        if(!plant[0].done){
            var grownFlower = false;
            for(var i=0; i < plant.length; i++){
                // Does a flower already exist here ?
                if(plant[i].flower){
                    plant[i].flower += 0.1;
                    if(plant[i].flower < this.flowerSize){
                        this.drawFlower(plant[i].endX, plant[i].endY, plant[i].flower);
                        grownFlower = true;
                    }
                } else {
                    // if no should we add one?
                    if(plant[0].flowers < this.maxFlowerNb){ // only a certain number of flower per tree
                        if(plant[i].depth < 1/3*this.plantDepth){ // only up from a certain point
                            if(Math.random()>0.8){
                                this.drawFlower(plant[i].endX, plant[i].endY, 1);
                                plant[i].flower = 1;
                                plant[0].flowers++;
                                grownFlower = true;
                            }
                        }
                    }
                }
            }
            // If we have many flowers and they are all grown we can stop testing
            if(plant[0].flowers == this.maxFlowerNb && !grownFlower){
                plant[0].done = true;
            }
        }
    },
    
    drawFlower: function (startX, startY, size) {
        this.context.fillStyle = "rgb(150,0,0)";
        this.context.beginPath();
        this.context.arc(startX, startY, size, 0, 2*Math.PI, false);
        this.context.fill();    
    }
};
