﻿var m_ClusterNameState=undefined;
var m_AsyncProgressPrevID;

function SetMachineName(progressId)
{
    var machineName=m_ClusterNameState;
    m_AsyncProgressPrevID=m_ClusterNameState;
    
    var params=progressId.split(";");
    try
    {
        if (params.length>1)
        {
            machineName=params[1];
        }
    }
    finally
    {
        m_ClusterNameState = machineName;
    }
}

function Get_AOFramework(){
	var AOFramework
	
	if( window.top && window.top.control_frame && window.top.control_frame.AOFrameworkTOP)
	{
		AOFramework = window.top.control_frame.AOFrameworkTOP
	}
	else if(window.dialogArguments)
	{
		AOFramework = window.dialogArguments[window.dialogArguments.length-1].AOFrameworkTOP
	}
	else if(window.opener)
	{
	    try
	    {
		    AOFramework = window.opener.top.control_frame.AOFrameworkTOP
		}
		catch(err)
		{
		    AOFramework = window.opener.dialogArguments[window.opener.dialogArguments.length-1].AOFrameworkTOP
		}
	}
	return AOFramework;
}

if (("unfdefined"==typeof(AOFramework))|| ( AOFramework==null)) var AOFramework=Get_AOFramework();
function SetClusterName(clusterName)
{
    try
    {
        if(clusterName!=null || (window.opener==null && window.dialogArguments==null))
        {
            AOFramework.ClusterName = clusterName;
        }
    }
    catch(err)
    {}
}
function SOAP_IsError(SOAPResult){
	return SOAPResult.error;
}

function SOAP_Format_Error_Message(SOAPResult){
    if( typeof(SOAPResult.errorDetail.stringDetail) != "undefined" &&
	    SOAPResult.errorDetail.stringDetail != "" )
	{
	    return SOAPResult.errorDetail.stringDetail;
	}
	var xfaultcode   = "Error Code:"+SOAPResult.errorDetail.code+".\n ";
	var xfaultstring = "String:"+SOAPResult.errorDetail.string+". \n";
	var xfaultsoap="";
	if (SOAPResult.errorDetail.raw!=null)	
		xfaultsoap   = "Row:" +SOAPResult.errorDetail.raw+". \n";
	
	var strResult2="";
	
    strResult2 = SOAPResult.errorDetail.string.split("-->");
    if (strResult2.length>=2)
	    strResult2=strResult2[1].replace(/(^\s*)|(\s*$)/g, "")
    else
	    strResult2=strResult2[0];	
    
	var xmlDOC = new ActiveXObject("MSXML2.DOMDocument");
	var strResult = "<root>" + strResult2 + "</root>";	
	strResult=strResult.replace("&lt;BOName&gt;","<BOName>");
	strResult=strResult.replace("&lt;/BOName&gt;","</BOName>");
	strResult=strResult.replace("&lt;Row&gt;","<Row>");
	strResult=strResult.replace("&lt;/Row&gt;","</Row>");
	strResult=strResult.replace("&lt;MessageID&gt;","<MessageID>");
	strResult=strResult.replace("&lt;/MessageID&gt;","</MessageID>");
	strResult=strResult.replace("&lt;Message&gt;","<Message>");
	strResult=strResult.replace("&lt;/Message&gt;","</Message>");
	strResult=strResult.replace("&lt;ElementName&gt;","<ElementName>");
	strResult=strResult.replace("&lt;/ElementName&gt;","</ElementName>");
	
	var parseOK=xmlDOC.loadXML(strResult);
	if (parseOK)
	{
		if (xmlDOC.selectSingleNode("/root/BOName")==null)		
			strResult = "<root><BOName></BOName><Row></Row><MessageID></MessageID><ElementName></ElementName><Message>" + strResult2 + "</Message></root>";
	}
	else
	{
	    //if the message from the server is not well formatted XML manipulate the
	    //message using regular expression
	    var sMessage = "Unexpected error:ao_functions_soap.js:line 131";
	    try
	    {
	        strResult.search(/(\<Message\>.*\<\/Message\>)/g);
	        sMessage = RegExp.$1;
	        sMessage = sMessage.replace(/(<\/Message>)|(<Message>)/g,"");
	        if( sMessage == "" )
	        {
	            strResult.search(/(\<root\>.*\<\/root\>)/g);
	            sMessage = RegExp.$1;
	            sMessage = sMessage.replace(/(<\/root>)|(<root>)/g,"");
	        }
	        if( sMessage == "" )
	        {
	            sMessage = strResult;
	        }
	        sMessage = "<![CDATA["+sMessage+"]]>"
	    }
	    catch(err)
	    {sMessage = strResult}
		strResult = "<root><BOName></BOName><Row></Row><MessageID></MessageID><ElementName></ElementName><Message>"+sMessage+"</Message></root>";
    }
	return strResult;
}
function SOAP_Get_XMLObj(SOAPResult){
	var resXML= new ActiveXObject("microsoft.xmldom");	
	resXML.validateOnParse = AS_IsDebugMode();
	if (SOAPResult.value==null) {
		resXML.loadXML("<root/>");
	}
	else 
	if (resXML.loadXML(SOAPResult.value))
	{
		//alert(SOAPResult.value);
	}
	else{
		resXML.loadXML("<error><body>"+resXML.parseError.reason+"</body></error>");
	}
	AS_CheckXSLError(resXML);
	return resXML;
}

function LoadDictionary(_async)
{
	try
	{
		_async = (typeof(_async)!="undefined");
		var lang_id = _GetGlobalVar("lang_id");
		var serviceName = "SpellerService";
		AOFramework.useService("../NetSpeller/" + serviceName + ".asmx?wsdl", serviceName)
		callObj = AOFramework.createCallOptions()
		callObj.async = _async;
		callObj.funcName = "LoadDictionary";
		
		var serviceObj = eval("AOFramework." + serviceName);
		if( _async )
		{
			return serviceObj.callService(LoadDictionaryCallback,callObj,lang_id);
		}
		else
		{
			var res = serviceObj.callService(LoadDictionaryCallback,callObj,lang_id);
			_SetGlobalVar("ActivateDictionary",(!res.error && res.value == "true"));
		}
	}
	catch(err)
	{
		_SetGlobalVar("ActivateDictionary","false");
	}
}

