/**
 * Text Randomizer
 *
 * A simple script that allows you to randomize a block of text.
 * Optionally you can also print an author with for each block of text.
 *
 * @author			Barry Malcolm Harley
 * @version			1.0.0
 * @copyright		Copyright (c) 2011 ZootAlore! Creative
 */
 
/**
 * Load the randomizer
 *
 * @author 	Barry Malcolm Harley
 * @return 	void
 */
$(function() {
	randomText();							
});	
 
/**
 * Select a random text string from a JSON array and print in a container
 *
 * @author 	Barry Malcolm Harley
 * @return 	void
 */
function randomText() 
{
	// pull a list of text blocks from the JSON array
	$.getJSON('/static/js/txt-blocks.json', 
		function(data) 
		{
			// get random text block
			txtBlock = data.txtBlocks[randomize(data.txtBlocks.length)];
			
			// get a reference to the container element
			var txtContainer = document.getElementById("random-txt");
			// ... and get a reference to the author container
			var authContainer = document.getElementById("author");
			
			// print text block
			printToElement(txtContainer, txtBlock.text, '');
			// print author
			printToElement(authContainer, txtBlock.author, txtBlock.link);
			
		}
	);
}

/**
 * Generate a random number
 *
 * @author 	Barry Malcolm Harley
 * @param	int
 * @return 	int
 */
function randomize(max)
{
	// generate a random number
	return Math.floor(Math.random()*max);
}

/**
 * Print some text in a containing element
 *
 * @author 	Barry Malcolm Harley
 * @param	DOM object
 * @param	string
 * @return 	void
 */

function printToElement(element, txt, link)
{
	var label = '';
	
	// build anchor if set
	if (link != null && link != '')
	{
		label = document.createElement('a');
		label.setAttribute('href', link);
		var dash = document.createTextNode('- ');
		var txtNode = document.createTextNode(txt);
		label.appendChild(txtNode);
		element.appendChild(dash);
		element.appendChild(label);
	}
	// or just get the txt if no link set
	else if(txt != "" && txt != null)
	{
		label = document.createTextNode(txt);
	}	
	
	// print to container
	element.appendChild(label);
}
