function getMoreHistory()
{
	var indexVal = parseInt($('#history_index').val());
	if (indexVal <= $('#total_pages').val())
	{
		$.ajax({
			type: "POST",
			url: document.location.href,
			data: {page: indexVal},
			success: addMoreHistory,
			error: failure
		});
	}
}

function failure()
{
	$('#more_history').html("<p><b>Nem sikerült kapcsolatot teremteni a szerverrel.</b><br>Várj egy kicsit, majd próbáld újra.</p>");
}

function addMoreHistory(data)
{
	if (data == '')
	{
		$('#more_history').hide();
		$('#no_results').show();
		$('#more_loading').hide();
	}
	else
	{
		if (parseInt($('#total_pages').val()) == 1)
		{
			$("#more_history").html($("#more_history").html() + data);
			$('#more_loading').hide();
		}
		else
		{
			if (parseInt($('#history_index').val()) == parseInt($('#total_pages').val()))
			{
				$('#more_history').html($('#more_history').html() + data);
				$('#more_loading').hide();
				$('#history_index').val(parseInt($('#history_index').val()) + 1);
			}
			else
			{
				$('#more_loading').show();
				$('#more_history').html($('#more_history').html() + data);
				$('#history_index').val(parseInt($('#history_index').val()) + 1);
			}
		}
	}
	isUpdating = false;
}

function updatePage()
{
	if (isUpdating == false && mouseState == "up" && getY(document.getElementById('rel')) - getScrollHeight() < preloadDistance)
	{
		isUpdating = true;
		getMoreHistory();
	}
	if (parseInt($('#history_index').val()) <= parseInt($('#total_pages').val()) && parseInt($('#total_pages').val()) != 1)
	{
		setTimeout("updatePage()", checkInterval);
		$('#more_loading').show();
	}
}

function onMouseDown(e)
{
	mouseState = "down";
}

function onMouseUp()
{
	mouseState = "up";
}

var checkInterval = 10;
var preloadDistance = 600;
var isUpdating = false;
var mouseState = "up";

$(window).load(function(){
	document.onmousedown = onMouseDown;
	document.onmouseup = onMouseUp;
	
	$('#history_index').val(2);
	
	setTimeout("updatePage()", 0);
});

function getWindowHeight()
{
	if (self.innerHeight)
	{
		fh = self.innerHeight;
	}
	else
		if (document.documentElement && document.documentElement.clientHeight)
		{
			fh = document.documentElement.clientHeight;
		}
		else if (document.body)
		{
			fh = document.body.clientHeight;
		}
	return parseInt(fh);
}

function getScrollHeight()
{
	var y;
	if (self.pageYOffset)
	{
		y = self.pageYOffset;
	}
	else if (document.documentElement && document.documentElement.scrollTop)
	{
		y = document.documentElement.scrollTop;
	}
	else if (document.body)
	{
		y = document.body.scrollTop;
	}
	return parseInt(y) + getWindowHeight();
}

function getY(e)
{
	var rv = 0;
	while (e != null)
	{
		rv += e.offsetTop;
		e = e.offsetParent;
	}
	return rv;
}