//web service functions
var AKA_XMLNS = "http://tempuri.org/";
//var AKA_URL = "http://www.akanda.com";

var IE = false;
if (document.all != null) {
    IE = true;
}

var WS_ACCESS_MANAGER	= "../Admin/Services/AccessManager.asmx";
var WS_ADMIN_ONLY		= "../Admin/Services/AdminOnly.asmx";
var WS_CONFIG_MANAGER	= "../Config/Services/ConfigManager.asmx";
var WS_PUBLIC			= "../WebServices/PublicServices.asmx";
var WS_LOGIN			= "../Admin/Services/Login.asmx";

var SOAP_READY_STATE_UNITIALIZED = 0; 
var SOAP_READY_STATE_LOADING = 1; 
var SOAP_READY_STATE_LOADED=2; 
var SOAP_READY_STATE_INTERACTIVE = 3; 
var SOAP_READY_STATE_COMPLETE = 4;

var SOAP_ERROR_PAGE = "../Script/SoapError.htm"
var SOAP_ERROR_WIN, SOAP_ERROR_MESSAGE; 

function GetXmlResponse(serviceUrl, async, callback, cbParams) {
    var xml = GetHtmlResponse(serviceUrl, async, callback, cbParams);
    var doc = new ActiveXObject("Microsoft.XMLDOM");
    doc.loadXML(xml);
    return doc;
}

function GetHtmlResponse(serviceUrl, async, callback, cbParams) {
  	var oHttp = getXMLHTTP();
	async = (async == true);
	oHttp.open("POST", serviceUrl, async);
	oHttp.setRequestHeader("Content-Type", "text/html; charset='utf-8'");
	if (callback != null) {
	    var sFunc = (cbParams == null) ? callback + "(oHttp)" : callback + "(oHttp, cbParams)";
		oHttp.onreadystatechange = function() { eval(sFunc) }
	}	
	oHttp.send();
	if (async) return true;
	if (oHttp.status == 200) {
	    var ret = oHttp.responseText;
	    return ret;
	} else {
	    var errMsg = oHttp.responseText;
	    if (errMsg.indexOf("<html>") < 0) { //plain text:
	        alert(serviceUrl + "\n" + errMsg);
	    } else { //html:
	        ShowError(errMsg + "<hr>URL: " + serviceUrl);
	    }
	}
}

function FillListboxByXml(listBox, xmlNode, codePath, valuePath, showCode) {
    if (xmlNode == null) {
        listBox.innerHTML = "";
        return;
    }    
    var nodes = (xmlNode.length == null) ? xmlNode.selectNodes("node()") : xmlNode; //can be a nodelist already
    var N = nodes.length;
    var en = new Enumerator(nodes);
    var opts = listBox.options;
    //opts.clear();
    listBox.innerHTML = "";
    for (; !en.atEnd(); en.moveNext()) {
        var node = en.item();
        var code = GetNodeVal(node, codePath, ""); //GetNodeVal is in table.js
        var val;
        //var ar = valuePath.split(':');
        val = GetNodeVal(node, valuePath, code);
        if (showCode) val = code + ": " + val;
        var opt = new Option(val, code);
        opts.add(opt);
    }
    if (opts.length > 0) opts.selectedIndex = 0;
}

function GetCodeValueList(xmlNode, codePath, valuePath) {
    var nodes = (nodes.length == null) ? xmlNode.selectNodes("/.") : xmlNode;
    var N = nodes.length;
    var e = new Enumerator(nodes);
    var ret = new Array(N,2);
    var i=0;
    for (; !e.atEnd(); e.moveNext()) {
        var node = e.item();
        var code = GetNode(node, codePath, "");
        var val = GetNode(node, valuePath, code);
        //var pair = new Array(1,1);
        ret[i,0] = code;
        ret[i,1] = val;
        i++;
    }
    if (opts.length > 0) opts.selectedIndex = 0;
}

function GetXmlResponseNode(oHttp, methodName) {
    var doc = oHttp.responseXml;
    if (doc.documentElement == null) return null;
    var rootNode = doc.documentElement.selectSingleNode("soap:Body/" + methodName + "Response/" + methodName + "Result");
    return rootNode;
}


function BuildXmlString(name, value) {
	var doc = new ActiveXObject("Microsoft.XMLDOM");
	var node = doc.createElement(name);
	node.text = value;
	return node.xml;
}

