GALILEO.util.Event.columnMove = new YAHOO.util.CustomEvent("columnMove");

/**
 * Utilidad de movimiento de columnas
 * oDataTable Tabla de datos
 * sHandleId Id del elemento sobre el que haremos el dragger
 * sGroup (Opcional) Grupo al que pertenece el dragger
 * oConfig (Opcional) Configuraciones adicionales
 **/
GALILEO.util.GColumnMover = function(oDataTable, sHandleId, sGroup, oConfig) {
	
	if(oDataTable && sHandleId) {
        this._datatable = oDataTable;
        this.init(sHandleId, sGroup, oConfig);		
        this._initializeMover();
        this.setConstraints();
    }
};

YAHOO.extend(GALILEO.util.GColumnMover, YAHOO.util.DDProxy);

GALILEO.util.GColumnMover.prototype._datatable = null;
GALILEO.util.GColumnMover.prototype._thDestino = null;
GALILEO.util.GColumnMover.prototype._isFinalTarget = false;

GALILEO.util.GColumnMover.prototype._initializeMover = function() {
	
	this.initFrame();	
	
	var s = this.getDragEl().style;
    s.borderColor = s.borderWidth = s.borderStyle = '';	
};

GALILEO.util.GColumnMover.prototype.setConstraints = function() {

	this.setYConstraint(0,0);
	
	var theadRegion = YAHOO.util.Dom.getRegion(this._datatable.getTheadEl());
	var region = YAHOO.util.Dom.getRegion(this.getEl().parentNode);
	this.setXConstraint(region.left - theadRegion.left + 10, theadRegion.right - region.right + 10);
};
   
GALILEO.util.GColumnMover.prototype.startDrag = function(x,y) {

	var dragEl = this.getDragEl();
	var clickEl = this.getEl();
	
	if (YAHOO.util.Dom.hasClass(clickEl, YAHOO.widget.DataTable.CLASS_LABEL)) {
		dragEl.innerHTML = this._getText(clickEl);
		YAHOO.util.Dom.setStyle(dragEl, 'width', clickEl.parentNode.offsetWidth + 'px');
		YAHOO.util.Dom.setStyle(dragEl, 'height', clickEl.offsetHeight + 'px');
		YAHOO.util.Dom.addClass(dragEl, 'gyui-dt-move');
		YAHOO.util.DragDropMgr.mode = 1;
	}
};


GALILEO.util.GColumnMover.prototype.b4Drag = function(e) {
	this.resetConstraints();
	this.setDelta(0,0);
	this.setConstraints();
	GALILEO.util.GColumnMover.superclass.b4Drag.call(this, e);
};

GALILEO.util.GColumnMover.prototype.onDragOver = function (e, ids) {
	if (YAHOO.util.Dom.hasClass(this.getEl(), YAHOO.widget.DataTable.CLASS_LABEL)) {
		this._thDestino = this._getBestId(ids).getEl().parentNode.parentNode;
	}
};

GALILEO.util.GColumnMover.prototype.endDrag = function (e) {
	if (YAHOO.util.Dom.hasClass(this.getEl(), YAHOO.widget.DataTable.CLASS_LABEL)) {
		YAHOO.util.DragDropMgr.mode = 0;
		var startIndex = this.getEl().parentNode.parentNode.cellIndex;
		if (this._thDestino) {
			var finalIndex = this._thDestino.cellIndex;
			this._moveColum(startIndex, finalIndex);
			GALILEO.util.Event.columnMove.fire({start: startIndex, final: finalIndex, isFinalTarget: this._isFinalTarget});
		}
	}
};

GALILEO.util.GColumnMover.prototype._getText = function(el) {
	var text = "";
	var enlaces = GALILEO.util.Dom.getElementsByTagName('a', el);
	if (enlaces.length > 0) {
		var imgs = GALILEO.util.Dom.getElementsByTagName('img', enlaces[0]);
		if (imgs.length > 0) {
			enlaces[0].removeChild(imgs[imgs.length - 1]);
		}	
		text = enlaces[0].innerHTML;
	}
	else {
		text = el.innerHTML;
	}
	
	return text;
};

