// ACAjax : wrapper sur XmlHTTP ; compatible avec prototype.js
// new ACAjax.Request(
//  "http://www.allocine.fr/series/ficheserie.html",
//  {
//   method:"get",
//   onSuccess:function(xhr){window.alert(xhr.responseText);},
//   onFailure:function(xhr){window.alert(xhr.status);},
//   parameters:"cserie=221"
//  }
// );
//
// Helper ACAjax.encodeParameters : ACAjax.encodeParameters({cSerie:221,csaison:1492}) revoie "cserie=221&csaison=1492"
// Helper ACAjax.sameDomain       : ACAjax.sameDomain("http://01net.allocine.fr/ws.html") depuis "http://01net.allocine.fr/XXX" revoie "http://www.allocine.fr/ws.html"

ACAjax = {};

ACAjax.Request = function(url, options){
	var request = null;

	var tentatives = [
		function(){return new XMLHttpRequest();},
		function(){return new ActiveXObject("Msxml2.XMLHTTP");},
		function(){return new ActiveXObject("Microsoft.XMLHTTP");},
		];

	for (i=0;(null==request)&&i<tentatives.length;i++)
	{
		try{
			request = tentatives[i]();
		}
		catch(e){
			continue;
		}
	}

	if (null == request)
		throw new Error("XmlHttp non supporté");

	options = options||{};

	request.onreadystatechange = function() {
        if (request.readyState == 4)
			if ( (request.status == 200) && (options.onSuccess) )
	            options.onSuccess(request);
			else if (options.onFailure)
				options.onFailure(request)
    }

	options.method = options.method || "get";

	switch(options.method.toLowerCase()){
		case "get":
		    request.open(options.method.toUpperCase(), ACAjax.sameDomain(url) + (options.parameters?("?" + options.parameters):""), true);
			request.send(null);
			break;
		case "post":
		    request.open(options.method.toUpperCase(), ACAjax.sameDomain(url), true);
			request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
			request.setRequestHeader("Content-Length", (options.parameters?("'" + options.parameters.length + "'"):"0"));
			request.send(options.parameters||"");
			break;
		default:
			break;
	}
}

ACAjax.sameDomain = function(url){
	return url.replace(/^[^/]+\/\/[^/]+/,
		window.location.protocol
		+ "//"
		+ window.location.host
		+ (window.location.port?(":" + window.location.port):"")
	);
}

ACAjax.EncodeParameters = function(parameters){
	if ("object" == typeof parameters){
		var ar = [];
		for (name in parameters){
			var value = parameters[name].toString();
			ar.push(encodeURIComponent(name).replace(/%20/,"+") + '=' +
				encodeURIComponent(value).replace(/%20/,"+"));
		}
		return ar.join("&");
	}
	else
		return "";
}