function AutoSpellCheck(text)
{
	var serviceName = "SpellerService";
	AOFramework.useService("../NetSpeller/" + serviceName + ".asmx?wsdl", serviceName)
	callObj = AOFramework.createCallOptions()
	callObj.async = false;
	callObj.funcName = "AutoSpellText";
	
	var serviceObj = eval("AOFramework." + serviceName);
	return serviceObj.callService(LoadDictionaryCallback,callObj,text);
}

function LoadDictionaryCallback(res)
{
	m_activateDictionary = (!res.error && res.value == "true");
}

function _RunSoapCommandEx(serviceName, functionName, portName)
{
	var argumentsStr = ""
	var SessionID = _GetGlobalVar("SessionID")
	var callObj
	
	AOFramework.useService("../WEB_Framework/" + serviceName + ".wsdl", serviceName)

	callObj = AOFramework.createCallOptions()
	callObj.async = false
	callObj.funcName = functionName
	callObj.portName = portName

	if(typeof(SessionID) != "undefined" && SessionID != null)
	{
		callObj.SOAPHeader = '<SOAP-ENV:Header SOAP-ENV:mustUnderstand="0">';
		callObj.SOAPHeader += '<SessionID>' + SessionID + '</SessionID>';  
		callObj.SOAPHeader += "</SOAP-ENV:Header>";  
	
		AO_GetPrimaryWindow().top.control_frame.updateSessionTimer();
	}
	
	var serviceObj = eval("AOFramework." + serviceName)

		

	
	for(var i = 3; i < arguments.length; i++) // starting from 2 because of serviceName and functionName
		argumentsStr += ", arguments[" + i + "]"
	
	return eval("serviceObj.callService(callObj" + argumentsStr + ")")
}

function _RunSoapCommandAsync(serviceName, functionName)
{
	var argumentsStr = ""
	var SessionID = _GetGlobalVar("SessionID")
	var callObj
	
	AOFramework2.useService("../WEB_Framework/" + serviceName + ".wsdl", serviceName)

	callObj = AOFramework2.createCallOptions()
	callObj.async = true
	callObj.funcName = functionName

	if(typeof(SessionID) != "undefined" && SessionID != null)
	{
		//callObj.SOAPHeader = '<SOAP-ENV:Header SOAP-ENV:mustUnderstand="1">';
		//callObj.SOAPHeader += '<SessionID>' + SessionID + '</SessionID>';  
		//callObj.SOAPHeader += "</SOAP-ENV:Header>";  
	
		AO_GetPrimaryWindow().top.control_frame.updateSessionTimer();
	}
	
	var serviceObj = eval("AOFramework2." + serviceName)
	
	for(var i = 2; i < arguments.length; i++) // starting from 2 because of serviceName and functionName
		argumentsStr += ", arguments[" + i + "]"
	
	callID = eval("serviceObj.callService(new Function(),callObj" + argumentsStr + ")")
}

function _RunSoapCommand(serviceName, functionName)
{
	var argumentsStr = ""
	var SessionID = _GetGlobalVar("SessionID")
	var callObj
	
	AOFramework.useService("../WEB_Framework/" + serviceName + ".wsdl", serviceName)

	callObj = AOFramework.createCallOptions()
	callObj.async = false
	callObj.funcName = functionName

	if(typeof(SessionID) != "undefined" && SessionID != null)
	{
		//callObj.SOAPHeader = '<SOAP-ENV:Header SOAP-ENV:mustUnderstand="1">';
		//callObj.SOAPHeader += '<SessionID>' + SessionID + '</SessionID>';  
		//callObj.SOAPHeader += "</SOAP-ENV:Header>";  
	
		AO_GetPrimaryWindow().top.control_frame.updateSessionTimer();
	}
	
	var serviceObj = eval("AOFramework." + serviceName)
	
	for(var i = 2; i < arguments.length; i++) // starting from 2 because of serviceName and functionName
		argumentsStr += ", arguments[" + i + "]"
	
	return eval("serviceObj.callService(callObj" + argumentsStr + ")")
}

function _RunSoapCommandDotNet(serviceName, functionName)
{
	var argumentsStr = ""
	var SessionID = _GetGlobalVar("SessionID")
	var callObj
	
	AOFramework = typeof(AOFramework)=="undefined"?AOFrameworkTOP:AOFramework;
	AOFramework.useService("../WEB_Framework/" + serviceName + ".asmx?wsdl", serviceName)

	callObj = AOFramework.createCallOptions()
	callObj.async = false
	callObj.funcName = functionName

	
	if(typeof(SessionID) != "undefined" && SessionID != null && SessionID  != "undefined")
	{
		callObj.SOAPHeader += '<SessionID>' + SessionID + '</SessionID>'; 
	
		AO_GetPrimaryWindow().top.control_frame.updateSessionTimer();
	}

	if(typeof(window.top.m_LoginScreen) != "undefined" && window.top.m_LoginScreen != null)
		callObj.SOAPHeader += '<LoginScreen>' + window.top.m_LoginScreen + '</LoginScreen>';

	try
	{
	if(GetCookie("ComputerID_" + _GetGlobalVar("ProfileID") + "__" + _GetGlobalVar("PortalUserLogin")) != null)
		callObj.SOAPHeader += '<ComputerID>' + GetCookie("ComputerID_" + _GetGlobalVar("ProfileID") + "__" + _GetGlobalVar("PortalUserLogin")) + '</ComputerID>';
	}
	catch(e){}

	var serviceObj = eval("AOFramework." + serviceName)
	
	for(var i = 2; i < arguments.length; i++) // starting from 2 because of serviceName and functionName
		argumentsStr += ", arguments[" + i + "]"
	try
	{
		if(AS_IsDebugMode())
		{
			var params = "";
			for(var j = 2; j < arguments.length; j++)
			{
				params += arguments[j]+",";
			}
			var strXml = "<SoapMsg><serviceName>"+serviceName+"</serviceName><functionName>"+functionName+"</functionName>"+
						 "<Parameters>"+params+"</Parameters></SoapMsg>";
		}
	}
	catch(err)
	{/*do nothing*/}
	var soapResult = eval("serviceObj.callService(callObj" + argumentsStr + ")");
	
	return soapResult
}



