/**********************************************************
/	Project : Travel Studio
/	Description: Contains XMLDOc manipulation functions.
/
/	File	: PrepareXML.js
/	Author  : Mazher Mian
/	Created : 04/Feb/2000
/
***********************************************************/
/*History 
Who 		When		WHAT
SD[01]		17 OCT 2K	update the submitrequest and sesionrequest so it can display custom message
*/
/*******************************************************
/ Functions define in this module.
/ ================================================================
function PrepareDocument(xmldoc,rprogid,rmethod)
function AddObj(xmldoc,status)
function AddObjPara(xmldoc,objindex,paraindex,value,type)
function FillCombo( r_cbo, r_xmldoc, r_codePosition, r_namePosition )
function EmptyCombo( r_obj )
function SubmitRequest()
function SubmitSessionRequest()
function GetSessionResponse()
function IsErrorInResponseXML()
function FindCodeByName( r_codeposition, r_nameposition, r_name )
function AddDataToTempStore( r_store, r_name, r_value )
function RemoveDuplicateCode( r_xmldoc )
function FindNameByCodeEx( r_codeposition, r_nameposition, r_code , r_XML )


/
********************************************************/


// ================================================================
// MAIN functionality.
// ================================================================

// The XMLHTTP object
var oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
var vSync = 0;

// The XML object
var oRequestXML = new ActiveXObject("Microsoft.XMLDOM");
var oResponseXML = new ActiveXObject("Microsoft.XMLDOM");
	
var tmp;
var Error = 0;
var ErrorDescription = "";

var gObjIndex = 0;

function PrepareDocument(xmldoc,rprogid,rmethod  , rServerName )
{
	var irscallroot = xmldoc.createElement("IRSCALL");
	xmldoc.documentElement = irscallroot;

	var progid = xmldoc.createElement("PROGID");
	progid.text = rprogid;
	irscallroot.appendChild( progid );

	var methodname = xmldoc.createElement("METHODNAME");
	methodname.text = rmethod;
	irscallroot.appendChild( methodname );

	var parameters = xmldoc.createElement("PARAMETERS");
	irscallroot.appendChild( parameters );

	if (rServerName+"" != "undefined" && rServerName+"" != "")
	{
		var serverName = xmldoc.createElement("SERVERNAME");
		serverName.text = rServerName;
		irscallroot.appendChild( serverName )	

	}
	var objparam = xmldoc.createElement("OBJECTS");
	irscallroot.appendChild( objparam );
	
	gObjIndex = -1;
}


function AddObj(xmldoc,status)
{
	var rootNode = xmldoc.documentElement;
	var objparam = xmldoc.getElementsByTagName("OBJECTS");

	var obj = xmldoc.createElement("OBJ");
	
	if( status != "" )
	{
		var statusAttr = xmldoc.createAttribute("FUN");
		statusAttr.text = status;
		obj.attributes.setNamedItem( statusAttr );
	}
	
	objparam.item(0).appendChild( obj );
	
	// there is only one OBJECTS collectyion so no need to take OBJECTS index
	// append OBJ and increment in global variable.
	gObjIndex = gObjIndex + 1;
}

function AddObjPara(xmldoc,objindex,paraindex,value,type)
{
	var rootNode = xmldoc.documentElement;
	var obj = xmldoc.getElementsByTagName("OBJ");

	var para = xmldoc.createElement("PARA"+paraindex);

	if( type >0 )
	{
		var typeAttr = xmldoc.createAttribute("TYPE");
		if(value.length==0)
			typeAttr.text = "1";	// set VT_NULL
		else
			typeAttr.text = type;
		para.attributes.setNamedItem( typeAttr );
	}
	
	para.text = value;
	obj.item(objindex).appendChild( para );
}



function FillCombo( r_cbo, r_xmldoc, r_codePosition, r_namePosition )
{
	var oNodeList, iItem, oNode;
	
	//EmptyCombo(r_cbo);
	
	oNodeList = r_xmldoc.getElementsByTagName( "OBJ" );

	if( oNodeList.length > 0 )
	{
		for( iItem = 0 ; iItem < oNodeList.length; iItem++ )
		{
			var oOption, oChildren;
			
			oOption = document.createElement( "OPTION" );
			r_cbo.options.add( oOption );
			
			oNode = oNodeList.item( iItem );
			oChildren = oNode.childNodes
			oOption.innerText = oChildren.item(r_namePosition).text
			oOption.value = oChildren.item(r_codePosition).text
		}
	}
}

