var XML2Object = function(param_xml){
	this.src = param_xml;
	this.finalObject  = this.parseElement(this.src.childNodes[0]);
	var self = this;
};



XML2Object.prototype = {

		LISTABLE_KEYWORD:'listable',
		
		
		parseElement:function(param_xml){
			//alert('new node : ' +  param_xml.nodeName);
			var res = {};
			var i = 0;
			
			
			if (this.isListable(param_xml)) {	
				res = [];
				i = 0;
				for (i < 0 ; i < param_xml.childNodes.length; ++i) {
					res[i] = this.parseElement(param_xml.childNodes[i]);
				}
				return res;
			}
			
			if (this.hasAttributes(param_xml)) {
				//alert('property has attributes');
				res = this.getAttributes(param_xml);
				if (!this.hasComplexContent(param_xml) && !this.isEmpty(param_xml)){
					res.value = param_xml.childNodes[0].nodeValue;
				}
			}
			
			if (!this.hasAttributes(param_xml) && !this.hasComplexContent(param_xml) && !this.isEmpty(param_xml)){
				//alert('property has no attributes and no complex content');
				res = param_xml.childNodes[0].nodeValue;
			}

			if(!this.hasComplexContent(param_xml)){
				//alert('property has no complex content');
				return res;
			}

			//alert('nothing special, iterating on children');
			if (res == null) 
				res = { };
			for (i < 0 ; i < param_xml.childNodes.length; ++i) {
				//alert('found one children ' + param_xml.childNodes[i].nodeName);
				res[param_xml.childNodes[i].nodeName]  = this.parseElement(param_xml.childNodes[i]);
			}

			return  res;
		},
		
		
		hasComplexContent:function(param_xml){			
			if(param_xml.childNodes.length == 0)
				return false;
			
			if(param_xml.childNodes.length > 1)
				return true
			
			if(param_xml.childNodes[0].nodeName == "#text" || param_xml.childNodes[0].nodeName == "#cdata-section")
				return false;
			else
				return true;
		},
		
		
		isEmpty:function(param_xml){
			return param_xml.childNodes.length == 0 ? true : false;
		},
		

		hasAttributes:function(param_xml) {
			if(param_xml.attributes == null)
				return false;
			
			var count = 0;
			for (i = 0; i< param_xml.attributes.length;i++){ 
				if(param_xml.attributes[i].nodeName != XML2Object.prototype.LISTABLE_KEYWORD)
					count++;
			}

			return count > 0 ? true : false;
		},
			

		getAttributes:function(param_xml) {
			var result = {};
			for (i=0;i < param_xml.attributes.length;i++){ 
				if(param_xml.attributes[i].nodeName != XML2Object.prototype.LISTABLE_KEYWORD){
					 result[param_xml.attributes[i].nodeName] = param_xml.attributes[i].nodeValue;
				}
			}
			return result;
		},
		
		
		isListable:function(param_xml) {
			if (jQuery(param_xml).attr(XML2Object.prototype.LISTABLE_KEYWORD) != undefined)
				return true	
			return false;
		}


};
