/**
 * @author Karsten John Gerber (karsten.john.gerber[at]googlemail.com)
 */
(function($) {

    /**
     * @constructor
     * @param {Integer} _delay the delay in seconds
     * @param {Integer} _repeatCount optional if not given or 0 the timer will be triggered again and again
	 */
	LIB3m5.JQueryTimer = function(_delay, _repeatCount) {
		this.$ = $(this);

        this.delay = _delay;
        this.repeatCount = _repeatCount;

        this.endlessly = _repeatCount === undefined || _repeatCount == 0;

        this.timerId_ = null;
    };

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// STATIC VARS
    LIB3m5.JQueryTimer.EVT_TIMER           = "EVT_TIMER";
    LIB3m5.JQueryTimer.EVT_TIMER_COMPLETE  = "EVT_TIMER_COMPLETE";
	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // PUBLIC METHODS

    LIB3m5.JQueryTimer.prototype.start = function () {
        this.startInternalTimer_();
    };

    LIB3m5.JQueryTimer.prototype.stop = function () {
        this.stopInternalTimer_();
    };

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // PRIVATE METHODS

    LIB3m5.JQueryTimer.prototype.startInternalTimer_ = function () {
        var _this = this;

        var onTimer = function () {
            _this.$.trigger(LIB3m5.JQueryTimer.EVT_TIMER);

            if(!_this.endlessly) {
                _this.repeatCount--;
                if(_this.repeatCount <=0 ) {
                    _this.stopInternalTimer_();
                    _this.$.trigger(LIB3m5.JQueryTimer.EVT_TIMER_COMPLETE);
                }
            }
        };

        this.stopInternalTimer_();
        this.timerId_ = setInterval(onTimer, this.delay);
    };

    LIB3m5.JQueryTimer.prototype.stopInternalTimer_ = function () {
        clearInterval(this.timerId_);
    };

})(jQuery);
