﻿/// <reference name="MicrosoftAjax.js"/>

// Clock (Knsb.Live.Web)
// Product:  KNSB Live Web Framework
// Assembly: Knsb.Live.Web
//
// Copyright © 2008 Emando Software. All rights reserved.
// Contact: j.h.stokking@emando.nl

Type.registerNamespace("LiveWeb");

LiveWeb.Clock = function() {
    LiveWeb.Clock.initializeBase(this);
    this._targetInterval = 100;
    this._seconds = 0;
    this._enabled = false;
    this._startTime = null;
    this._lastTime = null;
    this._clockID = null;
}

LiveWeb.Clock.prototype =
{
    get_seconds: function() { return this._seconds.toFixed(1); },    
    get_targetInterval: function() { return this._targetInterval; },
    set_targetInterval: function(value) { this._targetInterval = value; },
    
    add_update: function(handler) { this.get_events().addHandler("update", handler); },
    remove_update: function(handler) { this.get_events().removeHandler("update", handler); },
    
    onUpdate: function() {
        var handler = this.get_events().getHandler("update");
        if (handler) {
            handler(this, Sys.EventArgs.Empty);
        }
    },
    
    start: function(offset) {
        if (this._enabled) {
            this.stop();
        }
        Sys.Debug.trace("Starting clock.");
        this._enabled = true;
        this._interval = this._targetInterval;
        if (offset != null) {
            this._seconds = offset;
            this._startTime = new Date().getTime() - offset * 1000;
        }
        else {
            this._seconds = 0;
            this._startTime = new Date().getTime();
        }
        this._lastTime = new Date().getTime();
        this.onUpdate();
        this.startTimer();
    },
    startTimer: function() {
        var clock = this;
        this._clockID = setTimeout(function() { clock.handleTimeout(); }, this._interval);
    },
    handleTimeout: function() {
        var currentTime = new Date().getTime();
        var delay = currentTime - this._lastTime - this._targetInterval;
        this._lastTime = currentTime;
        this._interval = Math.max(10, this._interval - delay);
        this._seconds = (currentTime - this._startTime) / 1000;
        if (this._enabled) {
            this.onUpdate();
            this.startTimer();
        }
    },
    stop: function() {
        this._enabled = false;
        clearTimeout(this._clockID);
        Sys.Debug.trace("Clock stopped.");
    },
    reset: function() {
        this._seconds = 0;
        this.onUpdate();
    }
}

LiveWeb.Clock.registerClass("LiveWeb.Clock", Sys.Component);