// ***
// *** XML manipulation
// ***

/* ************************************************************************** */
/* *** Header declarations ************************************************** */
/* ************************************************************************** */

/* ************************************************************************** */
/* *** Extending standard objects ******************************************* */
/* ************************************************************************** */

/* ************************************************************************** */
/* *** Custom contents ****************************************************** */
/* ************************************************************************** */

/*
	Evaluatse really simple XPath expressions (1st parameter) on given context
	node (2nd parameter).
	
	Allowed combinations for expressions:
		- element names separated by slash. ie. 'entry/title'
		- attribute names as terminating nodes. ie. 'entry/link/@href'
		- element condition by simple attribute evaluation. 
			ie. 'entry[@class="main"]/link/@href'
			
	A syntax description for the XPath would be:
	
	
*/
function evaluateSimpleXPath(expr, aNode) {
	
	var separator = "/"
	var reExpr = /\[([^=]+)=([^\]]+)\]/g

	var pcs = String(expr).split(separator)
	d("esxp: evaluating expression '" + expr + "' as " + pcs.length + " pieces expression from element '" + aNode.nodeName + "'")
	var nodeType = pcs[0].charAt(0) == "@" ? Node.ATTRIBUTE_NODE : Node.ELEMENT_NODE
	var condition = Node.ELEMENT_NODE == nodeType ? reExpr.exec(pcs[0]) : []
	
	var r = ""
	
	// don't know if this is required
	if (nodeType == Node.ATTRIBUTE_NODE)
		return aNode.getAttribute(pcs[0].substr(1)) // to remove leading @
	
	if (aNode.nodeName == pcs[0].replace(reExpr, "") && aNode.nodeType == nodeType){
		
		if (condition == null || condition[0] == "" || aNode.getAttribute(condition[1].substr(1)) == condition[2].replace(/[\'\"]/ig, "")) {
			
			d("esxp: really got a matching element. even with conditions")
		
			if (pcs.length > 1) {
				
				if (pcs[1].charAt(0) == "@") {
					d("esxp: next is attribute with value '" + aNode.getAttribute(pcs[1].substr(1)) + "'")
					return aNode.getAttribute(pcs[1].substr(1))
				}
				
				for (var i = 0; i < aNode.childNodes.length; i++)
					r += evaluateSimpleXPath(buildFromArray(pcs, separator, 1), aNode.childNodes[i])
			} else
				return aNode.textContent
		} // if on condition
	} //
		
	return r
	
} // evaluateSimpleXPath