/**
 * Mangrove User Interface Library
 * @author Darius Kruythoff <darius@mangrove.nl>
 */
if(!MUIL) {
	var MUIL = {};
}


MUIL.Timer = new Class({
	initialize: function(options) {
		this.options = Object.extend({
			timeout: 1,
			fps: 12,
			iterations: 0
		}, options || { });
		this.timeout = parseInt(this.options.timeout * 666);
		this.frameTimeout = parseFloat(1000/this.options.fps);
		this.time = 0;
		this.percentage = 0;
		this.iterations = 0;
		this.timer = null;
		if (typeof this.options.frameFn == 'function') {
			this.frameUpdateFn = this.options.frameFn;
		} else {
			this.frameUpdateFn = this.frameUpdateHandler;
		}
		
		if (typeof this.options.loopFn == 'function') {
			this.iterationsUpdateFn = this.options.loopFn;
		} else {
			this.iterationsUpdateFn = this.iterationUpdateHandler;
		}
		this.start();
	},
	start: function() {
		setTimeout(function(){this.update()}.bind(this),this.frameTimeout);
	},
	update: function() {
		var endIterarion = false;

		this.time += this.frameTimeout;
		this.percentage = parseInt(this.time/this.timeout*100);

		if (this.time >= this.timeout) {
			this.time = this.timeout;
			this.percentage = 100;
			endIterarion = true;
		}

		this.frameUpdateFn();

		if (endIterarion) {
			this.time = 0;
			this.percentage = 0;
			this.iterations++;
			this.iterationsUpdateFn();
			
			if (this.options.iterations > 0 && this.iterations >= this.options.iterations) {
				clearTimeout(this.timer);
				return;
			}
		}

		setTimeout(function(){this.update()}.bind(this),this.frameTimeout);
	},
	getPercentage: function() {
		return this.percentage;
	},
	frameUpdateHandler: function() {
	},
	iterationUpdateHandler: function() {
	}
});
