
// Constructeur
Ajax = function()
{
	this.request = null;
	if(window.XMLHttpRequest) this.request = new XMLHttpRequest();
	else if(window.ActiveXObject) this.request = new ActiveXObject("Msxml2.XMLHTTP");
	else this.request = new ActiveXObject("Microsoft.XMLHTTP");

	this.send = function(config) { Ajax.send(this, config); };
	this.returnResponse = function() { return this.request.responseText; };
	this.dump = function() { Ajax.dump(this); };
};


// Méthode d'envoie des données
Ajax.send = function(obj, config)
{
		obj.url			= typeof config.url			== "undefined" ? "/" : config.url;
		obj.method		= typeof config.method		== "undefined" ? "GET" : config.method;
		obj.callback	= typeof config.callback	== "undefined" ? false : config.callback;
		if(obj.callback != false)
		{
			obj.callback.type	= typeof config.callback.type	== "undefined" ? "none" : config.callback.type;
			obj.callback.name	= typeof config.callback.name	== "undefined" ? "none" : config.callback.name;
			obj.callback.format = typeof config.callback.format == "undefined" ? "string" : config.callback.format;
		}
		obj.type		= typeof config.type		== "undefined" ? true : config.type;

		obj.request.open(obj.method, obj.url, obj.type);
	
		if(obj.method == "POST") obj.request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	
		obj.request.send(null); // Envoie de la requête
		obj.request.onreadystatechange = function() { Ajax.getResponse(obj); };
};


// Renvoie le résultat suivant le callback
Ajax.setCallbackResponse = function(obj)
{
	switch(obj.callback.type)
	{
		case 'innerHTML': if(document.getElementById(obj.callback.name)) document.getElementById(obj.callback.name).innerHTML = obj.request.responseText; break;
		case 'value': if(document.getElementById(obj.callback.name)) document.getElementById(obj.callback.name).value = obj.request.responseText; break;
		case 'function':
			switch(obj.callback.format)
			{
				case 'string' : eval(obj.callback.name+'("'+obj.request.responseText+'")'); break;
				case 'json': eval(obj.callback.name+'('+obj.request.responseText+')'); break;
			}
		break;
	}
};


// Exécute le callback si il est spécifié
Ajax.getResponse = function(obj)
{
	if(obj.request.readyState == 4 && obj.request.status == 200)
		if(obj.callback != false && obj.callback.type != "none" && obj.callback.name != "none")
			Ajax.setCallbackResponse(obj);
};


// Affichage de l'objet
Ajax.dump = function(obj)
{
	text = "Dump de l'objet Ajax :\n";
	text += "URL : "+obj.url+"\n";
	text += "METHOD : "+obj.method+"\n";
	text += "TYPE : "+obj.type+"\n";
	text += "CALLBACK : "+obj.callback+"\n";
	if(obj.callback != false)
	{
		text += "\t- TYPE : "+obj.callback.type+"\n";
		text += "\t- NAME : "+obj.callback.name+"\n";
		text += "\t- FORMAT : "+obj.callback.format+"\n";
	}
	alert(text);
};

