var DataGrid = Class.create();

DataGrid.prototype = {
	initialize : function(tableID, sql, limit) {
		this.headers = '';
		this.sql = sql;
		this.searchQuery = '';
		this.table = $(tableID);
		this.limit = limit;
		this.totalHeaders = 1;
		this.totalResults = 0;
		this.offset = 0;
		this.order = 'name ASC';
		this.activeHeader = '';
		
		this.showLoading();
		
		this.getResults(this.sql);
	},
	showLoading : function() {
		//this.clearData();
		//this.clearFooter();
		
		if ($('griddata-tr-header')) {
			//$('griddata-tr-header').hide();
		}
		
		//tr = this.table.tBodies[0].appendChild(document.createElement('tr'));
		//td = document.createElement('td');
		//td.appendChild(document.createTextNode('Loading Data. Please Wait...'));
		//td.setAttribute('align', 'center');
		if (this.totalHeaders) {
			//td.colSpan = this.totalHeaders;
		}
		//tr.appendChild(td);
	},
	getResults : function () {
		var ajaxObj = new Ajax.Request(
			'/?class=bb_datagrid&method=getData&global[noincludes]=rawtext&global[no_css]=true&global[no_javascript]=true',
			{
				method: 'POST',
				parameters: 'global[fields][sql]=' + this.sql + '&global[fields][orderby]=' + this.order + '&global[fields][limit]=' + this.limit + '&global[fields][offset]=' + this.offset + '&global[fields][search]=' + this.searchQuery,
				onComplete: function(obj) {
					if (obj.responseXML.firstChild) {
						this.processResults(obj.responseXML);
					} else {
						this.clearData();
						tr = this.table.tBodies[0].appendChild(document.createElement('tr'));
						td = document.createElement('td');
						td.appendChild(document.createTextNode('There was a problem trying to retrieve your results.'));
						td.setAttribute('align', 'center');
						td.colSpan = this.totalHeaders;
						tr.appendChild(td);
					}
				}.bind(this)
		});
	},
	processResults : function (xml) {
		this.clearData();
		
		var tmpHeaders = '';
		var cnt = 0;
		
		//Process Header. Need to find a better way of checking whether it's the same header..
		var headers = xml.getElementsByTagName('header');
		for (i = 0; i < headers.length; i++) {
			tmpHeaders += headers[i].firstChild.nodeValue;
			cnt++;
		}
		
		this.totalHeaders = cnt;
		
		if (tmpHeaders != this.headers) {
			this.headers = tmpHeaders;
			
			this.clearHeader();
			
			var headersFields = xml.getElementsByTagName('header-field');
			
			tr = this.table.tHead.appendChild(document.createElement('tr'));
			tr.setAttribute('id', 'griddata-tr-header');
			for (i = 0; i < headers.length; i++) {
				td = document.createElement('td');
				td.appendChild(document.createTextNode(headers[i].firstChild.nodeValue));
				td.setAttribute('id', 'griddata-header' + headersFields[i].firstChild.nodeValue);
				tr.appendChild(td);
				$('griddata-header' + headersFields[i].firstChild.nodeValue).addClassName('griddata-header');
			}
			
			$$('.griddata-header').each(function(elm) {
				if (elm.innerHTML == 'Name') {
					elm.setStyle({cursor: 'hand', width: '140px'});
				} else {
					elm.setStyle({cursor: 'hand'});
				}
				
				Event.observe(elm, 'click', function(e) {
					elm = Event.element(e);
					field = elm.id.replace('griddata-header', '');

					if (this.activeHeader && (this.activeHeader.innerHTML != elm.innerHTML)) {
						if (this.activeHeader.hasClassName('griddata-order-desc')) {
							this.activeHeader.removeClassName('griddata-order-desc');
						} else if (this.activeHeader.hasClassName('griddata-order-asc')) {
							this.activeHeader.removeClassName('griddata-order-asc');
						}
					}
					if ((this.activeHeader.innerHTML == elm.innerHTML) || (!this.activeHeader.innerHTML && elm.innerHTML == 'Name')) {
						if (elm.hasClassName('griddata-order-desc')) {
							elm.addClassName('griddata-order-asc');
							elm.removeClassName('griddata-order-desc');
							this.orderBy(field, 'asc');
						} else {
							elm.addClassName('griddata-order-desc');
							elm.removeClassName('griddata-order-asc');
							this.orderBy(field, 'desc');
						}
					} else {
						this.activeHeader = elm;
						elm.addClassName('griddata-order-asc');
						this.orderBy(field, 'asc');
					}
				}.bind(this));
			}.bind(this));
		}
		
		if ($('griddata-tr-header')) {
			$('griddata-tr-header').show();
		}
		
		//Process Data
		var rows = xml.getElementsByTagName('row');
		for (i = 0; i < rows.length; i++) {
			tr = this.table.tBodies[0].appendChild(document.createElement('tr'));
			tr.setAttribute('id', 'griddata-data' + i);
			if (i % 2 == 0) {
				$('griddata-data' + i).addClassName('griddata-data-even');
			} else {
				$('griddata-data' + i).addClassName('griddata-data-odd');
			}
			var cells = rows[i].getElementsByTagName("cell");
			for (j = 0; j < cells.length; j++) {
				td = document.createElement('td');
				td.setAttribute('id', 'griddata-data' + i + '-' + j);
				tr.appendChild(td);
				if (cells[j].hasChildNodes()) {
					$('griddata-data' + i + '-' + j).update(cells[j].firstChild.nodeValue);
				} else {
					$('griddata-data' + i + '-' + j).update('&nbsp;');
				}
			}
		}
		
		//Show Footer
		var pageStart = this.offset + 1;
		var total = xml.getElementsByTagName('total');
		total = total[0].firstChild.nodeValue * 1;
		
		var pageTotal = (this.offset + this.limit) * 1;
		
		if (pageTotal > total) {
			pageTotal = total;
		}
		
		var html = '';
		
		if (pageStart != 1) {
			html += '<a href="javascript:void(0);" id="griddata-footer-prevpage"><<</a> ';
		}
		
		if (total) {
			html += 'Currently Viewing ' + pageStart + '-' + pageTotal + ' of ' + total;
		} else {
			html += 'Your search returned no results';
		}
		
		if (pageTotal != total) {
			html += ' <a href="javascript:void(0);" id="griddata-footer-nextpage">>></a>';
		}
		
		if (total) {
			//html += ' <br /><a href="javascript:void(0);" id="griddata-footer-exportcsv">Export Csv</a>';
		}
		
		this.clearFooter();
		
		tr = this.table.tFoot.appendChild(document.createElement('tr'));
		td = document.createElement('td');
		td.innerHTML = html;
		td.setAttribute('align', 'center');
		if (this.totalHeaders) {
			td.colSpan = this.totalHeaders;
		}
		tr.appendChild(td);
		
		if ($('griddata-footer-prevpage')) {
			Event.observe($('griddata-footer-prevpage'), 'click', function(e) {
				this.prevPage();
			}.bind(this));
		}
		
		if ($('griddata-footer-nextpage')) {
			Event.observe($('griddata-footer-nextpage'), 'click', function(e) {
				this.nextPage();
			}.bind(this));
		}
		
		if ($('griddata-footer-exportcsv')) {
			Event.observe($('griddata-footer-exportcsv'), 'click', function(e) {
				this.exportCsv();
			}.bind(this));
		}
		
		tt_Init();
	},
	exportCsv : function() {
		window.location = '/?class=bb_datagrid&method=exportCsv&global[fields][sql]=' + this.sql + '&global[fields][orderby]=' + this.order;
	},
	orderBy : function (field, order) {
		this.showLoading();
		this.order = field + ' ' + order;
		this.getResults();
	},
	prevPage : function () {
		this.showLoading();
		this.offset -= this.limit;
		this.getResults();
	},
	nextPage : function () {
		this.showLoading();
		this.offset += this.limit;
		this.getResults();
	},
	search : function (searchQuery) {
		this.showLoading();
		this.offset = 0;
		this.order = '';
		this.searchQuery = searchQuery;
		this.getResults();
	},
	clearData : function () {
		if (this.table.tBodies[0].hasChildNodes()) {
			while (this.table.tBodies[0].childNodes.length >= 1 ) {
				this.table.tBodies[0].removeChild(this.table.tBodies[0].firstChild);
			}
		}
	},
	clearHeader : function () {
		if (this.table.tHead.hasChildNodes()) {
			while (this.table.tHead.childNodes.length >= 1 ) {
				this.table.tHead.removeChild(this.table.tHead.firstChild);
			}
		}
	},
	clearFooter : function () {
		if (this.table.tFoot.hasChildNodes()) {
			while (this.table.tFoot.childNodes.length >= 1 ) {
				this.table.tFoot.removeChild(this.table.tFoot.firstChild);
			}
		}
	}
}

