////////////////////////////////////////////////////////////////////////////////
//
// Klasse:
//  cAjaxRequest
////  
// @Copyright:
//  (pp)Software
//  www.ppi-software.de
// @Autor:
//  Dennis Schmitt (schmitt@ppi-software.de)
// @Protocol:
//  02.02.2008 - Dennis Schmitt | Intial public release
//  
//
 
var cAjaxRequest =
{
	//////////////////////////////////////////////////////////////////////////////
	// m_bEnabled:Bool
	// true if the XmlHttpRequest was successful initialized
	m_bEnabled: 			false,
	
	//////////////////////////////////////////////////////////////////////////////
	// m_bInProcess:Bool
	// true, if we are in a request and the other requests goes to the queue
	m_bInProcess: 		false,
	
	//////////////////////////////////////////////////////////////////////////////
	// m_bInProcess:Object
	// reference to the XmlHttpRequest Object
	m_xmlHttpRequest: null,
	
	//////////////////////////////////////////////////////////////////////////////
	// m_WaitingQueue:Array
	// only one request at the same time, the rest goes in the queue
	m_WaitingQueue: 	new Array(),
	
	//////////////////////////////////////////////////////////////////////////////
	// m_ContainerObj:Object
	// reference to the container, there we want to fill with content
	m_ContainerObj: 	null,
	
	m_nAjaxQueyCounter:	500,
	
	m_LoadingImageFileName: "ajax-loader2.gif",
	
	//////////////////////////////////////////////////////////////////////////////
	// m_ContainerObj:String
	// the loadingindicator
	m_LoadingString: 	'<span style="font-size:11px;">'+
						'<img src="images/{INDICATOR_IMAGE}" align="absmiddle" width="16" height="16" />'+
						'&nbsp;loading</span>',
	
	//////////////////////////////////////////////////////////////////////////////
	// struct for readystate
	_ReadyState:
	{
		_Uninitialized: 0,
		_Loading: 			1,
		_Loaded:				2,
		_Interactive:		3,
		_Complete: 			4
	},
	
	//////////////////////////////////////////////////////////////////////////////
	// struct for received status
	_Status:
	{
		_OK: 			200,
		_Created: 		201,
		_Accepted: 		202,
		_NoContent: 	204,
		_BadRequest: 	400,
		_Forbidden: 	403,
		_NotFound: 		404,
		_Gone: 			410,
		_ServerError: 500
	},
	
	//////////////////////////////////////////////////////////////////////////////
	// struct with allowed methods
	_Method:
	{
		_get: 		"GET",
		_post: 		"POST",
		_put: 		"PUT",
		_delete: 	"DELETE"
	},
	
	//////////////////////////////////////////////////////////////////////////////
	// struct for caching
	_Cache:
	{
		_noCache: 0,
		_Cache:		1
	},
	
	//////////////////////////////////////////////////////////////////////////////
	// struct for synchron or asynchorn request
	_Sync:
	{
		_aSync: true,
		_Sync:	false
	},
	
	//////////////////////////////////////////////////////////////////////////////
	// initObject() : void
	// initialize the XmlHttpRequest
	initObject: function()
	{
		cAjaxRequest.m_xmlHttpRequest = cAjaxRequest.getXMLHttpRequest();
		cAjaxRequest.m_bEnabled = (cAjaxRequest.m_xmlHttpRequest != null);
	},
	
	setNewIntervallCounter: function( nData )
	{
		cAjaxRequest.m_nAjaxQueyCounter = nData;	
	},
	
	//////////////////////////////////////////////////////////////////////////////
	// getXMLHttpRequest() : Object
	// get the XMLHttpRequest object from the browser
	getXMLHttpRequest: function()
	{
		axObjs = new Array( 'Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0',
				                'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 
				                'Microsoft.XMLHTTP' );
		                
		for( var i=0; i<axObjs.length; i++ )
		{
			try
			{
				return new ActiveXObject( axObjs[i] );
			}
			catch( eXeption ){}
		}
		
		// for FF and Mozilla
		return new XMLHttpRequest();
	},
	
	//////////////////////////////////////////////////////////////////////////////
	// getUrl( params: Object, callback_args: Array ) : Void
	// -
	getUrl: function( params, callback_args )
	{
		// cAjaxRequest doesnt exist? so create one object
		if( !cAjaxRequest.m_bEnabled ) cAjaxRequest.initObject();
		
		var rUrl = params.url;
		if( !rUrl ) throw "A URL must be specified";
				
		var rCache		 	= params.cache 		|| cAjaxRequest._Cache._noCache;
		var rMethod    	= params.method 	|| cAjaxRequest._Method._get;
		var rSync 		 	= params.sync 		|| cAjaxRequest._Sync._aSync;
		var rCallback  	= params.callback;
		var rContainer 	= params.container;
		var rLoading	 	= params.loading 	|| false;
		var rDirektFill = params.fillIn 	|| false;
		var rPostData   = params.data			|| null;
		
		if( params.indicator )
			cAjaxRequest.m_LoadingString = cAjaxRequest.m_LoadingString.replace( /\{INDICATOR_IMAGE\}/, params.indicator );
		
		if( rContainer )
		{
			cAjaxRequest.setupContainer( rContainer );
			
			// set the loadingindicator if rLoading = true
			if( rLoading )
				cAjaxRequest.fillContainer( cAjaxRequest.m_LoadingString );
		}
		
		// only one request at the same time, so add to queue
		if( cAjaxRequest.m_bInProcess )
		{
			cAjaxRequest.m_WaitingQueue.push( new Array(params, callback_args) );
			return;
		}
		
		cAjaxRequest.m_bInProcess = true;
		
		// add a unique id at the end of the url, if noCache was set
		if( rCache == cAjaxRequest._Cache._noCache )
		{
			var sep = (-1 < rUrl.indexOf("?")) ? "&" : "?";
			rUrl = rUrl + sep + "__=" + encodeURIComponent((new Date()).getTime());
		}
		
		cAjaxRequest.m_xmlHttpRequest.open( rMethod, rUrl, rSync );
		
		// define onreadystatechange
		cAjaxRequest.m_xmlHttpRequest.onreadystatechange = function()
		{
			// return if the readyState is not 4:completely load
			if( cAjaxRequest.m_xmlHttpRequest.readyState != cAjaxRequest._ReadyState._Complete ) return;
			
			var Result = new Array();
			var Respon = cAjaxRequest.m_xmlHttpRequest.getResponseHeader('Content-type');
      
      // check the headerinformations from the reqeuested url of xml or text
      if( Respon.indexOf('xml') > -1 )
        Result.push(cAjaxRequest.m_xmlHttpRequest.responseXML);
      else
        Result.push(cAjaxRequest.m_xmlHttpRequest.responseText);
        
			
			if( rContainer && ( !rLoading || rDirektFill ) )
			{
				cAjaxRequest.setupContainer( rContainer );
				cAjaxRequest.fillContainer( Result );
			}
			
			// execute the callback function that defined
			if( rCallback ) rCallback.apply( null, Result );
			
			// request now finished, so we can do the next
			cAjaxRequest.m_bInProcess = false;
			
			// we still have some requests in the queue? So execute the next request
			if( cAjaxRequest.m_WaitingQueue.length > 0 && !cAjaxRequest.m_bInProcess )
			{
				nextUrl = cAjaxRequest.m_WaitingQueue.shift();

				window.setTimeout("cAjaxRequest.getUrl(nextUrl[0],nextUrl[1])", cAjaxRequest.m_nAjaxQueyCounter );
			}
		}
		
		if( rPostData )
		{
			cAjaxRequest.m_xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			cAjaxRequest.m_xmlHttpRequest.setRequestHeader("Content-length", rPostData.length);
			cAjaxRequest.m_xmlHttpRequest.setRequestHeader("Connection", "close");
		}
		cAjaxRequest.m_xmlHttpRequest.send( rPostData );
	},
	
	//////////////////////////////////////////////////////////////////////////////
	// setupContainer( ConterinerId: String ) : void
	// set the container object to the member variable
	setupContainer: function( ConterinerId )
	{
		cAjaxRequest.m_ContainerObj = document.getElementById( ConterinerId );
	},
	
	//////////////////////////////////////////////////////////////////////////////
	// fillContainer( Data: String || XMLObject ) : void
	// fills the container that defined with the data
	fillContainer: function( Data )
	{
		if(cAjaxRequest.m_ContainerObj == null) return;
		
		cAjaxRequest.m_ContainerObj.innerHTML = Data;
	}
}


cAjaxRequest.initObject();
