//ajax.jx

function Ajax() {

	var ths = this;

	//public properties
	this.url = null;
	this.req = null;
	this.onload = null;
	this.onerror = null;





	//constructor
    if (window.XMLHttpRequest) {
        this.req = new XMLHttpRequest();
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
        this.req = new ActiveXObject("Microsoft.XMLHTTP");
    }
    
    if(!this.req) {
		//throw error
		alert("XMLHttpRequest unsupported");
		return;
    }



	this.processReqChange = function() {
		if (this.req.readyState == 4) { //4=complete
			if ((this.req.status == 200 || this.req.status == 304) && this.req.responseXML.documentElement) { //OK (and valid XML document)?
				if (this.onload) this.onload(this.req);
			} else {
				if (this.onerror) this.onerror(this.req);
			}
		}
	}
	
	//public
	this.load = function(url) {
		//this.req.onreadystatechange = this.processReqChange;
		
		//if (owner == null) {
		//	throw new Error("Please set the Ajax owner property before calling the load method.");
		//}
		
		if (url != undefined) {
			this.url = url;
		}

		this.req.onreadystatechange = function() {ths.processReqChange()}; //FIND A SOLUTION!!!! this is a hack!!!
		this.req.open("GET", this.url, true);
		this.req.setRequestHeader("x-ajax-version","0.1.0");
		this.req.send(null);
	}



}



//global helper functions

function getChildNode(node, name) {
	for (var i=0;i<node.childNodes.length;i++) {
		if (node.childNodes[i].nodeName == name) {
			return node.childNodes[i];
		}
	}
	throw "Node "+name+" is not a child node of "+node.nodeName;
}
function getNodeText(node, name) {
	return getInnerText(getChildNode(node,name));
}
function getInnerText (node) {
	if (node.textContent) {
		return node.textContent;
	} else if (node.text) {
		return node.text;
	} else if (node.innerText) {
		return stripcdata(node.innerText);
	} else {
		switch (node.nodeType) {
		case 3:
		case 4:
			return "nodeValue"+node.nodeValue;
			break;
		case 1:
		case 11:
			var innerText = '';
			for (var i = 0; i < node.childNodes.length; i++) {
				innerText += getInnerText(node.childNodes[i]);
			}
			return innerText;
			break;
		default:
			return '';
		}
	}
}

function stripcdata(str) {
	if (str.substr(0,9) == "<![CDATA[") {
		return str.substr(9,str.length-12);
	} else {
		return str;
	}
}
