/**
 * XmlPost handler
 *
 * XmlPost uses POST requests to receive XML responses
 *
 * @author Ollie Maitland
 * @copyright Byng Systems LLP
 * @requires Mootools-1.2
 */

Byng.register('byng.ajax.post',
{
	/**
	 * Extend the ByngAjax dispatcher
	 * 
	 */
	Extends : 'byng.ajax',
	
	/**
	 * Construct the XmlPost class
	 * 
	 * @param Object options
	 */
	initialize : function (options)
	{
		if ($type(options) == 'string') {
			// legacy support for parameterised construct
			options = { 'gateway' : options };
		}
		
		if ($type(options) == 'object') {
			this.parent(options);
			if (!this.options.onComplete) {
				this.addEvent('complete', $empty);
			}		
		}
		
		this.addEvent('response', this.process.bind(this));
	},
		
	/**
	 * Fetch the XML response and format into JavaScript array
	 * 
	 * @param Function readHandler
	 */ 
	fetch : function (options)
	{
		if ($type(options) == 'function') {
			options = {'onComplete' : options}
		}
		
		// set the global scope object
//		if (XmlPostObj != this) XmlPostObj = this;

		if ($type(options) == 'object') {
			this.setOptions(options);
			if (this.options.onComplete) {
				this.addEvent('complete', this.options.onComplete);
			}
		}
		
		return this.post();	
	},
	
	/**
	 * Set the action
	 * 
	 * @param String action
	 */ 
	setAction : function (action) 
	{	
		this.options.vars.set('action', action);
		this.composeQueryString ();
	},
	
	/**
	 * Process the XML response
	 * 
	 * @param String xml XML reply
	 */
	process : function (xml) 
	{
		if (this.debug == true) {
			alert (xml);
		}
		
		if (xml == "") {
			throw ("Empty response from server");
		}
	
		// Get a local istance of ByngXml
		var parser = new ByngXml();
	
		try {
			// Parse the Xml
			xmlTree = parser.parseXml(xml);
		} catch (e) {
			if (Byng.debug) alert (e);
		}
		
		this.fireEvent('complete', [xmlTree, this]);
	}
	
});

/**
 * @legacy
 */
var XmlPost = Byng.source('byng.ajax.post');
