/**
 * Some extended mootools functions for Feed Hole
 */

function $F(id)
{
	return $(id).value;
}

Element.extend({
	show: function() {
		this.setStyle('display','');
	},
	
	hide: function() {
		this.setStyle('display','none');
	},
	
	toggle: function() {
		this.getStyle('display') != 'none' ? this.setStyle('display','none') : this.setStyle('display','');
	},
	
	moveToBottom:function(){var w=this.clone();this.remove();$(document.body).adopt(w);}
});

Sortables = Sortables.extend({
	
	initialize: function(list, options) {
		this.parent(list, options);
		
		var widget_list = false;
		
		// FH specific
		var handles = $$('.handle');
		handles.each(function(handle){
			handle.addEvent('mousedown', this.fh_mousedown.bind(this, handle) );
			handle.addEvent('mouseup', this.fh_mouseup.bind(this) );
		}.bind(this));
		this.selected_widget = false;
		
		this.fh_serialize();
		
		document.addEvent('mousemove', this.fh_mousemove.bind(this));
		this.is_dragging = false;
	},
	
	fh_mousedown: function(el) {
		this.is_dragging = true;
		this.selected_widget = el.getParent().getParent().getParent().getParent().id;
		this.selected_widget = this.selected_widget.substring(4, this.selected_widget.length); // grab widget id
		
		this.droppables = $$(this.options.droppables);
	},
	
	fh_mousemove: function(e) {
		if( this.is_dragging ) {
			this.mouse = e.client;
			for(var i = 0; i < this.droppables.length; i++) {
				var check = this.fh_checkAgainst(this.droppables[i]);
				if( check ) {
					this.droppables[i].setStyle('background','#ffffff');
				} else {
					this.droppables[i].setStyle('background','#111111');
				}
			}
		}
	},
	
	fh_mouseup: function(e) {
		this.is_dragging = false;
		
		this.mouse = e.client;
		var droppables = $$(this.options.droppables);
		for(var i = 0; i < droppables.length; i++) {
			var check = this.fh_checkAgainst(droppables[i]);
			if( check && this.options.onDrop ) {
				this.options.onDrop(this.selected_widget, droppables[i]);
				return true;
			}
		}
	},

	fh_checkAgainst: function(el) {
		el = el.getCoordinates();
		var now = this.mouse;
		return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top);
	},
	
	/**
	 * Only update the necessary columns
	 */
	fh_serialize: function() {
		this.state = this.serialize();
		this.cur_state = [];
		this.update_state = []; 
		var change = false;
		
		for( var i = 0; i < this.state.length; i++ ) {
			this.cur_state[i] = '';
			for( var j = 0; j < this.state[i].length; j++) {
				this.cur_state[i] += this.state[i][j]+',';
			}
			
			if( this.prev_state && this.cur_state[i] != this.prev_state[i] && this.cur_state[i] != '' ) {
				this.update_state[i] = this.state[i];
				change = true;
			} else {
				this.update_state[i] = false;
			}
		}

		this.prev_state = this.cur_state;
		
		return change ? this.update_state : false;
	}
});