//////////////////////////////////
//
//	xmlHttpRequest.js - created 4-16-2005 by Brandon Medenwald
//	
//	This JavaScript file allows for XML HTTP Requests to immediately post and receive data from the server.
//	It has been designed to be invoked with one function call and immediately eval whatever JavaScript statements are returned.
//	
//	The function loadJavaScriptDoc should be called.  It has the following parameters:
//		* type: (querystring, form) this is the type of attributes that will be passed with the remote call
//			- querystring will take "attributes" and pass them directly to the new page
//			- form will take the form that is name in "attributes" and create a querystring from it
//		* page: this is the page to pass this request to, usually "mainmenu.cgi"
//		* attributes: this is either the query string to pass (with no question mark) or the form name depending on the "type"
//		* pleaseWaitDiv: (true, false, div name) this determines whether to display a "Please Wait" message
//			- true displays the default Please Wait message in the center of the window
//			- false disables any type of Please Wait message
//			- div name is the name of a div the will be set to display and later hidden, used for custom Please Wait messages
//		* debug: (true, false) when set to true, it will return an alert with the raw JavaScript code that is returned without executing it
//	
//	Other Important Notes:
//		* command_line_mode is automatically included to avoid the html tags when receiving a response from this call.  Because it is piped 
//			in directly to an "eval" statement, html tags cannot be present
//		* when executing this with "type" of form, the "cmd" input item must contain a "+" and not a " ".  For example: 
//				- instead of using "url search/reports/shortdisplay.html", you should use "url+search/reports/shortdisplay.html"
//		* When building the page to be passed back for eval execution, make sure to include a Content-Type Header.  
//			To make this simple, it is stored inside of an include file (common/xmlContentType.html)
//			This function will error out if not included.  For example, if you wish to simply return an alert box: 
//				`include:common/xmlContentType.html`
//				alert('Here it is');
//		
//////////////////////////////////

// global request variable
var reqNum = 0;

// preload generic "Please Wait" spinning cube
req_cube = new Image(); req_cube.src = "/images/blue_cube_anim.gif";