function EmptyCombo( r_obj )
{
	var varOptionsList;
	varOptionsList = r_obj.options.childNodes;

	while (  varOptionsList.length>0 )
	{
		varOptionsList ( 0 ).removeNode();
	}
}

function LoadXSL(r_oXSL, r_XSLFile)
{
	window.status = "Loading data...";
	r_oXSL.async = false;
	if( r_oXSL.load( GetHome()+r_XSLFile ) == false )
	{
		window.alert( "Failed to load XSL" );
	}
	window.status = "Data loading done.";
	window.status = "Ready";
}

function SubmitRequest(strStatus)
{
	//soc[1]update by Shahjahan//to display the status message
	//16 oct
	if (typeof(strStatus)=="undefined")  
		strStatus="Loading data..."   //default Stasus...
	//eoc sd[1]
	window.status = strStatus;
	PutText("*** From Submit Request--opening HHTP Connection")
	oXMLHTTP.open( "POST", GetObjectPath(), vSync, "", "" );
	PutText("*** From Submit Request--Sending xml--xml is "+oRequestXML.xml)
	oXMLHTTP.send( oRequestXML );
	PutText("*** From Submit Request--Status of Session -- is (" + oXMLHTTP.Status + ")["+oXMLHTTP.StatusText + "] ")
	PutText("*** From Submit Request--Recieving XML --Text is "+oXMLHTTP.responseText)
	if (!oResponseXML.loadXML( oXMLHTTP.responseXML.xml ))
	{
		//alert ("Session Response could not be loaded into DOM");
		TSWebXMLErrAlert(oXMLHTP, oResponseXML);
		PutText("*** From Submit Request--DOM error for Last Request")
	}	
	else
		PutText("*** From Sumbit Request--Recieving XML --XML is "+oResponseXML.xml);
	window.status = "Data loading done.";
	window.status = "Ready";
}

function SubmitSessionRequest(strStatus)
{
	//socsd[1] update by Shahjahan//to display the status message
	//16 oct
	if (typeof(strStatus)=="undefined")  
		strStatus="Loading data..."   //default Stasus...
	//eoc sd[1]
	window.status = strStatus;
	PutText("*** From SESSION  Request--opening HHTP Connection")
	oXMLHTTP.open( "POST", GetSessionObjectPath(), vSync, "", "" );
	PutText("*** From Session Request--Sending xml--xml is "+oRequestXML.xml)
	oXMLHTTP.send( oRequestXML );
	
	PutText("*** From Session Request--Status of Session -- is (" + oXMLHTTP.Status + ")["+oXMLHTTP.StatusText + "] ")
	PutText("*** From Session Request--Recieving XML --Text is "+oXMLHTTP.responseText)

	//BOC Hameed
	// responseText is used instead of responseXML.xml as incase of
	//extended characters, blank string is retrieved in the later case.
	//if (!oResponseXML.loadXML( oXMLHTTP.responseXML.xml ))
	if (!oResponseXML.loadXML( oXMLHTTP.responseText ))
	//EOC Hameed
	{
		//alert ("Session Response could not be loaded into DOM");
		TSWebXMLErrAlert(oXMLHTTP, oResponseXML);
		PutText("*** From Submit Request--DOM error for Last Request")
	}
	else
		PutText("*** From Session Request--Recieving XML --XML is "+oResponseXML.xml)
	window.status = "Data loading done.";
	window.status = "Ready";
}

function GetSessionResponse()
{
	var root = oResponseXML.documentElement;
	var	Node;
	
	if(root == null) return "Error";
	
	if( root.hasChildNodes() )
	{
		Node = root.childNodes.item(0);
		return Node.text;
	}
}

function IsErrorInResponseXML()
{
	// Check any Error returned.
	//--------------------------
	var Nodes = oResponseXML.getElementsByTagName("ERROR")
	if( Nodes.length > 0 )
	{
		if( Nodes.item(0).hasChildNodes() )
		{
			ErrorDescription = Nodes.item(0).childNodes.item(0).text;
		}
		else
			ErrorDescription = "Unknown error.";
		
		return true;
	}
	return false;
}

