/**
 * Virtual French Tutor AJAX helper functions
 * @author Paul Allsopp <paul@vtribes.com>
 */

/**
 * This function simply checks to make sure the ajax library
 * is loaded and if it is not, it loads it
 */
window.onload = function()
{
	if(typeof ajaxLibraryLoaded == 'undefined')
	{
		var baseUrl = location.protocol + "//" + location.hostname;
		var head = document.getElementsByTagName('head')[0];
		var script = document.createElement('script');
		script.type = "text/javascript";
		script.src = baseUrl + "/vg_warehouse/ajax.js";
		head.appendChild(script);
	}
}

/**
 * This function send a post request to the ajax manager and calls the
 * server-side RPC file to request the new block content
 * @var Int block_idx Index number for requested block
 * @see vg_warehouse/ajax.js::sendPostRequest
 */
function getBlockHTML(block_idx)
{
	var file = "vg_rpc/vft_rpc.php";
	var cmd = "get_new_block_content";
	var data = "blockIdx=" + block_idx;
	
	var block = document.getElementById("content_block");
	block.innerHTML = "<div style='width:100%; text-align:center;font-size:18pt;'>Please Wait...</div>";
	
	sendPostRequest(file, cmd, data, swapBlocks, errFunc);
}

/**
 * This function will be called by the ajax manager if it received
 * a success message from the server and has the new content
 * @var HTMLDocumentElement doc The document element attached to the XML
 * @see vg_warehouse/ajax.js::sendPostRequest
 */
function swapBlocks(doc)
{
	if(typeof doc.getElementsByTagName('content') == 'undefined')
	{
		return errFunc("Server returned bad document element.");
	}
	
	var content = doc.getElementsByTagName('content')[0].firstChild.data;
	var block = document.getElementById("content_block");
	block.innerHTML = content;
		
	return;
}

/**
 * This is an error function called by the ajax manager when
 * the server returns an error or empty XML document
 */
function errFunc(err)
{
	if(typeof err == 'undefined' || err == '')
	{
		err = "Error: Server returned an error, but error type is unknown";
	}
	
	alert(err);
	return false;
}

