﻿function Petals(element, element2, petalSwitch) {
    var that = this;

    var petalElement = document.getElementById(element);
    petalElement.style.top = "-200px";
    this.petalElem = petalElement;
    var fallImages = [];
    var fallTimer = null;    
    var fallImageIndex = 0;
    var fILoopDirection = 0;
    var fILoopLength = 0;
    var fISidewaysIncrement = 0;
    var FALLRATE = 10;
    var FALLCONEANGLE = Math.PI / 4;
    var FALLCONETANGENT = Math.tan(FALLCONEANGLE / 2);
    var MAXSIDEWAYSINCREMENT = 8;
    
    var engineTimer = null;
    var switchImageElement = document.getElementById(element2);
    var switchImages = [];
    var switchTimer = null;    
    var switchImageIndex = 0;
    var targetX = parseInt(switchImageElement.style.left) + Math.round((switchImageElement.width) / 2);
    var targetY = parseInt(switchImageElement.style.top);

    var state = Petals.UNINITIALIZED;  // fallingFree, fallingToTarget, fallingOnSwitch, fallingOffSwitch, restingOnSwtich, restingOnFloor

    // preload fall images
    for (var i=1; i<31; i++) {
        var imageFile = "images/Switch Petal/cp" + i + ".png";
        var image = new Image();
        image.src = imageFile;
        fallImages.push(image);
    }
        
    // preload switch images
    for (var i=1; i<11; i++) {
        var imageFile = "images/Switch Petal/SP" + i + ".jpg";
        var image = new Image();
        image.src = imageFile;
        switchImages.push(image);
    }    
    
    this.setSidewaysIncrement = function () {
        var px = parseInt(petalElement.style.left) + Math.round((petalElement.width) / 2);
        var py = parseInt(petalElement.style.top) + parseInt(petalElement.height) + FALLRATE * fILoopLength;
        var vx = px - targetX;
        var vy = py - targetY;
        var maxX = vy * FALLCONETANGENT;

        // once py is below targetY loop is shortened and x is forced to targetX 
        if (vy > 0) {
            fILoopLength = Math.min(fILoopLength, 5);
            maxX = 0;   
        }
        
        var intermediateXtarget = (Math.random() - 0.5) * maxX * 2;
        
        // increment is (target - position) divided into equal steps
        fISidewaysIncrement = Math.floor((intermediateXtarget - vx) / fILoopLength);
        if (fISidewaysIncrement > MAXSIDEWAYSINCREMENT)
            fISidewaysIncrement = MAXSIDEWAYSINCREMENT;
        else if (fISidewaysIncrement < -MAXSIDEWAYSINCREMENT)
            fISidewaysIncrement = -MAXSIDEWAYSINCREMENT;
    }
 
    this.nextFallImage = function() {
        fILoopLength--;
        if (fILoopLength <= 0) {
            fILoopLength = Math.floor(Math.random() * fallImages.length / 1.5) + 1;
            that.setSidewaysIncrement();
            
            // set loop direction to -1, 0, or + 1, with reduced odds of 0 (which means no image change)
            for (var i = 0; i < 3; i++) {
                fILoopDirection = Math.floor(Math.random() * 3) - 1;  
                if (fILoopDirection != 0)
                    break;
                // also shorten loops for stationary (direction=0) loops
                fILoopLength = Math.floor(fILoopLength / 3);
            }
        }
        fallImageIndex = (fallImageIndex + fILoopDirection) % fallImages.length;
        if (fallImageIndex < 0) 
            fallImageIndex = fallImages.length - 1;
        return fallImages[fallImageIndex].src;
    }
    
    this.nextPetal = function (petalFunction) {
        petalElement.src = petalFunction();
            petalElement.style.top = parseInt(petalElement.style.top) + FALLRATE + "px";
            petalElement.style.left = parseInt(petalElement.style.left) + fISidewaysIncrement + "px";

    }
    
    this.nextSwitchImage = function () {
        switchImageIndex++;
        if (switchImageIndex < switchImages.length) {
            switchImageElement.src = switchImages[switchImageIndex].src;
        }
        else {
            that.petalSwitchStop();
            setTimeout(projector1.startRollDown, 1800);                        
        }
    }

    this.engine = function() {
        switch (that.state) {

            case Petals.UNINITIALIZED:
                break;

            case Petals.FALLINGFREE:
                that.nextPetal(that.nextFallImage);
                break;

            case Petals.FALLINGTOTARGET:
                that.nextPetal(that.nextFallImage);
                if (parseInt(petalElement.style.top) > 450) {
                    that.state = Petals.FALLINGONSWITCH;
                    that.stopEngine();
                    petalSwitch.petalFallOn();
                }
                break;

            case Petals.FALLINGONSWITCH:
                break;

            case Petals.FALLINGOFFSWITCH:
                break;

            case Petals.RESTINGONSWITCH:
                break;

            case Petals.RESTINGONFLOOR:
                break;

            case Petals.DRAGGING:
                break;

            case Petals.READYTOFALL:
                break;

            case Petals.TARGETSEQUENCE:
                break;

            case Petals.RESTINGSEQUENCE:
                break;
        }
    }
}