function SoapHtmlEncode(s) {
	var re = /</g;
	s = s.replace(re, "#lt;");
	re = />/g;
	s = s.replace(re, "#gt;");
	re = /&/g;
	s = s.replace(re, "&amp;");
	return s;
}
function SoapHtmlDecode(s) {
    var re = /&lt;/g;
    s = s.replace(re, "<");
    re = /&gt;/g;
    return s.replace(re, ">");
}

function SoapErrorMsg(retString) {
	if (retString == "") return true;
	var doc = new ActiveXObject("Microsoft.XMLDOM");
	doc.loadXML(retString);
	if (doc.xml == "" && retString != "") return retString;
	var faultNode = doc.selectSingleNode("//faultstring");
	if (faultNode == null) return true;
	return faultNode.text;
}

function GetSoapErrorMessage(msg) {
	var k = msg.toString().indexOf("[[");
	var ret;
	if (k >= 0) {
		var k2 = msg.toString().indexOf("]]");
		ret = s.toString().substring(k+2, k2);
	} else {
		ret = msg;
	}	
	return ret;
}

var gNoWSAccess = false;
/*
BDias. July.10.2008
The callback method must have two inputs and do a check or else SoapInvokeService will not work as expected.
i.e. Sample callback method
function Finished(oHttp, methodName)
{
    if (oHttp.readyState != SOAP_READY_STATE_COMPLETE) return; 
    SomeMethod();
}    
*/

function SoapInvokeService(serviceUrl, methodName, paramXml, async, xmlns, callback, noMessage, getXml, showErrors) {

    //showErrors = true;
    try
    {
        var ref = location.href;
        var parts = ref.split('/');
        var ns = AKA_XMLNS;
	    if (xmlns) ns = xmlns;
	    if (paramXml == null) paramXml = "";

//	    if (location.protocol == "https:" && serviceUrl.toLowerCase().indexOf('https:') < 0) {

//	        if (serviceUrl.toLowerCase().indexOf('..')==0)
//	            serviceUrl = serviceUrl.substring(2);
//	        if (serviceUrl.toLowerCase().indexOf('/') != 0)
//	            serviceUrl = '/' + serviceUrl;
//	        serviceUrl = "https://" + location.host + "/" + parts[3] + serviceUrl;
//	    }

	    var env = SoapBuildEnvelope(methodName, paramXml, xmlns);
    	
	    var oHttp = getXMLHTTP();
    	
	    async = (async == true);

	    oHttp.open("POST", serviceUrl, async);
	    oHttp.setRequestHeader("Content-Type", "text/xml; charset='utf-8'"); //utf-8 is not default, need to set explicitely, otherwise SP and FR won't send correctly - bug in .NET, they'll fix in a next release
	    var hdr = ns + methodName;

	    oHttp.setRequestHeader("SOAPAction", hdr);

	    if (callback != null) {
		    oHttp.onreadystatechange = function() { eval(callback + "(oHttp, methodName);") }
	    }	
	    oHttp.send(env);

	    if (async) return true;
	    if (oHttp.status == 200) {
		    if (getXml) {
		      var rootNode = GetXmlResponseNode(oHttp, methodName);
		      return rootNode;
		    } 
		    //var ret = SoapGetResult(oHttp.responseXml, methodName);
		    var ret = SoapGetResult(oHttp, methodName);
		    if (ret == null) ret = true;
		    return ret;
	    } else {	
		    //If there is an internal string (error message) surrounded by "[[" and "]]" (e.g. "Error:ORA-251 [[...my message...]]"), 
		    //only this message will be displayed - this used to suppress system messages from SOAP, Oracle, etc.
		    var s = SoapErrorMsg(oHttp.responseText);
		    if (showErrors == true) {
		        var errMsg = serviceUrl + ": " + methodName + ": " + GetSoapErrorMessage(s);
		        if (errMsg.indexOf("<html>") < 0) { //plain text:
		            alert(errMsg);
		        } else { //html:
		            ShowError(errMsg);
		        }
		    }    
		    var k = s.toString().indexOf("[[");
		    if (s.toString().indexOf("User is undefined") >= 0) {
			    var msg = "Web service access denied.\n\nYour session was closed on the server.\nPlease login again.";
			    if (gNoWSAccess) {
				    window.status = msg;
			    } else {
				    alert(msg);
			    }
			    gNoWSAccess = true;
			    return false;
		    } else {
			    if (s.toString().toLowerCase().indexOf("access denied") >= 0) {
			        if (!noMessage) {
			            alert("You don't have an access to the requested Web Service:\n\n" + serviceUrl);
			            return null;
			        }
			    }	
		    }
    		
		    if (k >= 0) {
			    var k2 = s.toString().indexOf("]]");
			    var msg = s.toString().substring(k + 2, k2);
			    if (showErrors == 2) return msg;
                ShowError(msg);
		    }
		    else {
		        if (showErrors == 2) {
		            var msg;
		            var k1 = s.indexOf("ExceptionDetail]");
		            if (k1 >= 0) {
		                var k2 = s.indexOf("(Fault");
		                if (k2 > k1+17) {
		                    msg = s.substring(k1 + 17, k2);
		                } else {
		                    msg = s;
		                }
		            } else {
		                msg = s;
		            }
		            return msg;
		        }
		        try {
		            ShowError(s);
		        } catch (err) { }
		    }
		    return false;
	    }	
	}
	catch(e)
	{
    	ShowError(e);
	}
}