// this is the function to be called by our page
function loadJavaScriptDoc(type, page, attributes, pleaseWaitDiv, debug, opts)
{	
	// set variables
	var reqIndex = "req" + (++reqNum);
	var iframeIndex = "ifr" + (reqNum);
	var waitIndex = "wait" + (reqNum);
	
	// set options
	var async = (opts && opts.async !== undefined) ? opts.async : true;
	var useEscape = (opts && opts.useEscape ===true);
	
	if( page == 'mainmenu.cgi' )
		page = '/cgi-bin/mainmenu-compress.cgi';
	if( page == '/cgi-bin/mainmenu.cgi' )
		page = '/cgi-bin/mainmenu-compress.cgi';	
		
	// display a "Please Wait" message, if requested
	if (pleaseWaitDiv == true)
	{
		// create the generic Please Wait div
		if ( !document.getElementById('newPleaseWait') )
		{
			var newPleaseWaitObject = document.createElement('div');
			newPleaseWaitObject.id = 'newPleaseWait';
			newPleaseWaitObject.style.position='absolute';
			newPleaseWaitObject.style.overflow='hidden';
			newPleaseWaitObject.style.height='60px';
			newPleaseWaitObject.style.width='150px';
			newPleaseWaitObject.style.left = ( getWindowWidth() / 2 - 75 ) + 'px';
			newPleaseWaitObject.style.top = ( getWindowHeight() / 2 - 30 ) + 'px';
			newPleaseWaitObject.style.padding='8px';
			newPleaseWaitObject.style.borderRight='2px solid #444444';
			newPleaseWaitObject.style.borderBottom='2px solid #777777';
			newPleaseWaitObject.style.borderLeft='2px solid #AAAAAA';
			newPleaseWaitObject.style.borderTop='2px solid #BBBBBB';
			newPleaseWaitObject.style.backgroundColor='rgb(230,230,220)';
			newPleaseWaitObject.style.backgroundImage='url(/images/gradient-dossier.png)';
			newPleaseWaitObject.style.backgroundRepeat='repeat-y';
			newPleaseWaitObject.style.color='black';
			newPleaseWaitObject.innerHTML = '<table border="0" align="center" height="100%" width="100%" cellpadding="2" cellspacing="1" style="font-family:Arial,Helvetica;font-size:10pt;"><tr><td rowspan="2"><img src="/images/blue_cube_anim.gif" border="0"></td><td><center><b>Please Wait</b></td><td rowspan=2><img src="/images/blue_cube_anim.gif" border="0"></td></tr><tr><td><center>Loading...</td></tr></table>';
			PWObj = document.body.appendChild(newPleaseWaitObject);
		}
		else
		{
			document.getElementById('newPleaseWait').style.display = '';
		}
	}
	else if (pleaseWaitDiv != '' && pleaseWaitDiv != false && document.getElementById( pleaseWaitDiv ))
           document.getElementById( pleaseWaitDiv ).style.display = '';
		
	// if type is form, set attributes to a query string of form elements
	if (type == 'form') attributes = buildQueryString(attributes, '', useEscape);
	
	if (attributes == '') attributes = null;
	
	// add command_line_mode to disable the html tags
	attributes =  attributes + '&command_line_mode=true';

    // Opera prior to version 8 doesn't support XML-HTTP, yet doesn't report an error
    try
    {
		if( navigator.userAgent.indexOf('Opera/7.') != -1 || navigator.userAgent.indexOf('Opera 7.') != -1)
		{
			window[waitIndex] = pleaseWaitDiv;
			callToServer('',page, attributes, pleaseWaitDiv, reqIndex, waitIndex, iframeIndex);
			return;
		}
    	
		if (window.XMLHttpRequest) // branch for native XMLHttpRequest object
		{
		   window[reqIndex] = new XMLHttpRequest();
			window[waitIndex] = pleaseWaitDiv;
			window[reqIndex].onreadystatechange = function() {
				// only if window[reqIndex] shows "loaded"
				if (window[reqIndex].readyState == 4)
				{
					// only if "OK", code 200
					if (window[reqIndex].status == 200) (debug) ? alert(window[reqIndex].responseText) : eval(window[reqIndex].responseText) ;
					else alert("There was a problem retrieving the data: " + window[reqIndex].statusText + "(" + window[reqIndex].status + ")");		
					
					hideNewPleaseWaitDiv(pleaseWaitDiv);
					
					// clear global variables
					window[reqIndex] = null;
					window[waitIndex] = null;
					window[iframeIndex] = null;
				}
			};
			window[reqIndex].open("POST", page, async);
			window[reqIndex].setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			window[reqIndex].setRequestHeader( 'referer','http://' + gethost() );
			window[reqIndex].send(attributes);
		}
		else if (window.ActiveXObject) // branch for IE/Windows ActiveX version
		{
			window[reqIndex] = new ActiveXObject("Microsoft.XMLHTTP");
			window[waitIndex] = pleaseWaitDiv;
			if (window[reqIndex])
			{
				window[reqIndex].onreadystatechange = function() {
					// only if window[reqIndex] shows "loaded"
					if (window[reqIndex].readyState == 4)
					{
						// only if "OK", code 200
						if (window[reqIndex].status == 200) (debug) ? alert(window[reqIndex].responseText) : eval(window[reqIndex].responseText) ;
						else alert("There was a problem retrieving the data: " + window[reqIndex].statusText + "(" + window[reqIndex].status + ")");						
						
						hideNewPleaseWaitDiv(pleaseWaitDiv);
						
						// clear global variables
						window[reqIndex] = null;
						window[waitIndex] = null;
						window[iframeIndex] = null;
					}
				};
				window[reqIndex].open("POST", page, async);
				window[reqIndex].setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				window[reqIndex].setRequestHeader( 'referer','http://' + gethost() );
				window[reqIndex].send(attributes);
			}
		}
	}
	catch(err)
	{
		// alert("Your browser does not support XML HTTP Requests");
		window[waitIndex] = pleaseWaitDiv;
		callToServer('',page, attributes, pleaseWaitDiv, reqIndex, waitIndex, iframeIndex);
	}
    
    /* set timeout to prevent a stranded 
    window.setTimeout(function() 
	{
		if ( callInProgress(window[reqIndex]) )
		{
			window[reqIndex].abort();
			alert("There was a problem retrieving the data: the operation timed out.  Please try again.");
			
			hideNewPleaseWaitDiv(req_pleaseWaitDiv);
			
			// clear global variables
			window[reqIndex] = null;
			window[waitIndex] = null;
			window[iframeIndex] = null;
		}
	},60000); // 60 seconds
	*/
}

