﻿// JScript source code
//--CONSTANTS--------------------------------------------
var HTTP_STATUS_OK = 200;
var READYSTATE_COMPLETED = 4;

//--GLOBAL VARIABLES-------------------------------------
var requests = new Array();		//array to hold active HtmlRequest objects
requests[0] = null;

var divLevel = 1;               //current z-index to add divs at

//--HtmlRequest(obj, target, userFunction)----------------
// Class that holds a request object and the target HTML
// element that its return text should be loaded into. A
// optional parameter is the userFunction, which details a 
// function to be called once the HtmlRequest is complete.
//--------------------------------------------------------
function HtmlRequest(obj, target, userFunction) {
	this.obj = obj;
	this.target = target;
	//this.popupMsg = popupMsg;
	this.userFunction = userFunction;
}

//--readHTML(url, params, target, loadMsg, method, userFunction)--------
// This function is used to load straight HTML from the url into the
// target HTML element. This is used by any requests that do not need to
// parse the data returned from the server. URL is the url to send the
// information to, while the params are ampersand-delimited name-value
// pairs (ex. arg1=value1&arg2=value2). Method can be "GET" or "POST".
// The XMLHttpRequest is constructed depending on method chosen. loadMsg
// is the text to display in the target element while the XMLHttpRequest
// is being performed. userFuncton is an optional function to be called
// upon the XMLHttpRequest successfully completing.
// IMPORTANT:
// All parameters that need to be passed to the target page should be
// passed through the params argument. The url should NOT include any
// querystring variables.
//---------------------------------------------------------------------
function readHTML(url, params, target, loadMsg, method, userFunction) {
	//always add a random number parameter to the params list, to ensure
	//the XMLHttpRequest page requested is not a cached version.
	params = buildParamList(params, "rndm", getRandomInteger(0, 100000));
	
	var rIndex = requests.length;	//current request index, one past the end of the current requests array by default
	var req;	//local request variable
	if (loadMsg != "") {
		//if a non-empty loadMsg was passed in, display it in the target element
		document.getElementById(target).innerHTML = loadMsg;
	}
	for (var i=0; i<rIndex; i++) {
		//See if there are any empty array spots
		if (requests[i] == null) {
			//Empty array spot, use this spot instead of adding a new element to the end of the array
			rIndex = i;
			break;
		}
	}
	if (window.XMLHttpRequest) {
		//native XMLHttpRequest object
		req = new XMLHttpRequest();
		req.onreadystatechange = function () {readHTMLHandler();};
		//add req to the requests array before opening it, so it can be found by the
		//request handler (readHTMLHandler) later.
		objReq = new HtmlRequest(req, target, userFunction);
		requests[rIndex] = objReq;
		if (method.toLowerCase() == "post") {
			req.open("POST", url, true);
			req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			req.send(params);
		} else {
			req.open("GET", url + "?" + params, true);
			req.send(null);
		}
		
	} else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHttp");
		if (req) {
			req.onreadystatechange = function () {readHTMLHandler();};
			//add req to the requests array before opening it, so it can be found by the
			//request handler (readHTMLHandler) later.
			objReq = new HtmlRequest(req, target, userFunction);
			requests[rIndex] = objReq;
			if (method.toLowerCase() == "post") {
				req.open("POST", url, true);
				req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				req.send(params);
			} else {
				req.open("GET", url + "?" + params, true);
				req.send(null);
			}
			
		}
	}
}

//--readHTMLHandler()------------------------------------
// This function handles the data returned from the
// XMLHttpRequest object called by the readHTML function.
//-------------------------------------------------------
function readHTMLHandler() {
	//loop through all active requests to see if any are loaded
	for (var i=0; i<requests.length; i++) {
		if (requests[i] != null && requests[i].obj.readyState == READYSTATE_COMPLETED) {
			if (requests[i].obj.status == HTTP_STATUS_OK) {
				
				results = requests[i].obj.responseText;
				var target = requests[i].target;
				if (target != "") {
					//determine if this is an input element (form element: text, select, etc..)
					if (target.type) {
						//determine what type it is, so as to access it correctly
						if (target.type == "text" || target.type == "hidden") {
							target.value = results;
						} else if (target.type == "select-one" || target.type == "select-multiple") {
							//loop through the select and highlight the option whose value or text
							//matches the results
							for (var j=0; j<target.length; j++) {
								if (target[j].value == results || target[j].text == results) {
									target[j].selected = true;
								}
							}
						}
					} else {
						document.getElementById(requests[i].target).innerHTML = results;
					}
				}
				//see if there is a user defined funtion to run upon completion
				if (requests[i].userFunction) {
					//this protects from recursion. if the userFunction defined contains a function that calls
					//readHTML, then this part of the code will be reached by that call BEFORE this request is
					//set to null, thereby causing the userFunction to be executed again and again.
					var uf = requests[i].userFunction;
					requests[i] = null;
					eval(uf);
				} else {
					//remove object from requests array so it is not referenced again
					requests[i] = null;
				}
			} else {
				window.alert("Error reading from server:\n" + requests[i].obj.statusText);
				requests[i] = null;
			}
		}
	}
}

//--buildParamList(paramList, name, value)------------------------
// Takes an existing parameter list (or empty string) and appends
// a name/value pair to the string. e.g.
//		buildParamList("cid=1", "prod", "2");
// would return:
//		"cid=1&prod=2"
//----------------------------------------------------------------
function buildParamList(paramList, name, value) {
	if (paramList != undefined && paramList != "") {
		//not an empty list, so preface this name/value pair with an ampersand
		paramList += "&" + name + "=" + value;
	} else {
		//empty so far, add first parameter set
		paramList = name + "=" + value;
	}
	
	return paramList;
}

//--getRandomInteger(lBound, uBound)---------------------
// Returns a random integer between lBound and uBound.
//-------------------------------------------------------
function getRandomInteger(lBound, uBound) {
	var range = uBound - lBound;
	var rnd = (Math.random() * range) + lBound;
	rnd = Math.round(rnd);
	return rnd;
}