// MUST run onload as we depend on the width/height of the images
jQuery(window).load(function() {
	var $ = jQuery;
	function makeLabel(x, y, dimension) {
		// <strong>16</strong> people at a width of <strong>290px</strong>
		var bits = ['<strong>' + y + '</strong>'];
		bits[1] = (y == 1) ? 'person' : 'people';
		bits[2] = 'at a ' + dimension + ' of';
		// Round x to the nearest 10:
		bits[3] = '<strong>' + (Math.round(x / 10) * 10) + 'px</strong>';
		return bits.join(' ');
	}

	// Create the tooltip
	var tooltip = $('p#tooltip');
	if (!tooltip.length) {
		var tooltip = $(
			'<p id="tooltip">...</p>'
		).appendTo(document.body).hide();
	}
	$('img.chart').unbind('mousemove').each(function() {
		var img = $(this);
		
		// Extract the valid data points for this image from the src
		var bits = /chd=t:(.*?)\|(.*?)&/.exec(unescape(img.attr('src')));
		// Used to use allowed_vals, now using x_to_y instead
		var allowed_vals = {};
		var x_to_y = {};
		if (bits) {
			var x_vals = bits[1].split(',');
			var y_vals = bits[2].split(',');
			for (var i = 0, j = x_vals.length; i < j; i++) {
				allowed_vals['' + x_vals[i] + ':' + y_vals[i]] = 1;
				x_to_y[x_vals[i]] = y_vals[i];
			}
		} else {
			return true; // Skip this one
		}
		
		var dimension = img.hasClass('width') ? 'width' : 'height';
		
		var klass = img.attr('class');
		var match_min_x = /x-min-(\d+)/.exec(klass);
		var match_max_x = /x-max-(\d+)/.exec(klass);
		var match_min_y = /y-min-(\d+)/.exec(klass);
		var match_max_y = /y-max-(\d+)/.exec(klass);
		if (!match_min_x || !match_max_x || !match_min_y || !match_max_y) {
			return true; // skip this one and continue
		}
		var min_x = parseInt(match_min_x[1], 10);
		var max_x = parseInt(match_max_x[1], 10);
		var min_y = parseInt(match_min_y[1], 10);
		var max_y = parseInt(match_max_y[1], 10);
		var graph_width = img.width();
		var graph_height = img.height() - 15; // 15px for lower axis label
		img.css('cursor', 'crosshair').mousemove(function(ev) {
			var offset = $(this).offset();
			var x = ev.pageX - offset.left;
			var y = graph_height - (ev.pageY - offset.top);
			var point_x = Math.ceil(
				((x / graph_width) * (max_x - min_x)) + min_x
			);
			var point_y = Math.ceil(
				((y / graph_height) * (max_y - min_y)) + min_y
			);
			/*
			// Check if value is in allowed_vals
			var val_to_check = '' + (
				Math.round(point_x / 10) * 10
			) + ':' + point_y;
			if (typeof allowed_vals[val_to_check] == 'undefined') {
				tooltip.hide();
				return;
			}
			*/
			var looked_up_y = x_to_y['' + (Math.round(point_x / 10) * 10)];
			if (typeof(looked_up_y) == 'undefined') {
				tooltip.hide();
				return;
			}
			tooltip.css({
				'top': ev.pageY + 5,
				'left': ev.pageX + 5
			}).html(makeLabel(point_x, looked_up_y, dimension)).show();
		}).mouseout(function() {
			tooltip.hide();
		});
	});
});

