﻿/*-------------------------------------------------------------------------------------------------
 <project>
 SunGardHE.AWC
 </project>
 <file>
 AWCAjax.js
 </file>
 <company>
 Advancement Solutions, SunGard Higher Education
 http://www.sungardhe.com
 </company>
 <copyright>
  
 Copyright (c) 2003-2007 
 All Rights Reserved.
 
 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 
 OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.
</copyright>
<summary>
 AWC AJAX WebFramework
 Supported Browsers: IE 6.0+, Opera 8+, Mozilla based browsers 
</summary>
<history>   
 Developer	Date		Version	Change
 --------------------------------------------------------------------------------------------------
 Sweatt     10/22/2007  1.1.0.0 Initial Creation
 --------------------------------------------------------------------------------------------------
</history> 
----------------------------------------------------------------------------------------------------*/
var WEB = {
    DOM         : Object,
    AJAX        : Object,
    Collection  : Object
};
/*----------------------------------------------------------------------------------------------------
  WEB.DOM                                                                                                                 
----------------------------------------------------------------------------------------------------*/
// <name>
//  WEB.DOM.isIE
// </name>
// <summary>
//  Boolean variable for determining if the client browser is Internet Explorer.
// </summary>
// <returns>True if the client browser is Internet Explorer, otherwise false</returns>
// <example>
//  if(WEB.DOM.isIE){
//      alert("You're using IE");
//  }
// </example>
WEB.DOM.isIE = (navigator.userAgent.indexOf("MSIE") >= 0);
// <name>
//  WEB.DOM.isMozilla
// </name>
// <summary>
//  Boolean variable for determining if the client browser is Mozilla.
// </summary>
// <returns>True if the client browser is Mozilla, otherwise false</returns>
// <example>
//  if(WEB.DOM.isMozilla){
//      alert("You're using Mozilla");
//  }
// </example>
WEB.DOM.isMozilla = (navigator.userAgent.indexOf("Gecko") >= 0);
// <name>
//  WEB.DOM.isOpera
// </name>
// <summary>
//  Boolean variable for determining if the client browser is Opera.
// </summary>
// <returns>True if the client browser is Opera, otherwise false</returns>
// <example>
//  if(WEB.DOM.isOpera) {
//      alert("You're using Opera");
//  }
// </example>
WEB.DOM.isOpera = (navigator.userAgent.indexOf("Opera") >= 0);
// <name>
//  WEB.DOM.isFirefox
// </name>
// <summary>
//  Boolean variable for determining if the client browser is Firefox.
// </summary>
// <returns>True if the client browser is Firefox, otherwise false</returns>
// <example>
//  if(WEB.DOM.isFirefox) {
//      alert("You're using Firefox");
//  }
// </example>
WEB.DOM.isFirefox = (navigator.userAgent.indexOf("Firefox") >= 0);
/*----------------------------------------------------------------------------------------------------
  WEB.Collection                                                                                                                
----------------------------------------------------------------------------------------------------*/
// <name>
//  WEB.Collection.Mapping
// </name>
// <summary>
//  Map class for holding key value pairs.
// </summary>
// <returns>The new WEB.Collection.Mapping object.</returns>
// <example>
//  var m = new WEB.Collection.Mapping();
//  m.add("name1","value1");
//  m.add("name2","value2");
//  alert( m.get("name1") ); //alerts "value1"
// </example>
WEB.Collection.Mapping = function() {
    var len     = 0;
    var keys    = new Array();
    var values  = new Array();
    // <name type="function">
    //  WEB.Collection.Mapping.get
    // </name>
    // <summary>
    //  Method for returning the value associated with a key.
    // </summary>
    // <param name="key">The key to return the associated value of.</param>
    // <returns>The value associated with the key.</returns>
    // <example>
    //  var m = new WEB.Collection.Mapping();
    //  m.add("name1","value1");
    //  m.add("name2","value2");
    //  alert( m.get("name1") ); //alerts "value1"
    // </example>
    this.get = function(key) {
        var val = null;
        for (var index = 0; index < len; index++) {
            if (keys[index] == key) {
                val = values[index];
                break;
            }
        }
        return val;
    }
    // <name type="function">
    //  WEB.Collection.Mapping.put
    // </name>
    // <summary>
    //  Method for storing an associated key value.
    // </summary>
    // <param name="key">The key to associate with the value.</param>
    // <param name="value">The value associated with the key.</param>
    // <example>
    //  var m = new WEB.Collection.Mapping();
    //  m.add("name1","value1");
    //  m.add("name2","value2");
    //  alert( m.get("name1") ); //alerts "value1"
    // </example>
    this.put = function(key, value) {
        keys[len]       = key;
        values[len++]   = value;
    }
    // <name type="function">
    //  WEB.Collection.Mapping.length
    // </name>
    // <summary>
    //  Method for returning the count of items in the map.
    // </summary>
    // <returns>The count of items in the map.</returns>
    // <example>
    //  var m = new WEB.Collection.Mapping();
    //  m.add("name1","value1");
    //  m.add("name2","value2");
    //  alert( m.length ); 
    //  alerts 2
    // </example>
    this.length = function() {
        return len;
    }
    // <name type="function">
    //  WEB.Collection.Mapping.contains
    // </name>
    // <summary>
    //  Method for determining if the map contains a specific key.
    // </summary>
    // <param name="key">The key to search for.</param>
    // <returns>True if the map contains the key, otherwise false.</returns>
    // <example>
    //  var m = new WEB.Collection.Mapping();
    //  m.add("name1","value1");
    //  m.add("name2","value2");
    //  alert( m.contains("name1") ); //alerts true
    // </example>
    this.contains = function(key) {
	    var doesContain = false;
        for(var index = 0; index < len; index++) {
            if(keys[i] == key) {
                doesContain = true;
                break;
            }
        }
        return doesContain;
    }
    // <name type="function">
    //  WEB.Collection.Mapping.remove
    // </name>
    // <summary>
    //  Method for removing a key value pair by key name.
    // </summary>
    // <param name="key">The key to search for.</param>
    // <example>
    //  var m = new WEB.Collection.Mapping();
    //  m.add("name1","value1");
    //  m.add("name2","value2");
    //  m.remove("name1");
    //  alert( m.contains("name1") ); //alerts false
    // </example>
    this.remove = function(key) {
        var keyArrays   = new Array();
        var valueArrays = new Array();
        var i           = 0;
        for (var index = 0; index < len;  index++) {
            if (keys[index] != key) {
                keyArrays[i]        = keys[index];
                valueArrays[i++]    = values[index];
            }
        }
        keys    = keyArrays;
        values  = valueArrays;
	    len     = i;
    }
}
/*----------------------------------------------------------------------------------------------------
  WEB.AJAX                                                                                                               
----------------------------------------------------------------------------------------------------*/
// <name>
//  WEB.AJAX
// </name>
// <summary>
//  Class for performing AJAX.
//  Developer Note: .NET WebService Methods must be tagged with [SoapRpcMethod, WebMethod] 
//  for parameters to be passed using Mozilla based browsers.
// </summary>
// <returns>The new WEB.AJAX object.</returns>
// <example>
//  var ajax = new WEB.AJAX();
//  function ajaxCallPostBack(content){
//      alert(content); //displays the contents of the page.
//  }
//  ajax.callWebPage("myPage.html", ajaxCallPostBack); //call myPage.html and pass the contents to ajaxCallPostBack.
// </example>
WEB.AJAX = function() {
    var nameSpace = "http://tempuri.org/";
    var map = new WEB.Collection.Mapping();
    // private method for returning an ajax enabled object specific to a browser
    var ajaxObject = function() {
        try {
            return new XMLHttpRequest();
        } catch(ex){};
        try {
            return new ActiveXObject("Microsoft.XMLHTTP");
        } catch(ex){};
        try {
            return new SOAPCall();
        } catch(ex){};
    }
    // <name type="function">
    //  WEB.AJAX.onError
    // </name>
    // <summary>
    //  Method for handling ajax errors.
    // </summary>
    // <example>
    //  var ajax = new WEB.AJAX();
    // 
    //  function ajaxCallPostBack(content) {
    //      alert(content); //displays the contents of the page
    //  }
    //  function ajaxError(error) {
    //      alert(error); //alert the error
    //  }
    //  ajax.onErrror = ajaxError; //assign error handler
    //  ajax.callWebPage("myPage.html", ajaxCallPostBack); //call myPage.html and pass the contents to ajaxCallPostBack</example>
    this.onError = function(error) {
        alert(error);
    }
    // <name type="function">
    //  WEB.AJAX.callWebPage
    // </name>
    // <summary>
    //  Method for calling a page using AJAX.
    // </summary>
    // <param name="Url">The url of the page to call.</param>
    // <param name="CallPostbackFunction">The function to call when the AJAX call succeeds.</param>
    // <param name="Method">(Optional) supports GET or POST, default is GET</param>
    // <param name="Arguments">(Optional) POST arguments.</param>
    // <param name="ActionMethod">(Optional) Action Method Type, numeric</param>
    // <param name="Async">(Optional) Specify XML Doument or Plain Text default is 1 = xml, 2 = text </param>
    // <param name="Async">(Optional) Specify synchronous/asynchronous mode, default is true.</param>
    // <example>
    //  var ajax = new WEB.AJAX();
    // 
    //  function ajaxCallPostBack(content){
    //      alert(content); //displays the contents of the page.
    //  }
    //  ajax.callWebPage("myPage.html", ajaxCallPostBack); //call myPage.html and pass the contents to ajaxCallPostBack.
    // </example>
    this.callWebPage = function(Url, CallPostbackFunction, Method, Arguments, ActionMethod, XmlText, Async) {        
        try {
            var ajax = ajaxObject();
            if (!XmlText || XmlText == null) 
                XmlText = 1;
                
            ajax.onreadystatechange = function() {
                if (ajax.readyState == 4) {
                    // To make sure valid response is received from the server, 200 means response received is OK
                    if (ajax.status == 200) {
                        if (!ActionMethod || ActionMethod == null) {
                            if (XmlText == 1)
                                CallPostbackFunction(ajax.responseXML.documentElement);
                            else if (XmlText == 2)
                                CallPostbackFunction(ajax.responseText);
                        } else {
                            if (XmlText == 1)
                                CallPostbackFunction(ActionMethod, ajax.responseXML.documentElement);
                            else if (XmlText == 2)
                                CallPostbackFunction(ActionMethod, ajax.responseText);
                        }
                        //ajax.readyState == "complete"
                    }
                }
            };                
            if (!Method || Method == null) 
                Method = "GET";
            if (!Arguments || Arguments == null) 
                Arguments = null;
            if (Async == null) 
                Async = true;
                
            ajax.open(Method, Url, Async);
            if (Method == "POST")
                ajax.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                
            ajax.send(Arguments);
        } catch(ex) {
            this.onError(ex);
        }
    }
    // <name type="function">
    //  WEB.AJAX.callWebService
    // </name>
    // <summary>
    //  Method for calling a webservice using AJAX.
    // </summary>
    // <param name="serviceUrl">The url of the service to call.</param>
    // <param name="soapMethod">The method of the service to call.</param>
    // <param name="callPostbackFunction">The function to call when the AJAX call succeeds.</param>
    // <param name="param1, param2 ... paramN">Optional parameters passed to the webservice.  
    //  Parameters must be in the 
    //  form of "name=value".</param>
    // <example>
    //  var ajax = new WEB.AJAX();
    // 
    //  function ajaxCallPostBack(content) {
    //      alert(content); //displays the contents of the page.
    //  }
    //  ajax.callWebService("http://myserver.com/myService.asmx", "myMethod", ajaxCallPostBack); //call myService.asmx and pass the contents to ajaxCallPostBack.
    // </example>
    this.callWebService = function(serviceUrl, soapMethod, callPostbackFunction /*, unlimited params */) {
        var callServiceError = this.onError;
        var ajax = ajaxObject();
        if (!ajax.encode) {
            if(serviceUrl.indexOf("http://") < 0)
                serviceUrl = "http://" + serviceUrl;
                
            serviceUrl += "?WSDL";
            
            var soapEnvelope = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
            soapEnvelope += "<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/\">";
            soapEnvelope += "<soap:Body>";
            soapEnvelope += "<" + soapMethod + " xmlns=\"" + nameSpace + "\">";
            
            if (arguments.length > 3) {
                for (var index = 3; index < arguments.length; index++) {
                    var params = arguments[index].split("=");
                    soapEnvelope += "<" + params[0] + ">";
                    soapEnvelope += params[1];
                    soapEnvelope += "</" + params[0] + ">";
                }
            }			
            soapEnvelope += "</" + soapMethod + ">";
            soapEnvelope += "</soap:Body>";
            soapEnvelope += "</soap:Envelope>";
            
            ajax.onreadystatechange = function() {
                if (ajax.readyState == 4) {
                    if (WEB.DOM.IsOpera) {
                        //opera
                        var response = ajax.responseXML.getElementsByTagName(soapMethod + "Result")[0];
                        if (!response)
                            response = ajax.responseXML.getElementsByTagName(soapMethod + "Response")[0];
                        if (!response) {
                            callServiceError("WebService does not contain a Result/Response node");
                            return;
                        }
                        ajax.callPostbackFunction(ajax.responseXML.getElementsByTagName(soapMethod + "Result")[0].innerHTML);
                    } else if (WEB.DOM.isIE) {
                        //IE
                        var responseXml = new ActiveXObject('Microsoft.XMLDOM');
                        responseXml.loadXML(ao.responseText);
                            
                        var responseNode = responseXml.selectSingleNode("//" + soapMethod + "Response");
                        if(!responseNode)
                            responseNode = responseXml.selectSingleNode("//" + soapMethod + "Result");
                        if(!responseNode)
                            callServiceError("Response/Result node not found.\n\nResponse:\n" + ajax.responseText);
                            
                        var resultNode = responseNode.firstChild;
                        if (resultNode != null) {
                            try {
                                callPostbackFunction(resultNode.text);
                            } catch(ex) {
                                callServiceError(ex);
                            }
                        } else {
                            try {
                                callPostbackFunction();
                            } catch(ex) {
                                callServiceError(ex);
                            }
                        }
                    } else if (WEB.DOM.isMozilla) {
                        //Mozilla
                        var xmlDocument = new DOMParser().parseFromString(ajax.responseText, "text/xml");
                        
                        var xr = xmlDocument.evaluate("//" + soapMethod + "Result", xmlDocument.childNodes[xmlDocument.childNodes.length-1], null, XPathResult.ANY_TYPE, null);
                        var responseNode = xr.iterateNext();
                        
                        if(!responseNode)
                            callServiceError("Response/Result node not found.\n\nResponse:\n" + ajax.responseText);
                        
                        var resultNode = responseNode.firstChild;
                        if (resultNode != null) {
                            try {
                                callPostbackFunction(resultNode.textContent);
                            } catch(ex) {
                                callServiceError(ex);
                            }
                        } else {
                            try {
                                callPostbackFunction();
                            } catch(ex) {
                                callServiceError(ex);
                            }
                        }
                    }
                }
            };
            ajax.open("POST", serviceUrl, true);			
            ajax.setRequestHeader("Content-Type", "text/xml");
            ajax.setRequestHeader("SOAPAction", nameSpace + soapMethod);
            try{
                ajax.send(soapEnvelope);
            } catch(ex) {
                serviceCallError(ex);
            }
        } else {
            var soapParams  = new Array();
            var headers     = new Array();
            var soapVersion = 0;
            var object      = nameSpace;
            
            if (serviceUrl.indexOf("http://") < 0)
                serviceUrl = document.location + serviceUrl;
            
            ajax.transportURI   = serviceUrl;
            ajax.actionURI      = nameSpace + soapMethod;
            
            for (var index = 3; index < arguments.length; index++){
                var params = arguments[index].split("=");
                soapParams.push(new SOAPParameter(params[1], params[0]));
            }
            try {
                ajax.encode(soapVersion, soapMethod, object, headers.length, headers, soapParams.length, soapParams);
            } catch(ex) {
                serviceCallError(ex);
            }
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
            } catch(ex) {
                return false;
            }
            try {
                ajax.asyncInvoke(
                    function (response, call, status) {
                        if (response.fault)
                            return callServiceError(response.fault);
                        if (!response.body) 
                            callServiceError("Service " + call.transportURI + " not found.");
                        else {
                            try {
                                callPostbackFunction(response.body.firstChild.firstChild.firstChild.data);
                            } catch(ex) {
                                callServiceError(ex);
                            }
                        }
                    }
                );
            } catch(ex) {
                serviceCallError(ex);
            }
        }
    }
    // <name type="function">
    //  WEB.AJAX.setNameSpace
    // </name>
    // <summary>
    //  Method for setting the name space of the service call.
    // </summary>
    // <param name="ns">The service name space.</param>
    // <example>
    //  var ajax = new WEB.AJAX();
    // 
    //  function ajaxCallPostBack(content) {
    //      alert(content); //displays the contents of the page.
    //  }
    //  ajax.setNameSpace("mynamespace");
    //  ajax.callWebPage("myService.asmx", "myMethod", ajaxCallPostBack); //call myService.asmx and pass the contents to ajaxCallPostBack
    // </example>
    this.setNameSpace = function(ns) {
        nameSpace = ns;
    }
    // <name type="function">
    //  WEB.AJAX.getNameSpace
    // </name>
    // <summary>
    //  Method for returning the name space of the service call.
    // </summary>
    // <returns>The namespace of the service call.</returns>
    // <example>
    //  var ajax = new WEB.AJAX();
    // 
    //  function ajaxCallPostBack(content) {
    //      alert(content); //displays the contents of the page.
    //  }
    //  var ns = ajax.getNameSpace(); //returns the name space
    //  ajax.callWebPage("myService.asmx", ajaxCallPostBack); //call myService.asmx and pass the contents to ajaxCallPostBack
    // </example>
    this.getNameSpace = function() {
        return ns;
    }
}

