
var _ms_XMLHttpRequest_ActiveX = ""; // Holds type of ActiveX to instantiate
var _ajax;                           // Reference to a global XMLHTTPRequest object for some of the samples
var _logger = true;                  // write output to the Activity Log
var _status_area;                    // will point to the area to write status messages to

BASE_URL = "."

if (!window.Node || !window.Node.ELEMENT_NODE) {
    var Node = { ELEMENT_NODE: 1, ATTRIBUTE_NODE: 2, TEXT_NODE: 3, CDATA_SECTION_NODE: 4, ENTITY_REFERENCE_NODE: 5,
                  ENTITY_NODE: 6, PROCESSING_INSTRUCTION_NODE: 7, COMMENT_NODE: 8, DOCUMENT_NODE: 9, DOCUMENT_TYPE_NODE: 10,
              DOCUMENT_FRAGMENT_NODE: 11, NOTATION_NODE: 12 };
}

// From prototype.js @ www.conio.net | Returns an object reference to one or more strings
// ignore the fact that there are no arguments to this method -- javascript doesn't care how many you send (not strongly typed)
// The method checks the actual # of arguments -- returns a single object or an array
function $() {
    var elements = new Array();

    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];

        if (typeof element == 'string')
            element = document.getElementById(element);

        if (arguments.length == 1)
            return element;

        elements.push(element);
    }

    return elements;
}

// Method to get text from an XML DOM object
function getTextFromXML( oNode, deep ) {
    var s = "";
    var nodes = oNode.childNodes;

    for (var i = 0; i < nodes.length; i++) {
        var node = nodes[i];

        if (node.nodeType == Node.TEXT_NODE) {
            s += node.data;
        } else if (deep == true && (node.nodeType == Node.ELEMENT_NODE || node.nodeType == Node.DOCUMENT_NODE
                                       || node.nodeType == Node.DOCUMENT_FRAGMENT_NODE)) {
            s += getTextFromXML(node, true);
        };
    }

    ;
    return s;
}

;

// If you plan on doing anything outside of North America, then you'd better encode the things you pass back and forth
// the escape() method in Javascript is deprecated -- should use encodeURIComponent if available
function encode( uri ) {
    if (encodeURIComponent) {
        return encodeURIComponent(uri);
    }

    if (escape) {
        return escape(uri);
    }
}

function decode( uri ) {
    uri = uri.replace(/\+/g, ' ');

    if (decodeURIComponent) {
        return decodeURIComponent(uri);
    }

    if (unescape) {
        return unescape(uri);
    }

    return uri;
}

// log information to the status area textfield
function logger( text, clear ) {
    if (_logger) {
        if (!_status_area) {
            _status_area = document.getElementById("status_area1");
        }

        if (_status_area) {
            if (clear) {
                _status_area.value = "";
            }

            var old = _status_area.value;
            _status_area.value = text + ((old) ? "\r\n" : "") + old;
        }
    }
}


/*
 * AJAXRequest: An encapsulated AJAX request. To run, call
 * new AJAXRequest( method, url, async, process, data )
 *
 */

function executeReturn( AJAX ) {
    if (AJAX.readyState == 4) {
        if (AJAX.status == 200) {
            logger('AJAXRequest is complete: ' + AJAX.readyState + "/" + AJAX.status + "/" + AJAX.statusText);
        if ( AJAX.responseText ) {
            logger(AJAX.responseText);
            logger("----------------");
            //eval(AJAX.responseText);
        }
    }
    }
}

