var $img;
var $ppv = 3; //pixels per verse
var $max = 31085;
var $timeoutId = 0;
var $timeoutMS = 200;

$(document).ready(function()
{
	$img = $('#image').offset();
	$img.width = $('#image img').width();
	$img.height = $('#image img').height();
	//$ppv = Math.sqrt(($img.width * $img.height) / $max);
	$('#image img').click(handleClick);
	$('#image')	.mousemove(handleHover)
				.attr('current-offset', -1)
				.mouseover(handleOver)
				.mouseout(handleOut);
	$('#verse-form').submit(handleSubmit);
});

function handleClick($e)
{
	$offset = getOffset($e);
	$.get('html/' + $offset + '.html', function($response) { $('#text').html($response); });
}

function handleHover($e)
{
	handleOut($e);
	$timeoutId++;
	var $timeId = $timeoutId;
	setTimeout(function() { handleStop($e, $timeId) }, $timeoutMS);
}

function handleStop($e, $timeId)
{
	//console.log($timeId, $timeoutId);
	if ($timeId != $timeoutId) return;
	$offset = getOffset($e);
	if ($offset > $max) return;
	$('#hover').css({
		display: 'block',
		position: 'absolute',
		left: $e.pageX + 'px',
		top: $e.pageY + 'px'
		});
	if ($offset != $('#hover').attr('current-offset'))
	{
		$('#hover').attr('current-offset', $offset);
		$.get('html/' + $offset + '.html', function($response) { $('#hover').html($response); });
	}
}

function handleOver($e)
{
	$timeoutId++;
	$('#hover').css('display', 'block');
}

function handleOut($e)
{
	$timeoutId++;
	$('#hover').css('display', 'none');
}

function handleSubmit($e)
{
	$e.preventDefault();
	$.get('tools/verse', { verse: $('#verse').val() }, function($response) { handleSubmitCallback($response) } );
}

function handleSubmitCallback($offset)
{
	if ($offset.length == 0) $offset = 'parse-error';
	$.get('html/' + $offset + '.html', function($response) { $('#text').html($response); });
}

function getOffset($e)
{
	var $x = $e.pageX - $img.left;
	var $y = $e.pageY - $img.top;
	var $offset = (Math.floor($y / $ppv) * $img.width / $ppv) + Math.floor($x / $ppv);
	return $offset;
}