// usage:
// place your bar contained in a barcontainer and optionally a clock and view for the percentage done.
// Clock and percentage done gets their innerHTML set, the bar fills up to the width of its container
// then just call
// initiateTimeBar(id of your bar, id of your clock or "", id of your percentage view or "", time left, time total
var timers = new Array();
	
function initiateTimeBar(barId, clockId, percentageId, timeleft, duration, textMax, textSuffix, callBackFinish,notitleupdate) 
{
	
	bar = document.getElementById(barId);
	bar.duration = duration;
	bar.timeLeft = timeleft;
	//updateBar(barId, clockId, percentageId);
	updateBar(barId, clockId, percentageId, textMax, textSuffix, callBackFinish,notitleupdate);

	var funcString = "timerEvent('" + barId + "','" + clockId + "','" + percentageId + "','" + textMax + "','" + textSuffix+ "','" + callBackFinish + "', 1," + notitleupdate + ")";
	timers[barId] = setInterval(funcString, 1000);
	
}
	
function timerEvent(barId,b,c,d,e,f,g,h)
{
	bar = document.getElementById(barId);
	bar.timeLeft = Math.max(0, bar.timeLeft - g);
	updateBar(barId,b,c,d,e,f,h);
}
function timerset(barId,time)
{
	bar = document.getElementById(barId);
	bar.timeLeft = time;
	//updateBar(barId,b,c,d,e,f,h);
}
function updateBar(barId, clockId, percentageId, textMax, textSuffix, callbackFinish,notitleupdate)
{
	
	var bar = document.getElementById(barId);
	var currentWidth = parseInt(bar.style.width);
	newWidth = (bar.duration - bar.timeLeft) / bar.duration * 100;
	
	//bar.style.width
	
	
	
	if(newWidth>0)
	{
		bar.style.width = newWidth + "%";
	}

	if(percentageId != null) {
		percentage = document.getElementById(percentageId);
		if(percentage != null)
			percentage.innerHTML = Math.floor(newWidth * textMax / 100) + textSuffix;
	}

	if(clockId != null) {
		clock = document.getElementById(clockId);
		if(clock != null) {
			hours = Math.floor(bar.timeLeft / 3600);
			minutes = Math.floor((bar.timeLeft % 3600) / 60);
			seconds = bar.timeLeft % 60;
			clock.innerHTML = hours + 'h:' + minutes + "m:" + seconds + "s";
			
			var t = document.title.split("-").length;		
			if(!notitleupdate)
			{
				document.title = (hours > 0 ? (hours + 'h:') : "") + minutes + "m:" + seconds + "s" + " - " + document.title.split("-")[t - 1].replace(/^\s+/, '');
			}
		}
	}

	if(bar.timeLeft == 0) {	
		clearInterval(timers[bar.id]);
		if(typeof window[callbackFinish] == 'function') {
			window[callbackFinish]();
		}
	}

}

