/**
 * Timer.js
 * 
 * La classe Timer permet d'utiliser par l'intermédiaire d'un objet les 
 * événements périodiques à la place de setTimeout() ou setInterval().
 * 
 * Les événements crés sont onstart (), onloop () et onend ().
 * onstart () : Le compteur vient d'être déclanché.
 * onloop ()  : Un tour de compteur vient d'être achevé.
 * onend ()   : Tous les tours demandés du compteur ont été achevés.
 * 
 * Les propriétés éditables sont :
 * timeout : La durée en millisecondes d'un tour.
 * loops   : Le nombre de tour à effectuer.
 * 
 * Les propriétés en lecture seule sont :
 * currentLoop : Le nombre de tours effectués.
 * 
 * Les méthodes appelables sont :
 * start (timeout, loops) : Démarre le compteur. Lance l'événement onstart ().
 * loop () : Décompte un tour et lance l'événement onloop (). Cette fonction ne retarde pas le tour suivant.
 * end ()  : Termine l'ensemble des tours et déclanche l'événement onend ().
 * 
 * @author Julien PLÉE <julien.plee@aims-interactive.com>
 * @copyright AIMS-Interactive.com
 */

function Timer (timeout, loops)
{
	if (! ((typeof (timeout) == 'undefined') || (timeout == null)) )
		this.timeout = timeout;
	
	if (! ((typeof (loops) == 'undefined') || (loops == null)) )
		this.loops = loops;
}

Timer.prototype = {
	handler: null,
	handlerType: null,
	timeout: null,
	loops: 1,
	currentLoop: 0,
	running: false,
	onloop: null,
	onstart: null,
	onend: null,
	start: function (timeout, loops) {
		if (! ((typeof(timeout) == 'undefined') || (timeout == null)) )
			this.timeout = timeout;
		if (! ((typeof (loops) == 'undefined') || (loops == null)) )
			this.loops = loops;
		if ((typeof(this.timeout) == 'undefined') || (this.timeout == null))
			return false;
		if (this.running == true)
			this.end ();
		this.running = true;
		if (this.loops == 1)
		{
			this.handlerType = 'Timeout';
		}
		else
		{
			if (! (this.loops > 1))
				this.loops = 0;
			this.handlerType = 'Interval';
		}
		var obj = this;
		this.handler = window['set'+this.handlerType] (function () {
			obj.loop ();
		}, this.timeout);
		if ((typeof(this.onstart) != 'undefined') && (this.onstart != null))
			this.onstart ();
	},
	loop: function () {
		++this.currentLoop;
		if ((typeof(this.onloop) != 'undefined') && (this.onloop != null))
			this.onloop ();
		if ((this.loops > 0) && (this.currentLoop >= this.loops))
			return this.end ();
		return true;
	},
	end: function () {
		if ((typeof (this.handler) == 'undefined') || (this.handler == null))
			return false;
		if ((typeof (this.handlerType) == 'undefined') || (this.handlerType == null))
			return false;
		window['clear'+this.handlerType] (this.handler);
		this.handler = null;
		this.handlerType = null;
		this.running = false;
		if ((typeof (this.onend) != 'undefined') && (this.onend != null))
			this.onend ();
	}
};