///////////////////////////////////////////////////////////////////////////////
//	Ajax Core
// 
//	Description:
//		This is the base code foundation for AJAX applications
//
//	Author: Kevin De Angelis
// 	Born on Date: 	2007.01.28
//
//	Revisions:
//		2007.01.28 	KJD: Initial script created
//		2007.01.31	KJD: Error trapping
//		2007.02.02	KJD: Check text/xml file header for IE
//
///////////////////////////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////////////////////////
// GetFile 			Call to get a file
// Author: 			Kevin De Angelis
// Date: 			2007.01.30
// Receive: 		string, string, string
// Return: 			string/object/array
//
//	USAGE:
//		var myvariable = GetFile( thisfilename, thistype, thisobjecttype );
//
//		thisfilename 	- name of the file that you would like returned (ie. test.xml)
//		thistype		- TEXT,XML
//		thisobjecttype	- object, array, string
//
///////////////////////////////////////////////////////////////////////////////
function GetFile( thisfilename, thistype, thisobjecttype )
{
	var thisitem;

	if( thisfilename )
	{
		if( thistype == 'TEXT' )
		{
		
			// Request file
			thisitem = RequestFile( thisfilename, thistype );

			if( thisobjecttype == 'array' )
			{
				thisitem = thisitem.replace('\r','');
				thisitem = thisitem.split('\n');
			}
		}
		else if( thistype == 'XML' )
		{
			thisitem = RequestFile( thisfilename, thistype );
			
			if( thisobjecttype == 'array' )
			{
				thisitem = XML2Array( thisitem );
			}
		}
		else
		{
			// 2007.01.31 KJD: Invalid request type
			AjaxDisplayError( 1 );
		}
		
		return thisitem;
	}
	else
	{
		// 2007.01.31 KJD: Invalid request type
		AjaxDisplayError( 5 );
	}
}


///////////////////////////////////////////////////////////////////////////////
// ShowXMLArray 	Show XML array object as text string
// Author: 			Kevin De Angelis
// Date: 			2007.01.30
// Receive: 		array, string
// Return: 			string
///////////////////////////////////////////////////////////////////////////////
function ShowXMLArray(input, _indent)
{
	var indent = (typeof(_indent)=='string')?_indent+'\t':'\t';
	var paren_indent = (typeof(_indent)=='string')?_indent+'\t':'';

	if ( typeof(input) == 'string' )
	{
		var output = "'"+ input +"'\n"
	} 
	else if ( typeof(input) == 'boolean' )
	{
		var output = (input?'true':'false') +"\n"
	} 
	else if ( typeof(input) == 'object' )
	{
		var output = ((input.reverse)?'Array':'Object') +"\n"
		output += paren_indent + "(\n";
		
		for ( var i in input )
		{
			output += indent + "["+ i +"] => "+ ShowXMLArray(input[i],indent)
		}
		
		output += paren_indent + ")\n"
	}
	return output
}



///////////////////////////////////////////////////////////////////////////////
// XML2Array 		Convert XML file into an Array
// Author: 			Kevin De Angelis
// Date: 			2007.01.30
// Receive: 		object, array
// Return: 			array
//
//	NOTE: This function only works properly with unique node names!
//
///////////////////////////////////////////////////////////////////////////////
function XML2Array( thisobject, thisarray )
{
	if( typeof thisarray == 'undefined' )	{		var thisarray = new Array();	}

	if( thisobject )
	{
		// 2007.01.31 KJD: Build numeric array
		for( var i = 0; i< thisobject.childNodes.length; i++ )
		{
			var thislength = thisarray.length;

			if( thisobject.childNodes[i].childNodes.length )
			{
				thisarray[ thislength ] = new Array();
				thisarray[ thislength ] = XML2Array( thisobject.childNodes[i], thisarray[ i ] );
			}
			else
			{
				// 2007.01.31 KJD: Fixes FF Bug with witespace
				var thisvalue = trim(thisobject.childNodes[i].nodeValue)
				if(thisvalue)
				{
					thisarray[ thislength ] = thisvalue;
				}
			}
		}	
	}
	else
	{
		// 2007.01.31 KJD: surpress error if no xml
		// AjaxDisplayError( 2 );
	}
		
	return thisarray;
}

