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 = false;                  // write output to the Activity Log
var _status_area;                    // will point to the area to write status messages to
var _option_mouseovercolor = "#CCCCCC";
var _select_backgroundcolor = "#FFFFFF";
var _input_class = "";
var _alertinput_class = "";


function processGetSuggestionList(myAJAX,divID,formID) {
    if (myAJAX.readyState == 4) {
        if (myAJAX.status == 200) {
			var airports = "";
			var response = decode(myAJAX.responseText);
			var form = $(formID);
			if (response.search("NORESULT") < 0) {
				var returnParms = response.split("|");
				for (var i = 0; i < returnParms.length; i++) {
					var value = returnParms[i];
					airports += "<option value=\"" + value + "\" onmouseover=\"this.style.backgroundColor='" + _option_mouseovercolor + "'\" onmouseout=\"this.style.backgroundColor=''\">" + value + "</option>";
	            }
				if (form) {
					//form.className = _input_class;
				}
				var obj = $(divID);
				if (obj) {
					obj.innerHTML = "<select id=\"sel_" + divID + "\" onchange=\"selectAirport('" + divID + "','" + formID + "',this);\" class=\"" + _input_class + "\" style=\"width:100%; background-color:" + _select_backgroundcolor + "\" size=\"10\">" + airports + "</select>";
					if (returnParms.length < 10)
						$("sel_" + divID).size = returnParms.length < 2 ? 2 : returnParms.length;
					obj.style.visibility = "visible";
					showSuggestionList = 0;
				}
			} else {
				if (form) {
					//form.className = _alertinput_class;
				}
				clearSuggestionList(divID);
			}
        } else {
            //alert("There was a problem retrieving the data:\n" + myAJAX.statusText);
        }
    }
}

/*
 * 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(divID,formID, 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.divID = divID;
	self.formID = formID;

    // 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);
        self.process(self.AJAX,self.divID,self.formID);
    }

    // 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 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;
}



// 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( estring ) {
    var hex = '0123456789ABCDEF';
    var encString = '';
    var e_char = '';
    var e_len = estring.length;

    for(var e_i = 0; e_i < e_len; e_i++ )    {
        e_char = parseInt( estring.charCodeAt( e_i ) );
        encString += '%' + hex.charAt( (e_char >> 4) % 16 ) + hex.charAt( e_char % 16 );
    }
    return encString;
}

function encode_orig( uri ) {
    if (encodeURIComponent) {
	  	return encodeURIComponent(uri);
    }

    if (escape) {
        return escape(uri);
    }
}

function decode( uri ) {
    if (unescape) {
        return unescape(uri);
    }
	if (decodeURIComponent) {
		return decodeURIComponent(uri);
    }
    return uri;
}

// log information to the status area textfield
function logger( text, clear ) {
    if (_logger) {
        if (!_status_area) {
            _status_area = document.getElementById("status_area");
        }

        if (_status_area) {
            if (clear) {
                _status_area.value = "";
            }

            var old = _status_area.value;
            _status_area.value = text + ((old) ? "\r\n" : "") + old;
        }
    }
}

function toggleLog( button ) {
	var disp=$('status_area').style.display;
	if ( disp == 'none' ) {
		$('status_area').style.display = 'block';
		button.value= 'Stop & Hide Log';
		_logger = true;
	} else {
		$('status_area').style.display = 'none';
		button.value= 'Show Log';
		_logger = false;
	}
}
