/************************************************************************************/
//	Timer.js
//	Fichier de fonction pour un timer en Ajax
/************************************************************************************/

/** Constante de fonctionnement
 *		SBTIMER_RAZ		1
 *		SBTIMER_LAUNCH	2
 *		SBTIMER_PAUSE	3
 *		SBTIMER_STOP	4
 */

function SBTimer() {}
SBTimer = function() {
	this.zone_affichage = null;
	this.value = 0;
	this.timeout = null;
}

SBTimer.prototype = {

	init : function(p_id_zone_affichage, p_start_value, p_is_launched) {
		if(!document.getElementById) return false;

		var zone_affichage = document.getElementById(p_id_zone_affichage);
		if(zone_affichage) {
			this.zone_affichage = zone_affichage;
			this.value = p_start_value;

			if(p_is_launched) {
				this.tic();
			}

			this.print();
		}
		return false;
	},

	tic : function() {
		var current = this;
		this.timeout = setTimeout(function() { current.increment(); }, 1000);
	},

	increment : function() {
		this.value++;
		this.tic();
		this.print();
	},

	raz : function() {
		this.value = 0;

		this.serverSend(1);
	},

	launch : function() {
		this.tic();

		this.serverSend(2);
	},

	pause : function() {
		clearTimeout(this.timeout);

		this.serverSend(3);
	},

	serverSend : function(p_message_type) {
		var current = this;
		var XHR = new XHRConnection();
			XHR.appendData('message_type', p_message_type);
			XHR.sendAndLoad(serveur_site+"ajax/timer.php", "POST", function() { current.print() });
	},

	print : function() {
		var to_print = this.formatTime();

		var textNode = document.createTextNode(to_print);
		clearContent(this.zone_affichage, 0);
		this.zone_affichage.appendChild(textNode);
	},

	report : function() {
		if(!document.getElementById) return false;

		var champ = document.getElementById('duree_appel');
		if(champ) {
			var to_export = this.formatTime();
			champ.value = to_export;
			return true;
		}
		return false;
	},

	formatTime : function() {
		var time_hours = 0;
		var time_minutes = 0;
		var time_seconds = this.value;

		// Conversion en minutes.
		if(time_seconds > 60) {
			time_minutes = parseInt(time_seconds/60);
			time_seconds = parseInt(time_seconds - (time_minutes*60));
		}
		// Conversion en heure
		if(time_minutes > 60) {
			time_hours = parseInt(time_minutes/60);
			time_minutes = parseInt(time_minutes - (time_hours*60));
		}

		// Conversion pour l'affichage.
		if(time_hours < 10) {
			time_hours = '0'+time_hours;
		}
		if(time_minutes < 10) {
			time_minutes = '0'+time_minutes;
		}
		if(time_seconds < 10) {
			time_seconds = '0'+time_seconds;
		}

		return time_hours+':'+time_minutes+':'+time_seconds;
	}
}