// translate a form's elements into a query string
function buildQueryString(theFormName, questionMark, useEscape)
{
	theForm = document.forms[theFormName];
	var qs = '';
	for (e=0; e < theForm.elements.length; e++)
	{
      if (theForm.elements[e].name != '' && 
          ( (theForm.elements[e].type == 'checkbox' && theForm.elements[e].checked) || 
            (theForm.elements[e].type == 'radio' && theForm.elements[e].checked) ||
            (theForm.elements[e].type != 'checkbox' && theForm.elements[e].type != 'radio')))
		{
			qs += (qs == '') ? questionMark : '&' ;
			qs += theForm.elements[e].name + '=' + ((useEscape) ? escape(theForm.elements[e].value) : encodeURIComponent(theForm.elements[e].value));
		}
	}
	return qs;
}

function discoverWaitDiv(req_pleaseWaitDiv)
{
	if (req_pleaseWaitDiv == false || req_pleaseWaitDiv == 'false' || req_pleaseWaitDiv == '') return false;
	var numberFound = 0;
	
	for (x = 1; x <= reqNum; x++)
		if ((window['wait' + x] + '') == (req_pleaseWaitDiv + '')) numberFound++; // add empty string operations to guarantee string comparison in Opera
	
	return (numberFound > 1) ? true : false ;
}

function hideNewPleaseWaitDiv(req_pleaseWaitDiv)
{
	// check the global window[] variables associated with please wait divs
	// if another XMLHTTPRequest is using the same div, then do not hide it
	
	if (!discoverWaitDiv(req_pleaseWaitDiv))
	{
		// hide the "Please Wait" message if necessary
		if (req_pleaseWaitDiv == true || req_pleaseWaitDiv == 'true') 
			document.getElementById("newPleaseWait").style.display = "none";
		else if (req_pleaseWaitDiv != '' && req_pleaseWaitDiv != false && req_pleaseWaitDiv != 'false' && document.getElementById( req_pleaseWaitDiv ))
			document.getElementById( req_pleaseWaitDiv ).style.display = 'none';
	}
} 

function callInProgress(localReq)
{
	if ( localReq == undefined ) return false;
	
	switch ( localReq.readyState )
	{
		case 1, 2, 3:
			return true;
		break;

		// Case 4 and 0
		default:
			return false;
		break;
	}
}

function getWindowHeight()
{
	var windowHeight=0;
	if (typeof(window.innerHeight)=='number')
	{
		windowHeight=window.innerHeight;
	}
	else
	{
		if (document.documentElement && document.documentElement.clientHeight)
		{
			windowHeight = document.documentElement.clientHeight;
		}
		else
		{
			if (document.body && document.body.clientHeight)
			{
				windowHeight = document.body.clientHeight;
			}
		}
	}
	return windowHeight;
}

function getWindowWidth()
{
	var windowWidth=0;
	if (typeof(window.innerWidth)=='number')
	{
		windowWidth=window.innerWidth;
	}
	else
	{
		if (document.documentElement && document.documentElement.clientWidth)
		{
			windowWidth = document.documentElement.clientWidth;
		}
		else
		{
			if (document.body && document.body.clientWidth)
			{
				windowWidth = document.body.clientWidth;
			}
		}
	}
	return windowWidth;
}





//////////////////////////////////
//
// former calltoserver.js script
//	* used as a fallback for the XML-HTTP Request Object
//
//////////////////////////////////

