
var XML = new Class({ 
	debug : false,
	
	initialize : function(xml, expected_root_name, debug)
	{
		if(debug)
			this.debug = true;
			
		if(!xml || !xml.firstChild)
			return  this.Error('XML invalide\n' + xml, true);
		
		if(expected_root_name && xml.firstChild.nodeName != expected_root_name)
			return  this.Error('Root node name doesn\'t match expected node name\n' + xml.firstChild.nodeName + ' should be ' + expected_root_name);
			
		this.xml = xml.firstChild;
	},
	
	getNode : function(node_name, node)
	{
		if(this.blocked)
			return;
			
		return this.getNodes(node_name, node)[0];
	},
	
	getNodes : function(node_name, node)
	{
		if(this.blocked)
			return;
			
		if(!node)
			node = this.xml;
		
		var l = [];
		var i = 0;
		var n = node.firstChild;
		while(n)
		{
			if(n.nodeName == node_name)
				l[i++] = n;
			n = n.nextSibling;
		}
			
		return l;
	},
	
	getValue : function(node_name, node)
	{
		if(this.blocked)
			return;
			
		if(node_name.firstChild)
			return node_name.firstChild.nodeValue;

		return this.getValues(node_name, node)[0];
	},
	
	getValues : function(node_name, node)
	{
		if(this.blocked)
			return;
			
		if(node_name.firstChild)
			return this.Error('Can\'t get multiple values from one node');
			
		var s = [];
		var l = this.getNodes(node_name, node);
		for(var i = 0; i < l.length; i++)
			s[i] = this.getValue(l[i]);
		
		return s;

	},
	
	Parse : function(node_name, node, cb)
	{
		if(this.blocked)
			return;
			
		if(!cb)
			return this.Error('No callback defined for parsing');
		if(!node_name)
			return this.Error('No node name to parse');

		var l = this.getNodes(node_name, node);
		for(var i = 0; i < l.length; i++)
			cb(l[i]);
		
		return l.length;
	
	},
		
	
	ParseErrors : function(cb, elmt_filter)
	{
		if(this.blocked)
			return;
			
		if(!elmt_filter)
			elmt_filter = 'err_{champs}';
		
		var l = this.Parse('erreur', this.getNode('erreurs'), function(n)
		{	
			var c = this.getValue('champs', n);
			var m = this.getValue('message', n);
			var el = $(elmt_filter.replace(/{champs}/, c));
			if(el)
				el.setHTML(m);
			if(cb)
				cb(el, c, m);
		}.bind(this));
		
		return l > 0;
	},
	
	
	Error : function(err_msg, block)
	{
		if(block)
			this.blocked = true;
		this.error = err_msg;
		if(this.debug)
			alert(this.error);
	}
	
		


});