function _RunSoapCommandDotNetAsync(serviceName, functionName)
{
	var argumentsStr = ""
	var SessionID = _GetGlobalVar("SessionID")
	var callObj
	
	AOFramework2.useService("../WEB_Framework/" + serviceName + ".asmx?wsdl", serviceName)

	callObj = AOFramework2.createCallOptions()
	callObj.async = true
	callObj.funcName = functionName

	
	if(typeof(SessionID) != "undefined" && SessionID != null)
	{
		callObj.SOAPHeader += '<SessionID>' + SessionID + '</SessionID>'; 
	
		AO_GetPrimaryWindow().top.control_frame.updateSessionTimer();
	}
		
	var serviceObj = eval("AOFramework2." + serviceName)
	
	for(var i = 2; i < arguments.length; i++) // starting from 2 because of serviceName and functionName
		argumentsStr += ", arguments[" + i + "]"
	
	var soapResult = eval("serviceObj.callService(new Function(),callObj" + argumentsStr + ")")
	
	return soapResult
}
// -- new functionality
// ************************************************************************************************************
function _RunSoapCommandDotNetAsync2(serviceName, functionName, callbackFunctionName)
{
	var argumentsStr = ""
	var SessionID = _GetGlobalVar("SessionID")
	var callObj
	
	AOFramework2.useService("../WEB_Framework/" + serviceName + ".asmx?wsdl", serviceName)

	callObj = AOFramework2.createCallOptions()
	callObj.async = true
	callObj.funcName = functionName

	
	if(typeof(SessionID) != "undefined" && SessionID != null)
	{
		callObj.SOAPHeader += '<SessionID>' + SessionID + '</SessionID>'; 
	
		AO_GetPrimaryWindow().top.control_frame.updateSessionTimer();
	}
		
	var serviceObj = eval("AOFramework2." + serviceName)
	
	for(var i = 3; i < arguments.length; i++) // starting from 2 because of serviceName and functionName
		argumentsStr += ", arguments[" + i + "]"
	
	var soapResult = eval("serviceObj.callService("+callbackFunctionName+",callObj" + argumentsStr + ")")
	
	return soapResult
}

function SOAP_InteractWithServerAsync2(macroName,BOName,macroParams,updateStateXML,requestStateXML,startFromRecord,recordLimit,saveState, closeState,callbackFunctionName)
{    	
	var m_StateIDtemp;	
	if(typeof(m_StateID) == "undefined")
		m_StateIDtemp = -1;
	else m_StateIDtemp = m_StateID;	
	return  _RunSoapCommandDotNetAsync2("BCBase", "InteractWithServer2",callbackFunctionName, m_StateIDtemp, _GetGlobalVar("SessionID"), macroName,m_BCName,BOName,GetAOXML(macroParams),updateStateXML,requestStateXML,startFromRecord,recordLimit,saveState, closeState)
}

function SOAP_GetStateUIAsync2(requestStateXML,startFromRecord,recordLimit,callbackFunctionName)
{    
	var m_StateIDtemp;	
	if(typeof(m_StateID) == "undefined")
		m_StateIDtemp = -1;
	else m_StateIDtemp = m_StateID;	
	return  _RunSoapCommandDotNetAsync2("BCBase", "GetStateUI2",callbackFunctionName, m_StateIDtemp, _GetGlobalVar("SessionID"), m_BCName, requestStateXML, startFromRecord, recordLimit)
}
// ************************************************************************************************************



function _RunSoapCommand2(serviceName, functionName,callbackFunctionName)
{
	var argumentsStr = ""
	var SessionID = _GetGlobalVar("SessionID")
	var callObj
	if(typeof(AOFramework2)=="undefined") AOFramework2 = AOFrameworkTOP2;
	AOFramework2.useService("../WEB_Framework/" + serviceName + ".asmx?wsdl", serviceName)

	callObj = AOFramework2.createCallOptions()
	callObj.async = true
	callObj.funcName = functionName

	if(typeof(SessionID) != "undefined" && SessionID != null)
	{
		callObj.SOAPHeader += '<SessionID>' + SessionID + '</SessionID>'; 
		
		if(typeof(m_moduleName) != "undefined" && m_moduleName != null)
			callObj.SOAPHeader += '<ModuleName>' + m_moduleName + '</ModuleName>';
	
		AO_GetPrimaryWindow().top.control_frame.updateSessionTimer();
	}

	var serviceObj = eval("AOFramework2." + serviceName)
	
	for(var i = 3; i < arguments.length; i++) // starting from 2 because of serviceName and functionName
		argumentsStr += ", arguments[" + i + "]"
	
	
	callID = eval("serviceObj.callService("+callbackFunctionName+",callObj" + argumentsStr + ")")
}


function _RunSoapCommand3(serviceName, functionName,callbackFunctionName)
{
	var argumentsStr = ""
	var SessionID = _GetGlobalVar("SessionID")
	

	AOFramework2.useService("../WEB_Framework/" + serviceName + ".asmx?wsdl", serviceName)

	callObj = AOFramework2.createCallOptions()
	callObj.async = true
	callObj.funcName = functionName

	if(typeof(SessionID) != "undefined" && SessionID != null)
	{
		callObj.SOAPHeader += '<SessionID>' + SessionID + '</SessionID>'; 
		
		if(typeof(m_moduleName) != "undefined" && m_moduleName != null)
			callObj.SOAPHeader += '<ModuleName>' + m_moduleName + '</ModuleName>';
	
		AO_GetPrimaryWindow().top.control_frame.updateSessionTimer();
	}

	var serviceObj = eval("AOFramework2." + serviceName)
	
	for(var i = 3; i < arguments.length; i++) // starting from 2 because of serviceName and functionName
		argumentsStr += ", m_AsyncCallParams.argsObj[" + i + "]"
	
	var controlFrame = AO_GetPrimaryWindow().top.control_frame

	controlFrame.m_AsyncCallParams = new controlFrame.AsyncCallParams(callObj, serviceObj, arguments)

	callID = controlFrame.eval("m_AsyncCallParams.serviceObj.callService("+callbackFunctionName+",m_AsyncCallParams.callObj" + argumentsStr + ")")
}