function AJAXRequest( method, url, data, process, async, dosend) {
    // self = this; creates a pointer to the current function
    // the pointer will be used to create a "closure". A closure
    // allows a subordinate function to contain an object reference to the
    // calling function. We can't just use "this" because in our anonymous
    // function later, "this" will refer to the object that calls the function
    // during runtime, not the AJAXRequest function that is declaring the function
    // clear as mud, right?
    // Java this ain't

    var self = this;

    // check the dom to see if this is IE or not
    if (window.XMLHttpRequest) {
    // Not IE
        self.AJAX = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
    // Hello IE!
        // Instantiate the latest MS ActiveX Objects
        if (_ms_XMLHttpRequest_ActiveX) {
            self.AJAX = new ActiveXObject(_ms_XMLHttpRequest_ActiveX);
        } else {
        // loops through the various versions of XMLHTTP to ensure we're using the latest
        var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP",
                        "Microsoft.XMLHTTP"];

            for (var i = 0; i < versions.length ; i++) {
                try {
            // try to create the object
            // if it doesn't work, we'll try again
            // if it does work, we'll save a reference to the proper one to speed up future instantiations
                    self.AJAX = new ActiveXObject(versions[i]);

                    if (self.AJAX) {
                        _ms_XMLHttpRequest_ActiveX = versions[i];
                        break;
                    }
                }
                catch (objException) {
                // trap; try next one
                } ;
            }

            ;
        }
    }

    self.status = 0;
    self.readyState = 0;
    self.responseText = ""

    var requestTimer = setTimeout(function() {
       self.AJAX.abort();
       // Handle timeout situation
       self.status = 200;
       self.readyState = 4;
       self.responseText = "timeout"
       self.process(self);
    }, 90 * 1000);


    // if no callback process is specified, then assing a default which executes the code returned by the server
    if (typeof process == 'undefined' || process == null) {
        process = executeReturn;
    }

    self.process = process;

    // create an anonymous function to log state changes
    self.AJAX.onreadystatechange = function( ) {
        //logger("AJAXRequest Handler: State =  " + self.AJAX.readyState);
        if (self.AJAX.readyState == 4) {
            clearTimeout(requestTimer);
        }
        self.process(self.AJAX);
    }

    // if no method specified, then default to POST
    if (!method) {
        method = "POST";
    }

    method = method.toUpperCase();

    if (typeof async == 'undefined' || async == null) {
        async = true;
    }

    logger("----------------");
    logger("AJAX Request: " + ((async) ? "Async" : "Sync") + " " + method + ": URL: " + url + ", Data: " + data);

    self.AJAX.open(method, url, async);

    if (method == "POST") {
        //self.AJAX.setRequestHeader("Connection", "close");
        self.AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        self.AJAX.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
    }

    if (method == "FILE") {
        self.AJAX.setRequestHeader("Connection", "close");
        self.AJAX.setRequestHeader("Content-Type", "multipart/form-data");
        self.AJAX.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
    }

    // if dosend is true or undefined, send the request
    // only fails is dosend is false
    // you'd do this to set special request headers
    if ( dosend || typeof dosend == 'undefined' ) {
        if ( !data ) data="";
        self.AJAX.send(data);
    }
    return self.AJAX;
}


function getFormData( value, dataset, target, parm2, parm3 ) {
    return new AJAXRequest( "POST", BASE_URL + "/servlet/get_formdata", "dataset=" + dataset + "&target=" + target + "&value=" + value );
}

// build a string containing every field on the passed form
// skip disabled controls
function clearFormValues( form ) {
    form = $(form);
    var field = "";
    var value = "";
    var valueString = "";
    var replaceID = "";
    var parentNode = form.parentNode;

    for (var i = 0; i < form.elements.length; i++) {
        var field = form.elements[i];

        if (field.type == "button" || field.type=="submit") {
            // do nothing
        }
        else {

            if (!field.disabled) {
                value = '';
                if (field.type == 'checkbox') {
                    if (field.checked) {
                        field.checked = false;
                    }
                }
                else if (field.type == 'radio') {
                    if (field.checked) {
                        field.checked = false;
                    }
                }
                else if (field.type == 'select-one') {
                    field.value = '';
                }
                else {
                    field.value = '';
                }

            }
        }
    }

    return;
}


