/*******************

Author: Mateus Artur Schneiders (Sioux)
Date: 02/13/2010
Objectivo: Sort table columns with AJAX requests

*********************/
function AjaxTableSorter(form, target, tableId, requestPage)
{
	this._targetId = target;
	this._tableId = tableId;
	this._formId = form;
	this._requestPage = requestPage;
	this._sortColumns;
	this._sortedColumns;
	this.setTableId     = function(id){ this._tableId = id;}
	this.setRequestPage = function(requestPage){ this._requestPage = requestPage;}
	this.getTargetId    = function(){ return this._targetId; }
	this.getTableId 	= function(){ return this._tableId; }
	this.getRequestPage = function(){ return this._requestPage; }
	this.getSortColumns = function(){ return this._sortColumns; }
	this.getSortedColumns = function(){return this._sortedColumns; }
	this.getForm = function(){return this._formId;}
	
	this.addSortColumn  = function(idx, sortName){ 
		if(!this.getSortColumns()) {
			this._sortColumns = new Array();
		}			
		var col = new SortColumn(idx, sortName);
		
		this.getSortColumns().push(col); 
		this._updateSortColumn(col);
	}
	
	this._getColumnCollection = function(){
		var table = document.getElementById(this.getTableId());
		if(table){
			return table.getElementsByTagName("TH");
		}
		return null;
	}
	
	this._updateSortColumn = function(col){
		var columnCollection = this._getColumnCollection();
		if(columnCollection){
			var column = columnCollection[col.getIndex()];
			col.setElement(column);
			
			column.parentRef = this;
			column.colReference = col;
			$(column).attr('title', 'Clique para Ordenar');
			$(column).bind('click', function(){ this.parentRef.doSort(this.colReference); });
		}
	}
	
	this.doSort = function(col)
	{
		var el = document.getElementById(this._targetId);
		var form = document.getElementById(this._formId);
		
		if(el && form){
			el.value = col.getSortName();
			form.submit();
		}
		return;
	}
}

function SortColumn(idx, sortName)
{
	this._index = idx;
	this._sortName = sortName;
	this._domElement;
	this._sortType;
	this._isSorted;
	this.getIndex    = function(){ return this._index; }
	this.getSortName = function(){ return this._sortName; }
	this.getElement  = function(){ return this._domElement; }
	this.getSortType = function(){ return this._sortType; }
	this.getIsSorted = function(){ return this._isSorted; }
	this.setElement  = function(el) { this._domElement = el; }
	this.setSortType = function(sortType){ this._sortType = sortType;}
	this.setIsSorted = function(value) { this._isSorted = value; }
}