GALILEO.util.GColumnMover.prototype._getBestId = function(dds) {

	var winner = null;
	var len = dds.length;
	
	if (len === 1) {
		winner = dds[0];
		if (YAHOO.util.Dom.hasClass(winner.getEl(), GALILEO.widget.GDataTable.FIRST_TARGET_CLASS) || YAHOO.util.Dom.hasClass(winner.getEl(), GALILEO.widget.GDataTable.LAST_TARGET_CLASS)) {
			this._isFinalTarget = true;
		}
	}
	else {
		var maxCellIndex = 0;
		for (var i = 0; i < len; i++) {
			var dd = dds[i];
			
			if (YAHOO.util.Dom.hasClass(dd.getEl(), GALILEO.widget.GDataTable.FIRST_TARGET_CLASS) || YAHOO.util.Dom.hasClass(dd.getEl(), GALILEO.widget.GDataTable.LAST_TARGET_CLASS)) {
				winner = dd;
				this._isFinalTarget = true;
				break;
			} else if (maxCellIndex < dd.getEl().parentNode.parentNode.cellIndex) {
				winner = dd;
				maxCellIndex = dd.getEl().parentNode.parentNode.cellIndex;
			}
		}
	}
	
	return winner;
};

GALILEO.util.GColumnMover.prototype._moveColum = function(startIndex, finalIndex) {
	
	var row = null;
	var ultima = false;
	var i = this._datatable.getTheadEl().rows.length;

	if (this._isFinalTarget && (this._datatable.getTheadEl().rows[0].cells.length === (finalIndex + 1))) {
		ultima = true;
	}
	
	if (!ultima && (startIndex < finalIndex) && !this._isFinalTarget) {
		finalIndex = finalIndex - 1;
	}
	else if (finalIndex === 0 && !this._isFinalTarget) {
		finalIndex = 1;
	}
	
	if (startIndex != finalIndex) {
		while (i--) {
			row = this._datatable.getTheadEl().rows[i];
			var x = row.removeChild(row.cells[startIndex]);
			if (this._isFinalTarget && finalIndex === 0) {
				YAHOO.util.Dom.insertBefore(x, row.firstChild);
			} else {
				if (!ultima) {
					YAHOO.util.Dom.insertBefore(x, row.cells[finalIndex]);
				} else {
					row.appendChild(x);
				}
			}
		}
		
		i = this._datatable.getTbodyEl().rows.length;
		while (i--) {
			row = this._datatable.getTbodyEl().rows[i];
			var x = row.removeChild(row.cells[startIndex]);
			if (this._isFinalTarget && finalIndex === 0) {
				YAHOO.util.Dom.insertBefore(x, row.firstChild);
			} else {
				if (!ultima) {
					YAHOO.util.Dom.insertBefore(x, row.cells[finalIndex]);
				} else {
					row.appendChild(x);
				}
			}
		}
	}
};








/**
 * Definicion de un componente de tabla de datos, el cual posee los efectos de ordenacion, seleccion de
 * filas, movimiento y cambio de columnas.
 * @param el id o htmlObject que identifica el elemento contenedor de la tabla con la que vamos a trabajar
 * @param aColumnDefs Definiciones de columna, ver documentacion de yui para mas informacion
 * @param oResponseSchema Definicion del esquema del datasource de la tabla
 * @param oConfigs (Opcional) Objeto con configuraciones adicionales para la construccion de la datatable
 * @param oTfoot (Opcional) Objeto con la configuracion base del tfoot
 *			- rows Array de filas del tfoot
 *  	        - className: Nombre de la clase que tendra el tr del tfoot
 *      	    - cells Array con los datos de las celdas del tfoot para la fila
 *                  - data String con los datos a mostrar
 *                  - colspan Cuantas columnas ha de expandirse esa columna del tfoot
 *                  - className Clase que posee la columna del tfoot 
 * @param paginadorConfig (Opcional) Configuracion del paginador
 *          - name: Nombre del paginador
 *          - url: Url donde dirigir la peticion
 *          - accion: Accion a invocar con la paginacion
 *          - noForm: Indica si el paginador debe usar un formulario o no
 **/
