/*
 * jQuery UI Nested Sortable 1.2.1
 *
 * Copyright 2010, Manuele J Sarfatti
 *
 * http://mjsarfatti.com/sandbox/nestedSortable
 *
 * Depends:
 *	 jquery.ui.core.js 1.8+
 *	 jquery.ui.widget.js 1.8+
 *	 jquery.ui.sortable.js 1.8+
 */
(function($) {

	$.widget("ui.nestedSortable", $.extend({}, $.ui.sortable.prototype, {


		_intersectsWithPointer: function(item) {

			var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
				isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
				isOverElement = isOverElementHeight && isOverElementWidth,
				verticalDirection = this._getDragVerticalDirection(),
				horizontalDirection = this._getDragHorizontalDirection();

			if (!isOverElement)
				return false;

			$(item.item).find(".tc_module").each(function(i,e){
				return false;
				
			});
			
			return this.floating ?
				( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
				: ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );

		},	
		
		
		_mouseDrag: function(event) {

		//Compute the helpers position
		this.position = this._generatePosition(event);
		this.positionAbs = this._convertPositionTo("absolute");

		if (!this.lastPositionAbs) {
			this.lastPositionAbs = this.positionAbs;
		}

		//Do scrolling
		if(this.options.scroll) {
			var o = this.options, scrolled = false;
			if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {

				if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
				else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity)
					this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;

				if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
				else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity)
					this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;

			} else {

				if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
				else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
					scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);

				if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
				else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
					scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);

			}

			if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
				$.ui.ddmanager.prepareOffsets(this, event);
		}

		//Regenerate the absolute position used for position checks
		this.positionAbs = this._convertPositionTo("absolute");

		//Set the helper position
		if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
		if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';

		var skip_areas = false;
		
		//Rearrange
		for (var i = this.items.length - 1; i >= 0; i--) {
			//Cache variables and intersection, continue if no intersection
			var item = this.items[i];			
			
			var itemElement = item.item[0], intersection = this._intersectsWithPointer(item);

			if (!intersection) continue;
			if(itemElement != this.currentItem[0] //cannot intersect with itself
				&&	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
				&&	!$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
				&& (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
				//&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container
			) {

				this.direction = intersection == 1 ? "down" : "up";

				if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
					
					/*
					if($(item.item[0]).hasClass('tc_area')){
						for (var j = this.items.length - 1; j >= 0; j--) {
							var firstchild = $('#' + $(item.item[0]).attr('id') + ' .tc_module').first();
							var jitem = $(this.items[j].item[0]);					
							if(jitem.attr('id')  ==  firstchild.attr('id'))
							{
								if(this.direction == "down") this.direction = "up"; else this.direction = "down";
								item = this.items[j];
							}
						}
					}
					*/
					if($(item.item[0]).hasClass('tc_module'))
					{
						this._rearrange(event, item);
						console.log("interact" +  $(item.item[0]).attr('id'));
					}else{
						//console.log(this.direction);
						//console.log(item.item[0]);
						console.log(this.direction);
						skip_areas = true;
						break;
					}
				} else {
					skip_areas = true;
					break;
				}

				this._trigger("change", event, this._uiHash());
				skip_areas = true;
				break;
			}
		}
		
	
		/*
		if(!skip_areas)
		for (var i = this.items.length - 1; i >= 0; i--) {
			//Cache variables and intersection, continue if no intersection
			var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
			if (!intersection) continue;

			if(itemElement != this.currentItem[0] //cannot intersect with itself
				&&	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
				&&	!$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
				&& (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
				//&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container
			) {

				this.direction = intersection == 1 ? "down" : "up";

				if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
					if($(item.item[0]).hasClass('tc_area'))
					{
						this._rearrange(event, item);
						console.log("interact");
					}else{
						break;
					}
				} else {
					break;
				}

				this._trigger("change", event, this._uiHash());
				break;
			}
		}		
*/
		//Post events to containers
		this._contactContainers(event);

		//Interconnect with droppables
		if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);

		//Call callbacks
		this._trigger('sort', event, this._uiHash());

		this.lastPositionAbs = this.positionAbs;
		return false;

	},

		_intersectsWith: function(item) {

		var x1 = this.positionAbs.left,
			x2 = x1 + this.helperProportions.width,
			y1 = this.positionAbs.top,
			y2 = y1 + this.helperProportions.height;

		var l = item.left,
			r = l + item.width,
			t = item.top,
			b = t + item.height;

		var dyClick = this.offset.click.top,
			dxClick = this.offset.click.left;

		var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;

		if(	   this.options.tolerance == "pointer"
			|| this.options.forcePointerForContainers
			|| (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
		) {
			return isOverElement;
		} else {

			return (l < x1 + (this.helperProportions.width / 1) // Right Half
				&& x2 - (this.helperProportions.width / 1) < r // Left Half
				&& t < y1 + (this.helperProportions.height / 18) // Bottom Half
				&& y2 - (this.helperProportions.height / 18) < b ); // Top Half

		}
	}
	}));
	$.ui.nestedSortable.prototype.options = $.extend({}, $.ui.sortable.prototype.options, $.ui.nestedSortable.prototype.options);

})(jQuery);