function SOAP_RetrieveXMLNoLimit(XMLCriteria)
{	
	if(AS_IsDebugMode(true))
	{
	    NU_BuildNunitCommand("objRandom.GetRow",XMLCriteria);
	}
	return _RunSoapCommandDotNet("DataViewMgr", "RetrieveXMLNoLimit", _GetGlobalVar("SessionID"), XMLCriteria)
}

function SOAP_IsReportActive(reportName)
{
	var SOAPResult =  _RunSoapCommandDotNet("CacheEngine", "GetSelectedCacheXML",  "ast_report",true,"report_type","a2_report","report_name='"+reportName+"'","",true );
	if(SOAP_IsError(SOAPResult))
	{
		return false;
	}
	else
	{
		var doc = new ActiveXObject("microsoft.xmldom");
		doc.loadXML(SOAPResult.value);
		var reportType = doc.selectSingleNode("//report_type");
		if( reportType == null ) return false;
		return reportType.text == "A";
	}
}

function SOAP_RetrieveXMLBatch(XMLCriteria)
{
    if(AS_IsDebugMode(true))
	{
	    NU_BuildNunitCommand("objRandom.GetRow",XMLCriteria);
	}
	//return _RunSoapCommandDotNet("DataViewMgr", "RetrieveXMLBatch", _GetGlobalVar("SessionID"), XMLCriteria)
	return _RunSoapCommandDotNet("DataViewMgr", "RetrieveXMLBatchNoLimit", _GetGlobalVar("SessionID"), XMLCriteria);
}

function SOAP_Export( Format, Filename, DocTemplate, Delimiter, BoName  )
{		
	if ( BoName == null )
	{
		BoName = m_aliases[get_PrimaryBoIndex(currTab)].split(":")[0];
	}
	var bcName = m_BCName;
	var sessionId = _GetGlobalVar("SessionID");
	var stateId = m_StateID;
	return _RunSoapCommandDotNet("DataViewMgr", "Export", sessionId, bcName, BoName, Format, stateId,  Filename, DocTemplate, Delimiter );
}

function SOAP_ExportQuery( XMLCriteria, Format, Filename, DocTemplate, Delimiter )
{		
	return _RunSoapCommandDotNet("DataViewMgr", "ExportQuery", _GetGlobalVar("SessionID"), XMLCriteria, Format, Filename, DocTemplate, Delimiter )
}

function SOAP_PrepareSalesPerformanceReport( AS_HIERARCHY, AS_HIER_TYPE, AS_TOP_NODE, AS_TOP_NODE_TYPE, AD_START_DATE, AD_END_DATE, AS_FORECAST_METHOD )
{
	return _RunSoapCommandDotNet("DataViewMgr", "PrepareSalesPerformanceReport", AS_HIERARCHY, AS_HIER_TYPE, AS_TOP_NODE, AS_TOP_NODE_TYPE, AD_START_DATE, AD_END_DATE, AS_FORECAST_METHOD );
}

function SOAP_PreparePipelineVisibilityReport( adt_trend_date, adt_as_of_date, as_sale_rep, adt_start_date, adt_end_date, as_pipe_start, as_pipe_end, as_territory, an_probfrom, an_probto, an_totalmny )
{
	return _RunSoapCommandDotNet("DataViewMgr", "PreparePipelineVisibilityReport", adt_trend_date, adt_as_of_date, as_sale_rep, adt_start_date, adt_end_date, as_pipe_start, as_pipe_end, as_territory, an_probfrom, an_probto, an_totalmny );
}

function SOAP_RetrieveXML(XMLCriteria)
{	
	if (typeof(m_RetrieveNoLimit)!="undefined" && m_RetrieveNoLimit==true)
		return SOAP_RetrieveXMLNoLimit(XMLCriteria);
	else
	{
		if(AS_IsDebugMode(true))
	    {
	        NU_BuildNunitCommand("objRandom.GetRow",XMLCriteria);
	    }
	
		var oSOAPResult =  _RunSoapCommandDotNet("DataViewMgr", "RetrieveXML", _GetGlobalVar("SessionID"), XMLCriteria)
		
		if(AS_IsDebugMode(true))
	    {
	        NU_CreateQueryComment(oSOAPResult)
	    }
		return oSOAPResult;
	}
}
function SOAP_RetrieveXMLfromCache(portalName, XMLCriteria)
{	
	if(AS_IsDebugMode(true))
	{
	    NU_BuildNunitCommand("objRandom.GetRow",XMLCriteria);
	}
	return _RunSoapCommandDotNet("DataViewMgr", "GetPortalXML", String(_GetGlobalVar("SessionID")), portalName, XMLCriteria)
}

function SOAP_GetPortalMenu()
{	 
	return _RunSoapCommandDotNet("DataViewMgr", "GetPortalMenu")
}


function SOAP_CanFind(EntityName,keyValue)
{	 
	if(AS_IsDebugMode(true))
	{
	    NU_BuildNunitCommand("NUCanFind",EntityName,"SessionID",keyValue);
	}
	var result = _RunSoapCommandDotNet("DataViewMgr", "CanFind", EntityName, _GetGlobalVar("SessionID"), keyValue)

	if (SOAP_IsError(result)) return false;

	return result.value;	 
}


function SOAP_CanFindEx(EntityName,keyName,keyValue)
{	
	var result = _RunSoapCommandDotNet("DataViewMgr", "CanFindEx", EntityName, _GetGlobalVar("SessionID"), keyName, keyValue)
	
	if (SOAP_IsError(result)) return false;
	
	return result.value;		
}

function SOAP_GetDescr(EntityName,keyValue,elementName)
{			
	var result = _RunSoapCommandDotNet("DataViewMgr", "GetDescr", EntityName, _GetGlobalVar("SessionID"), keyValue, elementName)
	
	if (SOAP_IsError(result)) return false;
	
	return result.value;
}

