
// Copyright (C) 2002  SJS Solutions Ltd

// IE4's setTimeout and setInterval only accept strings rather than
// anonymous functions. Strings are OK for the simplest of expressions, but
// if the code that needs to be executed starts to span multiple lines,
// passing in an anonymous function is much more convenient, because 
// it's much easier to read, and syntax highlighting still works.
//
// More importantly though it allows us to use closures, yay!

var _timerCounter = 0;

function _makeTimerObject(func)
{
    var t = new Object;

    t.func = func;
    t.valueOf = function () { return this.timerID; };

    return t;
}

function _liftTimerObjectToToplevel(timer)
{
    var name = "_timer" + _timerCounter++;
    eval(name + " = timer;"); 

    timer.toplevelName = name;

    return name;
}

function mySetTimeout(func, msecs)
{
    var t = _makeTimerObject(func);
    var tname = _liftTimerObjectToToplevel(t);
    
    // the not null if is there because apparently (emperical evidence
    // while testing mySetInterval using MSIE5.5) the timer can go off
    // even after being cleared. Though, this probably is really only
    // possible with (my)SetInterval for safety I put it here too
    t.timerID = setTimeout('if (typeof(' + tname + ') != "undefined") { ' + tname + ".func(); delete " + tname + " }", msecs);

    return t;
}

function mySetInterval(func, msecs)
{
    var t = _makeTimerObject(func);
    var tname = _liftTimerObjectToToplevel(t);

    // see mySetTimeout for a rationale for the if
    t.timerID = setInterval('if (typeof(' + tname + ') != "undefined") { ' + tname + '.func(); }', msecs);

    return t;
}

function myClearTimeout(timer)
{
    if (typeof(timer) == "object") {
        clearTimeout(timer.timerID);
        eval("delete " + timer.toplevelName);
    }
}
