﻿/*********************************************************************************
* ------------------------------------------------------------------------------ *
* AJAX.js                     Author: Jason Jurusz                      ver.3.31 *
* Initial Release: 11/13/04	                       Last Version Update: 09/04/10 *
* ------------------------------------------------------------------------------ *
* Change Log: Now supports Lazy and Strict success protocols (see examples), the *
* Request Object is ALWAYS dynamically created on the fly, callBack function is  *
* now required to be passed, and JSON objects are supported natively.            *
* ------------------------------------------------------------------------------ *
* Example:                                                                       *
*  - Posting to web service http://example.com/getAjaxData.php.                  *
*  - CallBack Function is handleAjaxResponse(JsonObj)                            *
*  - Expected format is {success:|BOOL|, userName:|STRING|, lastLogin:|STRING|}  *
*  - Lazy criteria is acceptable                                                 *
*                                                                                *
* Make the AJAX Call:                                                            *
*   var getAct = "http://example.com/getAjaxData.php?userId=123&pwd=ABCDEFG";    *
*   ajaxExec(getAct, 'handleAjaxResponse', false);                               *
* ------------------------------------------------------------------------------ *
*********************************************************************************/

/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ *
+	Method:			createRequestObject
+	Params:			none
+	Usage:			internal
+	Dependencies:	none
+	Creates a Request object, beginning with IE 5.5 and proceeding until success
*  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
function createRequestObject() {
	var ro; 																				// General Declarations
	try {																					// Attempt to...
		ro = new ActiveXObject("Msxml2.XMLHTTP"); 											// ... create a deprecated XMLHTTP object
	} catch (e) {																			// When that fails...
		try {																				// ... then we'll attempt to...
			ro = new ActiveXObject("Microsoft.XMLHTTP"); 									// ... create a slightly LESS deprecated XMLHTTP object
		} catch (e2) {
			ro = null;
		}
	}
	if (!ro && typeof XMLHttpRequest != "undefined") {										// Finally, after verifying the user's not on some ancient browser...
		ro = new XMLHttpRequest(); 															// ... create a MODERN XMLHTTP Request Object...
	}
	return ro; 																				// ... and return it.
}

/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ *
+	Method:			ajaxExec
+	Params:			STR: action: The web service URL with querystring params
+					STR: responseFunctionName: The method called with results
+					BOL: useStrict: 1 for Complete AND Success, 0 for Complete
+	Usage:			public
+	Dependencies:	createRequestObject
+	Executes the web service request and sets the event listeners up to fire the
+	specified method when the query is successful & results are obtained
*  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
function ajaxExec(action, responseFunctionName, useStrict) {
	var reqObj, rn; 																		// General Declarations
	useStrict	= (useStrict == undefined) ? true : useStrict; 								// Default transfer type to strict
	reqObj		= createRequestObject(); 													// Create our HTTP Request Object
	rn			= Math.floor(Math.random() * 999) + "=" + Math.floor(Math.random() * 999);	// Add a randomized QS param to prevent caching (XXX=YYY)
	action		= (action.indexOf("?") == -1) ? action + "?" + rn : action + "&" + rn; 		// Append it on to the supplied action parameter

	reqObj.open('get', action, true); 														// Open the HTTP connection
	if (useStrict == true) {																// If we're using a strict protocol...
		reqObj.onreadystatechange = function() {											// ... set the event handler ...
			strictResponse(reqObj, responseFunctionName); 									// ... to use strict readyState status checks.
		};
	} else {																				// Otherwise...
		reqObj.onreadystatechange = function() {											// ... set the event handler ...
			lazyResponse(reqObj, responseFunctionName); 									// ... to use lazy readyState status checks.
		};
	}

	reqObj.send(null);
}

/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ *
+	Method:			strictResponse
+	Params:			OBJ: reqObj: The response object itself
+					STR: responseFunctionName: The method called with results
+	Usage:			internal
+	Dependencies:	createRequestObject, ajaxExec
+	Fires the specified method when the ready state is complete and the status
+	was successful.
*  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
function strictResponse(reqObj, responseFunctionName) {
	if (reqObj.readyState == 4 && reqObj.status == 200) {									// If the readyState is 4 (complete) and status is 200 (successful)...
		var response = reqObj.responseText; 												// ... gather the response.
		if (response.indexOf("{") != -1 && response.indexOf("}") != -1) {					// If the response appears to be a JSON object...
			eval("response = " + response); 												// ... convert its type from STRING to OBJECT.
		}
		var evalStr = (responseFunctionName + "(response)");
		eval(evalStr); 																		// Call the specified response handler, passing it the recieved response.
	}
}

/* +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ *
+	Method:			lazyResponse
+	Params:			OBJ: reqObj: The response object itself
+					STR: responseFunctionName: The method called with results
+	Usage:			internal
+	Dependencies:	createRequestObject, ajaxExec
+	Fires the specified method when the ready state is complete
*  +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
function lazyResponse(reqObj, responseFunctionName) {
	if (reqObj.readyState == 4) {															// If the readyState is 4 (complete)...
		var response = reqObj.responseText; 												// ... gather the response.
		if (response.indexOf("{") != -1 && response.indexOf("}") != -1) {					// If the response appears to be a JSON object...
			eval("response = " + response); 												// ... convert its type from STRING to OBJECT.
		}
		var evalStr = (responseFunctionName + "(response)");
		eval(evalStr); 																		// Call the specified response handler, passing it the recieved response.
	}
}