function FindCodeByName( r_codeposition, r_nameposition, r_name )
{
	// Find the code of oLogonUserName in XML doc, and update variable.
	// ---------------------------------
	//oNodes = rootNode.selectSingleNode(eval('OBJ[$any$ PARA2="'+oLogonUserName+'"]'));
	
	var Nodes = oResponseXML.getElementsByTagName("OBJ")
		if( Nodes.length >0 )
		{	
			var i; var name;
			for( i=0; i< Nodes.length ; i++)
			{
				name = Nodes.item(i).childNodes.item( r_nameposition ).text;
				if( name == r_name )
				{
					return eval(Nodes.item(i).childNodes.item( r_codeposition ).text * 1);
				}
			}
		}
	return -1;
}

function AddDataToTempStore( r_store, r_name, r_value )
{
	var oOption, oElement;
	
	// r_name.document.getElementsByName("firstName");
	oElement = parent.document.all(r_name);
	if( oElement != null )
	{
		oElement.value = r_value;
	}
	else
	{
		oOption = document.createElement('<INPUT type="text" name="'+r_name+'">');
		oOption.value = r_value;
		//r_store.appendChild(oOption);
	
		var temp = r_store.innerHTML;
		r_store.innerHTML = temp +" "+r_name+" "+ oOption.outerHTML;
	}
}


function RemoveDuplicateByCol( r_xmldoc, r_col )
{
	var oObjects, iItem, oObjs, currNode, oldChild;
	
	oObjects = r_xmldoc.getElementsByTagName( "OBJECTS" );
	oObjs = r_xmldoc.getElementsByTagName( "OBJ" );

	var Rows = oObjs.length;
	aList = new Array(Rows);

	var Count = oObjs.length
	if( Rows > 0 )
	{
		iItem = 0;
		while( iItem < Count )
		{
			currNode = oObjects.item(0).childNodes.item( iItem );
			if( FoundInList( currNode.childNodes.item(r_col).text, aList, Rows) )
			{
				oldChild = oObjects.item(0).removeChild(currNode);
				Count--;
			}
			else
			{
				aList[iItem] = currNode.childNodes.item(r_col).text;
				iItem++;
			}
		}
	}
	
}


function FoundInList(r_value, r_array, r_size)
{
	var i;
	for( i = 0 ; i < r_size; i++ )
	{
		if( r_array[i] == r_value )
		{
			return true; 
		}
	}
	return false;
}

function FindNameByCodeEx( r_codeposition, r_nameposition, r_code , r_XML )
{
	
	var Nodes = r_XML.getElementsByTagName("OBJ")
		if( Nodes.length >0 )
		{	
			var i; var code;
			for( i=0; i< Nodes.length ; i++)
			{
				code = Nodes.item(i).childNodes.item( r_codeposition ).text
				if( parseInt(code) == parseInt(r_code) )
				{
					return Nodes.item(i).childNodes.item( r_nameposition ).text;
				}
			}
		}
	return '';
}


//////////////////////// Rules specific functions (Start) /////////////////////

/*
	This function sets oRequestXML for getting rules from the server.
*/
function PrepareRuleDocument(r_oXMLDocument, r_strProgID, r_strMethod)
{
	var irscallroot = r_oXMLDocument.createElement("IRSCALL");
	r_oXMLDocument.documentElement = irscallroot;

	var progid = r_oXMLDocument.createElement("PROGID");
	progid.text = r_strProgID;
	irscallroot.appendChild( progid );

	var methodname = r_oXMLDocument.createElement("METHODNAME");
	methodname.text = r_strMethod;
	irscallroot.appendChild( methodname );
}

/*
	This function actually submits the request to server and loads the
	returned xml into oResponseXML object.
*/
function SubmitRuleRequest()
{
	oXMLHTTP.open( "POST", GetRulesPath(), vSync, "", "") ;
	oXMLHTTP.send( oRequestXML ) ;
	if (! oResponseXML.loadXML(oXMLHTTP.responseXML.xml) )
	{
		alert("Response could not be loaded") ;
		TSWebXMLErrAlert(oXMLHTTP, oResponseXML);
		
	}
}

/*
	This function takes xml dom object and a key as parameters, and returns a
	list of "VALIDATOR" whose "APPLIEDON" attribute's value is equal to r_Key.
*/
function GetValidatorsForField(r_oDOM, r_Key)
{
	var pattern = "VALIDATOR[@APPLIEDON = \"" + r_Key + "\"]" ;
	var oValidators = r_oDOM.documentElement.selectNodes(pattern) ;
	return oValidators ;
}

