/*
	TODOs: 
	1. Write exntended functions to do basic things like _recursively_ pull all text out of a node, so it gets childNode text too.
	2. Add functionality to classes to use sources other than ajax calls (divs, arrays, etc).
		This also means that you'll have to change the dictionary class to possibly not use XMLHandler, etc.
*/

function XMLHandler(xmlSource, file, parentClass, elementID, onReadyCallBack)
{
	if(file) this.file = file;
	if(parentClass) this.parentClass = parentClass
	if(onReadyCallBack) this.onReady = onReadyCallBack;
	
	/* alert("xmlSource: " + xmlSource + "\n" +
		  "file: " + file + "\n" +
		  "parentClass: " + parentClass + "\n" +
		  "elementID: " + elementID + "\n" +
		  "onReadyCallBack: " + onReadyCallBack); */
	
	if(xmlSource == "ajax") this.ajaxHandler = new AjaxHandler(file, this, "ajaxCallBack");
	else
	{
		if(xmlSource == "element" && elementID)
		{
			this.xml = $("#" + elementID).get(0).firstChild.documentElement;
			this.xml = $(this.xml);
			// alert(this.xml.get(0).firstChild.tagName)
			if(this.onReady) this.parentClass[this.onReady]();
		}
		else
		{
			// ERROR.
		}
	}
}
XMLHandler.prototype.file;
XMLHandler.prototype.xml;
XMLHandler.prototype.xmlSource; // Ajax or element/etc...
XMLHandler.prototype.ajaxHandler;
XMLHandler.prototype.parentClass;
XMLHandler.prototype.onReady;

// TODO: Implement better error catching/checking...
XMLHandler.prototype.openFile = function(file){
	if(!file) file = this.file;
	// alert("Opening file: " + file);
	
	// Problem: need a callback for something here to know when the XML is ready to be "fetched".
	this.ajaxHandler = new AjaxHandler(file, this, "ajaxCallBack");
	// jQuery.get(file, "", function(data){ this.xml = data; }, "xml");
}

// NOTE: Shouldn't have to pass the parent class all the way through the ajax call.
XMLHandler.prototype.ajaxCallBack = function(request, status)
{	
	// alert("ajaxCallBack...");
	if(request.responseXML) this.xml = $(request.responseXML.documentElement);
	// alert("XML from callBack: " + this.xml);
	if(this.onReady) this.parentClass[this.onReady]();
	
	// var t = this.xmlToJSON();
	
	// alert(thisClass.getElements("name:eq(2)").text());
	/* alert(arguments.callee.caller);
	var x = this.getElements("word:eq(2)");
	if(x[0]) alert("In XML class: " + x[0].tagName);
	else alert("No result"); */
}

XMLHandler.prototype.getElements = function(selector)
{
	var t = $(selector, this.xml);
	return t;
}

XMLHandler.prototype.xmlToJSON = function(xml)
{
	if(!xml) xml = this.xml;
	var t = $.xmlToJSON(xml);
	if(t)
	{
		/* alert(t.word[0].name[0].Text);
		for(var n in t.word[0].name[0])
		{
			document.getElementById("test").innerHTML += n + "<br>";
		} */
		return t;
	}
	else
	{
		alert("No result");
		return null;
	}
}