// Use this library to coordinate synchronized aninmation processes
// Add an anamation to be executed
var pendingAnimations = new Array();
function addAnimation(element, styleAttrib, context, fromValue, toValue, duration){
  var newAnimation = new Object();
  newAnimation.element = element;
  newAnimation.styleAttrib = styleAttrib;
  newAnimation.context = context;
  newAnimation.value = fromValue;
  newAnimation.fromValue = fromValue;
  newAnimation.toValue = toValue;
  newAnimation.duration = duration;
  pendingAnimations.push(newAnimation);
}

function executeAnimations(){
  // Remember when the animation started 
  var startTime = new Date();

  // Define a function that will do the animation on a timer event
  var animationHandler = function(){
    // Determine the percent of the total duration time
    var nowTime = new Date();
    var elapsedTime = nowTime.getTime() - startTime.getTime();
    // Iterate through all pending animations
    for(var index = pendingAnimations.length - 1; index > -1 ; index--){
      var animation = pendingAnimations[index];
      // Determine the percent that this animation is completed
      percentDone = elapsedTime / animation.duration;
      // Set current animation value
      if(percentDone > .99){
        animation.element.style[animation.styleAttrib] = animation.context.replace('$value$', animation.toValue);
        // Remove completed animation 
        pendingAnimations.splice(index, 1);
      }else if(!isNaN(animation.toValue)){
        // Handle Easing
        percentDone = percentDone + (percentDone * (1 - percentDone))
        animation.value = animation.fromValue + ((animation.toValue - animation.fromValue) * percentDone);
        // Set the style
        animation.element.style[animation.styleAttrib] = animation.context.replace('$value$', animation.value);
      }
    }
    // Stop timer when all animations are complete
    if(pendingAnimations.length == 0){
      clearInterval(animationTimer);
    }
  }
  // Start the timer
  var animationTimer = setInterval(animationHandler, 10);
}