function callToServer( formname, actionname, params, req_pleaseWaitDiv, reqIndex, waitIndex, iframeIndex )
{
	if (!document.createElement) return true;
	
	// declare some variables
	var IFrameDoc;
	var URL = '';
	
	if( actionname ) URL = actionname;
	else URL = document.forms[formname].action;
	
	if( params ) URL += '?' + params;
	else URL += buildQueryString(formname, '?');
	
	if (!window[iframeIndex] && document.createElement)
	{
		// create the IFrame and assign a reference to the object to our global variable window[iframeIndex].
		// this will only happen the first time callToServer() is called
		try
		{
			var tempIFrame=document.createElement('iframe');
			tempIFrame.setAttribute('id', iframeIndex);
			tempIFrame.setAttribute('onload','executeJS(\'' + req_pleaseWaitDiv + '\', \'' + reqIndex + '\', \'' + waitIndex + '\', \'' + iframeIndex + '\');');
			tempIFrame.style.border='0px';
			tempIFrame.style.width='0px';
			tempIFrame.style.height='0px';
			window[iframeIndex] = document.body.appendChild(tempIFrame);
      
			if (document.frames && !window[iframeIndex])
			{
				// this is for IE5 Mac, because it will only
				// allow access to the document object
				// of the IFrame if we access it through
				// the document.frames array
				window[iframeIndex] = document.frames[iframeIndex];
			}
		}
		catch(exception)
		{
			// This is for IE5 PC, which does not allow dynamic creation
			// and manipulation of an iframe object. Instead, we'll fake
			// it up by creating our own objects.
			iframeHTML='\<iframe id="' + iframeIndex + '" onload="executeJS(\'' + req_pleaseWaitDiv + '\', \'' + reqIndex + '\', \'' + waitIndex + '\', \'' + iframeIndex + '\');" style="';
			iframeHTML+='border:0px;'; 
			iframeHTML+='width:0px;';
			iframeHTML+='height:0px;';
			iframeHTML+='"><\/iframe>';
			document.body.innerHTML+=iframeHTML;
			window[iframeIndex] = new Object();
			window[iframeIndex].document = new Object();
			window[iframeIndex].document.location = new Object();
			window[iframeIndex].document.location.iframe = document.getElementById(iframeIndex);
			window[iframeIndex].document.location.replace = function(location)
			{
				this.iframe.src = location;
			}
		}
	}
	
	// Opera 7.54 (Oct 2004) requires that document.location.replace() be called
	// before the document object is created.
	if( navigator.userAgent.indexOf('Opera') != -1 && !window[iframeIndex].document )
	{
		window.setTimeout("document.getElementById('" + iframeIndex + "').document.location.replace('/blank.html');", 50 );
		var callback = 'callToServer(\'' + formname + '\'';
		if( actionname )
			callback += ',\'' + actionname + '\'';
		if( params )
		{
			if( !actionname )
				callback += ',\'\'';
			callback += ',\'' + params + '\'';
		}
		callback += ',\'' + req_pleaseWaitDiv + '\'';
		callback += ',\'' + reqIndex + '\'';
		callback += ',\'' + waitIndex + '\'';
		callback += ',\'' + iframeIndex + '\'';
		callback += ')';
		window.setTimeout(callback,150);
		return false;
	}

	if (navigator.userAgent.indexOf('Gecko') !=-1 && !window[iframeIndex].contentDocument)
	{
		// we have to give NS6 a fraction of a second
		// to recognize the new IFrame
		var callback = 'callToServer(\'' + formname + '\'';
		if( actionname )
			callback += ',\'' + actionname + '\'';
		if( params )
		{
			if( !actionname )
				callback += ',\'\'';
			callback += ',\'' + params + '\'';
		}
		callback += ',\'' + req_pleaseWaitDiv + '\'';
		callback += ',\'' + reqIndex + '\'';
		callback += ',\'' + waitIndex + '\'';
		callback += ',\'' + iframeIndex + '\'';
		callback += ')';
		setTimeout(callback,10);
		return false;
	}
  
	if (window[iframeIndex].contentDocument)
	{
		// For NS6
		IFrameDoc = window[iframeIndex].contentDocument; 
	}
	else if (window[iframeIndex].contentWindow)
	{
		// For IE5.5 and IE6
		IFrameDoc = window[iframeIndex].contentWindow.document;
	}
	else if (window[iframeIndex].document)
	{
		// For IE5
		IFrameDoc = window[iframeIndex].document;
	}
	else 
	{
		return true;
	}
   IFrameDoc.location.replace(URL);

	return false;
}

function executeJS(req_pleaseWaitDiv, reqIndex, waitIndex, iframeIndex)
{
	var myJS = eval(iframeIndex + '.document.body.innerHTML');
	
	eval(myJS);
	
	// hide the Please Wait div
	hideNewPleaseWaitDiv(req_pleaseWaitDiv);
	
	// clear global variables
	window[reqIndex] = null;
	window[waitIndex] = null;
	window[iframeIndex] = null;
}

function gethost() 
{ 
	var host = new String(document.location); 
	var urlArr = new Array(); 
 
	urlArr = host.split('/'); 
	return(urlArr[2]); 
} 

