/**
* class XMLHelper
* Basic class to simplify extraction of XML object
* compliments the HTTPRequest class
* Required files - none
*
* @author Flash
*/

/**
* Constructor
*
* @param XMLObject xml		XML object, the type of thing that gets returned by http request method
* @return XMLHelper
*/
function XMLHelper(xml) {
	this._xml = xml;
}

/**
* Makes sure we have a valid XMLObject to work with
*
* @return boolean			Whether we have a valid XMLObject
*/
XMLHelper.prototype.isValid = function() {
	return (typeof(this._xml) == 'object' && this._xml != null);
}

/**
* Gets a tag's XML elements
*
* @param string tagName		Name of the tag to retrieve
* @param Mixed xml			Accept XML object, or name of parent xml object, defaults to full xml object
* @return XMLCollection		Collection of XMLObjects
*/
XMLHelper.prototype.getElements = function(tagName, xml) {

	//default to full object
	switch (typeof(xml)) {
	case 'object':
		break;
	case 'string':
		xml = this.getElement(xml);
		break;
	default:
		xml = this._xml;
	}

	return xml.getElementsByTagName(tagName); 
}

/**
* Gets a first element matching the tag
*
* @param string tagName			Name of the tag to retrieve
* @param XMLObject xml			XML object to extract tag from, defaults to full xml object
* @return XMLObject				Single XMLObject
*/
XMLHelper.prototype.getElement = function(tagName, xml) {
	
	var elements = this.getElements(tagName, xml);

	if (elements && elements.length > 0) {
		return elements.item(0);
	}

	return null;
}

/**
* Gets the value of an XML tag
*
* @param string tagName			Name of the tag to retrieve
* @param XMLObject xml			XML object to extract tag from, defaults to full xml object
* @return string				The value of the XML tag
*/
XMLHelper.prototype.getValue = function(tagName, xml) {

	var element = this.getElement(tagName, xml);

	if (! element) {
		return element;
	}
	
	//check if element is single tag (self closing tag)
	if (element.firstChild == null) {
		return element.nodeValue ? element.nodeValue : '';
	}
	
	//else return contents of first child
	return element.firstChild.nodeValue ? element.firstChild.nodeValue : '';
}

/**
* Gets an attribute of an XML tag
*
* @param mixed element			XML Element to retireve attirbute from or name of element
* @param XMLObject xml			XML object to extract tag from, defaults to full xml object
*/
XMLHelper.prototype.getAttribute = function(element, attribute, xml) {

	if (typeof(element) == 'string') {
		element = this.getElement(element, xml);
	}

	if (! element) {
		return null;
	}

	//make sure we have the getAttribute method
	//IE doesn't know what it is, hence the unknown check
	//if also borks if you try to check element.getAttribute directly
	//damn broken piece of ...
	if (typeof(element.getAttribute) == 'function'
		|| typeof(element.getAttribute) == 'unknown') {
		return element.getAttribute(attribute);
	}

	return null;
}