function ShowErrorDetails() {
    var win = SOAP_ERROR_WIN;
    var err = SOAP_ERROR_MESSAGE;

    if (win == null) return;
    try {
        win.focus();
        var iframe = win.document.getElementById('frDetail');
        if (iframe) {
            var iframeDoc;
            if (iframe.contentDocument) {
                iframeDoc = iframe.contentDocument;
            }
            else if (iframe.contentWindow) {
                iframeDoc = iframe.contentWindow.document;
            }
            else if (window.frames[iframe.name]) {
                iframeDoc = window.frames[iframe.name].document;
            }

            if (iframeDoc) {
                iframeDoc.open();
                iframeDoc.write(err);
                iframeDoc.close();
                return;
            }
        }
    }
    catch (er) {
        try {
            win.close();
            var newWindow = window.open(SOAP_ERROR_PAGE, 'soaperror', "width=450px, height=145px, titlebar=no, location=no, toolbar=no, status=no, menubar=no, resizable=yes");
            newWindow.document.getElementById('dvDetail').innerText = err;
            if (newWindow != null) newWindow.focus();
        }
        catch (e) { alert(e); }
    }

}

function ShowError(err) {
    var width = 450;
    var height = 145;
    var maxErrorDialogAttempts = 5;
    var left = parseInt((screen.availWidth / 2) - (width / 2));
    var top = parseInt((screen.availHeight / 2) - (height+150));
    var SOAP_ERROR_PAGE_FEATURES = "width=450px, height=145px, left=" + left + ", top=" + top + ", titlebar=no, location=no, toolbar=no, status=no, menubar=no, resizable=yes";
    var d = new Date();
    //var win = window.open(SOAP_ERROR_PAGE, 'soaperror' + d.getMilliseconds(), SOAP_ERROR_PAGE_FEATURES); //too many windows may open!
    var win = window.open(SOAP_ERROR_PAGE, 'soaperror', SOAP_ERROR_PAGE_FEATURES);
    if (win != null) win.focus();

    SOAP_ERROR_WIN = win;
    SOAP_ERROR_MESSAGE = err;
    setTimeout(ShowErrorDetails, 1000);
}

///<summary>
///Get a browser specific implementation of the 
///XMLHTTP object.
///</summary>
function getXMLHTTP()
{
	var oHttp = null;
	try
    {    // Firefox, Opera 8.0+, Safari    
		oHttp=new XMLHttpRequest();  
		oHttp.overrideMimeType("text/xml");
  
	}
	catch (e)
    {    // Internet Explorer    
		try
		{      
			oHttp=new ActiveXObject("Msxml2.XMLHTTP");      
		}
		catch (e)
		{      
			try
			{        
				oHttp=new ActiveXObject("Microsoft.XMLHTTP");        
			}
			catch (e)
			{        
				alert("Your browser does not support AJAX!");        
			}      
		}    
	}
	return oHttp;
}


