/**
 * ByngTable exporter
 * 
 * Exports a table to an interchangeable format (e.g. Excel)
 * 
 * @requires Mootools-1.2
 * 
 * @author Ollie Maitland
 * @copyright Byng Systems LLP
 */
Byng.register('byng.table.export', 
{
	
	Implements : [Options],
	
	/**
	 * Instance of the ByngTable
	 * 
	 * @param ByngTable
	 */
	table : null,
	
	/**
	 * Holds headings
	 * 
	 */
	headings : [],
	
	/**
	 * Row data
	 * 
	 */
	rowData  : [],
	
	/**
	 * Holds the default options
	 * 
	 */
	options : {
		'request' : null,
		'onComplete' : null,
		'target' : null,
		'source' : null
	},
	
	/**
	 * Initialise the table export
	 * 
	 * @param Object options
	 */
	initialize : function ( table, options )
	{
		this.setOptions( options );
		
		if (!options.request) {
			this.options.request = new ByngRequest('default','exporter','ui','ajax');
			this.options.request.setAction('output');
		}
		
		if (!options.source) {
			this.options.source = document.getElements('table.listing');
		}
		
		this.table = table;
	},
	
	/**
	 * Find data within an element
	 * 
	 * @param DomElement elem
	 */
	findData : function(elem) 
	{
		// check if there is a child ement
		if(elem.firstChild) {
			var text = '';
			$each(elem.childNodes, function(node) {
				if (text == '') {
					text = this.findData(node);
				}	
			}.bind(this));
			return text;
		}else{
			return (elem.textContent ? elem.textContent.trim() : (elem.data ? elem.data.trim() : ''));
		}
	},
	
	/**
	 * Parse table data into a transit data structure
	 * 
	 */
	parseData : function ()
	{
		this.options.source.getElements('thead th').each(function(th, pos) {
			this.headings.push(this.findData(th));
		}.bind(this));
		
		this.rowData = [];
		this.options.source.getElements('tbody tr').each(function(tr,count) {
			
			// new row array
			var row = [];
			
			// loop over the td array
			tr.getElements('td').each(function(td){
				row.push(this.findData(td));
			}.bind(this));
			
			this.rowData.push(row);	
		}.bind(this));
	},
	
	/**
	 * Submit an export for building
	 * 
	 * @return void
	 */
	submit : function ()
	{
		try {
			this.parseData();
			Byng.transit.setRequest(this.options.request);
			Byng.transit.post({
						'onComplete' : Byng.transit.download.bind(this)
						}, {
						'data'       : Byng.transit.toJson(this.rowData),
						'headings'   : Byng.transit.toJson(this.headings),
						'output'     : 'csv'
			});
		} catch (e) {
			throw e;
		}
	}
	
});

if (typeof(ByngTable) != "undefined") {
	// implement ByngTable.toFile() method
	ByngTable.implement({
		toFile : function () {
			if (!this.__exporter) {
				this.__exporter = Byng.init('byng.table.export', this, {
					'source' : this.getTable()
				});
			}
			this.__exporter.submit();
		}
	});
}
