
//
// This file contains utilities to work with AJAX.
//
// Author: rsacek
//


//
// Returns an instance of the XMLHttpRequest object.
// Returns :
//  1) The XMLHttpRequest object or 
//  2) "false" if it fails.
//
function buildXMLHttpRequest()
{
	var xmlRequestObj = false;

	// branch for native XMLHttpRequest object
	if(window.XMLHttpRequest)
	{
		try
		{
			xmlRequestObj = new XMLHttpRequest();
		}
		catch(e)
		{
			xmlRequestObj = false;
		}
	}
	else if(window.ActiveXObject)
	{
		// branch for IE/Windows ActiveX version
		try
		{
			xmlRequestObj = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				xmlRequestObj = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e)
			{
				xmlRequestObj = false;
			}
		}
	}

	return xmlRequestObj;
}

		
//
// Helper method to extract an XML nodes text. 
//
function parseXMLElementsData(xmlFragment, tagName, naValue)
{
	var element = xmlFragment.getElementsByTagName(tagName);
	if(element==null || element[0]==null || element[0].firstChild==null)
	{
		return naValue;
	}
	return element[0].firstChild.data;
}


// 
//  validator of an XML stream
//  return false or true
//
function isValidXML ( xmlStream )
{
	var xmlDoc = false;

	try //Internet Explorer
	{
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.load(xmlStream);

		if (xmlDoc.parseError.errorCode != 0)
		{
			alert("Error in line " + xmlDoc.parseError.line +
			" position " + xmlDoc.parseError.linePos +
			"\nError Code: " + xmlDoc.parseError.errorCode +
			"\nError Reason: " + xmlDoc.parseError.reason +
			"Error Line: " + xmlDoc.parseError.srcText);
			return(null);
		}
	}
	catch(e)
	{
		try //Firefox
		{
		xmlDoc=document.implementation.createDocument("","",null);
		xmlDoc.async=false;
		xmlDoc.load(dname);
		if (xmlDoc.documentElement.nodeName=="parsererror")
		  {
		  alert(xmlDoc.documentElement.childNodes[0].nodeValue);
		  return(null);
		  }
		}
		catch(e) {alert(e.message)}
	}
	try
	{
		return(xmlDoc);
	}
	catch(e) {alert(e.message)}
	return(null);
} 


