/*
	All the files here are used for ajax control and initialisation
*/

// used to hold xml arrays
var XMLarray;

// instantiate the ajax class
function newAjax() {
	// used to hold the instance for this class
	var Ajax;	
	// test to see if this is FF family and instantiate the xml http request class
	try {
		// Firefox, Opera 8.0+, Safari
		Ajax = new XMLHttpRequest();
	}
	// catch an error and react
	catch (e) {
		// test to see if this is IE family and instantiate the xml http request class
		try {
			Ajax = new XMLHttpRequest();
		}
		catch (e) {
			// test to see if this is old IE family and instantiate the xml http request class
			try {
				Ajax = new ActiveXObject("Microsoft.XMLHTTP")
			}
			// alert to the user this is not a ajax viable option
			catch (e) {
				alert("AJAX Sams4 application could not be instantiated, ERROR #001");
				return false;
			}
		}
	}
	return Ajax;	// return this instance
}

// a function to make xml an array
function parseXML() {
	// try multiple ways to get the XML into a jscript object
	try {
		var XMLresponse = new DOMParser().parseFromString(Ajax.responseText, 'text/xml');
	}
	catch (e) {
		var XMLDOM = new ActiveXObject('Microsoft.XMLDOM');
		XMLDOM.loadXML(Ajax.responseText);
		var XMLresponse = XMLDOM;
	}
	
	return XMLresponse;
}

// turn the XML into a single dimensional array
function XML_to_array(XML, name) {
	if (XML.hasChildNodes()) {
		for(var i=0; i<XML.childNodes.length; i++) {
			XML_to_array(XML.childNodes[i], XML.nodeName);
		}
	} else if (XML.nodeValue>'') {
		XMLarray[name] = XML.nodeValue;
	}
}

// instantiate a generic ajax class
var Ajax = newAjax();

function url_encode(text) {
		text = text.replace(/\+/g, "%2B");
		text = text.replace(/#/g, "%23");
		return text;
}

// send the message to irc
function populate_element(id, url) {
	
	var element = document.getElementById(id);
	if (element) {	// make sure the elements exist
		// send this to irc pm
		Ajax.open("GET", url_encode(url), false);
		// send null as a touch
		Ajax.send(null);

		// apply to chat window
		element.innerHTML = Ajax.responseText;
	}
}