var SortTable = Class.create();
SortTable.prototype = {
	initialize: function(table, options) {
		this.Table = $(table) || null;
		this.ColSort = null;
		this.sortingOrder = 'asc';

		this.TblArray = [];
		this.startRowsCollection = [];
		this.endRowsCollection = [];
		
		this.setOptions(options);
		this.init();
	},

	setOptions: function(options) {
		this.options = {
			startRows: 0,
			endRows: 0
		};

		Object.extend(this.options, options || {});
	},

	init: function() {
		if(!this.Table)
			return;

		for(var k=1; k<this.options.startRows+1; k++) {
			this.startRowsCollection.push(this.Table.rows[k]);
		}
		for(var k=this.Table.rows.length-this.options.endRows; k<this.Table.rows.length; k++) {
			this.endRowsCollection.push(this.Table.rows[k]);
		}
		for(var k=this.options.startRows+1; k<this.Table.rows.length-this.options.endRows; k++) {
			this.TblArray.push(this.Table.rows[k]);
		}
	},

	sortNow: function(element) {
		if(this.ColSort == element.cellIndex) {
			if(this.sortingOrder == 'asc')
				this.sortingOrder = 'desc';
			else
				this.sortingOrder = 'asc';
		} else {
			this.sortingOrder = 'asc';
		}
		this.ColSort = element.cellIndex;
		$A(this.Table.rows[0].cells).each(function(cell, k) {
			Element.removeClassName(cell, 'sorting_asc');
			Element.removeClassName(cell, 'sorting_desc');
		}.bind(this));
		Element.addClassName(this.Table.rows[0].cells[this.ColSort], 'sorting_'+this.sortingOrder);

		var tbl = this.TblArray.sortBy(function(row, k) {
			var acc = $A(row.cells).collect(function(cell, j) {
				var cnt = cell.innerHTML;
				cnt = cnt.replace(/&nbsp;/, ' ');
// 				return cell.innerHTML.stripTags();
				return cnt.stripTags();
			});
			var txtcontent = acc[this.ColSort];
			txtcontent = txtcontent || '';

			// Data
			if(txtcontent.match(/^\d\d[\/\-]\d\d[\/\-]\d\d$/) || txtcontent.match(/^\d\d[\/\-]\d\d[\/\-]\d\d\d\d$/)) {
				var d = txtcontent.substr(0, 2);
				var m = txtcontent.substr(3, 2);
				var y = txtcontent.substr(6);
				txtcontent = new Date(y, m, d).getTime();
				return txtcontent;
			}

			// Valuta
			if(txtcontent.match(/^[€]/)) {
				txtcontent = txtcontent.replace(/[^0-9,']/g, '');
				txtcontent = txtcontent.replace(/[,]/g, '.');
			}

			// Numerico
			if(txtcontent.match(/^[\d\.,]+$/))
				txtcontent = parseFloat(txtcontent);

			return txtcontent;
		}.bind(this));
		if(this.sortingOrder == 'desc')
			tbl = tbl.reverse();

		this.startRowsCollection.each(function(row) {
			this.Table.tBodies[0].appendChild(row);
		}.bind(this));

		tbl.each(function(row, k) {
			row.className = (k%2 == 1) ? 'darkbg' : 'lightbg';
			this.Table.tBodies[0].appendChild(row);
		}.bind(this));

		this.endRowsCollection.each(function(row) {
			this.Table.tBodies[0].appendChild(row);
		}.bind(this));
	}
}