/* Javascript clock */

function JClock(cid, starttime)
{
	var start;
	
	// clock container
	this.clock = document.getElementById(cid);
	if (!this.clock.firstChild)
	{
		this.clock.appendChild(document.createTextNode(' '));
	}
	
	// setting curtime
	if (typeof(starttime) == 'undefined')
	{
		var date = new Date();
		start = date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
	}
	else
		start = starttime;
	
	// parsing
	var c = start.split(':');
	
	this.h = parseInt(c[0]);
	this.m = parseInt(c[1]);
	this.s = parseInt(c[2]);
	
	// show current time
	this.display();
	
	// start first lanch to reach minute boundary
	if (this.s != 0)
	{
		var obj = this;
		setTimeout(function(){ obj.count(); obj.display(); obj.startCount(); }, (60 - this.s) * 1000);
	}
	else
		this.startCount();
}

JClock.prototype.display = function()
{
	this.clock.firstChild.nodeValue = this.ft(this.h) + ':' + this.ft(this.m);
}

JClock.prototype.ft = function(val)
{
	var val = val.toString();
	return val.length == 1 ? '0' + val : val;
}

JClock.prototype.count = function()
{
	this.m++;
	if (this.m == 60)
	{
		this.m = 0; this.h++;
	}
	if (this.h == 24)
	{
		this.h = 0;
	}
}

JClock.prototype.startCount = function()
{
	var obj = this;
	setInterval(function(){ obj.count(); obj.display(); }, 60000);
}