GALILEO.widget.GDataTable = function(el, aColumnDefs, oResponseSchema, oConfigs, oTfoot, paginadorConfig) {
	
	if (el && aColumnDefs && oResponseSchema) {
		if (typeof el == "string") {
			el = YAHOO.util.Dom.get(el);
		}
		
		this._id = el.id;
		
		var table = GALILEO.util.Dom.getElementsByTagName('table', el)[0];
		if (table) {
			var indexMoverColumns = new Array();
			
			for (var i = 0; i < aColumnDefs.length; i++) {
				if (aColumnDefs[i].move && aColumnDefs[i].move == true) {
					indexMoverColumns.push(i);
				}
			}
			var dataSource = new YAHOO.util.DataSource(table);
			dataSource.responseType = YAHOO.util.DataSource.TYPE_HTMLTABLE;
			dataSource.responseSchema = oResponseSchema;
	
			if (oConfigs.scrollable) {
				this._isScrollable = true;
			}
			
			GALILEO.widget.GDataTable.superclass.constructor.call(this, el, aColumnDefs, dataSource, oConfigs);
			if (oConfigs.selectionMode) {
				if (oConfigs.selectionMode == "single" || oConfig.selectionMode == "standard") {
					this.subscribe("rowMouseoverEvent", this.onEventHighlightRow); 
        			this.subscribe("rowMouseoutEvent", this.onEventUnhighlightRow); 
		    	    this.subscribe("rowClickEvent", this.onEventSelectRow); 
			    } else {
				    this.subscribe("cellMouseoverEvent", this.onEventHighlightCell); 
			        this.subscribe("cellMouseoutEvent", this.onEventUnhighlightCell); 
		    	    this.subscribe("cellClickEvent", this.onEventSelectCell); 
			    }
			}
			
			var realWidth = 0;
			if (this.getColumnSet()) {
				var columns = this.getColumnSet().keys;
				for (var i = 0; i < this.getColumnSet().keys.length; i++) {
					var column = this.getColumnSet().keys[i];
					YAHOO.util.Dom.setStyle(this.getThEl(column), 'width', this.getColumnSet().keys[i].width + 'px');
					column._minWidth = this.getColumnSet().keys[i].width;
					realWidth += (parseInt(this.getColumnSet().keys[i].width) + parseInt(GALILEO.widget.DataTable.config.paddingSize));
				}	
			}
				
			if (this._isScrollable) {
				if (GALILEO.util.Navigator.getBrowser() == 'gecko') {
					var lastColumn = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.DataTable.CLASS_LAST, 'th', this.getTheadEl())[0];
					var lastColumnWidth = this._getColumnWidth(lastColumn) + GALILEO.widget.GDataTable.SCROLL_WIDTH
					YAHOO.util.Dom.setStyle(lastColumn, 'width', lastColumnWidth + 'px')
				}
				/*else if (GALILEO.util.Navigator.getBrowser() == 'ie') {
					if (realWidth != 0) {
						YAHOO.util.Dom.setStyle(this.getTableEl().parentNode, 'width', realWidth + 'px');
					} else {
						realWidth = 0;
						for (var i = 0; i < this.getTheadEl().rows[0].cells.length; i++) {
							realWidth += parseInt(this.getTheadEl().rows[0].cells[i].offsetWidth);
						}	
						if (realWidth != 0) {
							YAHOO.util.Dom.setStyle(this.getTableEl().parentNode, 'width', realWidth + 'px');
						} else {
							YAHOO.util.Dom.setStyle(this.getTableEl().parentNode, 'width', '100%');
						}
					}
				}*/
			}

			this._idMoverGroup = "movers-" + this._id;
			for (var i = 0; i < indexMoverColumns.length; i++) {
				var index = indexMoverColumns[i];
				YAHOO.util.Dom.addClass(this.getTheadEl().rows[0].cells[index], GALILEO.widget.GDataTable.MOVER_CLASS);
				var span = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.DataTable.CLASS_LABEL, 'span' , this.getTheadEl().rows[0].cells[index])[0];
				if (span) {
					this._moverArray.push(new GALILEO.util.GColumnMover(this, span.id, this._idMoverGroup));
				}
			}
			
			var headRow = this.getTheadEl().rows[0];
			for (var i = 0; i < headRow.cells.length; i++) {
				var span = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.DataTable.CLASS_LABEL, 'span' , headRow.cells[i])[0];
				if (span) {
					span.innerHTML = this._getText(span);
				}
			}
			
			this._initFinalEls(this._idMoverGroup);
			this._createTfoot(oTfoot);
			
			if (paginadorConfig) {
				var paginadorCallback = {
					success: this._writePage,
					failure: GALILEO.util.Connect.handlerFailure,
					scope: this
				}
				if (paginadorConfig.noForm === true) {
					this._paginador = new GALILEO.widget.PaginadorRequestAsync(paginadorConfig.name, paginadorConfig.url, paginadorConfig.accion, paginadorCallback, paginadorConfig.params);
				} else {
					this._paginador = new GALILEO.widget.PaginadorAsync(paginadorConfig.name, paginadorConfig.url, paginadorConfig.accion, paginadorCallback, paginadorConfig.params);
				}
			}
			
			GALILEO.util.Event.columnMove.subscribe(this._resetTable, this);
			this.subscribe("columnResizeEvent", this._onColumnResizeEvent, this);
			//GALILEO.util.Event.expandedCollapsable.subscribe(this._onCollapsableEvent, this);
			//GALILEO.util.Event.collapsedCollapsable.subscribe(this._onCollapsableEvent, this);
			
			YAHOO.util.Dom.setStyle(this.getTableEl().parentNode, 'visibility', 'visible');
		}
	} 
};

