
/* URLs
DOM reference
http://www.w3.org/TR/2004/PR-DOM-Level-3-Core-20040205/DOM3-Core.html#infoset-mapping-DocumentMapping
XPath Reference
http://www.w3.org/TR/DOM-Level-3-XPath/xpath.html#TextNodes
*/
// on startup
function onStartup(){
  $(document).ready(function(){
	fillInXml();
    try{
		$("#xpathForm").validate({
			submitHandler: function(form) {
				// Do Ajax Submit here //   		$(form).ajaxSubmit();
				form = document.forms["xpathForm"];
				xpe = form.elements["xpathExpression"].value
				xml = form.elements["xml"].value
				var result;
				res = processXPath(xpe,xml,result)
				//alert("Res = "+Reflection.ReflectAllToString(res));
				form.elements["result"].value=parseXPathResult(res) ;// parseXPathResult(res);
				return false;
		   }
		})
	}catch(e){
		form.elements["result"].value="Invalid expression";
		return false;
	}
  });

 $(document).ready(function() {
   // do stuff when DOM is ready
   //alert("onStartup");
 });
}

function xmlToString(xml){
	return (new XMLSerializer()).serializeToString(xml);
}

function stringToXml(string){
	return (new DOMParser()).parseFromString(xmlstring, "text/xml");
}

function parseXPathResult(xpath){
	var val = xpath.iterateNext();
	var alertText = ""
	while (val) {
	  alertText += xmlToString(val) + "\n"
	  val = xpath.iterateNext();
	}
	return alertText;
}

function fillInXml(){
	var s = '\
<?xml version="1.0" ?> \n\
<company> \n\
  <employee id="001" sex="M" age="19">Premshree Pillai</employee> \n\
  <employee id="002" sex="M" age="24">Kumar Singh</employee> \n\
  <employee id="003" sex="M" age="21">Ranjit Kapoor</employee> \n\
  <turnover> \n\
    <year id="2000">100000</year> \n\
    <year id="2001">140000</year> \n\
    <year id="2002">200000</year> \n\
  </turnover> \n\
</company>';
	document.getElementById("xml").value=s;
}

function fillInEmployeesXpe(){
	document.getElementById("xpe").value="/company/employee";
}

function fillInEmployeesXpe2(){
	document.getElementById("xpe").value="//year";
}

function fillInEmployeesXpe3(){
	document.getElementById("xpe").value="/company/turnover/year[2]/text()";
}

function fillInNSXpe(){
	document.getElementById("xpe").value="//employee";
}

function fillInAttribXpe(){
	document.getElementById("xpe").value="//year/@id";
}
function fillInFnXpe(){
	document.getElementById("xpe").value="//employee";
}

function processXPath(xpathExpression, xml){
	//alert("Evaluating using "+xpathExpression+" on "+xml);
	var doc = new DOMParser().parseFromString( xml, "text/xml" ); 
	var contextNode = doc.documentElement; 
	var nsResolver = document.createNSResolver( contextNode.ownerDocument == null ? contextNode.documentElement : contextNode.ownerDocument.documentElement );
	var xpathResult = document.evaluate( xpathExpression, contextNode, nsResolver, XPathResult.ANY_TYPE, null );
	//alert("Res = "+xpathResult);
	return xpathResult
}