function SOAP_GetDescrTable(tableName, dbElementName, dbKeyName, keyValue)
{			
	var result = _RunSoapCommandDotNet("DataViewMgr", "GetDescrTable", tableName, _GetGlobalVar("SessionID"), dbElementName, dbKeyName, keyValue)
	
	if (SOAP_IsError(result)) return false;
	
	return result.value;
}

function SOAP_GetDescrEx(EntityName,keyName,keyValue,elementName,defaultValue)
{		
	var result = _RunSoapCommandDotNet("DataViewMgr", "GetDescrEx", EntityName, _GetGlobalVar("SessionID"), keyName, keyValue, elementName)
	
	if (SOAP_IsError(result)) return result.errorDetail.string;
	
	if (result.value=="") return defaultValue;
	
	return result.value;
}


/*
function SOAP_ExecMacro(macroName,BCName,BOName,macroParams,saveState,closeState,requestXML)
{	
	
	for (var i=0;i<macroParams.length;i++)	    
	{
		if (!(macroParams[i] instanceof Array) && !(typeof(macroParams[i])=="number")) 
			  macroParams[i]=Array(macroParams[i]);		 
			  
	}

	var m_StateIDtemp;	
	if(typeof(m_StateID) == "undefined")
		m_StateIDtemp = -1;
	else m_StateIDtemp = m_StateID;	

	return _RunSoapCommandDotNet("MacroController", "ExecMacroUI", macroName, BCName, BOName, macroParams, _GetGlobalVar("SessionID"), m_StateIDtemp, saveState, closeState, requestXML)
}
*/
/// <summary>
/// mainly used for internal use by the framework, can be called by the application although its recommended to
/// use more higher level functions.
/// </summary>
/// <param name="macroName">[required]macro name</param>
/// <param name="BCName">[required]bc name</param>
/// <param name="BOName">[required]bo name</param>
/// <param name="macroParams">[required]macro parameters as array (send Array(null) for no parameters)</param>
/// <param name="saveState">[required] true save the state</param>
/// <param name="closeState">[required] close the state</param>
/// <param name="requestXML">[required] xml string that request bo and fields(<root><GetCurrentState pageName='' stateID='-1'><BO alias='main'></BO></GetCurrentState></root>)</param>
/// <param name="requestStateXPathFilter">[optional] XPath filter used by the server to filter the XML response(the state send back to the client)</param>
/// <returns>SOAPResult object</returns>
function SOAP_ExecMacro(macroName,BCName,BOName,macroParams,saveState,closeState,requestXML, requestStateXPathFilter)
{	

	var m_StateIDtemp;	
	if(typeof(m_StateID) == "undefined")
		m_StateIDtemp = -1;
	else m_StateIDtemp = m_StateID;	
	m_sessionClosed=closeState; 	
	if (typeof(requestStateXPathFilter)=="undefined" || requestStateXPathFilter==null)
	{
	    if(AS_IsDebugMode(true))
        {
	        NU_BuildNunitCommand("NUExecMacro",macroName,BCName,BOName,macroParams,saveState,closeState,requestXML);
        }
		return _RunSoapCommandDotNet("BCBase", "ExecMacroUI", macroName, BCName, BOName, GetAOXML(macroParams), 
			_GetGlobalVar("SessionID"), m_StateIDtemp, saveState, closeState, requestXML);
	}
	else
	{
	    if(AS_IsDebugMode(true))
        {
	        NU_BuildNunitCommand("NUInteractWithServer","StateIDNew","SessionID",macroName,BCName,BOName,macroParams,"",requestXML,requestStateXPathFilter,false,false);
        }
		return _RunSoapCommandDotNet("BCBase", "InteractWithServer",m_StateIDtemp,  _GetGlobalVar("SessionID"),
			macroName, BCName,BOName,GetAOXML(macroParams),null, requestXML, requestStateXPathFilter,false,false);
    }
}

function SOAP_ExecMacro2(macroName,BCName,BOName,macroParams,saveState,closeState,requestXML,callbackFunctionName)
{	
	/*
	for (var i=0;i<macroParams.length;i++)	    
	{
		if (!(macroParams[i] instanceof Array) && !(typeof(macroParams[i])=="number")) 
			  macroParams[i]=Array(macroParams[i]);		 
			  
	}
	*/
	var m_StateIDtemp;	
	if(typeof(m_StateID) == "undefined")
		m_StateIDtemp = -1;
	else m_StateIDtemp = m_StateID;	
	
	if(AS_IsDebugMode(true))
    {
	    NU_BuildNunitCommand("NUExecMacro",macroName,BCName,BOName,macroParams,saveState,closeState,requestXML);
    }	
    var bSaveSynchronic = (_GetGlobalVar("Save_Synchronic")=="true");
    if(!bSaveSynchronic)
    {
	    _RunSoapCommand2("BCBase", "ExecMacroUI", callbackFunctionName,macroName, BCName, BOName, GetAOXML(macroParams), _GetGlobalVar("SessionID"), m_StateIDtemp, saveState, closeState, requestXML)
	}
	else
	{
	    _RemoveGlobalVar("Save_Synchronic");
	    var SOAPResult = _RunSoapCommandDotNet("BCBase", "ExecMacroUI",macroName, BCName, BOName, GetAOXML(macroParams), _GetGlobalVar("SessionID"), m_StateIDtemp, saveState, closeState, requestXML)
	    WebserviceCallback(SOAPResult);
	}
}

function SOAP_ExportReport2PDF(callbackFunctionName,exportPath,fileType,reportName,findXML,fileName)
{
	var SessionID = _GetGlobalVar("SessionID");
	var userCultureInfo = clientInformation.userLanguage;
	
	_RunSoapCommand2("ReportManager", "Export", callbackFunctionName,SessionID, findXML, reportName, fileType, exportPath,  userCultureInfo); //ASAP IL0703060006
}

function SOAP_DeleteReport(fileName)
{
	var SessionID = _GetGlobalVar("SessionID");
	
	_RunSoapCommandDotNet("ReportManager", "DeleteReportByName", fileName);
}

