var nowtimestamp = 0;
 
function set_timer(time){
	nowtimestamp = time;
}

function Countdown(){
	
	var endFunctionCallback = null; //la fonction ра appeler quand le timer s'arrete
	var container = "timer";
	var timeLeft = 100;
	var intervalObject = null;
	var lastTime;
	var displayReduce = false;
	
	this.setDuration = function(time) {
		timeLeft = time;
	}
	
	this.setContainer = function (cont) {
		container = cont;
	}
	
	this.setTypeAffichage = function (reduce) {
		displayReduce = reduce;
	}
	

	this.start = function(timestamp) {
		tmp = new Date();
		lastTime = tmp.getTime();
		if (timestamp != 0 && nowtimestamp != 0){
			lastTime -= Math.abs(nowtimestamp - timestamp);
			nowtimestamp = 0;
		}
		clearInterval(intervalObject);
		intervalObject = setInterval(this.callback, 1000);
	}
	
	this.stop = function() {
		clearInterval(intervalObject);
		intervalObject = null;
	}
	
	clear = function() {
		clearInterval(intervalObject);
		intervalObject = null;
	}
	
	this.callback = function() {
		tmp = new Date();
		//if (tmp.getTime() - lastTime >= 1000){
		timeLeft-= 1;
		if (timeLeft < 0){
			clear();
		}
		else {
			write(timeLeft,container,displayReduce);
		}
			//lastTime = tmp.getTime();
		//}
	}
	
	write = function(time,container,displayReduce) {
		var jour 	= (time - time % 86400)/86400;
		var heure 	= ((time - jour * 86400) - (time - jour * 86400) % 3600)/3600;
		var min 	= ((time - heure * 3600 - jour * 86400) - (time - heure * 3600 - jour * 86400) % 60)/60;
		var sec 	= time - min * 60 - heure * 3600 - jour * 86400;
		var delay   = 0;
		
		var jour_t,heure_t,minute_t,seconde_t;
		
		if (!displayReduce)
		{
			jour_t = "jour";
			heure_t = "heure";
			minute_t = "minute";
			seconde_t = "seconde";
		}
		else
		{
			jour_t = "j";
			heure_t = "h";
			minute_t = "m";
			seconde_t = "s";
		}
		
		var jour_toshow, heure_toshow,min_toshow, sec_toshow, toshow = "";
		
		jour_toshow = jour;
		heure_toshow = heure;
				
		if (sec - delay >= 0)
		{
			min_toshow = min;
			sec_toshow = sec - delay;
		}
		else if (sec - delay < 0)
		{
			if (min > 0)
				min_toshow = min - 1;
			sec_toshow = 60 - Math.abs(sec - delay);
		}
		
		if (jour_toshow > 1 && !displayReduce)
			toshow+= jour_toshow + " " + jour_t + "s ";
		else if (jour_toshow != 0)
			toshow+= jour_toshow + " " + jour_t + " ";
					
		if (heure_toshow > 1 && !displayReduce)
			toshow+= heure_toshow + " " + heure_t + "s ";
		else if (heure_toshow != 0)
			toshow+= heure_toshow + " " + heure_t + " ";
					
		if (min_toshow > 1 && !displayReduce)
			toshow+= min_toshow + " " + minute_t + "s";
		else if (min_toshow != 0)
			toshow+= min_toshow + " " + minute_t;
				
		if (min_toshow > 0 && !displayReduce)
			toshow+= " et ";
		else
			toshow+= " ";
				
		if (sec_toshow > 1 && !displayReduce)
			toshow+= sec_toshow + " " + seconde_t + "s";
		else if (sec_toshow >= 0)
			toshow+= sec_toshow + " " + seconde_t;
			
		$(container).html(toshow);
		
	}
	
}