YAHOO.extend(GALILEO.widget.GDataTable, YAHOO.widget.DataTable);

GALILEO.widget.GDataTable.prototype._moverArray    = new Array();
GALILEO.widget.GDataTable.prototype._terminalEl    = new Array();
GALILEO.widget.GDataTable.prototype._paginador     = null;
GALILEO.widget.GDataTable.prototype._isScrollable  = false;
GALILEO.widget.GDataTable.prototype._id = "";
GALILEO.widget.GDataTable.prototype._idMoverGroup = null;

GALILEO.widget.GDataTable.MOVER_CLASS = 'gyui-dt-isMove';
GALILEO.widget.GDataTable.FIRST_TARGET_ID = 'gyui-dt-id-static-first-move';
GALILEO.widget.GDataTable.FIRST_TARGET_CLASS = 'gyui-dt-static-first-move';
GALILEO.widget.GDataTable.LAST_TARGET_ID = 'gyui-dt-id-static-last-move';
GALILEO.widget.GDataTable.LAST_TARGET_CLASS = 'gyui-dt-static-last-move';
GALILEO.widget.GDataTable.SCROLL_WIDTH = 20;
GALILEO.widget.GDataTable.SORT_IMG_WIDTH = 20;
GALILEO.widget.GDataTable.RESIZER_WIDTH = 8;

GALILEO.widget.GDataTable.prototype.updateTfoot = function(oTfoot) {
	this.getTableEl().deleteTFoot();
	this._createTFoot();
};

GALILEO.widget.GDataTable.prototype._createTfoot = function(oTfoot) {
	
	if (oTfoot && oTfoot.rows) {
		this.getTableEl().createTFoot();
		for (var i = 0; i < oTfoot.rows.length; i++) {
  			var tfootRow = this.getTableEl().tFoot.insertRow(i);
  			if ( oTfoot.rows[i].className) {
  				YAHOO.util.Dom.addClass(tfootRow, oTfoot.rows[i].className);
  			}
  			if (oTfoot.rows[i].cells) {
  				for (var j = 0; j < oTfoot.rows[i].cells.length; j++) {
  					var columna = tfootRow.insertCell(j);
  					columna.innerHTML = (oTfoot.rows[i].cells[j].data) ? oTfoot.rows[i].cells[j].data : ""; 
  					if (oTfoot.rows[i].cells[j].colspan) {
  						columna.colSpan = oTfoot.rows[i].cells[j].colspan;
  					}
  					if (oTfoot.rows[i].cells[j].className) {
  						YAHOO.util.Dom.addClass(columna, oTfoot.rows[i].cells[j].className);
  					}
  				}
  			}
  		}
	}
};

