/**
 * @author bjackson
 */

/**
 * Get XML in and out of an associative array of property name/value pairs or an object.
 */
function PropertiesXML(properties)
{
	this.properties;

	this.setObject = function(obj, properties)
	{
		// TODO $this.properties =& Properties::get($obj, $properties);
	}

	/**
	 * Constructor.
	 * 
	 * @param properties an associative array if obj is null, otherwise an array of property names
	 * @param obj if not null then properties is an array of property names from the object
	 * @see Properties#get
	 */
	this.phpPropertiesXML = function(obj, properties)
	{
		if (!obj)
		{
			this.properties = properties ? properties : new Array();
		}
		else
		{
			this.setObject(obj, properties);
		}
	}

	this.phpPropertiesXML(null, properties);

	this.setXML = function(xml)
	{
		/*
		$dom = new XPath();
		if ($dom->open_string($xml))
		{
			$context = $dom->select('//Properties/Property');
			if ($context)
			{
				foreach ($context->nodeset as $node)
				{
					if ($node->has_attribute('name'))
					{
						$name = trim($node->get_attribute('name'));
						$result[$name] = trim($node->get_content());
					}
				}
			}
		}
		$this->properties = $result;
		$dom->close();
		*/
	}

	this.getXML = function()
	{
		var	xml = this.listBegin()
				+ this.getPropertyElements()
				+ this.listEnd();
		return xml;
	}

	this.listBegin = function()
	{
		return '<?xml version="1.0" encoding="UTF-8"?><Properties>';
	}
	
	this.listEnd = function()
	{
		return '</Properties>';
	}

	this.getPropertyElements = function()
	{
		var xml = '';
		for (name in this.properties)
		{
			xml += '<Property name="' + name + '">' + this.properties[name] + '</Property>';
		}
		return xml;
	}

	this.getAttribute = function(element, attribute, defaultValue)
	{
		var result;
		if (element.attributes)
		{
			result = element.getAttribute(attribute);
		}
		return result ? result : defaultValue;
	}

	this.getString = function(string, defaultValue)
	{
		var str = string ? string : defaultValue;
		// TODO: str.trim();
		return str;
	}

	this.getNodeContent = function(node)
	{
		var str = this.getString(node.nodeValue, "");
		for (var ii = 0; ii < node.childNodes.length; ii++)
		{
			str += this.getNodeContent(node.childNodes[ii]);
		}
		return str;
	}

	this.parse = function(xml)
	{
		var elements = xml.getElementsByTagName('Property');
		for (var ii = 0; ii < elements.length; ii++)
		{
			if (elements[ii].attributes)
			{
				var element = elements[ii];
				var name = this.getAttribute(element, 'name', null);
				if (name)
				{
					this.properties[name] = this.getNodeContent(element.firstChild);
				}
			}
		}
	}
}
