//
//  GlobalHandler.js
//
//  Purpose: to get around the problem when 'this' can't be passed as an argument
//           because the expression will get evaluated at a later time.
//           the undesirable alternative used to be using a global variable.
//
//  Copyright 2006, Paonan Hsieh, PH Engineerin.  All rights reserved
//

//
//  Usage example:
//    assuming we have a class named 'alarm'
//    by using the Global handle, we can call the class' member function setTimer 
//    and pass its handle to another function called by the timer.
//    because no global variables are used in the string 'cmd', we make the process reentrant
//    so multiple alarms can coexist.
//

/*
<script language="JavaScript" src="GlobalH.js"></script>
<script language="JavaScript">
<!--

if ( self != top )  
  var Global = top.Global;
else if ( ! self.GlobalHandlerDefined )
  document.writeln( '<script language="JavaScript" src="GlobalH.js"></script>' );

function main()
{
  var al = new alarm();
  al.setTimer( 100, 3 );
}

function alarm()
{
  this.type   = 0;
  this.handle = Global.register();
}
alarm.prototype.setTimer = function( t, x )  // this is a class member function that sets the timer
{
  this.type = x;
  var cmd   = "Go('" +this.handle+ "')";
  var timerID   = setTimeout( cmd, t );
}
alarm.prototype.doAlarm = function()
{
}
function Go( handle )  // this is a global function called by the interval timer
{
  var o = Global.getObject( handle );
  o.doAlarm();
}

//-->
</script>
*/

GlobalHandlerDefined = 0;

Global = new GlobalHandler;

// class constructor
function GlobalHandler()
{
//
// this class will be used by multiple modules, so construct only once, 
// otherwise previous stored information will be lost
//
  if ( ! GlobalHandlerDefined )
    {
    this.list = new Array();
    GlobalHandlerDefined = 1;
    }
}
// class public methods
GlobalHandler.prototype.register = function ( obj )
{
  var i = this.list.length;
  this.list[i] = obj;
  return i;
}
GlobalHandler.prototype.getObject = function( idx )
{
  if ( idx >=0 && idx < this.list.length )
    return this.list[idx];
  else
    return null;
}
GlobalHandler.prototype.getHandle = function ( obj )
{
  for ( var i = 0; i < this.list.length; i++ )
    {
    if ( this.list[i] == obj )
      return i;
    }
 return -1;
}