GALILEO.widget.GDataTable.prototype._getText = function(el) {
	var text = "";
	var enlaces = GALILEO.util.Dom.getElementsByTagName('a', el);
	if (enlaces.length > 0) {
		var imgs = GALILEO.util.Dom.getElementsByTagName('img', enlaces[0]);
		if (imgs.length > 0) {
			enlaces[0].removeChild(imgs[imgs.length - 1]);
		}	
		text = enlaces[0].innerHTML;
	}
	else {
		text = el.innerHTML;
	}
	
	return text;
};

GALILEO.widget.GDataTable.prototype._changeColumnOrder = function(startIndex, finalIndex, isFinalTarget) {
	var insertAntes = false;
	var inicio = 0;
	var fin = 0;
	var interLeft = 0;
	var interRight = 0;
	
	if (startIndex < finalIndex) {
		inicio = startIndex;
		if (isFinalTarget) {
			interRight = fin = finalIndex + 1;
		} else {
			interRight = fin = finalIndex
		}
		interLeft = inicio + 1;
	} else if (startIndex >= finalIndex) {
		insertAntes = true;
		if (finalIndex === 0 && !isFinalTarget) {
			interLeft = inicio = 1;
		} else {
			interLeft = inicio = finalIndex;
		}
		interRight = startIndex;
		fin = startIndex + 1;
	}
	
	var columnSet = this.getColumnSet();
	var flat = new Array();
	var keys = new Array();
	var tree = new Array();
	var headers = new Array();
	
	this.getColumnSet().flat = this._changeColumnSet(this.getColumnSet().flat, startIndex, insertAntes, inicio, interLeft, interRight, fin);	
	this.getColumnSet().tree[0] = this._changeColumnSet(this.getColumnSet().tree[0], startIndex, insertAntes, inicio, interLeft, interRight, fin);	
	this.getColumnSet().keys = this._changeColumnSet(this.getColumnSet().keys, startIndex, insertAntes, inicio, interLeft, interRight, fin);	
	this.getColumnSet().headers = this._changeColumnSet(this.getColumnSet().headers, startIndex, insertAntes, inicio, interLeft, interRight, fin);	
};

GALILEO.widget.GDataTable.prototype._changeColumnSet = function(array, start, insertAntes, inicio, interLeft, interRight, fin) {

	var left   = array.slice(0, inicio);
	var medium = array.slice(interLeft, interRight);
	if (insertAntes) {
		medium.unshift(array[start]);
	} else {
		medium.push(array[start]);
	}
	var right = array.slice(fin, array.length);	
	return new Array().concat(left, medium, right);
};

GALILEO.widget.GDataTable.prototype._resetTable = function (e, oArgs, obj) {
			
	obj._changeColumnOrder(oArgs[0].start, oArgs[0].final, oArgs[0].isFinalTarget);
	
	var oldFirstColumn = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.DataTable.CLASS_FIRST, 'th', obj.getTheadEl())[0];
	if (oldFirstColumn) {
		YAHOO.util.Dom.removeClass(oldFirstColumn, YAHOO.widget.DataTable.CLASS_FIRST);
	}
	
	var oldLastColumn = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.DataTable.CLASS_LAST, 'th', obj.getTheadEl())[0];
	if (oldLastColumn) {
		YAHOO.util.Dom.removeClass(oldLastColumn, YAHOO.widget.DataTable.CLASS_LAST);
	}
	var theadRow = obj.getTheadEl().rows[0];
	YAHOO.util.Dom.addClass(theadRow.cells[0], YAHOO.widget.DataTable.CLASS_FIRST);
	YAHOO.util.Dom.addClass(theadRow.cells[theadRow.cells.length - 1], YAHOO.widget.DataTable.CLASS_LAST);

	if (obj._isScrollable && GALILEO.util.Navigator.getBrowser() == 'gecko') {
		if (oldLastColumn.id != theadRow.cells[theadRow.cells.length - 1].id) {
			YAHOO.util.Dom.setStyle(oldLastColumn, 'width', (obj._getColumnWidth(oldLastColumn) - GALILEO.widget.GDataTable.SCROLL_WIDTH) + 'px');
			var lastColumnWidth = obj._getColumnWidth(theadRow.cells[theadRow.cells.length - 1]) + GALILEO.widget.GDataTable.SCROLL_WIDTH;
			YAHOO.util.Dom.setStyle(theadRow.cells[theadRow.cells.length - 1], 'width', lastColumnWidth + 'px')
		}
	}	

	obj._resetFinalEls();	
};

