﻿var TimerManager = {

    Timers: [],

    MakeNew: function() {
        var a = Object._extend([], Timer);
        var length = this.Timers.length;
        a.TimerNum = length;
        this.Timers[length] = a;
        return this.Timers[length];
    },

    GetTimer: function(timerId) {
        var length = this.Timers.length;
        var i = 0;
        for (i = 0; i < this.Timers.length; i++) {
            if (this.Timers[i].Id == timerId)
                return this.Timers[i];
        }
        return null;
    },

    TimerDispose: function() {
        var length = this.Timers.length - 1;
        if (this.Timers[length].numOfAction == 0) {
            this.Timers[length] = null;
            this.Timers.length -= 1;
        }
    }
}

var Timer = {

    id: null,

    numOfAction: 0,

    times: 0,

    TimerNum: 0,

    frequency: null,

    ParamObject: null,

    EndParamObject: null,

    Count: function() {
        this.numOfAction++;
        if (this.numOfAction > this.times) {
            this.Dispose();

        }
        else
            this.Callback(this.ParamObject);

    },

    Callback: null,

    EndCallback: null,

    TimerCallback: function() {
        this.Callback;
    },

    Initialize: function(callback, frequency, times, endCallback, paramObject, useParamInEndCallback) {
        if (this.id != null) return;
        this.times = times;
        this.frequency = frequency;
        this.Callback = callback;
        this.EndCallback = endCallback;
        this.ParamObject = paramObject;
        this.EndParamObject = useParamInEndCallback == true ? paramObject : null;
        this.id = setInterval("fTimerCallBack(" + this.TimerNum + ")", this.frequency);
    },
    Dispose: function() {
        clearInterval(this.id);
        this.EndCallback(this.EndParamObject);
        this.id = null;
        this.numOfAction = 0;
        TimerManager.TimerDispose();
    }
};

function fTimerCallBack(timerPosition) {
    var timer = TimerManager.Timers[timerPosition];
    timer.Count();
}