Petals.prototype.petalFallStart = function() {
    // element was hidden during image preloading - make it visible now
    this.petalElem.style.display = "block";
    this.state = Petals.FALLINGTOTARGET;
    this.startEngine(150);
}

Petals.prototype.petalFallStop = function () {
    clearInterval(this.fallTimer);
    this.fallTimer = null;
}

Petals.prototype.petalSwitchStart = function () {
    this.switchTimer = setInterval(this.nextSwitchImage, 150);
}

Petals.prototype.petalSwitchStop = function () {
    clearInterval(this.switchTimer);
    this.switchTimer = null;
}

Petals.prototype.startEngine = function(interval) {
    this.engineTimer = setInterval(this.engine, interval);
}

Petals.prototype.stopEngine = function() {
    clearInterval(this.engineTimer);
}

// Enumerated constants for state identification
Petals.UNINITIALIZED = 0;
Petals.FALLINGFREE = 1;
Petals.FALLINGTOTARGET = 2;
Petals.FALLINGONSWITCH = 3;
Petals.FALLINGOFFSWITCH = 4;
Petals.RESTINGONSWITCH = 5;
Petals.RESTINGONFLOOR = 6;
Petals.DRAGGING = 7;
Petals.READYTOFALL = 8;
Petals.TARGETSEQUENCE = 9;
Petals.RESTINGSEQUENCE = 10;


function Switch(petalElement) {
    // 0 = off, 1 = on
    var that = this;
    this.petal = null;  // will be initialized when Petals object is instantiated
    this.petalElement = petalElement;
    this.state = 0;
    this.petalState = 0;
    this.handleElement = document.getElementById("switchHandle");
    var imageDir = "images/Switch Petal/";
    var handleDownSequence = ["SwitchHandleUp.png", "SwitchHandleMidway.png", "SwitchHandleDown.png"];
    var handleUpSequence = ["SwitchHandleDown.png", "SwitchHandleMidway.png", "SwitchHandleUp.png"];
    var petalFallOnSequence = ["fallOn1.png", "fallOn2.png", "fallOn3.png", "fallOn4.png", "fallOn5.png", "fallOn6.png", "fallOn7.png", "PetalUp.png", "PetalMidway.png", "PetalDown.png"];
    var petalFallOffSequence = ["fallOff1.png", "fallOff2.png", "fallOff3.png", "fallOff4.png", "fallOff5.png", "fallOff6.png", "fallOff7.png", "fallOff8.png"];
    this.turnOffAnimation = initAnimation(this.handleElement, 150, handleDownSequence, imageDir);
    this.turnOnAnimation = initAnimation(this.handleElement, 150, handleUpSequence, imageDir);
    this.petalFallOnAnimation = initAnimation(petalElement, 150, petalFallOnSequence, imageDir, ["470px", "470px", "475px", "480px", "485px", "490px", "494px", "497px"], ["465px"], false);
    this.petalFallOnAnimation.syncWith(this.turnOffAnimation, this.turnOffAnimation.start, 6);
    this.petalFallOnAnimation.runOnCompletion(function() {
        // alert();
        that.petal.state = Petals.RESTINGONSWITCH;
        that.petalElement.onclick = that.handleElement.onclick;
        that.petalElement.style.cursor = "pointer";
        pictureShow();
    });
    this.petalFallOffAnimation = initAnimation(petalElement, 150, petalFallOffSequence, imageDir, ["499px", "512px", "519px", "517px", "530px", "516px", "514px", "518px"], ["465px", "470px", "485px", "500px", "510px", "516px", "516px", "516px"], false);
    this.petalFallOffAnimation.syncWith(this.turnOnAnimation, this.turnOnAnimation.start, 0);
    this.petalFallOffAnimation.runOnCompletion(function() {
        that.petal.state = Petals.RESTINGONFLOOR;
        that.petalElement.onclick = null;
        that.petalElement.style.cursor = "";
    });
}

Switch.prototype.toggle = function () {
    if (this.petalState == 1)
        this.petalFallOff();
    else if (this.state == 1)
        this.turnOff();
    else if (this.state == 0)
        this.turnOn();
}

Switch.prototype.turnOn = function() {
    if (this.state != 1) {
        this.state = 1;
        this.turnOffAnimation.stop();
        if (this.petal.state == Petals.RESTINGONSWITCH) {
            this.petalFallOffAnimation.start();
            this.petal.state = Petals.FALLINGOFFSWITCH;
        }
        else {
            this.turnOnAnimation.start();
        }
    }
}

Switch.prototype.turnOff = function() {
    if (this.state != 0) {
        this.state = 0;
        this.turnOnAnimation.stop();
        if (this.petal.state == Petals.RESTINGONSWITCH) {
            this.petalFallOffAnimation.start();
            this.petal.state = Petals.FALLINGOFFSWITCH;
        }
        else {
            this.turnOffAnimation.start();
        }
    }
}

Switch.prototype.petalFallOn = function() {
    this.petalState = 1;
    this.state = 1;
    //    this.turnOnAnimation.start();
    this.petalFallOnAnimation.start()
}

Switch.prototype.petalFallOff = function() {
    this.petalState = 0;
    this.state = 0;
    //this.turnOffAnimation.start();
    this.petalFallOffAnimation.start();
}