//********** GENERIC AJAX START *****************************
/** NOTES AND METHODS **
*************************
*** PROPERTIES
*************************

*   readystate :    (returns a 4-byte integer)
        0 ...Uninitialized  (created but open has not been called)
        1 ...Loading        (created but send has not been called)
        2 ...Loaded         (send has been called but status and headers are not available)
        3 ...Interactive    (some data has been received, calling responseBody and responseText properties at this state to obtain partial results will 
                                return an error, because status and response are not fully available)
        4 ...Completed      (All data has been received, and the complete data is available in the responseBody and responseText properties)
    
    responseBody:   (IE ONLY)(represents the response entity body as an array of unsigned bytes, namely as a SAFEARRAY of type VT_ARRAY | VT_UI1 contains raw
                        unencoded bytes as received directly from the server.  Therefore it may appear as binary-encoded data (UTF-8, UCS-2, UCS-4,
                        Shift_JIS, and so on)

    responseStream: (IE ONLY )(represents the response entity body as an IStream.  Stream returns the raw unencoded bytes as received directly from the server.
                        Therefore, depending on what the server sent it may appear as binary-encoded data (UTF-8, UCS-2, UCS-4, Shift_JIS, and so on)

    responseText:   (attempts to decode the response into a Unicode string.  It assumes the default encoding is UTF-8, but can decode any type 
                        UCS-2(big or little endian) or UCS-4 encoding as long as the server sends the appropriate Unicode byte-order mark.
                        It does NOT process the <? XML coding declaration.  If you know the response is going to be XML then use responseXML.

    responseXML:    (MS: default validation is turned off; If the response entity body is not valid XML, this property returns DOMDocument that was
                        parsed so that you can access the error.  This property does NOT return XMLDOMParseError itself but is accessible from
                        DOMDocument.  If the response is generated with ASP and the MIME type is not correctly set to "text/xml" using
                        Response.ContentType, responseXML will be empty.

    channel:        (Mozzila ONLY)

    status:         (Long integer, represents the returned status code as a long integer.  Valid only after the send method returns successfully.)
                    100     Continue                                        101     Switching protocols
                    200     OK                                              201     Created
                    202     Accepted                                        203     Non-Authoritative Information
                    204     No Content                                      205     Reset Content
                    206     Partial Content                                 300     Multiple Choices
                    301     Moved Permanently                               302     Found
                    303     See Other                                       304     Not Modified
                    305     Use Proxy                                       307     Temporary Redirect
                    400     Bad Request                                     401     Unauthorized
                    402     Payment Required                                403     Forbidden
                    404     Not Found                                       405     Method Not Allowed
                    406     Not Acceptable                                  407     Proxy Authentication Required
                    408     Request Timeout                                 409     Conflict
                    410     Gone                                            411     Length Required
                    412     Precondition Failed                             413     Request Entity Too Large
                    414     Request-URI Too Long                            415     Unsupported Media Type
                    416     Requested Range Not Suitable                    417     Expectation Failed
                    500     Internal Server Error                           501     Not Implemented
                    502     Bad Gateway                                     503     Service Unavailable
                    504     Gateway Timeout                                 505     HTTP Version Not Supported

    statusText:     (String. Represents the HTTP response as a BSTR value.  Valid only after the send method returns successfully)
    
*************************
** METHODS
*************************

    abort:  (Request is returned to the UNINITIALIZED state and open method must be called next)

    getAllResponseHeaders:  (Each header name/value pair is separated by a combination carriage return-line feed character(vbCrLf in MS VB)
                                valid only after send has successfully completed)

    getResponseHeader:  (Valid only after send method has successfully completed.  The line xmlhttp.getResponseHeader("Content-Type");, returns
                            the string "text/xml", assuming the server set "text/xml" as the content type.  The full list of available
                            header variables are in getAllResponseHeaders)
    
    open:   (syntax: xmlhttp.open(String method, String Url, boolean Async, String User, String Password)
                method  : http(s) only
                url     : URL to send the request
                async   : synchronous or asynchronous
                user    :   if necessary
                password:   if necessary
                After calling this method you must call send to send the request and data if any to the server.
                Even though this method accepts parameters for user / pass they are not automatically sent until the server sends back a 401

    send:   (This method is synchronous or asynchronous, depending on the value of bAsync parameter in the open method call.  bAsync can be true or false
                if its false this call does NOT return until the entire response is received or the protocol stack times out.  If true it returns
                immediately.  UTF-8 is assumed unless a Content-Type header with the appropriate content type is set.  If XML is sent UTF-8 is assumed unless 
                <? declaration for encoding is set.

    setRequestHeader:   (sets a variable and its value, if another of this name already exists its overridden.
                        setRequestHeader(String header, String value)

    overrideMimeType:   (can be used to override the type sent from the server.  Must be sent prior to send())
*************************
** EVENTS
*************************

    
*/
var xmlObj = null;
var thismsgbox = null;
var thisdataElement = null;
var thisreturnas = null;
var thistype = null;
var thisfunction = null;
var thisAfterProcess = null;
var thisdebug = null;
var formNamesArray = null;
var properFormArraySize = null;
var theseExceptions = null;

