$(function()
{
	loadArticles = parseInt(loadArticles) || 2;
	var totalArticles = $('#total_articles').val();
	var currentArticles = $('.news-article').length;
	
	$('#view-more').click(function()
	{
		if(totalArticles - currentArticles < loadArticles)
		{
			loadArticles = totalArticles - currentArticles;
			
			if(loadArticles == 0)
			{
				loadArticles = 2;
				currentArticles = 0;
				$data = showGetResult(loadArticles, currentArticles);
				showArticles($data);
				currentArticles = loadArticles;
			}
			else
			{
				currentArticles = totalArticles-1;
				$data1 = showGetResult(loadArticles, currentArticles);
				currentArticles = 0;
				$data2 = showGetResult(loadArticles, currentArticles);
				
				$data = $data1 + $data2;
				showArticles($data);
				currentArticles = 1;
				loadArticles = 2;			
			}			
		}
		else
		{
			$data = showGetResult(loadArticles, currentArticles);
			showArticles($data);
			currentArticles += loadArticles;
		}
		
		return false;
	});
});

function showGetResult(loadArticles, currentArticles)
{
	var result = null;
	var scriptUrl = 'getArticles.php?'+loadArticles+','+currentArticles;
	$.ajax
	({
		url: scriptUrl,
		type: 'get',
		dataType: 'html',
		async: false,
		success: function(data)
		{
			result = data;
		} 
	});
	
	return result;
}

function showArticles(response)
{
	// remove existing news articles so new ones can be loaded
	articleWidth = $('.news-article').outerWidth(true);
	articleHeight = $('.news-article').outerHeight(true);
	
	$('.news-article').each(function()
	{
		$(this).fadeOut(300, function(){ $(this).remove(); });
	});
	
	// load news articles
	$('#articles').append(response);	
	
	// re-initialise typeface rendering for new articles
	_typeface_js.initialize.done = false;
	_typeface_js.initialize(); 
	
	// slide animate the news articles from right side of the screen
	$('.news-article').each(function()
	{
		$(this).hide().fadeIn(1250);
	});
}

function popUpProperties(inobj)
{
	// Used to display javascript object properties
	op = window.open();
	op.document.open('text/plain');
	for (objprop in inobj) 
	{
		op.document.write(objprop + ' => ' + inobj[objprop] + '\n');
	}
	op.document.close();
}
