/*
    Timer: class for wrapping JavaScript timers
    Author: Theo M. Gerrits (tmg)
    
    Dependencies: Logger.js
    
    JavaScript1.3

    Copyright (C) 2005 Ontwerpfontein
*/


// Constructor
// Saves the Timer in the top Window object
function Timer(id)
{
    this.id = id;
    this.action = null;
    this.timeout = 0;
    this.timeoutId = null;
    this.paramBlock = null;
    this.obj = null;

    // save object in top window
    top[id] = this;
}


// Description     : initialise and start the Timer object.
// Parameters      : nSeconds: number of seconds to wait
//                   fnc: function to execute after timeout. If o is defined, then fnc will by applied to o (it will be executed as a method of o).
//                   p: (optional) parameter block: an object containing data that fnc needs or may alter
//                   o: (optional) object of which fnc is a method
// Returns         : void
Timer.prototype.start = function (nSeconds, fnc, p, o)
{
    with (this)
    {
        // only start new timer if none exists
        if (!timeoutId)
        {
            // init properties
            action = fnc;
            timeout = 1000*nSeconds;
            obj = o ? o : null;
            paramBlock = p ? p : null;
            
            // This starts a global timer in the top window with name id
            timeoutId = top.setTimeout("top." + id + ".doAction()", timeout);
            LOG.debug("Timer created with timeoutId: " + timeoutId);
        }
    }
}

// Description     : execute the Timer action function.
// Parameters      : none
// Returns         : the result of the executed function or void if it does not exist
Timer.prototype.doAction = function ()
{
    with (this)
    {
        // timeout received, so reset Id
        timeoutId = null;
    
        if (action)
        {
            if (obj)
            {
                // object method
                if (paramBlock)
                    return action.call(obj, paramBlock);
                else
                {
                    // LOG.note("Before executing call()..." + action.call + "; apply(): " + action.apply);
                    // MAC### IE5.2 Function.call() not supported
                    return action.call(obj);
                }
            }
            else
            {
                // normal function
                if (paramBlock)
                    return action(paramBlock);
                else
                    return action();
            }
        }
        else
            return;
    }
}

// Description     : stop the Timer prematurely.
// Parameters      : none
// Returns         : void
Timer.prototype.stop = function ()
{
    with (this)
    {
        LOG.debug("Timer Stop", id + ".timeoutId");
        if (timeoutId)
        {
            top.clearTimeout(timeoutId);
            timeoutId = null;
        }
    }
}
