// $Id: timer.js,v 1.5 2009/03/25 17:28:11 preston Exp $

function PollTimer(timerEventFunction, timeInterval)
{
    this.timerEvent = timerEventFunction;
    this.timeStep = (0 == timeInterval) ? 1000 : timeInterval; // use 1000ms standard
    this.interval = null; // needed for the clearInterval
}

PollTimer.prototype.restart = function()
{
    this.interval = window.setInterval(this.timerEvent, this.timeStep);
} // restart

PollTimer.prototype.stop = function()
{
    window.clearInterval(this.interval);
} // stop


function ClockTimer(idString, timeInterval)
{
    this.timerElement = document.getElementById(idString);
    this.timeStep = (0 == timeInterval) ? 1000 : timeInterval; // use 1000ms standard
    this.seconds = 0;
    this.interval = false; // needed for the clearInterval
}

ClockTimer.prototype.convert = function(t)
{
    var tt = t.toString(10);
    return (t < 10) ? ("0"+tt) : tt;
} // convert

ClockTimer.prototype.getHours = function()
{
    return Math.floor(this.seconds / 3600);
} // getHours

ClockTimer.prototype.getMinutes = function(s)
{
    var s = this.seconds;
    return Math.floor((s - 3600 * Math.floor(s / 3600)) / 60);
} // getMinutes

ClockTimer.prototype.getSeconds = function(s)
{
    var s = this.seconds;
    s = s - 3600 * Math.floor(s / 3600);
    return Math.floor(s - 60 * Math.floor(s / 60));
} // getSeconds

ClockTimer.prototype.setText = function()
{
    var s = this.seconds;
    var h = Math.floor(s / 3600);
    s = s - h*3600;
    var m = Math.floor(s / 60);
    s = s - m*60;
    
    this.timerElement.value = this.convert(h) + ":" + this.convert(m) + ":" + this.convert(s);
    return;
} // setText

/**
 * @return the time interval in seconds
 */
ClockTimer.prototype.getText = function()
{
    var str = this.timerElement.value.split(":");
    this.seconds = 3600*parseInt(str[0]) + 60*parseInt(str[1]) + parseInt(str[2]);
    return this.seconds;
} // getText

ClockTimer.prototype.restart = function()
{
    this.getText();
    this.interval = window.setInterval(this.timerEvent, this.timeStep);
} // restart

ClockTimer.prototype.timerEvent = function()
{
    this.seconds = this.seconds - 1;
    this.setText();
    if (0 == this.seconds) // don't be busy
    {
        this.stop();
    }
} // timerEvent

ClockTimer.prototype.stop = function()
{
    window.clearInterval(this.interval);
    this.setText();
} // stop

ClockTimer.prototype.isTimedOut = function()  {  return (0 == this.seconds)  }