///////////////////////////////////////////////////////////////////////////////
// RequestFile 		Make the request to receive a file
// Author: 			Kevin De Angelis
// Date: 			2007.01.30
// Receive: 		string, string
// Return: 			object
///////////////////////////////////////////////////////////////////////////////
function RequestFile( thisfilename, thistype )
{
	var http_request 	= false;
	var urlmethod 		= "GET";
	
	var thisinfo;
	
	// 2006.09.14 KJD: Determine the Browser we're using
	if( window.XMLHttpRequest )
	{
		// 2006.09.14 KJD: NON-IE Browsers
		http_request = new XMLHttpRequest();

		if ( http_request.overrideMimeType )
		{
			if( thistype == 'TEXT' )
			{
				http_request.overrideMimeType('text/html');
			}
			else if( thistype == 'XML' )
			{
				http_request.overrideMimeType('text/xml');
			}
		}
	}
	else if( window.ActiveXObject )
	{
		// 2006.09.14 KJD: Internet Explorer
		try
		{
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}

	// 2007.01.31 KJD: Try to capture error if run locally in FF
	try
	{
		// 2006.09.14 KJD: Open the URL ( true = continue even if object hasn't been receive, false = wait until we get a response )
		http_request.open( urlmethod, thisfilename, false );

		// 2006.09.14 KJD: If it's a GET request send a null response
		if( urlmethod == 'GET' )	{		http_request.send( null );	}
	}
	catch(e)
	{
		// 2007.02.01 KJD: IE only (file on different domain)
		AjaxDisplayError( 6 );
	}
		
	// readyState is 4 at this point
	thisinfo = CheckStatus( http_request, thistype );

	// 2007.01.31 KJD: Check for errors
	if( http_request.status != 200 )
	{
		if( http_request.status == 0 )	{	AjaxDisplayError( 3 );						}
		else							{	AjaxDisplayError( 4, http_request.status );	}
	}

	return thisinfo;
}

///////////////////////////////////////////////////////////////////////////////
// CheckStatus 		Check the status of a file call
// Author: 			Kevin De Angelis
// Date: 			2007.01.30
// Receive: 		object, string
// Return: 			object
///////////////////////////////////////////////////////////////////////////////
function CheckStatus( http_request, thistype )
{
	var thisinfo;
	if( http_request.readyState == 0 )
	{
		// Not initialized
	}
	else if( ( http_request.readyState == 1 ) || ( http_request.readyState == 2 ) )
	{
		// Loading
	}
	else if( http_request.readyState == 3 )
	{
		// Interactive
	}
	else if( http_request.readyState == 4 )
	{
		// 2006.09.14 KJD: Page is ready, check the status

		// 2006.09.14 KJD: These are the status codes ( 404,500, 200, etc )
		if( http_request.status == 200 )
		{
			// 2006.09.14 KJD: Page is good
			if( thistype == 'TEXT' )
			{
				thisinfo = http_request.responseText;
			}
			else if( thistype == 'XML' )
			{
				thisinfo = http_request.responseXML;
				thisinfo = GetRoot( thisinfo );
			}
		}
		else if( http_request.status == 404 )
		{
			// 2006.09.14 KJD: Page not found
		}
		else if( http_request.status == 500 )
		{
			// 2006.09.14 KJD: Server error
		}
	}
	else
	{
		// Anything else?
	}

	
	return thisinfo;
}

///////////////////////////////////////////////////////////////////////////////
// trim			trim a string
// Author: 		Kevin De Angelis
// Date: 		2007.01.31
// Receive: 	string
// Return: 		string
///////////////////////////////////////////////////////////////////////////////
function trim( str )
{
	str 	= str.replace(/^\s*|\s*$/g,"");
	return str;
}


///////////////////////////////////////////////////////////////////////////////
// GetRoot	- Get the XML root
// Author: 		Kevin De Angelis
// Date: 		2006.09.15
// Receive: 	XMLobject
// Return: 		string
///////////////////////////////////////////////////////////////////////////////
function GetRoot( varname )
{
	// 2006.09.15 KJD: Get root node (IE and FF do this differently)
	var root_node;

	// Check Header FOR IE
	try
	{
		if( varname.childNodes[0].nodeType == 1 )
		{
			// For FF
			root_node = varname.getElementsByTagName( varname.childNodes[0].nodeName ).item(0);
		}
		else if( varname.childNodes[1].nodeType == 1 )
		{
			// For IE
			root_node = varname.getElementsByTagName( varname.childNodes[1].nodeName ).item(0);
		}
	}
	catch(e)
	{
		AjaxDisplayError( 7 );
	}

	return root_node;
}


///////////////////////////////////////////////////////////////////////////////
// AjaxDisplayError		Display an error
// Author: 				Kevin De Angelis
// Date: 				2007.01.31
// Receive: 			number, string
// Return: 				null
///////////////////////////////////////////////////////////////////////////////
function AjaxDisplayError( errornumber, thisstring )
{
	var mystring = "";

	switch( errornumber )
	{
		case 1:		mystring="Invalid File Type requested.\nMust be XML or TEXT";		break;
		case 2:		mystring="Could not convert XML to Array\nXML not received.";		break;
		
		case 3:		mystring="Files must be placed on and run from a webserver.";		break;
		case 4:		mystring="Response from Server: " + thisstring;						break;
		
		case 5:		mystring="No file requested.";										break;
		
		case 6:		mystring="Cannot request file on a different domain.";				break;
		case 7:		mystring="Invalid File Header\nMust be text/xml.";					break;
	}
	
	alert("**ERROR**\n" + mystring );
	
	// 2007.01.31 KJD: STOP EVERYTHING IF THERE IS AN ERROR
	STOPEVERYTHING();  // fake function to stop everything.
}
