//________________________________________________________________________________________ 
//________________________________________________________________________________________ AJAX encapsulation

/*
 * Usage :	.startGET(the page, "TEXT" or "XML" , "" or "function to call when finished()", "" or "DOM ID for notification textbox");
 * 			.startPOST(the page, "TEXT" or "XML" , "" or "function to call when finished()", "" or "DOM ID for notification textbox");
 * Errors:
		ERR_NOTINIT 	{ JSON Object was never used }
		ERR_PARSE		{ JSON parsing error }
*/

function NV_ajax() {
	this.sendGET = NV_ajax_startGET;
	this.sendPOST = NV_ajax_startPOST;
	this.get_HttpObject = NV_ajax_getHttpObject;
	this.retrieveXML = NV_ajax_retrieveXML;
	this.retrieveText = NV_ajax_retrieveText;
	this.retrieveJSON = NV_ajax_retrieveJSON;
	this.inProgress = NV_ajax_inProgress;
	this.handleResponse = NV_ajax_handleResponse;
	
	var httpConn = NV_ajax_getHttpObject(); // Connection object
	var F_working = false; // Flag for 'in progress'
	var xmlDoc = ""; // Stores responseXML object if in XML mode
	var textDoc = ""; // Stores responseText if in Text mode
	var JSONDoc;// Stres JSON data in JSON mode
	var the_datatype = ""; // 'XML', 'TEXT', or 'JSON'
	var the_finisher = ""; // function to call when finished
	var the_notifier = ""; // the element that relays progress information
	var serverCode = ""; // HTTP code received from server
	var serverText = ""; // Text of HTTP code
	
	
	
	//____________________________________________________________________________________________________ 
	//____________________________________________________________________________________________________ Essentials
	(function (s) {
		// This prototype has been released into the Public Domain, 2007-03-20
		// Original Authorship: Douglas Crockford
		// Originating Website: http://www.JSON.org
		// Originating URL    : http://www.JSON.org/JSON.js

		// Augment String.prototype. We do this in an immediate anonymous function to
		// avoid defining global variables.
		
		var m = {
			'\b': '\\b',
			'\t': '\\t',
			'\n': '\\n',
			'\f': '\\f',
			'\r': '\\r',
			'"' : '\\"',
			'\\': '\\\\'
		};
  
		s.parseJSON = function (filter) {
			var j;

            function walk(k, v) {
                var i, n;
                if (v && typeof v === 'object') {
                    for (i in v) {
                        if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                            n = walk(i, v[i]);
                            if (n !== undefined) {
                                v[i] = n;
                            }
                        }
                    }
                }
                return filter(k, v);
            }
			
			
			/*We split the first stage into 4 regexp operations in order to work around
			crippling inefficiencies in IE's and Safari's regexp engines. First we
			replace all backslash pairs with '@' (a non-JSON character). Second, we
			replace all simple value tokens with ']' characters. Third, we delete all
			open brackets that follow a colon or comma or that begin the text. Finally,
			we look to see that the remaining characters are only whitespace or ']' or
			',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. */
		
			if (/^[\],:{}\s]*$/.test(this.toJSONString().replace(/\\./g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(:?[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
				j = eval('(' + this + ')');
				
				return (typeof filter === 'function') ? walk('', j) : j;
			}
			throw new SyntaxError("parseJSON");
		};
		
		s.toJSONString = function () {
			if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/[\x00-\x1f\\"]/g, function (a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
	}
	) (String.prototype);
	// End public domain parseJSON block
	
	/*
		* XMLHTTPRequest object
	*/
	
	function NV_ajax_getHttpObject() {
		var xmlhttp;
		/*@cc_on
		@if (@_jscript_version >= 5)
			try {
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (E) {
					xmlhttp = false;
				}
			}
		@else
			xmlhttp = false;
		@end @*/
		if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
			try {
				xmlhttp = new XMLHttpRequest();
				xmlhttp.overrideMimeType("text/xml"); 
			} catch (e) {
				xmlhttp = false;
			}
		}
	
		return xmlhttp;
	}
	
	
	/*
		* Notification, if requested
	*/
	
	function do_notify(thetext) {
		document.body.className = (thetext.length == 0) ? 'normal' : 'working';
		/*
		if (the_notifier != "") {
			
			try {
				document.getElementById(the_notifier).innerHTML = thetext;
			}
			catch(e) {
				if (document.getElementById(the_notifier))
					document.getElementById(the_notifier).innerHTML = "";
			}
		}
		*/
	}
	
	//____________________________________________________________________________________________________ 
	//____________________________________________________________________________________________________ Retrieval
	function NV_ajax_retrieveXML() {
		return xmlDoc;
	}
	
	function NV_ajax_retrieveText() {
		return textDoc;
	}
	
	function NV_ajax_retrieveJSON() {
		return JSONDoc;
	}
	
	function NV_ajax_inProgress() {
		return F_working;
	}
	
	//____________________________________________________________________________________________________ 
	//____________________________________________________________________________________________________ Processing
	function NV_ajax_startGET(thestr,thetype,thefinisher,thenotifier) {
		if (httpConn == null)
			httpConn = NV_ajax_getHttpObject();
		
		if (!F_working && httpConn) {
			xmlDoc = "";
			textDoc = "";
			JSONDoc = {"statusmsg":"ERR_NOT_INIT"};
			
			the_datatype = thetype;
			the_finisher = thefinisher;
			the_notifier = thenotifier;
			
			do_notify(' Working ... ');
			
			// Add random number to prevent caching in IE
			if (thestr.indexOf('?') == -1)
				thestr += "?the_sand=" + Math.random();
			else
				thestr += "&the_sand=" + Math.random();
			
			httpConn.open("GET", thestr, true);
			
			httpConn.onreadystatechange = NV_ajax_handleResponse;
			
			F_working = true;
			httpConn.send(null);
		}
	}
	
	function NV_ajax_startPOST(thestr,thetype,thefinisher,thenotifier) {
		
		if (httpConn == null)
			httpConn = NV_ajax_getHttpObject();
		
		if (!F_working && httpConn) {
			xmlDoc = "";
			textDoc = "";
			JSONDoc = {thestatus:"ERROR","statusmsg":"ERR_NOT_INIT"};
			
			the_datatype = thetype;
			the_finisher = thefinisher;
			the_notifier = thenotifier;
			
			do_notify(' Working ... ');
			
			var thestr_parts = thestr.split("?");
			var the_vars = "the_sand=" + Math.random();
			
			if (thestr_parts.length > 1)
				the_vars += "&" + thestr_parts[1];
			
			httpConn.open("POST", thestr_parts[0], true);
			httpConn.onreadystatechange = NV_ajax_handleResponse;
			
			the_datatype = thetype;
			the_finisher = thefinisher;
			
			httpConn.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			
			F_working = true;
			httpConn.send(the_vars);
		}
	}
	
	
	//____________________________________________________________________________________________________ 
	//____________________________________________________________________________________________________ Response Handling
	function NV_ajax_handleResponse() {
		
		/*
			--- Successful ---
			200 OK
						The request has succeeded. The information returned with the response 
						is dependent on the method used in the request, for example:
						GET an entity corresponding to the requested resource is sent in the response;
						HEAD the entity-header fields corresponding to the requested resource are sent 
							in the response without any message-body;
						POST an entity describing or containing the result of the action;
						TRACE an entity containing the request message as received by the end server.
								
			201 Created:
						The request has been fulfilled and resulted in a new resource being created. 
						The newly created resource can be referenced by the URI(s) returned in the 
						entity of the response, with the most specific URI for the resource given 
						by a Location header field. The response SHOULD include an entity containing 
						a list of resource characteristics and location(s) from which the user or 
						user agent can choose the one most appropriate. The entity format is s
						pecified by the media type given in the Content-Type header field. The 
						origin server MUST create the resource before returning the 201 status 
						code. If the action cannot be carried out immediately, the server SHOULD 
						respond with 202 (Accepted) response instead.
								
			205 Reset Content:
						The server has fulfilled the request and the user agent SHOULD reset the document 
						view which caused the request to be sent. This response is primarily intended 
						to allow input for actions to take place via user input, followed by a clearing 
						of the form in which the input is given so that the user can easily initiate 
						another input action. The response MUST NOT include an entity.
			
			--- Redirection ---
			301 Moved Permanently:
						The requested resource has been assigned a new permanent URI and any future 
						references to this resource SHOULD use one of the returned URIs. This response 
						is cacheable unless indicated otherwise.

						The new permanent URI SHOULD be given by the Location field in the response. 
						Unless the request method was HEAD, the entity of the response SHOULD contain 
						a short hypertext note with a hyperlink to the new URI(s).

						If the 301 status code is received in response to a request other than GET or 
						HEAD, the user agent MUST NOT automatically redirect the request unless it 
						can be confirmed by the user, since this might change the conditions under 
						which the request was issued.

						Note: When automatically redirecting a POST request after receiving a 301 
						status code, some existing HTTP/1.0 user agents will erroneously change 
						it into a GET request.
			
			--- Client errors ---
			400 Bad Request:
						The request could not be understood by the server due to malformed syntax. 
						The client SHOULD NOT repeat the request without modifications. 
			
			401 Unauthorized:
						The request requires user authentication. The response MUST include a 
						WWW-Authenticate header field (section 14.47) containing a challenge applicable 
						to the requested resource. The client MAY repeat the request with a suitable 
						Authorization header field (section 14.8). If the request already included 
						Authorization credentials, then the 401 response indicates that authorization 
						has been refused for those credentials.
			
			403 Forbidden:
						The server understood the request, but is refusing to fulfill it. Authorization 
						will not help and the request SHOULD NOT be repeated. If the request method 
						was not HEAD and the server wishes to make public why the request has not been 
						fulfilled, it SHOULD describe the reason for the refusal in the entity. If the 
						server does not wish to make this information available to the client, the 
						status code 404 (Not Found) can be used instead.
			
			404 Not Found:
						The server has not found anything matching the Request-URI. No indication is 
						given of whether the condition is temporary or permanent. This status code 
						is commonly used when the server does not wish to reveal exactly why the 
						request has been refused, or when no other response is applicable. 
			
			409 Conflict:
						The request could not be completed due to a conflict with the current state of 
						the resource. This code is only allowed in situations where it is expected that 
						the user might be able to resolve the conflict and resubmit the request. 
						The response body SHOULD include enough information for the user to recognize 
						the source of the conflict. Ideally, the response entity would include enough 
						information for the user or user agent to fix the problem; however, that might 
						not be possible and is not required.
						
						Conflicts are most likely to occur in response to a PUT request. For example, 
						if versioning were being used and the entity being PUT included changes to a 
						resource which conflict with those made by an earlier (third-party) request, 
						the server might use the 409 response to indicate that it can't complete the 
						request. In this case, the response entity would likely contain a list of the 
						differences between the two versions in a format defined by the response Content-Type. 
			
			--- Server Errors ---
			500 Internal Server Error:
						The server encountered an unexpected condition which prevented it from fulfilling 
						the request.
			
			502 Bad Gateway:
						The server, while acting as a gateway or proxy, received an invalid response from 
						the upstream server it accessed in attempting to fulfill the request.
			
			503 Service Unavailable:
						The server is currently unable to handle the request due to a temporary overloading 
						or maintenance of the server.
			
			504 Gateway Timeout:
						The server, while acting as a gateway or proxy, did not receive a timely response from 
						the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary 
						server (e.g. DNS) it needed to access in attempting to complete the request.
						
						Note: Note to implementors: some deployed proxies are known to
						return 400 or 500 when DNS lookups time out.
			
		*/
		
		if (httpConn.readyState == 4) {
			serverCode = httpConn.status;
			serverText = httpConn.statusText;
			
			switch (the_datatype) {
				case "XML":
					xmlDoc = httpConn.responseXML;
					break;
				case "TEXT":
					textDoc = httpConn.responseText;
					break;
				case "JSON":
					var T_JSON = httpConn.responseText;
					
					try {
						JSONDoc = T_JSON.parseJSON();
					}
					catch (EXC_JSONParse) {
						JSONDoc = {thestatus:"ERROR",statusmsg:"ERR_PARSE: "+EXC_JSONParse };
					}
					break;
				default:
					suicide = true;
					break;
			}
			
			do_notify('');
			
			F_working = false;
			delete httpConn;
			
			if (serverCode == 403) {
				window.handle_timeout();
			}
			
			if (the_finisher != "")
				eval("window." + the_finisher + ";");
			
		}
	}
	
}

function handle_timeout() {
	var A_loc = document.location.href.split("/");
	var T_loc = A_loc[A_loc.length-1].replace("?","&");
	document.location.replace("login.php?thereferer=" + T_loc);
}
