/* Silently create the mcd namespace if it does not exist */
if (typeof mcd === 'undefined') {
	var mcd = [];
}

/**
 * xmlHandler.js
 * 
 * controls xml importing, and converts XML to an array
 * 
 * @author Brendan Barr (bbarr@mcdpartners.com)
*/

mcd.xmlHandler = {
	
	/** 
	 * fetch XML
	 * 
	 * @param {Object} params
	 * @param {Function} success
	 * @param {Function} failure
	 */
	get : function(params, success, failure){
		
			failure = failure || mcd.privileges.page.error
		
			var xml = mcd.http.request(params);
			
			xml.onreadystatechange = function(){
				if (xml.readyState === 4) {
					
					if(xml.status === 200) {
						success(xml.responseXML);
					}
					else {
						failure();
					}
				}
			}
			xml.send('');
	},
	
	/**
	 * Used by buildArray method to convert an XML document node 
	 * (with children)to an Object, and add that Object to an Array
	 * 
	 * @param {XmlNode} node
	 * @param {Array} array
	 */
	toArray : function(node, array) {
		
		var subNodes = node.getElementsByTagName('*');
		var subObject = {};
		
		for(var i = 0; i < subNodes.length; i++) {
			
			var name = subNodes[i].tagName;
			
			// if nodeContent is null, assign an empty string
			var content = (subNodes[i].childNodes[0]) ? subNodes[i].childNodes[0].nodeValue : '';
			var children = subNodes[i].getElementsByTagName('*');
			
			//if(children == 'image'){alert('children name' + children);}
			
			// add children to parent Object
			if (children.length > 0) {
				subObject[name] = [];
				for (var x = 0; x < children.length; x++) {
					if (children[x].childNodes[0]) {
						/* nakhade added if condition 04/15/2011 to avoid image distortion if image size less than standard size 127*190 */
						//if image tag having style attribute add the nodevalue with attribute value in array
						if(children[x].attributes.length > 0){
								var imageStyle = children[x].attributes.getNamedItem('style').value;
								imageStyle = children[x].childNodes[0].nodeValue + ':' + imageStyle;
								subObject[name].push(imageStyle);
						}else{
								subObject[name].push(children[x].childNodes[0].nodeValue);
						}						
					}
					i++;
				}
			}
			else {
				subObject[name] = content;
			}
		}
		array.push(subObject);
	},
	
	/**
	 * Generate Array of Objects from XML Document Node Set
	 * 
	 * @param {XmlNodeSet} nodes
	 * @param {Array} array
	 * @param {Function} callback
	 */
	buildArray : function(nodes, array, callback) {
	
		for(var i = 0; i < nodes.length; i++) {
			mcd.xmlHandler.toArray(nodes[i], array);
		}
		
		callback();
	}
};
