
	// bluntAjax
	//		A simple and dirty little Ajax Processor that handles multiple, simultanious AJAX requests
	//		You should read this documentation in it's entirety to understand the use of this script
	//		It ain't that long anyway.
	
	/*
	*********************************************************************
	*                                                                   *
	*    NO WARRANTY                                                    *
	*    This code is provided "as is" without warranty of any kind,    *
	*    either expressed or implied, including, but not limited to,    *
	*    the implied warranties of merchantability and fitness for a    *
	*    particular purpose.                                            *
	*	                                                                  *
	*    You expressly acknowledge and agree that use of this code      *
	*    is at your own risk.                                           *
	*                                                                   *
	*********************************************************************
	*/
	
	// version 3.0.2
	// 20090630
	//		Removed a minor bug that caused a warning to be thrown when calling
	//		getElementById using an empty string (parameters) from wt3Modal class
	
	// version 3.0.1
	// 20090629
	//		Removed a bug that set both the div and the pass value to the value of
	//		the div or pass value parameters
	
	// version 3.0.0
	// 20090418
	// (NOTE: This version is not compatable with previous versions - was called "hajax")
	// rewitten to clean up and make calling easier by allowing parameters to be specified in any order
	//		and allowing for not including parameters that are not used
	// also renamed file and class to prefix with blunt to be more consistant with my other scripts
	// removed blocking of multiple requests, blocking of multiple requests is better accomplished with a
	// 		window disabler or modal window of some kind that prevents clicking of window objects
	// Once again tried to rewrite this to use true OOP, but there are serious problems passing parameters
	//		especially when it comes to onReadyStateChange passing to the function handleRequestStateChange()
	//		only the first state change is reported and the function does not return correclty
	//		something about "this" not passing by reference properly. I may sort this out in a future update.
	//		But since this class seems to function efficiantly now with this new version, it's not likely to be changed
	//		again unless it stops working in some future browser. The error comes down to the fact that JS does not pass
	//		variables by reference. I would need to create a hack where by the object "this" was passed to an outside function
	//		which would then be passed back to an internal function. For an example of this see the resize function of the
	//		diable class. Again, unless there is some pressing need to correct this, it won't be corrected.
	
	// for debuging, errors are alerted
	// set to false for operation
	var bluntAjaxDebug = true;
		// note, also displays development errors in modal class
	
	/*
		USAGE:
			
			As stated above, this is a major revision to the AJAX class. Allowing and blocking multiple requests has been completely removed. Rather than creating a hack in this new version a window disabler or modal widow setup should be used that disable the entire window during an AJAX call if you wish to block multiple simultanious requests. I have also tried to streamline the call to run the class so that only the parameters that are needed have to be used. With this version you can call ajax with any parameters in any order (except for the server file) and the class will detect what type of variables you have passed in and apply it to the correct parameter. Obviously, this means that there are some restrictions placed on what types of varaibles you can pass. See an explanation of each parameter. Each parameter listed below also lists what will happen if that parameter is not supplied.
		
		DEBUGING:
		
				For debugging purposes set the variable bluntAjaxDebug (located near the top of this script ^^ up there ^^) to true. This will cause any errors produced to be alerted with a JavaScript alert. Setting this vaue to false will cause bluntAjax to ignore all errors in operation. Once deployed an application should be error free and it is assumed that we don't want to display errors to a visitor.
			
		PARAMETERS
			
			As stated, any of the following parameters, with the exception of the URL parameter, may be included in the call or not and they may be included in any order. There is no need to supply a parameter that you are not using. Nor is it necessary to provide empty parameters to get to the ones you want to use like the last version, for example: bluntAjax('/page.html', '', '', 'POST');
			The URL parameter is the only required parameter and it must be the first parameter supplied.
			
			URL:
					URL is now the only required parameter. This is the url to the page on the server that ajax will call when making the request. A simple ajax call would look like the below statement. What happens when the server response is received depends on the other parameters that are passed.
					bluntAjax('http://mysite.com/mypage.html');
			
			Callback Function:
					If supplied, this will be the function that is called when a response is received from the server. If no function is provided then the default callback function is called. Below you will find an explanation of how to create a function for ajax to return a server response to as well as a list/explanation of the parameters that will be passed to that function. As bluntAjax is reading through the parameters it checks to see if any of them are actually a function. If it detects that the variable passed is a function then it applies the varaible to the call function. 
							The default call function:
									As stated previously, this new version of bluntAjax is designed with simpler operation in mind so that it can be used more easily and efficiantly. It is assumed that, in most cases, the default callback function will be used. This default function expects a single type of data to be returned from the server, a text string. This text string can be just plain text or in the form of (X)HTML (both are text). If an HTML element ID is specified when calling bluntAjax (see Element ID below) then whatever is returned is put into that element. If an element is not specified then whatever is returned will simply be displayed in a JavaScript alert message.
									
									A note about innerHTML:
											The innerHTML attribute is used to insert returned data into the element specified.
											innerHTML has some know issues that pertain to tables. innerHTML will break if you try to
											insert table elements into a table. For instance, let's say that you have a table with an
											id of "myTable" and the returned data is a <tr> element. Trying to insert the <tr> into the
											<table> will likely fail. However, inserting an entire table that starts with <table> and
											ends with </table> into another element usually works. Also, inserting HTML into a <td> element
											will work. This is just a problem with inserting <tr> into <table> or <td> into <tr>
			
			Call Method:
					Call method may be either 'GET' or 'POST'. bluntAjax looks at all string type variables and if a case insensitive match is made against either of these two values then the varaiable is used for the method. The default method is POST as I find this more secure and to my liking. The only reason you need to specify this parameter is if you want to use the GET method.
					
					Strings can cause the most dificulty when calling bluntAjax. Four of the parameters can be strings and method is one of these parameters. It is important not to use values that can look like these other parameters. For instance, it would not be a good idea to use an HTML element ID of 'post' or 'get' as these would be confused with the method argument.
			
			Server Paremeters:
					These are values that are to be sent to the server with the request. You must supply these parametes in the form of a Query String with varaible/value pairs, for example 'id=8&page=1'. bluntAjax will look at your string and if it finds the character "=" anywhere in the string then the value is assumed to be server parameters and the value will be assigned to the bluntAjax parameter. None of the other parameters should legally contain the "=" character, except for maybe the pass parameter. See that parameter for a discussion on the best method of using it.
					Not supplying server parameters simply means that no parameters will be sent to the sever.
			
			HTML Element ID
					bluntAjax detects if you are passing an HTML Element ID by testing to see if that Element ID exists in the current document. If it finds an element with the given id then the value is applied to this parameter. For this reason it would not be wise to pass a value to this parameter that is the same as the id of any element in the page unless it is the element you want your data inserted into.
			
			Pass:
					Anything not mentioned above will be considered a Pass Parameter. Whatever is supplied here will be "passed" to the callback function unaltered. Obviously, for this to have any meaning you must supply your own callback function. The default callback function will completely ignore any value in this parameter. The pass parameter may be nearly anything, excepting if it may be confused with any of the other parameters that may be passed. To avoid any confusion you should use an array if you will use this parameter. The reason for this is that none of the other parameters can be and array, so any array that bluntAjax finds in the parameter list will automatically be assigned to this parameter. If you pass other types of values then you must make sure they cannot be confused for one of the other parameter types.
			
		CALLBACK FUNCTIONS
				
				Callback functions are by far the hardest thing to understand about using AJAX. All of the available frameworks use callback functions to deal with the server's response to a request. Some of the frameworks try to hide these in order to make it simpler to the average user, making the callback function so generic that they become unusable for complex operations. In the end, if you plan to do anything more than display the server response on your page somewhere, you will still need to figure out the legistics or creating a callback function in whatever framework you decide to use. The bluntAjax default callback function accomplishes the same task that other frameworks provide and does not attempt to go any further. In most cases this will be enough, but if you need to do something more complex with the server respons than simply alert or display it on a page then you will need to build your own JavaScript function to do the work.
			
				A callback function is just like any other JavaScript function. You simple create the funtion and then supply that function when calling bluntAjax, for example:
						
						function myFunction() {
							DO SOMETHING
						}
						bluntAjax('/page.php', myFunction);
				
				The main thing that you need to consider when building this function are the values that will be passed to it when it is called. The folling parameters are passed in the same order as listed here:
						(server_response, id, pass, httpConnection, httpStatus, statusText, readError)
				
						server_response
								The data as returned by the server call. This is unaltered, so whatever your server script returns will be found in this parameter.
								
						id
								If an HTML Element ID was passed as one of the paremeters when calling bluntAjax, that ID will be in this parameter when the callback function is called. If no element id was passed to bluntAjax then this parameter will be === false
								
						pass
								If you included anything that would be considered by bluntAjax to be a "pass" parameter, then that value will be passed to the callback function, unaltered, in this parameter. If no value was given when calling bluntAjax then this parameter will === false
								
						httpConnection
								true or false, indicates that an http connection was/was not succesfully created
								
						httpStatus
								The last http status returned by the server. For successful operations this would be 200
								
						statusText
								Any text assocaited with the above httpStatus number. For example, an httpStatus of 200 this would be "OK"
								
						readError
								If any errors occur while attemting to read the server response, the error text will be in this parameter
			
			If is up to you to decide what should be done with any of the values sent to your callback function. For a simple example you can look at the default callback function at the end of this script bluntAjaxDefaultFunction()
	*/	
	
	function bluntAjax(url) {
		var callback = false;
		var parameters = '';
		var method = 'POST';
		var div = false;
		var pass = false;
		
		var aLength = arguments.length
		if (arguments.length > 1) {
			for(i=1; i<aLength; i++) {
				//alert(arguments[i]);
				switch (typeof(arguments[i])) {
					case 'function':
						callback = arguments[i];
						break;
					case 'object':
						pass = arguments[i];
						break;
					case 'string':
						var string = arguments[i];
						if (string != '') {
							if (string.toUpperCase() == 'POST' || string.toUpperCase() == 'GET') {
								method = string.toUpperCase();
								break;
							}
							if (string.indexOf('=') > -1) {
								// if the string contains an = then consider it the parameters
								// the only other value that may have an = in a string is the url
								// and we don't look at that argument
								parameters = string;
								break;
							}
							if(document.getElementById(string)) {
								// if this string is used as an element id then
								// it will be placed in the div parameter
								div = string;
							} else {
								pass = string;
							}
						}
						break;
					case 'boolean':
					default:
						// boolean parametes have only one place they can go since they are not used by this script
						pass = arguments[i];
						break;
				}
			}
		}
		if (callback === false) {
			callback = bluntAjaxDefaultFunction;
		}
		
		var httpConnection = false;
		var readError = false;
		var httpStatus = false;
		var statusText = false;
		var server_response = false;
		var xmlHttp = createXmlHttpRequestObject();
		
		process();
		
		function createXmlHttpRequestObject() {
			// create new XMLHttpRequest Object
			var xmlHttp = false;
			
			// will store the reference to the XMLHttpRequest object
			// this should work for all browsers except IE6 and older
			try {
				// try to create XMLHttpRequest object
				xmlHttp = new XMLHttpRequest();
			}
			catch(e) {
				// failed to create XMLHttpRequest object
				// assume IE6 or older
				var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
																				"MSXML2.XMLHTTP.5.0",
																				"MSXML2.XMLHTTP.4.0",
																				"MSXML2.XMLHTTP.3.0",
																				"MSXML2.XMLHTTP",
																				"Microsoft.XMLHTTP");
				// try every prog id until one works
				for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) {
					try { 
						// try to create XMLHttpRequest object
						xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
					} 
					catch (e) {}
					// failed to create object
					// do nothing and try the next
				}
			}
			// returns false if we were unable to create any object
			return xmlHttp;
		} // end function createXmlHttpRequestObject
		
		function process() {
			// make request to server
			var error = true;
			var post_args = parameters;
			if (xmlHttp) {
				httpConnection = true;
				var error = false;
				if (method == 'GET') {
					if (parameters != '') {
						url = url + '?' + parameters;
					}
					post_args = null;
				}
				try {
					xmlHttp.open(method, url, true);
					xmlHttp.onreadystatechange = handleRequestStateChange;
					if (method == 'POST') {
						//Send the proper header information along with the request
						xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
						xmlHttp.setRequestHeader("Content-length", post_args.length);
						xmlHttp.setRequestHeader("Connection", "close");
					}
					xmlHttp.send(post_args);
				}
				catch (e) {
					// unable error openenng connection
					statusText = 'Ajax Error sending request';
					error = true;
				}
			}
			
			if (error) {
				callback(server_response, div, pass, httpConnection, httpStatus, statusText, readError);
			}
		} // end function process
		
		function handleRequestStateChange()  {
			var error = false
			// wait for request to be complete and then process returned data
			readError = '';
			if (xmlHttp.readyState == 4) {
				// when readyState is 4 (done), we also read the server response
				// continue only if HTTP status is "OK"
				if (xmlHttp.status == 200)  {
					httpStatus = 200;
					statusText = xmlHttp.statusText;
					try {
						// read the message from the server
						server_response = xmlHttp.responseText;
					}
					catch(e) {
						// display error message
						//alert("Error reading the response: " + e.toString());
						readError = e.toString();
					}
				} else {
					// display status message
					//alert("There was a problem retrieving the data:\n" + xmlHttp.statusText);
					statusText = xmlHttp.statusText;
					httpStatus = xmlHttp.status;
				}
				// call the function to deal with the server response
				// pass status and errors to server response processor
				// it is up to that function to deal with any errors
				//alert(div);
				//alert(pass);
				callback(server_response, div, pass, httpConnection, httpStatus, statusText, readError);
			}
		} // end function handleRequestStateChange
		
	} // end function bluntAjax
	
	function bluntAjaxDefaultFunction(response, div, pass, httpConnection, httpStatus, statusText, readError) {
		if (httpConnection) {
			if (httpStatus == 200) {
				if (readError == '') {
					// call was successfull
					// throw response into inner html of passed div id
					// check for existance of div
						if (div !== false) {
							if (element = document.getElementById(div)) {
								element.innerHTML = response;
							} else {
								if (bluntAjaxDebug) {
									alert('Ajax Error: Element '+div+' Does Not Exist!');
								}
							}
						} else {
							alert(response);
						}
						if (pass !== false && bluntAjaxDebug) {
							alert('passed value = '+pass);
						}
				} else {
					if (bluntAjaxDebug) {
						alert('Ajax Error reading http response: '+readError);
					}
				}
			} else {
				if (bluntAjaxDebug) {
					alert('Ajax http Error: '+httpStatus+': '+statusText);
				}
			}
		} else {
			if (bluntAjaxDebug) {
				alert('Ajax Error: Failed to create an http connection!');
			}
		}
	} // end function bluntAjaxDefaultFunction
