/*
	This Javascript is able to retrieve and cache texts from a
	webservice/remote script using JSON as its communication format. 
	When a text is loaded it is cached in an array. The script
	is able to load a number of texts upon load. Each texts is
	identifed by a TextId.
*/

var textUrl = config.urlBase + "service/texts.php";

var 
	STATUS_OK = 100,
	STATUS_ERROR = 200;

var texts =
{
	cache : {},
	location  : "",
	
	/**
	 *	Determine the default location
	 */
	defaultLocation : function(defaultLocation)
	{
		texts.location = defaultLocation;
	},
	
	/**
	 *	Load more than one text.
	 */
	multiLoad : function(ids)
	{
		for (var key in ids)
		{
			texts.load(ids[key]);
		}
	},
	
	/**
	 *	This method loads a text through a blocking 
	 *  AJAX call. 
	 */
	load : function(id, extra)
	{
		$.getJSON(textUrl + "?id=" + escape(id), 
			function(data)
			{
				if (data.status == STATUS_OK)
				{
					texts.cache[data.info.textId] = data.info.text;

					if (typeof(extra) != 'undefined')
						extra();
				}
			}
		);
	},
	
	
	/**
	 *	Show a text identified by `id` in the div marked by `inBlock`
	 */
	show : function(id, inBlock)
	{
		if (typeof(inBlock) == "undefined")
			inBlock = texts.location;
		
		if (typeof(texts.cache[id]) == 'undefined')
		{
			texts.load(
					id, 
					function() 
					{
						$(inBlock).html(texts.cache[id]);						
					}
				);
		}
		else	
		{
			// apparently already in cache
			$(inBlock).html(texts.cache[id]);
		}
	}	
};
