var starttime = 0;
var offset = 0;
var watch;
var action = false;

function startwatch (start, stop) {
	var now = new Date();
	starttime = now.getTime();
	document.getElementById('startstop').innerHTML = '<img onClick="stopwatch(\'' + start + '\', \'' + stop + '\');" src="images/stop.gif" alt="' + stop + '" title="' + stop + '" />'
	action = true;
	updatewatch();
}

function stopwatch (start, stop) {
	var now = new Date();
	var stoptime = now.getTime();
	offset += stoptime - starttime;
	clearTimeout(watch);
	document.getElementById('startstop').innerHTML = '<img onClick="startwatch(\'' + start + '\', \'' + stop + '\');" src="images/start.gif" alt="' + start + '" title="' + start + '" />'
	action = false;
	showtime(offset);
}

function updatewatch () {
	var now = new Date();
	var nowtime = now.getTime();
	showtime(offset + nowtime - starttime);
	watch = setTimeout("updatewatch()", 1000);		
}

function showtime(moffset) {
	if (moffset / 1000 > 86399) {
		resetwatch();
	} else {
		var now = new Date(1970, 1, 1, 0, 0, moffset / 1000);
		var hh = now.getHours() <= 9 ? "0" + now.getHours() : now.getHours();
		var mm = now.getMinutes() <= 9 ? "0" + now.getMinutes() : now.getMinutes();
		var ss = now.getSeconds() <= 9 ? "0" + now.getSeconds() : now.getSeconds();
		document.getElementById('time').innerHTML = hh + ":" + mm + ":" + ss;
	}
}

function resetwatch(start, stop) {
	if (action) {
		stopwatch(start, stop);
		offset = 0;
		startwatch(start, stop);
	} else {
		offset = 0;
		showtime(offset);
	}
}