//version without alerts (for watch dog )
function SoapInvokeService2(serviceUrl, methodName, paramXml, async, xmlns) {
	var ns = AKA_XMLNS;
	if (xmlns) ns = xmlns;
	var env = SoapBuildEnvelope(methodName, paramXml, xmlns);
	var oHttp = getXMLHTTP();
	async = (async == true);
	oHttp.open("POST", serviceUrl, async);
	oHttp.setRequestHeader("Content-Type", "text/xml; charset='utf-8'"); 
	var hdr = ns + methodName;
	oHttp.setRequestHeader("SOAPAction", hdr);
	oHttp.send(env);
	if (async) return true; 
	if (oHttp.status == 200) {
		//var ret = SoapGetResult(oHttp.responseXml, methodName);
		var ret = SoapGetResult(oHttp, methodName);
		if (ret == null) ret = true;
		return ret;
	} else {	
		return false;
	}	
}

function SoapBuildEnvelope (methodName, parXml, xmlns) {
   	var ns = AKA_XMLNS;
	if (xmlns) ns = xmlns;
	var env = "<?xml version='1.0' encoding='utf-8'?>" 
	    + "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance ' " 
	    + " xmlns:xsd='http://www.w3.org/2001/XMLSchema' "
	    + " xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>"
	    + "<soap:Body>";
	env += "<" + methodName + " xmlns='" + ns + "'>";
	var re = /--/g;
	parXml = parXml.replace(re, "");

	env += parXml;  //sample parXml: <a>1</a><b>2</b>
	env += "</" + methodName + "></soap:Body></soap:Envelope>";
	return env;
}

function SoapBuildInputParam(name, value, doEncode) {
	if (doEncode) value = SoapHtmlEncode(value);
	return "<" + name + ">" + value + "</" + name + ">";
}

function SoapGetReturnValue(xml, xPath) {
	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc.loadXML(xml);
	var node = xmlDoc.selectSingleNode(xPath);
	if (node) {
		return node.text;
	} else {
		alert("Cannot find " + xPath + " in: \n\n" + xml);
		return null;
	}	
}

function SoapGetResult(oHttp, methodName) {
    var path = "//" + methodName + "Result";
    if (IE == true) {
        var node = oHttp.responseXML.selectSingleNode(path);
        if (node) {
            if (node.childNodes == null || node.childNodes.length < 1) {
                return node.text;
            } else {
                var dataNode = node.childNodes[0];
                if (dataNode.nodeName == "#text") {
                    return node.text;
                } else {
                    return dataNode;
                }
            }
        }
        else {
            return null;
        }
    }
    else {
        var xml = oHttp.responseText;
        xml = SoapHtmlDecode(xml);
        var parser = new DOMParser();
        doc = parser.parseFromString(xml, "text/xml");
        var nodes = doc.getElementsByTagName(methodName + "Result");
        var root = nodes[0].firstChild;
        var serializer = new XMLSerializer();
        var xml = serializer.serializeToString(root);
        return xml;
    }
}

function FillListboxByXml(listBox, xmlNode, codePath, valuePath, showCode) {
    var nodes = (xmlNode.length == null) ? xmlNode.selectNodes("node()") : xmlNode; //can be a nodelist already
    var N = nodes.length;
    var en = new Enumerator(nodes);
    var opts = listBox.options;
    //opts.clear();
    listBox.innerHTML = "";
    for (; !en.atEnd(); en.moveNext()) {
        var node = en.item();
        var code = GetNodeVal(node, codePath, ""); //GetNodeVal is in table.js
        var val = GetNodeVal(node, valuePath, code);
        if (showCode) val = code + ": " + val;
        var opt = new Option(code, val);
        opts.add(opt);
    }
    if (opts.length > 0) opts.selectedIndex = 0;
}

function GetCodeValueList(xmlNode, codePath, valuePath) {
    var nodes = (nodes.length == null) ? xmlNode.selectNodes("/.") : xmlNode;
    var N = nodes.length;
    var e = new Enumerator(nodes);
    var ret = new Array(N,2);
    var i=0;
    for (; !e.atEnd(); e.moveNext()) {
        var node = e.item();
        var code = GetNode(node, codePath, "");
        var val = GetNode(node, valuePath, code);
        //var pair = new Array(1,1);
        ret[i,0] = code;
        ret[i,1] = val;
        i++;
    }
    if (opts.length > 0) opts.selectedIndex = 0;
}

