﻿// JScript File
// Author : Ashish Jain

Array.prototype.addUnique = function(obj){
   for(var i =0; i<this.length; i++)
   {
      if(this[i].id == obj.id)
         return false;
   }
   this.push(obj);
   return true;
}

Array.prototype.getObj = function(id){
   for(var i =0; i<this.length; i++)
   {
      if(this[i].id == id)
         return this[i];
   }
   return null;
}

var Common =
{
   GetTimeStamp : function()
   {
      var date = new Date();
      return parseInt(date.getFullYear() + "" + date.getMonth() + "" + date.getDate()
               + "" + date.getHours() + "" + date.getMinutes() + "" + date.getSeconds() + "" + date.getMilliseconds());
   },
   
   AnimatorCollection : new Array()
}

function Animator(run, delay)
{
   try
   {
      this.id = Common.GetTimeStamp();
      if(typeof(run) != "function")
         throw "Invalid argument! fname. Expected type function."
      if(typeof(delay) != "number")
         throw "Invalid argument! delay. Expected type Integer."

      this.run = run;
      this.delay = parseInt(delay);
      this.timer = null;
      this.currTime = null;

      if(!Common.AnimatorCollection.addUnique(this))
         throw "Duplicate Object! object already present in the collection."

      this.isRunnable = true;
   }catch(e)
   {
      alert(e);
   }
}

Animator.prototype.start = function() {
   try
   {
      if(this.isRunnable)
      {
         this.time = (new Date()).getTime();
         this.timer = window.setInterval("Common.AnimatorCollection.getObj('" + this.id + "').run.call()", this.delay);
         this.isRunnable = false;
      }
      else
         throw "Invalid state! Animator is not in runnable state."
   }catch(e)
   {
      this.stop();
      alert(e);
   }
}

Animator.prototype.stop = function() {
   window.clearInterval(this.timer);
}

Animator.prototype.getTimeEllapsed = function() {
   return (new Date()).getTime() - this.time;
}
