/* classe per il countdown al prossimo GP */
var dataConstants = {
	DAYMIL: 86400000, // 1 giorno in millisecondi
	HOURMIL: 3600000, // 1 ora in millisecondi
	MINMIL: 60000, // 1 minuto in millisecondi
	SECMIL: 1000 // 1 secondo in millisecondi
};

var countdownObj = {
	days: 0,
	hours: 0,
	minutes: 0,
	seconds: 0
};

var countdown = Class.create();

countdown.prototype = {
	initialize:function (dateToCount){
		
	//(2010,11,31,23,59,59)
	// La data che ricevo e' quella della spagna. Devo adattarla alla timezone locale.
		
		this.dateToCount = dateToCount;
		var locale = new Date();
		var DT = 2 * locale.getTimezoneOffset() - (new Date(2008, 0)).getTimezoneOffset() - (new Date(2008, 6)).getTimezoneOffset();
		//console.log('DT: ' + DT);
		
		if (DT == -60 || DT == -1) {
			this.GMTdiff = ((locale.getTimezoneOffset() / 60) * - 1) - 2 ; // differenza di timezone tra le due country durante DST ( Daylight saving time /ora legale)
		}
		else {
			this.GMTdiff = ((locale.getTimezoneOffset() / 60) * - 1) - 1 ; // differenza di timezone tra le due country
		}
		
		//console.log(this.GMTdiff + " " + (-1)*(locale.getTimezoneOffset()/60) -2 );
		new PeriodicalExecuter(function(pe) {
			// calcolo la differenza tra le due date in millisecondi, poi calcolo il numero di giorni, ore e minuti 
			var now = new Date();
			var diff = this.dateToCount - now; 
			
			if (diff <=  1000) {
				pe.stop();
				//$('countnumbers').hide();
			}
			countdownObj.days = parseInt(diff / dataConstants.DAYMIL);
			var daymil = countdownObj.days * dataConstants.DAYMIL;
			countdownObj.hours = parseInt((diff - daymil) / dataConstants.HOURMIL) + this.GMTdiff;
			var hourmil = countdownObj.hours * dataConstants.HOURMIL;
			countdownObj.minutes = parseInt((diff - (daymil + hourmil)) / dataConstants.MINMIL);
			var minmil = countdownObj.minutes * dataConstants.MINMIL;
			countdownObj.seconds = parseInt((diff - (daymil + hourmil + minmil)) / dataConstants.SECMIL);

			if (diff <=  1000) {
				countdownObj.days = 0;
				countdownObj.hours = 0;
				countdownObj.minutes = 0;
				countdownObj.seconds = 0;
			}
			var spans = $$('.countdown span.number');
			if (countdownObj.days<100 && countdownObj.days>9)
    			spans[0].update("0"+countdownObj.days);
			else if (countdownObj.days<10)
				spans[0].update("00"+countdownObj.days);
			else
				spans[0].update(countdownObj.days);
			if (countdownObj.hours<10)
				spans[1].update("0"+countdownObj.hours);
			else
				spans[1].update(countdownObj.hours);
			if (countdownObj.minutes<10)
				spans[2].update("0"+countdownObj.minutes);
			else
				spans[2].update(countdownObj.minutes);
			if (countdownObj.seconds<10)
				spans[3].update("0"+countdownObj.seconds);
			else
				spans[3].update(countdownObj.seconds);
		}.bind(this), 1);
		
		
		
	}
	
	
}