function SOAP_ExecMacroAsync(macroName,BCName,BOName,macroParams)
{	
	_RunSoapCommandDotNetAsync("BCBase", "ExecMacroUI", macroName, BCName, BOName, GetAOXML(macroParams), _GetGlobalVar("SessionID"), -1, false, true, "")
}

function GetAOXML(params)
{
	if( params instanceof String )
		if( params.ToString().substring(0,1) == "<" )
			return params;
		
	return "<xml xmlns:dt='urn:schemas-microsoft-com:datatypes'>" + convertToXML(params) + "</xml>"
}

function convertToXML(convertMe)
{
	if (convertMe instanceof Array)
		return convertArrayToXML(convertMe)
	else
		return convertValueToXML(convertMe)
}

function convertValueToXML(value)
{	
 	if( value != null )
		return "<value dt:dt='" + typeof(value) + "'>" + SOAP_ReplaceSpecialChars(value) + "</value>"
		
	return ""
}

function convertArrayToXML(arr)
{
	var xmlToReturn = "<array>"
	
	for(var i=0; i< arr.length; i++)
		xmlToReturn += convertToXML(arr[i])
	
	return xmlToReturn + "</array>"
}


function SOAP_GetState(requestXML)
{
	if(AS_IsDebugMode(true))
	{
	    NU_BuildNunitCommand("NUGetStateUI","StateIDNew.Value", "SessionID", m_BCName, requestXML);
	}
	return _RunSoapCommandDotNet("BCBase", "GetStateUI", m_StateID, _GetGlobalVar("SessionID"), m_BCName, requestXML)
}

function SOAP_CloseState(stateID,BCName)
{	
	if(AS_IsDebugMode(true))
	{
	    NU_BuildNunitCommand("NUCloseState","eval:m_oFuncDeclaration.StateIDDeclaration('closeState')");
	}
	try
	{
	    stateID = typeof(stateID)=="undefined"?m_StateID:stateID;
	    BCName = typeof(BCName)=="undefined"?m_BCName:BCName;
	    var SOAPResult=_RunSoapCommandDotNet("BCBase", "CloseUI", stateID, _GetGlobalVar("SessionID"), BCName);
		if (!SOAP_IsError(SOAPResult))
		{
		    m_StateID = -1;
		    SetClusterName(null);
		}
		return SOAPResult;
	}
	catch(err)
	{/*do nothing*/}
}
function SOAP_CloseStateASync(stateID,BCName,callbackFunctionName)
{	
	if(AS_IsDebugMode(true))
	{
	    NU_BuildNunitCommand("NUCloseState","eval:m_oFuncDeclaration.StateIDDeclaration('closeState')");
	}
	stateID = typeof(stateID)=="undefined"?m_StateID:stateID;
	BCName = typeof(BCName)=="undefined"?m_BCName:BCName;
	_RunSoapCommand2("BCBase", "CloseUI", callbackFunctionName,stateID, _GetGlobalVar("SessionID"), BCName)
}

function SOAP_Sync2Server(boAlias,updateStateXML,saveState,closeState)
{
    if(AS_IsDebugMode(true))
    {
        NU_BuildNunitCommand("NUInteractWithServer","StateIDNew","SessionID","","",boAlias,"",updateStateXML,"","",saveState,closeState);
    }
    m_sessionClosed=closeState;    
	return SOAP_InteractWithServer("",boAlias,Array(""),updateStateXML,"","",saveState, closeState)
}

function SOAP_InteractWithServer(macroName,BOName,macroParams,updateStateXML,requestStateXML,requestStateXPathFilter,saveState, closeState,BCName)
{
	var m_StateIDtemp;	
	if(typeof(m_StateID) == "undefined")
		m_StateIDtemp = -1;
	else m_StateIDtemp = m_StateID;	
	if(validateObj.IsNothing(BCName)) BCName = m_BCName;
	if( BCName != m_BCName ) m_StateIDtemp = -1;
	if(AS_IsDebugMode(true))
    {
        NU_BuildNunitCommand("NUInteractWithServer","StateIDNew","SessionID",macroName,BCName,BOName,macroParams,updateStateXML,requestStateXML,requestStateXPathFilter,saveState,closeState);
    }	
    
	var SOAPResult= _RunSoapCommandDotNet("BCBase", "InteractWithServer", m_StateIDtemp, _GetGlobalVar("SessionID"), macroName,BCName,BOName,GetAOXML(macroParams),updateStateXML,requestStateXML,requestStateXPathFilter,saveState, closeState)
	
	if (!SOAP_IsError(SOAPResult))
	{
	   m_sessionClosed=closeState;  
	}
	
	return SOAPResult;
}

function SOAP_InteractWithServerAsync(macroName,BOName,macroParams,updateStateXML,requestStateXML,requestStateXPathFilter,saveState, closeState)
{
    if(AS_IsDebugMode(true))
    {
        NU_BuildNunitCommand("NUInteractWithServer","StateIDNew","SessionID",macroName,BCName,BOName,macroParams,updateStateXML,requestStateXML,requestStateXPathFilter,saveState,closeState);
    }	
	var m_StateIDtemp;	
	if(typeof(m_StateID) == "undefined")
		m_StateIDtemp = -1;
	else m_StateIDtemp = m_StateID;	
	return  _RunSoapCommandDotNetAsync("BCBase", "InteractWithServer",m_StateIDtemp, _GetGlobalVar("SessionID"), macroName,m_BCName,BOName,GetAOXML(macroParams),updateStateXML,requestStateXML,requestStateXPathFilter,saveState, closeState)
}



function SOAP_InteractWithServer2(macroName,BOName,macroParams,updateStateXML,requestStateXML,requestStateXPathFilter,saveState, closeState)
{
	if(AS_IsDebugMode(true))
    {
        NU_BuildNunitCommand("NUInteractWithServer","StateIDNew","SessionID",macroName,BCName,BOName,macroParams,updateStateXML,requestStateXML,requestStateXPathFilter,saveState,closeState);
    }	
	_RunSoapCommand2("BCBase", "InteractWithServer","", m_StateID, _GetGlobalVar("SessionID"), macroName,m_BCName,BOName,GetAOXML(macroParams),updateStateXML,requestStateXML,requestStateXPathFilter,saveState, closeState)
}
function SOAP_ReleaseLock(TableName,TableKey)
{	
	return _RunSoapCommandDotNet("LockManager", "ReleaseLock", _GetGlobalVar("SessionID"), TableName, TableKey)
}

