var start_time;
var start_button;
var stop_button;
var loop;

jQuery(document).ready(function(){

	jQuery(document).bind('keypress', 'Space', function(evt) {
		return false;
	});

	jQuery(document).bind('keyup', 'Space', function(evt) {
		if (start_time)
			unstart();
		else
			start();
		return false;
	});

	jQuery(document).bind('keyup', 'Esc', function(evt) {
		clear();
		return false;			
	});

});

function load() {
	start_button = document.getElementById('start_button');
	stop_button = document.getElementById('stop_button');
	clear();
}

function start() {
	start_time = new Date();

	jQuery(start_button).hide();
	jQuery(stop_button).show();

	loop = window.setInterval("update()", 1);
}

function update() {
	current_time = new Date();
	jQuery('#difference').text(format_seconds(current_time - start_time));
}

function format_seconds(seconds) {
	var diff = new Date(seconds);
	var minutes = diff.getMinutes();
	var seconds = diff.getSeconds();
	var milliseconds = diff.getMilliseconds();

	if (minutes < 10)
		minutes = "0" + minutes;
	if (seconds < 10)
		seconds = "0" + seconds;

	if (milliseconds < 10)
		milliseconds = "00" + milliseconds;
	else if (milliseconds < 100)
		milliseconds = "0" + milliseconds;

	return minutes + ":" + seconds + ":" + milliseconds;
}

function unstart() {
	clearInterval(loop);

	start_time = 0;
	current_time = 0;
	
	jQuery(start_button).show();
	jQuery(stop_button).hide();
}

function clear() {
	unstart();
	jQuery('#difference').text(format_seconds(0));
}


