$(document).delegate('a.expandstatistics', 'click', function(e) {
	e.preventDefault();
	$(this).closest('table').find('.toggle').toggle();
});

$(document).ready(function () {
	$(document).delegate('.bubbled', 'mouseenter', function (e) {
		$('#bubble').remove();
		var bubble = $('<div id="bubble"></div>');
		bubble.html($(this).find('.bubble').html());
		bubble.css('display', 'block');
		bubble.css('position', 'absolute');
		bubble.css('top', (e.pageY + 10));
		bubble.css('left', (e.pageX + 10));
		$(document.body).append(bubble);
	});
	$(document).delegate('.bubbled', 'mousemove', function (e) {
		var bubble = $('#bubble');
		if (bubble.length == 1) {
			bubble.css('top', (e.pageY + 10));
			bubble.css('left', (e.pageX + 10));
		}
	});
	$(document).delegate('.bubbled', 'mouseleave', function () {
		$('#bubble').remove();
	});
	$('.countdown').each(function () {
		var el = this;
		window.setTimeout(function () {
			countDown(el);
		});
	});
});

function zeroPad (num, length) {
	if (!length) return;
	if (!num) num = 0;
	var str = ''+num;
	while (str.length < length) {
		str = '0'+str;
	}
	return str;
}
function decreaseTime (h, m, s) {
	if (s == 0) {
		if (m == 0) {
			if (h == 0) return ['00', '00', '00'];
			return [zeroPad(h-1, 2), '59', '59'];
		}
		return [zeroPad(h, 2), zeroPad(m-1, 2), '59'];
	}
	return [zeroPad(h, 2), zeroPad(m, 2), zeroPad(s-1, 2)];
}
function countDown (el) {
	var remaining = $(el).text();
	if (!remaining) return;
	var matched = remaining.match(/(\d\d):(\d\d):(\d\d)/);
	if (!matched) return;
	var decreased = decreaseTime(parseInt(matched[1], 10), parseInt(matched[2], 10), parseInt(matched[3], 10));
	if (!decreased) return;
	$(el).text(zeroPad(decreased[0], 2)+':'+zeroPad(decreased[1], 2)+':'+zeroPad(decreased[2], 2));
	if ((decreased[0]+decreased[1]+decreased[2]) == 0) {
		$(el).trigger('countDown');
	}
	else {
		window.setTimeout(function () {
			countDown(el);
		}, 1000);
	}
}
