
var TimeTicker = new function () {
	var _tickers;
	var _handle;
	var _callback;

	var _help = {
		addZeros: function (str) {
			str = "00" + str;
			return str.substring(str.length - 2, str.length);
		},

		toInt: function (str) {
			return parseInt((str.indexOf("0") == 0) ? str.substring(1, 2) : str);
		}
	}

	var _start = function () {
		_log("starting timers");
		var tickerId = 0;
		var t, m, s, now = new Date().getTime();

		jQuery.each(_tickers, function () {
			t = $(this).html();
			var timeArr = t.split(":");
			m = _help.toInt(timeArr[0]);
			s = _help.toInt(timeArr[1]);

			this.id = ++tickerId;
			this.time = now + m * 60000 + s * 1000;
			this.completed = false;
		});

		_handle = setInterval(_tick, 1000);
	}

	var _purgeTimers = function () {
		var active = [];
		jQuery.each(_tickers, function () {
			if (!this.completed) {
				active.push(this);
			}
		});

		if (active.length <= 0) {
			_stop();
		}

		_tickers = active;
	}

	var _stop = function () {
		_log("stopping");
		clearInterval(_handle);
		_tickers = [];
	}

	var _log = function (message) {
		var loggingEnabled = false;

		if (loggingEnabled) {
			console.log(message);
		}
	}

	var _tick = function () {
		_log("_tick (active timers = " + _tickers.length + ")");

		jQuery.each(_tickers, function () {
			if (!this.completed) {
				var left = this.time - new Date().getTime();
				if (left > 0) {
					$(this).html(_help.addZeros(Math.floor(left / 60000)) + ":" + _help.addZeros(Math.floor((left - Math.floor(left / 60000) * 60000) / 1000)));
					if (left < 60000) {
						$(this).css("color", "#921f10");
					}
				}
				else {
					this.completed = true;
					if (_callback) {
						_log("callback function executing (source: ticker id = " + this.id + ")");
						_stop();
						_callback();
					}
					return;
				}
			}
		});
		_purgeTimers();
	}


	this.init = function (className, callback) {
		_stop();
		_tickers = $("." + className);
		_log("init: ticker count = " + _tickers.length);
		_callback = callback;
		_start();
	}
}