function getFormValues( form ) {
    form = $(form);
    var field = "";
    var value = "";
    var valueString = "";
    var replaceID = "";
    //var parentNode = form.parentNode;

    for (var i = 0; i < form.elements.length; i++) {
        var field = form.elements[i];

        if (field.type == "button" || field.type=="submit") {
            // do nothing
        }
        else {

            if (!field.disabled) {
                value = '';
                if (field.type == 'checkbox') {
                    if (field.checked) {
                        value = field.value;
                        valueString += ((valueString != '') ? '&' : '') + field.name + '=' + encode(value);
                    }
                }
                else if (field.type == 'radio') {
                    if (field.checked) {
                        value = field.value;
                        valueString += ((valueString != '') ? '&' : '') + field.name + '=' + encode(value);
                    }
                }
                else if (field.type == 'select-one') {
                    value = field.value;
                    valueString += ((valueString != '') ? '&' : '') + field.name + '=' + encode(value);
                }
                else {
                    value = field.value;
                    valueString += ((valueString != '') ? '&' : '') + field.name + '=' + encode(value);
                }

            }
        }
    }

    return valueString
}

function loading (id)
{
    if ($("loadingimage") != null) {
        if ($(id) != null) {
            $(id).innerHTML = $("loadingimage").innerHTML;
        }
        return;
    }

    $(id).innerHTML = '<img style="display:none;" width="0" height="0" id="'+id+'img" src="/images/loading.gif" border="0">';
    $(id+'img').style.width  = '59px';
    $(id+'img').style.height = '17px';
    $(id+'img').src = '/images/loading.gif';
    $(id+'img').style.display = 'block';

}


function clearloading (id)
{
    if ($(id) != null) {
        $(id).innerHTML = '';
    }
    return;
}

///////////////////////////////////////////////////////////////////////////////
//
// An AJAX class that wraps the functions above
//
//
// new ajaxit;
// ajaxit.thePage = "";
// ajaxit.params = "";
//
// new ajaxit.request("serverfunction",function(r) { alert(r); }; );
//
///////////////////////////////////////////////////////////////////////////////

function ajaxit(p)
{

    this.setDefault = function(p)
    {
        thePage=unescape(window.location.href)
        if(thePage.indexOf('?') != -1) {
            thePage=thePage.substring(0,thePage.indexOf('?'))
        }

        this.thePage = (typeof(p)!="undefined" && "thePage" in p) ? p.thePage : thePage;
        this.statusid = (typeof(p)!="undefined" && "statusid" in p) ? p.statusid : "";
        this.statusHTML = (typeof(p)!="undefined" && "statusHTML" in p) ? p.statusHTML : "<img src=\"sysimages/workingwheel.gif\" width=\"16\" height=\"16\" >";
        this.autoClear = (typeof(p)!="undefined" && "autoClear" in p) ? p.autoClear : 0;
    }

    this.thePage = "";
    this.statusid = "";
    this.statusHTML = "";
    this.autoClear = 0;

    this.setDefault (p);

}

ajaxit.prototype.request = function(sfn,p,cfn)
{
    var self = this;

    p = p.replace(/\&\=/gi,"");
    p = p + "&ajaxsfn=" + encode(sfn);

    if (self.statusid != "") {
        self.status (self.statusHTML);
    }

    return new AJAXRequest("post", this.thePage, p,
       function ( AJAX )
        {
            if (AJAX.readyState == 4) {

                if (AJAX.status != 200) {
                    self.status (AJAX.responseText);
                }
                else {

                    if (self.statusid != "" && parseInt(self.autoClear) == 0) {
                        ajaxitclearstatus(self.statusid);
                    }

                    if (typeof(cfn) != "undefined" && cfn) {
                        cfn(AJAX.responseText);
                    }

                    if (self.statusid != "" && parseInt(self.autoClear) > 0) {
                        setTimeout("ajaxitclearstatus('"+self.statusid+"')",self.autoClear);
                    }
                }

            }
        }, true);
};

ajaxit.prototype.status = function(s)
{
    if (this.statusid != "" && $(this.statusid)) {
        $(this.statusid).innerHTML = s;
    }
};


function ajaxitclearstatus(id)
{
    if (id != "") {
        $(id).innerHTML = "";
    }
}

