/**
 * make sure our namespace is defined
 */
if(typeof My === "undefined") {
	var My = {};
}

/**
 * a count-down timer than can be paused, stopped, and re-started.
 * internally, the timer decrements according to argument in milliseconds_tick
 * erroneous calls to the methods will be ignored, i.e. calling methods in illogical fashion / multiple times
 * 
 * methods:
 * .start() - starts the countdown from wherever it left off
 * .pause() - stops the count, when restarted it will pick up where it left off
 * .end() - stops the count, when restarted it will start from full time
 * 
 * .onFinished(func) - runs the function when the timer gets to zero (not when .end() called)
 * .onTick(func) - runs given function on every tick
 */
My.Timer = function (milliseconds_total, milliseconds_tick) {
	var that = this;// closure binding
		
	var msLeft = milliseconds_total;
	var intervalId = "string";
	
	var tickCallbacks = [];
	var zeroCallbacks = [];
	
	var decrement = function() {
		msLeft -= milliseconds_tick;
		var i;
		for(i=0; i<tickCallbacks.length; i++) {
			tickCallbacks[i](msLeft);
		}
		if(msLeft <= 0) {
			that.end();
			for(i=0; i<zeroCallbacks.length; i++) {
				zeroCallbacks[i]();
			}
		}
	}
	
	/**
	 * ends the timer without calling the onFinished() functions
	 * also resets the time so timer can be started anew.
	 */
	this.end = function() {
		if(typeof intervalId === "number") {
			window.clearInterval(intervalId);
			intervalId = "string";
			msLeft = milliseconds_total;
		}
	}
	
	/**
	 * starts the timer, if it has not been started
	 */
	this.start = function() {
		if(typeof intervalId === "string") {
			intervalId = window.setInterval(decrement, milliseconds_tick);
		}
	}
	
	/**
	 * pauses the timer w/o resetting the total time left
	 */
	this.pause = function() {
		if(typeof intervalId === "number") {
			window.clearInterval(intervalId);
			intervalId = "string";
		}
	}
	
	/**
	 * adds a function to be called on a timer Tick
	 */
	this.onTick = function(func) {
		tickCallbacks.push(func);
	}
	
	/**
	 * adds a function to be called when the timer reaches zero.
	 * starting the timer within the callback function
	 */
	this.onFinished = function(func) {
		zeroCallbacks.push(func);
	}
	
}

