
var Ajax = {
	
	requestsCounter: 0,
	requests: new Object(),
	requesting: false,
	loading: null,
	XMLHttpFactories: [
		function() {return new XMLHttpRequest()},
		function() {return new ActiveXObject('Msxml2.XMLHTTP')},
		function() {return new ActiveXObject('Msxml3.XMLHTTP')},
		function() {return new ActiveXObject('Microsoft.XMLHTTP')}
	],
	
	createXMLHTTPObject: function(){
		
		for(i=0; i<Ajax.XMLHttpFactories.length; i++){
			try {
				return Ajax.XMLHttpFactories[i]();
			}
			catch(e){
				continue;
			}
		}
		return false;
	},
	
	prepare: function(callback, xml, obj){
		
		Ajax.requests[Ajax.requestsCounter++] = {'callback': callback, 'xml': xml, 'obj': obj};
	},
	
	send: function(){
		
		// Only one request at the time
		if(Ajax.requesting)
			return false;
		else 
			Ajax.requesting = true;
		
		// Create a loading sign
		if(!Ajax.loading){
			
			var loading = Ajax.loading = document.createElement('div');
			loading.className = 'loading';
			document.getElementsByTagName('body')[0].appendChild(loading);
		}
		
		// Show the loading sign
		Ajax.loading.style.display = 'block';
		
		// Make the xml
		var xml = '<xml version="1.0" encoding="UTF-8"><commands>';
		
		for(var i in Ajax.requests){
			
			if(Ajax.requests[i]){
				
				xml += '<command id="' + i + '">';
				xml += Ajax.requests[i]['xml'];
				xml += '</command>';
			}
		}
		
		xml += '</commands></xml>';
		
		// Get the http request object
		var req = Ajax.createXMLHTTPObject();
		
		// If we cant get it we cant go further
		if(!req)
			return false;
		
		// Make a connection
		req.open('POST', '/ajax/', true);
		req.setRequestHeader('Content-Type', 'text/xml');
		
		// Set the listener
		req.onreadystatechange = function(){
			
			//alert(req.readyState +' '+ req.status);
			if(req.readyState == 4 && req.status == 200){
				
				// Get the commands
				var commands = req.responseXML.getElementsByTagName('command');
				var length = commands.length;
				
				// Loop throw the commands
				for(var i = 0; i < length; i++){
					
					if(commands[i]){
						
						// Get the id
						var command = commands[i];
						var id = command.attributes.getNamedItem('id').value;
						
						//var thiscallback = Ajax.requests.splice(id, 1);
						Ajax.requests[id]['callback'](command);
						
						delete Ajax.requests[id];
					}
				}
				
				// Say we are done requesting
				Ajax.requesting = false;
				
				// Request again if have something in the queue
				if(Ajax.requests.length){
					
					Ajax.send();
				}
				else {
					
					// Hide the loading sign if we are done
					Ajax.loading.style.display = 'none';
				}
			}
		}
		
		// Send the request
		req.send(xml);
		
		return true;
	}
}

