﻿function PerformWebMethod(methodName, parameterList, asynchronous, postFunction)
{
    if (asynchronous) {
        GeneralWebService.PerformWebMethod(methodName, parameterList,function(result) { SucceededCallbackWithContext(result, postFunction) },function(result) { FailedCallback(result, postFunction) }); 
    } else {
        return WebServiceSynchronousCall(methodName, parameterList);
    }
}

function SucceededCallbackWithContext(result, postFunction)
{   
    try {eval(postFunction +"("+result+")");} catch (err) {}
}

function FailedCallback(error)
{

}

function WebServiceSynchronousCall(method, parameters)
{
    var xr = null;
    if (window.XMLHttpRequest){ xr = new XMLHttpRequest();} // code for Mozilla
    else if (window.ActiveXObject){ xr = new ActiveXObject("Microsoft.XMLHTTP");} // code for IE
    
    // Create the SOAP Envelope
    var soap = "<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>" +
               "    <PerformWebMethod xmlns=\"http://tempuri.org/\">" + 
               "      <methodName>" + method + "</methodName>" +
               "      <parameterList><![CDATA[" + parameters + "]]></parameterList>" +
               "    </PerformWebMethod>" +
               "  </soap:Body>" +    
               "</soap:Envelope>";

    // Set up the POST
    // xr.onreadystatechange = some function... no need for it now
    xr.open("POST", "/Controls/GeneralWebService.asmx", false);
    xr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
    xr.setRequestHeader("SOAPAction", "http://tempuri.org/PerformWebMethod");
    xr.send(soap);
    var result = "";
    if (xr.readyState == 4) {                
        if (xr.status == 200) { //Successful Request
        var doc = xr.responseXML;
            if (doc.evaluate) { //XML Parsing in Mozilla
                result = doc.evaluate("//text()", doc, null, XPathResult.STRING_TYPE, null).stringValue;
            } else { //XML Parsing in IE (Prototype.Browser.IE)
                try {
                    result = doc.selectSingleNode("//text()").data;    
                } catch(e) {}
            }
        } else { //Error
            result = 'Fail';
        }
    }
    return result;
}
