﻿/// <reference name="MicrosoftAjax.js"/>

Type.registerNamespace("NextDigital.CityOfBallarat.Web.scripts");

NextDigital.CityOfBallarat.Web.scripts.Timer = function(interval) {
    NextDigital.CityOfBallarat.Web.scripts.Timer.initializeBase(this);
    this._interval = interval;
    this._enabled = false;
    this._internalClock = null;
}

NextDigital.CityOfBallarat.Web.scripts.Timer.prototype = {
    get_interval: function() {
        return this._interval;
    },
    set_interval: function(value) {
        if (this._interval !== value) {
            this._interval = value;
            this.raisePropertyChanged('interval');

            if (!this.get_isUpdating() && (this._internalClock !== null)) {
                this._stop();
                this._start();
            }
        }
    },
    get_enabled: function() {
        return this._enabled;
    },
    set_enabled: function(value) {
        if (value !== this.get_enabled()) {
            this._enabled = value;
            this.raisePropertyChanged('enabled');
            if (!this.get_isUpdating()) {
                if (value) {
                    this._start();
                }
                else {
                    this._stop();
                }
            }
        }
    },
    add_tick: function(handler) {
        this.get_events().addHandler("tick", handler);
    },
    remove_tick: function(handler) {
        this.get_events().removeHandler("tick", handler);
    },

    dispose: function() {
        this.set_enabled(false);
        this._stop();

        NextDigital.CityOfBallarat.Web.scripts.Timer.callBaseMethod(this, 'dispose');
    },
    reset: function() {
        NextDigital.CityOfBallarat.Web.scripts.Timer.callBaseMethod(this, 'updated');

        if (this._enabled) {
            this._stop();
            this._start();
        }
    },
    _internalClockCallback: function() {
        var handler = this.get_events().getHandler("tick");
        if (handler) {
            handler(this, Sys.EventArgs.Empty);
        }
    },
    _start: function() {
        this._internalClock = window.setInterval(Function.createDelegate(this, this._internalClockCallback), this._interval);
    },
    _stop: function() {
        window.clearInterval(this._internalClock);
        this._internalClock = null;
    }
}
NextDigital.CityOfBallarat.Web.scripts.Timer.registerClass('NextDigital.CityOfBallarat.Web.scripts.Timer', Sys.Component);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
