$(function() {
	jQuery.timeleft = function(seconds, truncate) {
	   	if ((seconds < 0) && !(truncate)) return "** ROUND ENDED **";
		var sec = seconds;
		var min = Math.floor(sec/60);
        sec = sec - min*60;
       	var hr = Math.floor(min/60);
       	min = min - hr*60;
       	var day = Math.floor(hr/24);
       	hr = hr - day*24;
       	if (truncate) {
       		if (day>0) return day + " d, " + hr + " hr";
       		if (hr>0) return hr + " hr, " + min +" min";
       		if (min>0) return min + " min, " + sec + " sec";
       		return sec + " sec";
     	} else {
	   		return day + " d, " + hr + " hr, " + min + " min, " + sec + " sec";
	   	}
	};
	
	jQuery.fn.baselinetime = function() {
		var nowtime = new Date();
		this.each(function() {
			if (!this.baseline) {
				var basedelta = parseInt($(this).children(".actual").text());
				this.baseline = nowtime.getTime() + 1000*basedelta;
				if (basedelta <= 0) {
				    this.direction = 1;
					this.truncate = true;
				} else {
					this.direction = -1;
					this.truncate = false;
				}
			}
		});
	};
	
	jQuery.fn.updatesecs = function() {
		this.each(function() {
			var nowtime = new Date();
			var secs = Math.round((this.direction*(nowtime.getTime() - this.baseline))/1000);
			$(this).text($.timeleft(secs, this.truncate));
		});
		return this;
		
	};

	jQuery.timespans = $(".countdown");
	
	$.timespans.baselinetime();
    setInterval('$.timespans.updatesecs()', 1000);
    
});