var arId				= 0;			// Ajax Request Id (Request-counter. Not used)
var ajaxLockCallback	= null;			// Callback function to be called when ajaxLock is released (Lock-queue is empty)
var ajaxLockState		= 'idle'		// State of ajaxLock. Idle until lock-queue is initialized
var ajaxThrottled		= false;		// Ajax is throttled if queue rises above ajaxQueueSize requests without lock beeing active
var ajaxBusy			= false;		// Ajax is busy whenever a request is in progress
var ajaxQueue			= new Array();	// Requests are queued when ajax is busy
var ajaxQueueSize		= 5;			// Number of queued requests to accept before getting throttled
var ajaxQueueWarnings	= true;			// Issue alert when ajax is throttled.

function executeAjax(path,callbackFunction,postData,useJSON, asyncRequest){
	if(typeof(useJSON) == 'undefined') useJSON = true;
	if(typeof(asyncRequest) == 'undefined') asyncRequest = true;

	if(ajaxBusy) {
		if(ajaxLockCallback) {
			ajaxLockState = 'active';
		}

		ajaxQueue[ajaxQueue.length] = new Array(path,callbackFunction,postData,useJSON);
		if(ajaxQueueWarnings) {
			if(ajaxQueue.length > ajaxQueueSize) {
				if(ajaxThrottled) {
					alert("Vennligst vent på klarsignal!");
				} else {
					ajaxThrottled = true;
					alert("Du jobber for fort...\nVennligst vent på klarsignal.");
				}
			}
		}
	} else {
		arId++;
		ajaxBusy = true;
		var requestObject = getXMLHTTP();
		if(requestObject){
			if (postData && (postData != '')) {
				requestObject.open("POST",path,asyncRequest);
			} else {
				requestObject.open("GET",path,asyncRequest);
			}
			requestObject.onreadystatechange=function() {
				if(requestObject.readyState==4) {
					if (requestObject.status != 200) {
						var msg = '';
						msg += "Det oppstod en feil i kommunikasjon mot serveren.\n\n";
						msg += "Forventet status-kode 200, men fikk feilkode " + requestObject.status + " fra serveren.\n\n";
						msg += "Feilmelding: " + requestObject.statusText + "\n";
						msg += "URL: " + path + "\n";
						msg += "document.location.href: " + document.location.href;
						
						alert(msg);
					} else {
						if(useJSON) {
							try {
								var responseObject = JSON.parse(requestObject.responseText);
	
								if(responseObject.errorMessage != null) {
									alert(responseObject.errorMessage);
								} else {
									callbackFunction(responseObject);
								}
							} catch(JSONError) {
								parseJSONError(JSONError,requestObject.responseText);
							}
						} else {
							var responseObject = requestObject.responseText;
							callbackFunction(responseObject);
						}
					}
	
					ajaxBusy = false;

					var ajaxQueueEmpty = true;
					if(ajaxQueue.length > 0) {
						ajaxQueueEmpty = false;
						var nextAjaxCall = ajaxQueue[0];
						var tmpQueue = new Array();
						for(var i=0; i<ajaxQueue.length-1; i++) {
							tmpQueue[i] = ajaxQueue[i+1];
						}
						ajaxQueue = tmpQueue;

						if(ajaxThrottled) {
							if(ajaxQueue.length == 0) {
								ajaxThrottled = false;
								alert("Synkronisert tilstand.\n\nDu kan fortsette!");
							}
						}

						executeAjax(nextAjaxCall[0],nextAjaxCall[1],nextAjaxCall[2],nextAjaxCall[3]);
					}

					if(ajaxLockCallback && ajaxQueueEmpty) {
						if(ajaxLockState == 'active') {
							ajaxLockState = 'idle';
							var evalFunction = ajaxLockCallback;
							ajaxLockCallback = null;
							ajaxQueueWarnings = true;
							eval(evalFunction + '();');
						}
					}
				}
			}

			// if there is postData present, we assume
			// that they are urlencoded form variables.
			if (postData && (postData != '')) {
				requestObject.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			} 
			requestObject.send(postData);
		}
	}
}

function lockAjax(callbackFunction) {
	if(ajaxLockCallback) {
		return false;
	}

	if(ajaxQueue.length == 0) {
		ajaxLockCallback = callbackFunction;
		ajaxLockState = 'idle';

		// Disable ajaxQueue-warnings to prevent
		// error messages from popping up while
		// report is being loaded.
		ajaxQueueWarnings = false;

		return true;
	} else {
		return false;
	}
}

function parseJSONError(JSONError,response) {
	if(response != '') {
		switch(JSONError.name) {
			case 'TypeError':
				alert(JSONError.message);
			break;

			case 'Error':
				alert(response);
			break;

			case 'JSONError':
				alert('JSON: ' + JSONError.message + ' at ' + JSONError.at + "\n\n" + JSONError.text.substr(JSONError.at-5,9) + "\n\n" + JSONError.text);
			break;

			default:
				alert(response);
		}
	} else {
		alert('Uventet hendelse: Tom respons fra server');
	}
}

function getXMLHTTP(){
	var AXObj = null;
	try{
		AXObj = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			AXObj = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(oc){
			AXObj = null;
		}
	}
	if(!AXObj && typeof XMLHttpRequest != "undefined") {
		AXObj = new XMLHttpRequest();
	}
	return AXObj;
}

function URLEncode(plaintext) {
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};

function showWait(message) {
	ind.show(message);
	/*
    if (typeof(message)=='undefined') message = '';

    overlib('<div align="center" style="background-color:white;width:100%;height:100%;"><div style="font-size: 18px;margin-top: 5px;margin-bottom: 5px;">Vennligst vent..</div><div style="font-size: 12px;text-align: middle;margin-bottom: 20px;padding-bottom:13px;">' + message + '</div><div align="center"><img src="{$icon.path}progressbars/progressbar_green.gif"></div></div>', STICKY, WIDTH, 400, HEIGHT, 150, CENTERPOPUP);
    */
}

function hideWait() {
	ind.hide();
    //nd(1);
}