GALILEO.widget.GDataTable.prototype._initFinalEls = function(idGroup) {

	this._terminalEl = new Array();
	var columns = YAHOO.util.Dom.getElementsByClassName(GALILEO.widget.GDataTable.MOVER_CLASS, 'th' , this.getTheadEl());
	if (columns && columns.length > 0) {
		var firstMove = GALILEO.util.Dom.createElement('span', [{name: 'id', value: YAHOO.util.Dom.generateId(null, GALILEO.widget.GDataTable.FIRST_TARGET_ID)}, {name: 'className', value: GALILEO.widget.GDataTable.FIRST_TARGET_CLASS}]);
		var divFirstMoveColumn = GALILEO.util.Dom.getElementsByTagName('div' , columns[0])[0];
		YAHOO.util.Dom.insertBefore(firstMove, divFirstMoveColumn.firstChild);
		this._terminalEl.push(new YAHOO.util.DDTarget(firstMove.id, idGroup));
		var lastMove = GALILEO.util.Dom.createElement('span', [{name: 'id', value: YAHOO.util.Dom.generateId(null, GALILEO.widget.GDataTable.LAST_TARGET_ID)}, {name: 'className', value: GALILEO.widget.GDataTable.LAST_TARGET_CLASS}]);
		var divLastMoveColumn = GALILEO.util.Dom.getElementsByTagName('div' , columns[columns.length - 1])[0];
		YAHOO.util.Dom.insertAfter(lastMove, divLastMoveColumn.lastChild);
		this._terminalEl.push(new YAHOO.util.DDTarget(lastMove.id, idGroup));
	}
};

GALILEO.widget.GDataTable.prototype._writePage = function(o) {

	var div = document.createElement('div');
	div.innerHTML = o.responseText;
	
	var data = this.getDataSource().parseHTMLTableData(null, GALILEO.util.Dom.getElementsByTagName('table', div)[0]);
	
	this.initializeTable(data.results);
	
	var oColumn = this.get("sortedBy").column;
	var sortDir = this.get("sortedBy").dir;
	if (oColumn && oColumn.sortable) {
		var sortFnc = (oColumn.sortOptions && YAHOO.lang.isFunction(oColumn.sortOptions.sortFunction)) ?
	    	oColumn.sortOptions.sortFunction : function(a, b, desc) {
	        	var sorted = YAHOO.util.Sort.compare(a.getData(oColumn.key),b.getData(oColumn.key), desc);
	            if(sorted === 0) {
	            	return YAHOO.util.Sort.compare(a.getId(),b.getId(), desc);
	            }
	            else {
	            	return sorted;
	            }
	    };
	
	    var desc = (sortDir == "desc") ? true : false;
	    this._oRecordSet.sortRecords(sortFnc, desc);
	    this.refreshView();
	    this.fireEvent("columnSortEvent",{column:oColumn,dir:sortDir});
	}
	

	if (this._isScrollable) {
		if (GALILEO.util.Navigator.getBrowser() == 'gecko') {
			var lastColumn = YAHOO.util.Dom.getElementsByClassName(YAHOO.widget.DataTable.CLASS_LAST, 'th', this.getTheadEl())[0];
			var lastColumnWidth = this._getColumnWidth(lastColumn) + GALILEO.widget.GDataTable.SCROLL_WIDTH
			if (lastColumnWidth < lastColumn.offsetWidth) {
				YAHOO.util.Dom.setStyle(lastColumn, 'width', (lastColumn.offsetWidth + GALILEO.widget.GDataTable.SCROLL_WIDTH) + 'px')
			} 
		}
		/*else if (GALILEO.util.Navigator.getBrowser() == 'ie') {
			YAHOO.util.Dom.setStyle(this.getTableEl().parentNode, 'width', (this.getTableEl().offsetWidth + GALILEO.widget.GDataTable.SCROLL_WIDTH) + 'px');
		}*/
	}
	
    var capaPaginador = YAHOO.util.Dom.get(this._paginador.getId());
    var paginadores = YAHOO.util.Dom.getElementsByClassName('paginador', 'div', div);
    if (paginadores && paginadores.length > 0) {
    	for (var  i = 0; i < paginadores.length; i++) {
    		if (paginadores[i].id === this._paginador.getId()) {
    			capaPaginador.parentNode.replaceChild(paginadores[i], capaPaginador);
    			break;
    		}
    	}
    	
    }
};
				