/**
*   uri                 Location of a path to a URL or a local File URI
*   requestType         GET or POST
*   msgboxForErrors     Location of error messages
*   returnedDataElement Where to post our information
*   responseReturnAs    xml or text
*   parseFunction       which function to use when parsing
*   formNames       required when requestType is POST this is an Array of form names
*   exceptions      optional form fields that you don't want to past in a POST
*   callAfterProcess    a function you would want to call after processing the parser
*   debug               show debug alerts   true or false
**/
function ajaxSendRequest(uri, requestType, msgboxForErrors, returnedDataElement, responseRtnAs, parseFunction, formNames, formSize, exceptions, callAfterProcess, debug){


    //Determine which type of Request to create
    if(xmlObj == null || xmlObj.readyState == 4) {
        setVariables(uri, requestType, msgboxForErrors, returnedDataElement, responseRtnAs, parseFunction, formNames, formSize, exceptions, callAfterProcess, debug);
    
        if(window.XMLHttpRequest){
            xmlObj = new XMLHttpRequest();
        } else if(window.ActiveXObject){
            xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            return;
        }
    
        xmlObj.onreadystatechange = eval(thisfunction);
    
        if(thistype == 'GET') {
            if(thisdebug == 'true') {
                alert("In GET");
            }
            xmlObj.open ('GET', uri, true);
            xmlObj.send (null);
        }
        else if (thistype == 'POST') {
            if(thisdebug == 'true') {
                alert("In POST");
            }
            
            xmlObj.open("POST", uri);
            xmlObj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xmlObj.send(getFormData(formNamesArray, theseExceptions, properFormArraySize, thisdebug));
        }
        uri = '';
	    requestType = '';
	    msgboxForErrors = '';
	    returnedDataElement = ''; 
	    responseRtnAs = '';
	    parseFunction = '';
	    formNames = new Array();
        formSize = 0;
	    exceptions = '';
        callAfterProcess = '';
	    debug = '';

        if(eval(thisAfterProcess) != null  && eval(thisAfterProcess) != '') {
            thisAfterProcess();
        }
    }
    else {
            setTimeout("ajaxSendRequest('"+uri+"', '"+requestType+"', '"+msgboxForErrors+"', '"+returnedDataElement+"', '"+responseRtnAs+"', '"+parseFunction+"', '"+formNames+"', '"+formSize+"','"+exceptions+"', '"+callAfterProcess+"','"+debug+"')", 1000);
    }
}




function setVariables(uri, type, msgbox, dataElement, returnas, retrieveFunction, formNames, formSize, exceptions, callAfterProcess, debug) {
    
   
    if(type != '') {
        thistype = type;
    }
    else {
        thistype = 'GET';
    }
    if(msgbox != '') {
        thismsgbox = msgbox;
    }
    else {
        //Show a modal box of data or some type of pop up message
        thismsgbox = '';
    }
    if(dataElement != '') {
        thisdataElement = dataElement;
    }
    else {
        thisdataElement = 'xmlObj';
    }
    if(returnas != '') {
        thisreturnas = returnas;
    }
    else {
        thisreturnas = 'text';
    }
    if(retrieveFunction != '') {
        thisfunction = retrieveFunction;
    }
    else {
        thisfunction = 'GET';
    }
    
    if(formNames != '') {
        formNamesArray = formNames;
    }
    else {
        formNamesArray = new Array();
    }
    
    if(formSize != '') {
        properFormArraySize = formSize;
    }
    else {
        properFormArraySize = formNames.length;
    }
    
    
    if(exceptions != '') {
        theseExceptions = exceptions;
    }
    else {
        theseExceptions = '';
    }
    
    if(callAfterProcess != '') {
        thisAfterProcess = callAfterProcess;
    }
    
    if(debug != '') {
        thisdebug = debug;
    }
    else {
        thisdebug = 'false';
    }
    if(thisdebug == 'true') {
        alert('URI: '+uri);
        alert('Type: '+type);
        alert('MsgBox: '+msgbox);
    }
}

function updateObj(obj, data) {
    if(thisdebug == 'true') {
        alert(data);
    }
   $(obj).firstChild.data = data;
}
function updateObjText(obj, data) {
    if(thisdebug == 'true') {
        alert(data);
    }
   $(obj).innerHTML = data;
}
function setErrorMessage(msgbox, message) {
    if(thisdebug == 'true') {
        alert(thismsgbox);
    }
    var userMessageElement = $(thismsgbox);
    userMessageElement.innerHTML = "<font color=\"red\">" + message + " </font>";
 }
//********** GENERIC AJAX END *****************************
