var Ajax = Ajax.extend({
	
	initialize: function(url, options)
	{
		this.addEvent('onRequest', this.options.onStartLoading || this.startLoading);
		this.addEvent('onSuccess', this.options.onEndLoading || this.endLoading);
		
		this.parent(url, options);

	},
	
	startLoading : function()
	{
		var u = this.options.loader || this.options.update;

		if(!u || $type(u) != 'element' || this.options.noloader)
			return;
	
		var c = u.getCoordinates();
		if(u.getStyle('position') == 'static')
			u.setStyle('position', 'relative');
		this.loader = new Element('div', 
			{ 
				'class' : 'loader',
				'styles' : 
				{
					'width' : Math.max(c.width - 2, 0),
					'height' : Math.max(c.height - 2, 0)
				}
			}).inject(u);
		this.loader.setStyle('opacity', 0.3);
	
		
		this.imgloader = new Element('img', 
			{
				'src' : 'images/loading.gif',
				'styles' : 
				{
					'position' : 'absolute',
					'left' : Math.max(c.width / 2 - 8),
					'top' : Math.max(c.height / 2 - 8)
				}
			}).inject(u);
	},
	
	endLoading : function()
	{
		if(this.loader)
			this.loader.remove();
		if(this.imgloader)
			this.imgloader.remove();
	}
	
});



function SendRequest(url, func)
{
	var xhr = null;
	
	resText = '';
	if(window.XMLHttpRequest)
		xhr = new XMLHttpRequest();
	else if(window.ActiveXObject)
		xhr = new ActiveXObject('Microsoft.XMLHTTP');
	else
		return alert('Non compatible');
	
	xhr.open('GET', url, true);
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4 || xhr.readystate == 4) 
			func(xhr);
		}
	xhr.send(null);
}

function StartLoading(id)
{
	if(typeof(id) == 'string')
		d = document.getElementById(id);
	else
		d = id;
	
	
	i = document.createElement('img');
	i.setAttribute('src', 'images/loading.gif');
	i.setAttribute('id', 'img_loading');
	
	l = document.getElementById('img_loading');

	
	if(d && !l)
		d.appendChild(i);
}

function StopLoading()
{
	l = document.getElementById('img_loading');
	if(l)
		l.parentNode.removeChild(l);
}

function XMLGetNode(node, name)
{
	var l = Array();
	
	if(!node)
		return l;
	
	var i = 0;
	var n = node.firstChild;
	
	while(n)
	{
		if(n.nodeName == name)
			l[i++] = n;
		n = n.nextSibling;
	}

	return l;
	
}

function XMLGetValue(node, name)
{
	if(!name)
	{
		if(node.firstChild)
			return node.firstChild.nodeValue;
		else
			return null;
	}
	
	s = Array();
	l = node.getElementsByTagName(name);
	
	for(var i = 0; i < l.length; i++)
	{
		if(l[i].firstChild)
			s[i] = l[i].firstChild.nodeValue;
		else
			s[i] = '';
	}

	if(s.length == 1)
		return s[0];
	else
		return s;
	
}

function XMLParseErrors(xml, cb)
{
	var err = XMLGetNode(XMLGetNode(xml, 'erreurs')[0] , 'erreur');

	for(var i = 0; i < err.length; i++)
	{
		var el = $('err_' + XMLGetValue(err[i], 'champs'));
		if(el)
		{
			el.setHTML(XMLGetValue(err[i], 'message'));
			if(cb)
				cb(el);
		}

	}
	
	return (err.length > 0);
}