﻿/***********************\
* ITALCOM S.p.A.        *
* Library: CSoap.js     *
* Version: 1.0          *
* Require: Core.js      *
* Objects: CSoap        *
*          CDomCache    *
\***********************/


var CSOAP_STRING = 1
var CSOAP_COLLECTION = 2

//=======
// CSoap
//=======
function CSoap()
{
	this.field = [];
	this.autoclear = true;
	this.faultcode = 0;
	
	this.envelope = CreateDOMDocument();
}
CSoap.prototype.debug = 0;

// Un solo canale http sincrono per tutti le CSoap
function CreateXMLHttpRequest() 
{ 
	var x = null; 
	try 
	{ x = new XMLHttpRequest();	} 
	catch(e) 
	{ x = new ActiveXObject("Microsoft.XMLHTTP"); } 
	return x;
}
CSoap.prototype.httpReq = CreateXMLHttpRequest();

// Dialogo di default per displayError() percorso relativo a web
var CSoapDlgError = "/KnoS/system/env/lib/dlg/DlgSoapError.asp";

CSoap.prototype.clearField
=//=======================
function (name)
{
	if (arguments.length < 1)  
		return this.field = [];
	for (var i=0; i<this.field.length; i++)
		if ( this.field[i][0] == name )
			return this.field.splice(i, 1);
}

CSoap.prototype.setField
=//=====================
// Es.:
//	setField("id", "val", [["a1", 1]]) => <id a1="1"><![CDATA[val]]></id>
//	setField("id", ["val1"], [["a1", 1]]) => <id a1="1"><Vs><V><![CDATA[val1]]></V></Vs></id>
//	setField("id", [["val1",[["a1", 1],["a2", 2]]], ...]) => <id><Vs><V a1="1" a2="2"><![CDATA[val1]]></V>...</Vs></id>
function (name, value, attribute)
{
	if ( arguments.length < 3 ) attribute = [];
	
	for (var i=0; i<this.field.length; i++)
		if ( this.field[i][0] == name )
			return this.field[i] = [name, value, attribute];
	
	return this.field[this.field.length] = [name, value, attribute];
}

CSoap.prototype.fieldValue
=//=======================
function (name)
{
	for (var i=0; i<this.field.length; i++)
		if ( this.field[i][0] == name )
			return this.field[i][1];
	return null;
}

CSoap.prototype.getField
=//=====================
function (name, defaultResult)
{
	if (arguments.length<2) defaultResult = null;
	try
	{
		return this.envelope.selectSingleNode("//"+name).text;
	}
	catch (e) 
	{
		return defaultResult;
	}
}

CSoap.prototype.getAttribute
=//=========================
function (nodeName, attrName, defaultResult)
{
	if (arguments.length<2) defaultResult = "";
	try
	{
		return this.envelope.selectSingleNode("//"+nodeName).attributes.getNamedItem(attrName).text;
	}
	catch (e)
	{
		return defaultResult;
	}
}

CSoap.prototype.getAttributeList
=//=============================
function (nodeName, attrName)
{
	var result = []
	try 
	{ 
		var nodeList = this.envelope.selectNodes("//"+nodeName);
		for (var i=0; i<nodeList.length; i++)
			result[result.length] = nodeList.item(i).attributes.getNamedItem(attrName).text;
	}
	catch(e) 
	{ 
		result = []; 
	}
	return result;
}

CSoap.prototype.getNodeList
=//========================
// attrList è un array di stringhe con i nomi degli attributi da considerate
// se attrList è un array vuoto viene riempito con l'elenco dei nomi degli attributi trovati
function (nodeName, attrList)
{
	return (XMLGetNodeList(this.envelope, nodeName, attrList));
}

CSoap.prototype.getEnum
=//====================
function (name, defaultResult)
{
	if ( arguments.length < 2 ) defaultResult = null;
	try
	{
		/*		
		return this.envelope.selectSingleNode("//"+name).text
		
		values = this.envelope.createElement("Vs");
		field.appendChild(values);
		for (j=0; j<this.field[i][2].length; j++)
		{
			if ( IsEmpty(this.field[i][2][j]) )
				continue;
			value = this.envelope.createElement("V");
			value.text = this.field[i][2][j];
			values.appendChild(value);									
		}
		request.appendChild(field);
		*/				
		return null;
	}
	catch (e) 
	{
		return null;
	}
}

CSoap.prototype.getAttributeEnum
=//=============================
function (nodeName, attrName)
{
	var result = [];
	try
	{
		var xmlDoc = CreateDOMDocument();
		xmlDoc.loadXML(this.getAttribute(nodeName, attrName));
		var node = xmlDoc.selectNodes("//V");
		for (var i=0; i<node.length; i++)
			result[result.length] = node.item(i).text;
		return result;
	}
	catch (e) 
	{
		return [];
	}
}

