// Javascript Timer Class

Timer = Class.create();
Timer.prototype = {

	maxTime: false,
	onTick: function() {},
	onMax: function() {},
	
	setMax: function(time) {
		this.maxTime = time;
	},		

	initialize: function() {
		this.timeout = false;
		this.tStart = false;
		this.timeElapsed = 0;
		this.addTime = 0;		
	},
	
	writeTime: function(time) {		
		var seconds  = Math.ceil(time/1000); // convert to seconds
		var minutes  = Math.floor(seconds/60);
		seconds	= seconds%60;
		minutes	= minutes > 0 ? minutes + ':' : '0:';
		if (seconds < 10) seconds = '0' + seconds;
		return 	minutes + seconds;
	},
	
  update: function() {		 
		 if(!this.tStart)	return false;
		 
		 var   tDate = new Date();
		 var   tDiff = tDate.getTime() - this.tStart.getTime();	 
		 
		 this.timeElapsed = tDiff + this.addTime;	 
		 this.onTick();
		 
		 if (this.maxTime) {
			if (this.timeElapsed >= this.maxTime) this.onMax();
		 }		 		 
		 
		 this.tick();
	},
	
	tick: function() {
		this.timeout = setTimeout(this.update.bind(this), 500);
	},
	
	start: function() {	 		
		 if (!this.tStart) this.tStart = new Date();
		 this.tick();
	},

	stop: function() {
		if (this.tStart) {
			 var   tDate = new Date();
			 var   tDiff = tDate.getTime() - this.tStart.getTime();	 		 
			 this.addTime += tDiff;
			 this.tStart = false;
		}
	  if (this.timeout) {
			clearTimeout(this.timeout);
			this.timeout  = false;
	  }
	},

	reset: function() {
		this.stop();
    this.initialize();
		this.onTick();
	}
	
}