GALILEO.widget.GDataTable.prototype._onColumnResizeEvent = function(oArgs, obj) {
	/*if (obj._isScrollable && GALILEO.util.Navigator.getBrowser() == 'ie') {
		YAHOO.util.Dom.setStyle(obj.getTableEl().parentNode, 'width', (obj.getTableEl().offsetWidth + GALILEO.widget.GDataTable.SCROLL_WIDTH) + 'px');
	}*/
	if (GALILEO.util.Navigator.getBrowser() == 'ie') {
		var column = oArgs.column;
		var columnEl = this.getThEl(oArgs.column);
		var widthString = YAHOO.util.Dom.getStyle(columnEl, 'width');
		if (widthString) {
			var exp = /(\d+)px/;
			var width = widthString.replace(exp, "$1");
			if (parseInt(width) < parseInt(column._minWidth)) {
				YAHOO.util.Dom.setStyle(columnEl, 'width', column._minWidth + 'px');
			}	
		}
	}
	
	
	obj._resetFinalEls();
};


GALILEO.widget.GDataTable.prototype._onCollapsableEvent = function(e, args, obj) {
	obj._resetFinalEls();
};

GALILEO.widget.GDataTable.prototype._resetFinalEls = function() {
	
	for (var i = 0; i < this._terminalEl.length; i++) {
		if (this._terminalEl[i]) {
			this._terminalEl[i].unreg();
			this._terminalEl[i].getEl().parentNode.removeChild(this._terminalEl[i].getEl());
		}
	}
	this._initFinalEls(this._idMoverGroup);
};

GALILEO.widget.GDataTable.prototype._getColumnWidth = function(el) {
	
	var widthString = YAHOO.util.Dom.getStyle(el, 'width');
	var exp = /(\d+)px/;
	var width = widthString.replace(exp, "$1");		
	if (GALILEO.util.String.isInt(width)) {
		return parseInt(width);
	}
	else {
		return el.offsetWidth;
	}
};




/* Parche para datatables que permiten scroll en ie, este parche, permite redimensionar
   el contenido de la tabla ya que incrementa el tamano del div que la contiene */
/*YAHOO.util.ColumnResizer.prototype.b4MouseDown = function(e) {
	if (GALILEO.util.Navigator.getBrowser() == 'ie' && YAHOO.util.Dom.hasClass(this.datatable.getTableEl().parentNode, YAHOO.widget.DataTable.CLASS_SCROLLABLE)) {
		YAHOO.util.Dom.setStyle(this.datatable.getTableEl().parentNode, 'width', '100%');
	}
};*/

/* Parche para datatables que se encuentran dentro de un tabview y el resizer se extablece en un
   valor top invalido */
   
YAHOO.util.ColumnResizer.prototype.onMouseUp = function(e) {
    //TODO: replace the resizer where it belongs:
    var resizeStyle = YAHOO.util.Dom.get(this.handleElId).style;
    resizeStyle.left = "auto";
    resizeStyle.right = 0;
    resizeStyle.marginRight = "-6px";
    resizeStyle.width = "6px";
    resizeStyle.top = "0px";
    //.yui-dt-headresizer {position:absolute;margin-right:-6px;right:0;bottom:0;width:6px;height:100%;cursor:w-resize;cursor:col-resize;}


    //var cells = this.datatable._elTable.tHead.rows[this.datatable._elTable.tHead.rows.length-1].cells;
    //for(var i=0; i<cells.length; i++) {
        //cells[i].style.width = "5px";
    //}

    //TODO: set new ColumnSet width values
    this.datatable.fireEvent("columnResizeEvent", {column:this.column,target:this.cell});
};   

