/* mooTblSort - Copyright (c) 2008 Adam Euans [adam.euans@gmail.com] */
var mooTblSort = new Class({	
	options: {
		onStart: null,
		onComplete: null,
		tbl: null,
		ignore: [],
		handle: []
	},

	initialize: function(el, options){
		options = options || {};
		options['tbl'] = $(el);
		$extend(this.options, options);

		if($type(this.options['ignore']) != 'array') this.options['ignore'] = [this.options['ignore']];

		this._dragObj;
		this._dragObjIndex;
		this._dragTmpObj;

		this.rows = this.options['tbl'].getElements('tr').filter(function(item, index){
			return !(this.options['ignore'].indexOf(item) >= 0)
			}, this);

		this.rows.each(function(el, index, array){
				this._sort(el, index, array)
			}, this);

		document.addEvent('mouseup', function(){
			if(this._dragObj){
				this.options.tbl.enableSelection();
				if($type(this.options.onComplete) == 'function') this.options.onComplete(this._dragObj, this.rows.indexOf(this._dragObj), this.rows);
				this._dragObj = null;
			}
		}.bind(this));
    },

	_sort: function(el, index, array){
		var handle = (this.options['handle'].length)? $$(this.options['handle']).filter(function(item){
				return el.hasChild(item)
			} , this) : el;
		$$(($splat(handle).length)? handle : el).addEvent('mousedown', function(){
				this._dragObj = el;
				this._dragObjIndex = el.rowIndex;
				this._dragTmpObj = el;
				this.options.tbl.disableSelection();
				if($type(this.options.onStart) == 'function') this.options.onStart(el, index, array);
		}.bind(this));

		el.addEvents({
			'mouseenter': function(){
				if(!this._dragObj || el.tagName == 'input' || el.tagName == 'select')return true;
				this._dragObj.inject(this.options.tbl.getElements('tr')[el.rowIndex], ((this._dragTmpObj.rowIndex < el.rowIndex)? 'after' : 'before'));
				this._dragTmpObj = el;
			}.bind(this)
		});
	},

	reset: function(options){
		var _tmp = this.rows[0];
		this.rows.each(function(el, index){
			el.inject(this.options.tbl.rows[index],'after')
		}.bind(this));
		if(options && $type(options.onComplete) == 'function') options.onComplete();
	}
	
});

Native.implement([Element], {
	disableSelection: function () {
		this.onselectstart = function(){ return false; };
		this.unselectable = "on";
		this.style.MozUserSelect = "none";
		this.style.cursor = "default";
		return this;
	},

	enableSelection: function () {
		this.onselectstart = null;
		this.unselectable = "off";
		this.style.MozUserSelect = "";
		this.style.cursor = "";
		return this;
	}
});