function SOAP_ClaimLock(TableName,TableKey,TimeOut,CheckOnly)
{
	var HoldingUserID=new String();
	return _RunSoapCommandDotNet("LockManager", "ClaimLock", _GetGlobalVar("SessionID"), TableName, TableKey, TimeOut, CheckOnly, HoldingUserID);
}

function SOAP_CalculateFormula(FormulaName)
{
	return _RunSoapCommandDotNet("FormulaManager", "CalculateFormula", _GetGlobalVar("SessionID"), FormulaName)
}

function SOAP_Login(User,Password,Portal,initialVarsXML)
{
	return _RunSoapCommandDotNet("SecurityManager", "Login", User, Password, Portal, initialVarsXML)
}

function SOAP_LogOut()
{

	var controlFrame = window.top.control_frame

	if(controlFrame)
	{
		controlFrame.m_moduleForPages = new Array();
		controlFrame.m_modulePermissions = new Array();
		controlFrame.m_pagesPermissions = new Array();
		controlFrame.m_moduleUIPermissions = new Array();
		controlFrame.m_pagesUIPermissions = new Array();
	}
	return _RunSoapCommandDotNet("SecurityManager", "Logout", _GetGlobalVar("SessionID"), "Normal Logout")
}

function SOAP_LogOutSession(sessionID)
{
	return _RunSoapCommandDotNet("SecurityManager", "Logout", sessionID, "Logout By "+_GetGlobalVar("SessionID"))
}

function SOAP_BillBatch(xmlString)
{	
	return _RunSoapCommand("BillingBatchEngine", "Invoice", _GetGlobalVar("SessionID"), xmlString)
}

function SOAP_InitBillingProgress(xmlString)
{	
	var result =  _RunSoapCommand("BillingBatchEngine", "InitProgress", _GetGlobalVar("SessionID"), xmlString);
	return result.value;
}

function SOAP_AsyncProgressMgrInit(totalSteps)
{		
	return _RunSoapCommandDotNet("AsyncProgressManager", "Init", _GetGlobalVar("SessionID"), totalSteps)
}

function SOAP_AsyncProgressMgrUpdate(progressID, stepsToAdvance, message, isError, isCompleted)
{							   
	SetMachineName(progressID);
	try
    {
        var result=_RunSoapCommandDotNet("AsyncProgressManager", "Update", _GetGlobalVar("SessionID"), progressID, stepsToAdvance, message, isError, isCompleted)
    }
    finally
    {
        m_ClusterNameState=m_AsyncProgressPrevID;
    }

	return result;
}

function SOAP_AsyncProgressMgrGetInfo(progressID)
{	
    //alert(progressID);							   
    SetMachineName(progressID);
    //alert(m_ClusterNameState)
    try
    {
        var result=_RunSoapCommandDotNet("AsyncProgressManager", "GetInfo", _GetGlobalVar("SessionID"), progressID)
        if(!SOAP_IsError(result))
            SetClusterName(result.value.ClusterName)

    }
    finally
    {
        m_ClusterNameState=m_AsyncProgressPrevID;
    }
    
	return result;
}

function SOAP_AsyncProgressCancel(progressID)
{								   
    SetMachineName(progressID);
    try
    {
        var result=_RunSoapCommandDotNet("AsyncProgressManager", "Cancel", _GetGlobalVar("SessionID"), progressID);
    }
    finally
    {
        m_ClusterNameState=m_AsyncProgressPrevID;
    }

	return result;
}


function SOAP_is_session_valid()
{
	return  _RunSoapCommandDotNet("GenericModule", "isSessionValid").value;
}	


function SOAP_f_get_rate(fromCurrency,toCurrency,convertDate)
{
	return _RunSoapCommandDotNet("GenericModule", "f_get_rate", fromCurrency, toCurrency, convertDate).value
}

function SOAP_f_get_convert_price(fromCurrency,toCurrency,convertDate,price)
{
	return _RunSoapCommandDotNet("GenericModule", "f_get_convert_price", fromCurrency,toCurrency,convertDate,price).value
}

function SOAP_f_get_convert_price_by_rate(amount,toCurrency,rate)
{
	return _RunSoapCommandDotNet("GenericModule", "f_get_convert_price_by_rate", amount,toCurrency,rate).value
}

//Begin Access to Google search engine
function SOAP_GoogleDoSearch(key, query, start, maxResults, filter, restrict, safeSearch, lr, ie, oe)
{
	return _RunSoapCommandDotNet("GoogleSearchProxy", "doGoogleSearch", key, query, start, maxResults, filter, restrict, safeSearch, lr, ie, oe).value
}

function SOAP_GoogleDoSpellingSuggestion(key, phrase)
{
	return _RunSoapCommandDotNet("GoogleSearchProxy", "doSpellingSuggestion", key, phrase).value
}

function SOAP_GoogleDoGetCachedPage(key, url)
{
	return _RunSoapCommandDotNet("GoogleSearchProxy", "doGetCachedPage", key, url).value
}
//End Access to Google search engine

function SOAP_smart_Request(Question, Areas)
{
	return _RunSoapCommand("SmaRTWS", "ProcessRequestEx", Question, _GetGlobalVar("SessionID"),
		"", Areas,-1,"min_answer_conf=25")
}

function SOAP_PMGenerate(xmlString)
{	
	return _RunSoapCommandAsync("PMBatchGen", "PMGenerate", _GetGlobalVar("SessionID"), xmlString)
}

function SOAP_InitPMProgress(xmlString)
{	
	var result =  _RunSoapCommandDotNet("PMBatchGen", "InitProgress", _GetGlobalVar("SessionID"), xmlString);
	return result.value;
}