/**
 * Sorts given Column.
 * Aņadimos que si son numeros lo compare como numero.
 *
 * @method sortColumn
 * @param oColumn {YAHOO.widget.Column} Column instance.
 */
GALILEO.widget.GDataTable.prototype.sortColumn = function(oColumn) {
    if(oColumn && (oColumn instanceof YAHOO.widget.Column)) {
        if(!oColumn.sortable) {
            YAHOO.util.Dom.addClass(this.getThEl(oColumn), YAHOO.widget.DataTable.CLASS_SORTABLE);
        }
        // What is the default sort direction?
        var sortDir = (oColumn.sortOptions && oColumn.sortOptions.defaultOrder) ? oColumn.sortOptions.defaultOrder : "asc";

        // Already sorted?
        var oSortedBy = this.get("sortedBy");
        if(oSortedBy && (oSortedBy.key === oColumn.key)) {
            if(oSortedBy.dir) {
                sortDir = (oSortedBy.dir == "asc") ? "desc" : "asc";
            }
            else {
                sortDir = (sortDir == "asc") ? "desc" : "asc";
            }
        }

        // Is there a custom sort handler function defined?
        var sortFnc;
        if (oColumn.sortOptions && YAHOO.lang.isFunction(oColumn.sortOptions.sortFunction)) {
        	sortFnc = oColumn.sortOptions.sortFunction;
        } else {
            sortFnc = function(a, b, desc) {
                    var sorted = null;
                    var aNumber = YAHOO.util.DataSource.parseNumber(a.getData(oColumn.key));
					var bNumber = YAHOO.util.DataSource.parseNumber(b.getData(oColumn.key));
					if (aNumber != null && bNumber!=null) {
						sorted = YAHOO.util.Sort.compare(aNumber, bNumber, desc);
					} else {
                    	sorted = YAHOO.util.Sort.compare(a.getData(oColumn.key),b.getData(oColumn.key), desc);
                    }

                    if(sorted === 0) {
                        return YAHOO.util.Sort.compare(a.getId(),b.getId(), desc);
                    }
                    else {
                        return sorted;
                    }
                }
        }

        // Do the actual sort
        var desc = (sortDir == "desc") ? true : false;
        this._oRecordSet.sortRecords(sortFnc, desc);

        // Update sortedBy tracker
        this.set("sortedBy", {key:oColumn.key, dir:sortDir, column:oColumn});

        // Reset to first page
        //TODO: Keep selection in view
        this.updatePaginator({currentPage:1});

        // Update the UI
        this.refreshView();

        this.fireEvent("columnSortEvent",{column:oColumn,dir:sortDir});
    }
    else {
    }
};

/**
 * Ordena la columna
 *
 * @method showColumn
 * @param column {String} Nombre/Key de la columna.
 * @param display {Boolena} Indica si debe mostrarse o no la columna.
 */
GALILEO.widget.GDataTable.prototype.showColumn = function(column, display) {
	var dis = (display) ? 'block' : 'none';

	var columna = this.getColumn(column);

	//oculto las filas correspondientes a la columna
	var filas = this.getTbodyEl().rows;
	for(i=0; i<filas.length; i++){
		var record = this.getRecord(i);
		var celda = this.getTdEl({record: record, column: columna});
		YAHOO.util.Dom.setStyle(celda, 'display', dis);
	}

	//oculto el titulo correspondiente a la columna
	var titulo = this.getThEl(columna);
	YAHOO.util.Dom.setStyle(titulo, 'display', dis);

	//ocultamos el pie
	if (this.getTableEl().tFoot) {
		var pie = this.getTableEl().tFoot.rows[0].cells[columna.getKeyIndex()];
		YAHOO.util.Dom.setStyle(pie, 'display', dis);
	}
};