CSoap.prototype.buildRequest
=//=========================
function ()
{
	var request, field, values, value, i, j, k;
	var template = '<SOAP:Envelope xmlns:SOAP="urn:schemas-xmlsoap-org:soap.v1"><SOAP:Body><Request></Request></SOAP:Body></SOAP:Envelope>';
	this.envelope.loadXML(template);

	request = this.envelope.selectSingleNode("//Request");
	for (i=0; i<this.field.length; i++)
	{
		field = this.envelope.createElement(this.field[i][0]);
		// Values
		switch ( typeof(this.field[i][1]) )
		{
			case "object":
				values = this.envelope.createElement("Vs");
				field.appendChild(values);
				for (j=0; j<this.field[i][1].length; j++)
				{
					if ( IsEmpty(this.field[i][1][j]) )
						continue;
					if ( typeof(this.field[i][1][j]) == "object" )
					{						
						if ( this.field[i][1][j].length == 1 )
						{
							// Caso pi�ù comune
							// setField("id", ["val1", "val2", ...], [["a1", 1]]) => <id a1="1"><Vs><V>val1</V><V>val2</V>...</Vs></id>
							value = this.envelope.createElement("V");
							value.appendChild(this.envelope.createCDATASection(this.field[i][1][j][0]));
							values.appendChild(value);
						}
						else
						{
							if ( typeof(this.field[i][1][j][1]) != "object" )
							{
								// Ad esempio: SaveInputPanel() di AmmDlgActionNotify
								// setField("idOuter", [["id1", "val1"], ["id2", "val2"], ...], [["a1", 1]]) => <idOuter a1="1"><id1>val1</id1><id2>val2</id2>..</idOuter>
								value = this.envelope.createElement(this.field[i][1][j][0]);
								value.appendChild(this.envelope.createCDATASection(this.field[i][1][j][1]));
								values.appendChild(value);
							}
							else
							{								
								// Ad esempio nelle richieste di feedback
								// setField("id", [["val1",[["a1", 1],["a2", 2]]], ...], [["a3", 3]]) => <id a3="3"><Vs><V a1="1" a2="2">val1</V>...</Vs></id>
								value = this.envelope.createElement("V");
								if (this.field[i][1][j][0] !== null)
									value.appendChild(this.envelope.createCDATASection(this.field[i][1][j][0]));
								for (k=0; k<this.field[i][1][j][1].length; k++)
									value.setAttribute(this.field[i][1][j][1][k][0], this.field[i][1][j][1][k][1]);
								values.appendChild(value);
							}
						}
					}
					else
					{
						value = this.envelope.createElement("V");
						value.appendChild(this.envelope.createCDATASection(this.field[i][1][j]));
						values.appendChild(value);
					}
				}
				request.appendChild(field);
				break;
				
			default:
				// setField("id", "val", [["a1", 1]]) => <id a1="1">val</id>
				request.appendChild(field);
				field.appendChild(this.envelope.createCDATASection(this.field[i][1]));
				break;		
		}
		// Attributes
		for (j=0; j<this.field[i][2].length; j++)
			field.setAttribute(this.field[i][2][j][0], this.field[i][2][j][1]);
	}
}

CSoap.prototype.parseResponse
=//==========================
function (aspSource, bDisplayError)
{
	if ( arguments.length < 2 ) bDisplayError = true;
try
{
	var debug = this.debug;
	this.buildRequest();
	
if (debug >= 1) if (!window.confirm(aspSource + "\n" + this.envelope.xml)) debug = 0;

	this.httpReq.open("POST", aspSource, false);
	this.httpReq.send(this.envelope.xml);

	if ( this.autoclear )
		this.clearField();	
	
if (debug >= 2) if (!window.confirm(this.httpReq.responseText)) debug = 0;
if (debug >= 3) if (!window.confirm(this.httpReq.responseXML.xml)) debug = 0;

	this.envelope = this.httpReq.responseXML;
	this.faultcode = this.envelope.selectSingleNode("//faultcode").text;
	
	if ( this.faultcode == 0 )
		return true;
	if ( bDisplayError )
		this.displayError(CSoapDlgError, this.envelope);
		
	return false;
}
catch (e) 
{
	//<!-- SOAP::REDIRECT(url) -->
	var str = ""+ this.httpReq.ResponseText;
	if (!IsEmpty(str))
		var r = str.match(/SOAP::REDIRECT\(([^)]*)\)/);
	if (!IsEmpty(r) && !IsEmpty(r[1]))
	{
		window.open(r[1], null, "height=400,width=600,status=yes,toolbar=no,menubar=no,location=no");
		return false;
	}
	if (!bDisplayError)
		return false;
	e.name = "";
	e.description = e.message = Language.label("Errore di comunicazione con il Server");
	ErrorAlert(e, "CSoap.parseResponse()");
	return false;
}
}

CSoap.prototype.displayError
=//=========================
function (aspSource, domError)
{
	if (IsEmpty(aspSource)) aspSource = CSoapDlgError;
	try
	{
		var arg = new Object();
		arg.DOMError = domError;
		window.showModalDialog(aspSource, arg, "status:no;resizable:yes;help:no;dialogHeight:300px;");
	}
	catch(e)
	{
		ErrorAlert(e, "DlgError()");
	}
}

CSoap.prototype.copyTo
=//===================
function (dst)
{
	for (var i=0; i<this.field.length; i++)
	{
		dst.field[i] = this.field[i];
		if(IsArray(this.field[i][0][1]))
			dst.field[i][1] = this.field[i][1].slice(0);
		else
			dst.field[i][1] = this.field[i][1];
		if (dst.field[i].length > 2)
			dst.field[i][2] = this.field[i][2].slice(0);
		else
			dst.field[i] = [];
	}
}


//===========
// CDomCache
//===========

function CDomCache(id)
{
	this.id = id;
	this.lastModified = "";
	this.document = CreateDOMDocument();
	this.document.loadXML("<Data/>");
	this.soap = new CSoap();
}

CDomCache.prototype.update
=//=======================
function ()
{
	var node = this.soap.envelope.selectSingleNode("//Data");
	if (node == null)
		return;
	this.lastModified = XMLGetAttributeText(node, "LastModified", "");
	this.document.loadXML(node.xml);
}

// Per evitare duplicati della cache
function GetDomCache(id)
{
	var gdc = window.GlobalDomCache;
	var opener = window.opener;
	if (gdc == null)
		while (opener != null)
			if ( (gdc = opener.GlobalDomCache) != null)
				break;
	if (gdc == null)
		gdc = window.GlobalDomCache = [];
	if (gdc[id] == null)
		gdc[id] = new CDomCache(id);
	return gdc[id];
}