/*
	This function takes "<ERROR_MESSAGES>" node and a message constant as 
	parameters and returns the text of the <MESSAGE> node of the 
	<ERROR_MESSAGE> node whose <CONSTANT> node's value is equal to r_lngConstant.
*/
function GetMessage(r_oValidator, r_lngConstant)
{
	var oErrorMessages = r_oValidator.childNodes.item(2) ;
	var pattern = "ERROR_MESSAGE[$any$ CONSTANT = \"" + r_lngConstant + "\"]" ;
	var oMessage = oErrorMessages.selectNodes(pattern) ;
	/*	oMessage will hold a single ERROR_MESSAGE node (provided that there would be
		only one message constant having value equal to r_lngConstant.
	*/
	if (oMessage.length > 0)
		return oMessage.item(0).childNodes.item(1).text ;
	else
		return "" ;	
}

/*
	This function takes the "<VALIDATOR>" node as parameter and returns the
	number of rules attached to this validator.
	It returns 0 if no rule is found.
*/
function GetRulesCount(r_oValidator)
{
	var count = 0 ;
	count = r_oValidator.childNodes.item(1).childNodes.length ;
	return count ;
}

/*
	This function returns the text of "<RULE>" node at index r_RuleIndex.
	r_RuleIndex is zero based.
	If there are no rules attached to this validator, it returns "".
*/
function GetRule(r_oValidator, r_RuleIndex)
{
	var oRules = r_oValidator.childNodes.item(1) ;
	if ((oRules.childNodes.length > 0) && (oRules.childNodes.length > r_RuleIndex))
		return oRules.childNodes.item(r_RuleIndex).text ;
	else
		return "" ;
}

// Don't change the name of "value" variable.
// If value is according to rule then RunRule would return "undefined" value,
// so this function returns 0 if the value is according to the rule, otherwise
// it returns the value returned by the RunRule function.
function CheckRule(r_Value, r_Body)
{
	var value = new String(r_Value) ;
	var RunRule = new Function("value", r_Body) ;
	var ReturnValue = RunRule(value) ;
	// If type of ReturnValue is "undefined" that means the value is
	// according to rule. So, set ReturnValue to zero.
	if (typeof(ReturnValue) == "undefined")
		ReturnValue = 0 ;
	return ReturnValue ;
}

/*
	This function checks whether the passed value is in correct date
	format, if so it returns true otherwise it returns false.
	Don't remove or change this method because server side
	rules code uses this function in rules xml to check whether
	the value is a valid date.
*/
function IsDate(r_strValue)
{
	var day = NaN ;
	try
	{
		var oDate = new Date(r_strValue) ;
		// Intentionally execute a method on object.
		day = oDate.getDay() ;
		if (isNaN(day))
			return false ;
		else
			return true ;
	}
	catch(e)
	{
		return false ;
	}
}

/*
	This function checks whether the passed value is numeric, if so it
	return true otherwise it returns false.
	Don't remove or change this method because server side
	rules code uses this function in rules xml to check whether
	the value is a valid number.
*/
function IsNumeric(r_strValue)
{
	try
	{
		//eval returns 0 if we pass empty string therefore we need another check.
		var a = eval(r_strValue * 1) ; 
		var b = parseInt(r_strValue) ;
		if (isNaN(a) || isNaN(b))
			return false ;
		else
			return true ;
	}
	catch(e)
	{
		return false ;
	}
}

function ValidateRules(r_oRulesXML, r_Key, r_Value)
{
	var oValidators = GetValidatorsForField(r_oRulesXML, r_Key) ;
	for (var i = 0 ; i < oValidators.length ; i++)
	{
		var oValidator = oValidators.item(i) ;
		var RulesCount = GetRulesCount(oValidator) ;
		for (var j = 0 ; j < RulesCount ; j++)
		{
			var rule = GetRule(oValidator, j) ;
			var ReturnValue = CheckRule(r_Value, rule) ;
			if (ReturnValue != 0) // Error code was returned.
				return (GetMessage(oValidator, ReturnValue)) ;
		}
	}
	// return empty string to signify the success.
	return "" ;
}

function PutText(strText){
	try{
	parent.txtdebug.value=parent.txtdebug.value+"\n"+strText+ "  on  "+GetCurrentTime()
	}
	catch(e){;}
}

function GetCurrentTime(){
var d= new Date()
return d
}

function TSWebXMLErrAlert(r_srcXMLstring, r_oDestXML){
	alert( "Error Description:" + r_oDestXML.parseError.reason + "\nror Number:" + r_oDestXML.parseError.errorCode + "\nError Source XML:" + r_oDestXML.parseError.srcText);
}

/////////////////////// Rules specific functions (End) ///////////////////////
