/** ! IMPORTANT NOTE: this script requires ajax_main.js ! **/
var retryOnError=false; //set true for recursive retries if a call fails
var languageLoader;
var langStrings;
var languageLoadingNotifier;

function getLangString(fieldName)
/*
An internal function which is made for quick&easy language text retrieve operation from the active language
This is a self-explanatory function I think :)
*/
{
	return getNodeValue(langStrings, fieldName, '');
}

function fillLangTexts(container)
/*
This function scans the sub elements of the object or object id *container* for *langText* defined elements and then
sets their innerHTML's to the appropriate text retrieved dynamically from the language XML file.

If container is not spesified the function automatically scans the whole document(usually this is useful).
*/
{ 
	if (!container) //if container is not defined
		container=document.body; //assign the document object
		
	if (typeof(container)=='string') //or it is an id of the object
		container=document.getElementById(container); //then get the object with the given id
		
	var elements;
	elements = container.childNodes; //get all sub elements under the container

	for (var i=0; i<elements.length; i++) { //scan through the sub elements
		if (elements[i].nodeType==1 && elements[i].getAttribute("langText")) //if the element has a defined "langText" attribute
			elements[i].innerHTML = getLangString(elements[i].getAttribute("langText")); //set its innerHTML from the language xml
		else if (elements[i].hasChildNodes()) //if the element has sub nodes
			fillLangTexts(elements[i]); //call to iterate over the sub nodes
	}
}

function loadLanguage(langCode)
{
	if (languageLoader) //if there is an ongoing languge load request
		abortNDestroyRequestObject(languageLoader); //abort it
	langFileName = ''+langCode+'.xml'; //determine the file name from the language code. This line can be edited for personalisation
	var onLanguageLoaded = function (requestObject)//start defining the callBack function for the language load request
	{
		if (requestObject.readyState==4 && (requestObject.status==200 || requestObject.status==0)) //if the XML file loaded succesfully
		{
			langStrings = requestObject.responseXML.getElementsByTagName('language')[0]; //assign the response to the langStrings object
			fillLangTexts(); //change all the language texts across the page
		}
		else if (requestObject.readyState==4 && retryOnError) //if the operation failed and retryOnError is true
			loadLanguage(langCode); //try to reload
		else if (requestObject.readyState!=4 && languageLoadingNotifier) //if the request is in progress and a loadingNotifier function is defined
			languageLoadingNotifier(langCode); //call the given loadingNotifier function
	};
	return (languageLoader=comfortableAJAXRequest("GET", langFileName, "", onLanguageLoaded)); //assign the created request object to the global languageLoader object and return it.
}