Dashboard = function() {}

Dashboard.init = function(divId, dataUrl)
{
	this.divId = divId;
	this.dataUrl = dataUrl;
	this.currentPage = 1;
	this.refetchTries = 0;
	
	// The div
	this.div = jQuery("#"+this.divId);
	this.div.html("");
	
	// Loading image and load more link
	this.loadingImg = "<img id=\"dashboard-loading\" alt=\"Loading...\" src=\"" + RESOURCE_URL + "/images/icons/loading.gif\" />";
	this.loadMore = "<a id=\"dashboard-more\" href=\"javascript:Dashboard.fetch()\">More &raquo;</div>";
	
	// Parameters saved, go fetch the data
	this.fetch();
}

Dashboard.fetch = function()
{
	// Create the url and next fetch() call will get the next page
	var url = this.dataUrl + "/page/"+this.currentPage;
	
	// Show the loading thingy and remove load more button
	jQuery("#dashboard-more").remove();
	this.div.append(this.loadingImg);
	
	// Retrieve from the server
	jQuery.get(url, function(content) {
		jQuery("#dashboard-loading").remove();
		content = jQuery.trim(content);
		
		// Continue with the next page later on
		Dashboard.currentPage++;
		
		// Must have some content..
		if (content.length == 0)
		{
			// Don't try more than X times
			if (Dashboard.refetchTries++ >= 5)
			{
				// No more content found.
				Dashboard.div.append("No more content available.");
				return;
			}
			
			// Try to load more
			Dashboard.fetch();
		}
		else
		{
			Dashboard.refetchTries = 0;
			
			// Add content and load more button
			Dashboard.div.append(content);
			Dashboard.div.append(Dashboard.loadMore);
		}
	});
}
