/**
 * Timer class
 *
 * $Id: timer.js 28 2006-08-08 14:04:53Z hawk $
 */

var Timer = Class.create();
Timer.prototype = {
  current: 0,
  timer  : null,

  initialize : function( callback, interval, repeat ) {
    if ( repeat   < 1 ) { throw new Error; }
    if ( interval < 1 ) { throw new Error; }
    this.callback = callback;
    this.interval = interval;
    this.repeat   = repeat;
  },

  start : function() {
    this.current = 0;
    if ( this.repeat == 1 ) {
      this.timer = setTimeout( this.handler.bind(this), this.interval );
    } else {
      this.timer = setInterval( this.handler.bind(this), this.interval );
    }
  },

  stop : function() {
    if ( this.repeat == 1 ) {
      clearTimeout( this.timer );
    } else {
      clearInterval( this.timer );
    }
  },

  restart : function() {
    this.stop();
    this.start();
  },

  handler : function() {
    this.callback( this.current );
    this.current++;
    if ( this.repeat <= this.current ) { this.stop(); }
  }
}