
/*
 * Original URL: http://www.hersto.com/Followers/
 *
 * Copyright (C) 2007 by Herbert Stocker
 *
 * You are allowed use/modify/port this software in any way you like
 * if you keep this terms of use, the reference to the original
 * author Herbert Stocker and the link to the original URL intact
 * and at a prominent place (the begining of a file) in your source file.
 *
 */


var HST_Ticker= new Object();

HST_Ticker.maConsumers= new Array();

HST_Ticker.LastTick= 0;

// allows to pause the time.
HST_Ticker.mOffset= 0;
HST_Ticker.mPaused= 0;
HST_Ticker.mPausedTime= 0;

HST_Ticker.mbAutoTick= true;
HST_Ticker.mSimulatedTime= 0;

HST_Ticker.mTimer= undefined; // keeps the return value of setTimeout(.) for killing.



HST_Ticker.Add= function(Obj)
{
  this.maConsumers[this.maConsumers.length]= Obj;
}

HST_Ticker.Remove= function(Obj)
{
  for(var C= 0; C<this.maConsumers.length; C++ )
  {
    if(this.maConsumers[C] == Obj)
    {
      for(var D= C; D<this.maConsumers.length - 1; D++ )
        this.maConsumers[D]= this.maConsumers[D + 1];

      this.maConsumers.length--;

return;
    }
  }
}




HST_Ticker.Tick= function()
{
  if(this.mTimer != undefined)
  {
    clearTimeout(this.mTimer);
    this.mTimer= undefined;
  }

  if(this.mbPaused)
return;

  var Now= this.getTime();

  if(!this.LastTick)
  {
    this.LastTick= Now;

    if(this.mbAutoTick) this.mTimer= setTimeout('HST_Ticker.Tick()', 3);
return;
  }

  var DeltaT= Now - this.LastTick;
  this.LastTick= Now;


  for(var C= 0; C<this.maConsumers.length; C++ )
  {
     this.maConsumers[C].Tick(Now, DeltaT);
  }

  if(this.mbAutoTick) this.mTimer= setTimeout('HST_Ticker.Tick()', 10);
}

HST_Ticker.mTimer= setTimeout('HST_Ticker.Tick()', 10);



HST_Ticker.getTime= function()
{
  if(this.mPaused)
return this.mPausedTime;
  else
  {
    if(this.mbAutoTick)
return this.getActualTime() - this.mOffset;
    else
return this.mSimulatedTime;
  }
}


HST_Ticker.getActualTime= function()
{
  return (new Date).getTime() / 1000;
}


HST_Ticker.Pause= function()
{
  if(!this.mPaused)
    this.mPausedTime= this.getTime();

  ++this.mPaused;
}


HST_Ticker.Resume= function()
{
  if(!--this.mPaused)
    this.mOffset+= this.getTime() - this.mPausedTime; // Since we've set mPaused already to 0, it does not longer return mPausedTime.
}




HST_Ticker.setSimulateTime= function(bSimulate)
{
  if(this.mbAutoTick && bSimulate)
  {
    clearTimeout(this.mTimer);
    this.mTimer= undefined;
    this.mSimulatedTime= this.getTime();
    this.mbAutoTick= false;
  }else

  if(!this.mbAutoTick && !bSimulate)
  {
    this.mOffset= this.getActualTime() - this.getTime();
    this.mbAutoTick= true;
    this.mTimer= setTimeout('HST_Ticker.Tick()', 10);
  }
}

HST_Ticker.SimulateTick= function(Delta)
{
  this.mSimulatedTime+= Delta;

  this.Tick();
}





function HST_alert(Text)
{
  HST_Ticker.Pause();

  alert(Text);

  HST_Ticker.Resume();
}