function SOAP_RunPMGenerator(xmlString)
{
	var result = _RunSoapCommandDotNet("PMGenerator", "RunPMBatch", xmlString);
	return result.value;
}

function SOAP_ValidateObject(objectType,context,accessRight)
{
	var res = _RunSoapCommandDotNet("SecurityManager", "ValidateObject", _GetGlobalVar("SessionID"), objectType, context, accessRight)
	
	return res.value;
}


function SOAP_ReplaceSpecialChars(charsArray)
{
/*
	for (var i=0;i<charsArray.length;i++)
	{
		if (!(typeof(charsArray[i])=="number")) 
		{
			if ((charsArray[i]!=null) && (typeof(charsArray[i])=="string"))
			{
*/
			if ((charsArray!=null) && (typeof(charsArray)=="string"))
			{		
					charsArray=charsArray.replace(/\&/g,"&amp;");			
					charsArray=charsArray.replace(/\</g,"&lt;");
					charsArray=charsArray.replace(/\>/g,"&gt;");
					charsArray=charsArray.replace(/\"/g,"&quot;");			
					charsArray=charsArray.replace(/\&amp;amp;/g,"&amp;");										 			  
			}
			//charsArray[i]=Array(charsArray[i]);		 			
/*
		}
	}
*/
	return charsArray;
}
function SOAP_RetrieveDDLBPriority()
{
	if (typeof(_GetGlobalVar("priority_ddlb"))=="undefined" || _GetGlobalVar("priority_ddlb")=="")
	{	
		ddlbStr="<ddlb><priority_class>";
		var strXML = "<Find entity_name='priority_class' query_name='priority_class_lup'><types values=''/><operators values=''/></Find>";
		//while(SOAP_ServiceAvail("DBManager")!=true);
		var child=null;
		var SOAPResult=SOAP_RetrieveXML(strXML);
		if (!SOAP_IsError(SOAPResult)){
			child = SOAP_Get_XMLObj(SOAPResult);				
			if (child!=null)
			{
				var nodes=child.selectNodes("/root/row");
				for (var i=0;i<nodes.length;i++)
				{
					ddlbStr+='<entry display_value="'+__ProperXMLVal(nodes[i].selectSingleNode("descr").text)+'" number="'+
						(i+1)+'" ap_color_combination="'+nodes[i].selectSingleNode("ap_color_combination").text+'" min_value="'+nodes[i].selectSingleNode("fr_priority").text+
						'" max_value="'+nodes[i].selectSingleNode("to_priority").text+'" color="'+
							nodes[i].selectSingleNode("color_id").text+'"/>';
				}						
				ddlbStr+="</priority_class></ddlb>";
				_SetGlobalVar("priority_ddlb",ddlbStr);
				child.loadXML(ddlbStr);					
				return child.selectSingleNode("/ddlb");			
			}		
			
		}		
		_SetGlobalVar("priority_ddlb","");	
		var aaa=new ActiveXObject("microsoft.xmldom")		
		aaa.loadXML("<ddlb/>");
		return aaa.selectSingleNode("/ddlb");		
	}
	else
	{
		var ddlbStr=_GetGlobalVar("priority_ddlb");
		var aaa=new ActiveXObject("microsoft.xmldom")		;
		aaa.loadXML(ddlbStr);
		return aaa.selectSingleNode("/ddlb");
	}

}

function SOAP_GetProfiles()
{
	return _RunSoapCommandDotNet("Settings", "GetProfiles").value
}

function SOAP_GetPermissionsXML(pageName,BCName)
{
	return _RunSoapCommandDotNet("Permissions", "GetPermissionsXML", pageName, BCName).value
}

function SOAP_ReportExists(tableName,searchByRecord,reportName)
{
// tableName = "a2_report"
// searchByRecord = "report_name"
    var SOAPResult=null;
    try
    {
		var sCondition= searchByRecord + " = '"+ reportName +"'" ;
        SOAPResult=_RunSoapCommandDotNet("CacheEngine", "IsRecordExists",UI_LANGUAGE + "_Report",searchByRecord,tableName,sCondition);
    }
    catch(e)
    {
        alert("Error in function SelectReports \r\n" + e.description);
    }
    return SOAPResult;
}

function SOAP_IsAttachmentExists(attachmentID)
{
	return _RunSoapCommandDotNet("Attachment", "Exists", attachmentID).value
}

function SOAP_CalcUsage(XMLCriteria, ProgressID)
{	
	return _RunSoapCommandDotNetAsync("UsageCalc", "CalcUsage",XMLCriteria, "", ProgressID,"")
}

function SOAP_CalcReorderFrequency(XMLCriteria, ProgressID)
{	
	return _RunSoapCommandDotNetAsync("ReorderFreqCalc", "CalcReorderFrequency",XMLCriteria, "", ProgressID,"")
}

function SOAP_StockLevelCalc(XMLCriteria, ProgressID, objectName)
{	
	return _RunSoapCommandDotNetAsync("StockLevelCalc", "CalcStockLevel",XMLCriteria, objectName, "", ProgressID,"")
}

function SOAP_GetReportModuleName(reportName)
{
	var SOAPResult =  _RunSoapCommandDotNet("CacheEngine", "GetSelectedCacheXML",  UI_LANGUAGE+"_report",true,"qbe_asp_name","a2_report","report_name='"+reportName+"'","",true );
	if(SOAP_IsError(SOAPResult))
	{
		return null;
	}
	else
	{
		var doc = new ActiveXObject("microsoft.xmldom");
		doc.loadXML(SOAPResult.value);
		var moduleNameElm = doc.selectSingleNode("//qbe_asp_name");
		if(moduleNameElm == null) return null;
		return (moduleNameElm.text).toLowerCase();
	}
}

function SOAP_GetDefaultPrinter(PrinterFunction,WarehouseId,NodeId)
{
    return  _RunSoapCommandDotNet("GenericModule", "GetDefaultPrinter",PrinterFunction,WarehouseId,NodeId);
}

function SOAP_RunReadingRequest(XMLCriteria, ProgressID)
{     
      return _RunSoapCommandDotNetAsync("ReadingRequestEngine", "ProcessRequest",XMLCriteria, "", ProgressID,"")
}

