﻿var animinterval = 30
var timerID
var animationArray = new Object()

function animationInterval(){
    var now = (new Date()).getTime()
    var size=0
    for (anims in animationArray) {
        size++
        if (now-animationArray[anims].startTime>animationArray[anims].duration){   
            animationArray[anims].callback(animationArray[anims].to)
            animationArray[anims].interruptable=true
            animationArray[anims].completionRoutine(animationArray[anims].to)
            //this following check might look odd but it is needed. Trust me
            if (now-animationArray[anims].startTime>animationArray[anims].duration) 
                delete animationArray[anims]
        } else {
            var n = (now-animationArray[anims].startTime)/animationArray[anims].duration
            if (n>1) n=1
            animationArray[anims].callback(ease(n)*(animationArray[anims].to-animationArray[anims].from)+animationArray[anims].from)
        }
    }
    
    if (size == 0) {
        //All animations are complete, so stop the loop
        clearInterval(timerID)
        timerID=null;
    }
}

function ease(n){
    //return -Math.cos(n * Math.PI ) / 2 + 0.5      //ease in+ease out following part of cosine curve
    if (n<.5)                                       //ease in+ease out following quadratic
        return n*n*2
    else 
        return 1-((1-n)*(1-n))*2

}

function animate(id, from, to, duration, callback, completionRoutine, interruptable) {
 
    if (browser.browser=='IE' && document.readyState != 'complete') return // timer gets cancelled otherwise
    
    if (id in animationArray) {
        //object is animating
        if (animationArray[id].interruptable==false) return false
    } else {
        animationArray[id]= new Object()
    }

    animationArray[id].completionRoutine=completionRoutine
    animationArray[id].interruptable=interruptable
    animationArray[id].duration=duration
    animationArray[id].from=from
    animationArray[id].to=to
    animationArray[id].callback=callback
    animationArray[id].startTime=(new Date()).getTime()
    
    callback(ease(0)*(to-from)+from)
    
    if (!timerID) timerID = setInterval('animationInterval()',animinterval)
    return true
}





