close

  
<p> /*
 * jQuery UI Sortable 1.6rc6
 *
 * Copyright (c) 2009 AUTHORS.txt (http://ui.jquery.com/about)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * http://docs.jquery.com/UI/Sortables
 *
 * Depends:
 *	ui.core.js
 */
(function($) {

$.widget("ui.sortable", $.extend({}, $.ui.mouse, {
	_init: function() {

  var o = this.options;
  this.containerCache = {};
  (this.options.cssNamespace &amp;&amp; this.element.addClass(this.options.cssNamespace+"-sortable"));

  //Get the items
  this.refresh();

  //Let's determine if the items are floating
  this.floating = this.items.length ? (/left|right/).test(this.items[0].item.css('float')) : false;

  //Let's determine the parent's offset
  this.offset = this.element.offset();

  //Initialize mouse events for interaction
  this._mouseInit();

	},

	destroy: function() {
  this.element
   .removeClass(this.options.cssNamespace+"-sortable "+this.options.cssNamespace+"-sortable-disabled")
   .removeData("sortable")
   .unbind(".sortable");
  this._mouseDestroy();

  for ( var i = this.items.length - 1; i &gt;= 0; i-- )
   this.items[i].item.removeData("sortable-item");
	},

	_mouseCapture: function(event, overrideHandle) {

  if (this.reverting) {
   return false;
  }

  if(this.options.disabled || this.options.type == 'static') return false;

  //We have to refresh the items data once first
  this._refreshItems(event);

  //Find out if the clicked node (or one of its parents) is a actual item in this.items
  var currentItem = null, self = this, nodes = $(event.target).parents().each(function() {
   if($.data(this, 'sortable-item') == self) {
    currentItem = $(this);
    return false;
   }
  });
  if($.data(event.target, 'sortable-item') == self) currentItem = $(event.target);

  if(!currentItem) return false;
  if(this.options.handle &amp;&amp; !overrideHandle) {
   var validHandle = false;

   $(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
   if(!validHandle) return false;
  }

  this.currentItem = currentItem;
  this._removeCurrentsFromItems();
  return true;

	},

	_mouseStart: function(event, overrideHandle, noActivation) {

  var o = this.options, self = this;
  this.currentContainer = this;

  //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
  this.refreshPositions();

  //Create and append the visible helper
  this.helper = this._createHelper(event);

  //Cache the helper size
  this._cacheHelperProportions();

  /*
   * - Position generation -
   * This block generates everything position related - it's the core of draggables.
   */

  //Cache the margins of the original element
  this._cacheMargins();

  //Get the next scrolling parent
  this.scrollParent = this.helper.scrollParent();

  //The element's absolute position on the page minus margins
  this.offset = this.currentItem.offset();
  this.offset = {
   top: this.offset.top - this.margins.top,
   left: this.offset.left - this.margins.left
  };

  // Only after we got the offset, we can change the helper's position to absolute
  // TODO: Still need to figure out a way to make relative sorting possible
  this.helper.css("position", "absolute");
  this.cssPosition = this.helper.css("position");

  $.extend(this.offset, {
   click: { //Where the click happened, relative to the element
    left: event.pageX - this.offset.left,
    top: event.pageY - this.offset.top
   },
   parent: this._getParentOffset(),
   relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
  });

  //Generate the original position
  this.originalPosition = this._generatePosition(event);
  this.originalPageX = event.pageX;
  this.originalPageY = event.pageY;

  //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
  if(o.cursorAt)
   this._adjustOffsetFromHelper(o.cursorAt);

  //Cache the former DOM position
  this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };

  //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
  if(this.helper[0] != this.currentItem[0]) {
   this.currentItem.hide();
  }

  //Create the placeholder
  this._createPlaceholder();

  //Set a containment if given in the options
  if(o.containment)
   this._setContainment();

  if(o.cursor) { // cursor option
   if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor");
   $('body').css("cursor", o.cursor);
  }

  if(o.opacity) { // opacity option
   if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity");
   this.helper.css("opacity", o.opacity);
  }

  if(o.zIndex) { // zIndex option
   if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex");
   this.helper.css("zIndex", o.zIndex);
  }

  //Prepare scrolling
  if(this.scrollParent[0] != document &amp;&amp; this.scrollParent[0].tagName != 'HTML')
   this.overflowOffset = this.scrollParent.offset();

  //Call callbacks
  this._trigger("start", event, this._uiHash());

  //Recache the helper size
  if(!this._preserveHelperProportions)
   this._cacheHelperProportions();


  //Post 'activate' events to possible containers
  if(!noActivation) {
    for (var i = this.containers.length - 1; i &gt;= 0; i--) { this.containers[i]._trigger("activate", event, self._uiHash(this)); }
  }

  //Prepare possible droppables
  if($.ui.ddmanager)
   $.ui.ddmanager.current = this;

  if ($.ui.ddmanager &amp;&amp; !o.dropBehaviour)
   $.ui.ddmanager.prepareOffsets(this, event);

  this.dragging = true;

  this.helper.addClass(o.cssNamespace+'-sortable-helper');
  this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
  return true;

	},

	_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 &amp;&amp; this.scrollParent[0].tagName != 'HTML') {

    if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY = 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
    &amp;&amp;	this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
    &amp;&amp;	!$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
    &amp;&amp; (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
   ) {

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

    if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
     this.options.sortIndicator.call(this, event, item);
    } 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;

	},

	_mouseStop: function(event, noPropagation) {

  if(!event) return;

  //If we are using droppables, inform the manager about the drop
  if ($.ui.ddmanager &amp;&amp; !this.options.dropBehaviour)
   $.ui.ddmanager.drop(this, event);

  if(this.options.revert) {
   var self = this;
   var cur = self.placeholder.offset();

   self.reverting = true;

   $(this.helper).animate({
    left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
    top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
   }, parseInt(this.options.revert, 10) || 500, function() {
    self._clear(event);
   });
  } else {
   this._clear(event, noPropagation);
  }

  return false;

	},

	cancel: function() {

  var self = this;

  if(this.dragging) {

   this._mouseUp();

   if(this.options.helper == "original")
    this.currentItem.css(this._storedCSS).removeClass(this.options.cssNamespace+"-sortable-helper");
   else
    this.currentItem.show();

   //Post deactivating events to containers
   for (var i = this.containers.length - 1; i &gt;= 0; i--){
    this.containers[i]._trigger("deactivate", null, self._uiHash(this));
    if(this.containers[i].containerCache.over) {
     this.containers[i]._trigger("out", null, self._uiHash(this));
     this.containers[i].containerCache.over = 0;
    }
   }

  }

  //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
  if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
  if(this.options.helper != "original" &amp;&amp; this.helper &amp;&amp; this.helper[0].parentNode) this.helper.remove();

  $.extend(this, {
   helper: null,
   dragging: false,
   reverting: false,
   _noFinalSort: null
  });

  if(this.domPosition.prev) {
   $(this.domPosition.prev).after(this.currentItem);
  } else {
   $(this.domPosition.parent).prepend(this.currentItem);
  }

  return true;

	},

	serialize: function(o) {

  var items = this._getItemsAsjQuery(o &amp;&amp; o.connected);
  var str = []; o = o || {};

  $(items).each(function() {
   var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
   if(res) str.push((o.key || res[1]+'[]')+'='+(o.key &amp;&amp; o.expression ? res[1] : res[2]));
  });

  return str.join('&amp;');

	},

	toArray: function(o) {

  var items = this._getItemsAsjQuery(o &amp;&amp; o.connected);
  var ret = []; o = o || {};

  items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
  return ret;

	},

	/* Be careful with the following core functions */
	_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) &gt; t &amp;&amp; (y1 + dyClick)  l &amp;&amp; (x1 + dxClick)  item[this.floating ? 'width' : 'height'])
  ) {
   return isOverElement;
  } else {

   return (l  0 ? "down" : "up");
	},

	_getDragHorizontalDirection: function() {
  var delta = this.positionAbs.left - this.lastPositionAbs.left;
  return delta != 0 &amp;&amp; (delta &gt; 0 ? "right" : "left");
	},

	refresh: function(event) {
  this._refreshItems(event);
  this.refreshPositions();
	},

	_getItemsAsjQuery: function(connected) {

  var self = this;
  var items = [];
  var queries = [];

  if(this.options.connectWith &amp;&amp; connected) {
   var connectWith = this.options.connectWith.constructor == String ? [this.options.connectWith] : this.options.connectWith;
   for (var i = connectWith.length - 1; i &gt;= 0; i--){
    var cur = $(connectWith[i]);
    for (var j = cur.length - 1; j &gt;= 0; j--){
     var inst = $.data(cur[j], 'sortable');
     if(inst &amp;&amp; inst != this &amp;&amp; !inst.options.disabled) {
      queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not("."+inst.options.cssNamespace+"-sortable-helper"), inst]);
     }
    };
   };
  }

  queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not("."+this.options.cssNamespace+"-sortable-helper"), this]);

  for (var i = queries.length - 1; i &gt;= 0; i--){
   queries[i][0].each(function() {
    items.push(this);
   });
  };

  return $(items);

	},

	_removeCurrentsFromItems: function() {

  var list = this.currentItem.find(":data(sortable-item)");

  for (var i=0; i = 0; i--){
    var cur = $(this.options.connectWith[i]);
    for (var j = cur.length - 1; j &gt;= 0; j--){
     var inst = $.data(cur[j], 'sortable');
     if(inst &amp;&amp; inst != this &amp;&amp; !inst.options.disabled) {
      queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
      this.containers.push(inst);
     }
    };
   };
  }

  for (var i = queries.length - 1; i &gt;= 0; i--) {
   var targetData = queries[i][1];
   var _queries = queries[i][0];

   for (var j=0, queriesLength = _queries.length; j = 0; i--){
   var item = this.items[i];

   //We ignore calculating positions of all connected containers when we're not over them
   if(item.instance != this.currentContainer &amp;&amp; this.currentContainer &amp;&amp; item.item[0] != this.currentItem[0])
    continue;

   var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;

   if (!fast) {
    if (this.options.accurateIntersection) {
     item.width = t.outerWidth();
     item.height = t.outerHeight();
    }
    else {
     item.width = t[0].offsetWidth;
     item.height = t[0].offsetHeight;
    }
   }

   var p = t.offset();
   item.left = p.left;
   item.top = p.top;
  };

  if(this.options.custom &amp;&amp; this.options.custom.refreshContainers) {
   this.options.custom.refreshContainers.call(this);
  } else {
   for (var i = this.containers.length - 1; i &gt;= 0; i--){
    var p = this.containers[i].element.offset();
    this.containers[i].containerCache.left = p.left;
    this.containers[i].containerCache.top = p.top;
    this.containers[i].containerCache.width	= this.containers[i].element.outerWidth();
    this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
   };
  }

	},

	_createPlaceholder: function(that) {

  var self = that || this, o = self.options;

  if(!o.placeholder || o.placeholder.constructor == String) {
   var className = o.placeholder;
   o.placeholder = {
    element: function() {

     var el = $(document.createElement(self.currentItem[0].nodeName))
      .addClass(className || self.currentItem[0].className+" "+self.options.cssNamespace+"-sortable-placeholder")
      .removeClass(self.options.cssNamespace+'-sortable-helper')[0];

     if(!className)
      el.style.visibility = "hidden";

     return el;
    },
    update: function(container, p) {

     // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
     // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
     if(className &amp;&amp; !o.forcePlaceholderSize) return;

     //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
     if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); };
     if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); };
    }
   };
  }

  //Create the placeholder
  self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem));

  //Append it after the actual current item
  self.currentItem.after(self.placeholder);

  //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
  o.placeholder.update(self, self.placeholder);

	},

	_contactContainers: function(event) {
  for (var i = this.containers.length - 1; i &gt;= 0; i--){

   if(this._intersectsWith(this.containers[i].containerCache)) {
    if(!this.containers[i].containerCache.over) {

     if(this.currentContainer != this.containers[i]) {

      //When entering a new container, we will find the item with the least distance and append our item near it
      var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[i].floating ? 'left' : 'top'];
      for (var j = this.items.length - 1; j &gt;= 0; j--) {
       if(!$.ui.contains(this.containers[i].element[0], this.items[j].item[0])) continue;
       var cur = this.items[j][this.containers[i].floating ? 'left' : 'top'];
       if(Math.abs(cur - base)  this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
    if(event.pageY - this.offset.click.top &gt; this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
   }

   if(o.grid) {
    var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
    pageY = this.containment ? (!(top - this.offset.click.top  this.containment[3]) ? top : (!(top - this.offset.click.top  this.containment[2]) ? left : (!(left - this.offset.click.left = 0; i--){
    if($.ui.contains(this.containers[i].element[0], this.currentItem[0]) &amp;&amp; !noPropagation) {
     delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
     delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.containers[i]));
    }
   };
  };

  //Post events to containers
  for (var i = this.containers.length - 1; i &gt;= 0; i--){
   if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
   if(this.containers[i].containerCache.over) {
    delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
    this.containers[i].containerCache.over = 0;
   }
  }

  //Do what was originally in plugins
  if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor
  if(this._storedOpacity) this.helper.css("opacity", this._storedCursor); //Reset cursor
  if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index

  this.dragging = false;
  if(this.cancelHelperRemoval) {
   if(!noPropagation) {
    this._trigger("beforeStop", event, this._uiHash());
    for (var i=0; i  *',
  placeholder: false,
  scope: "default",
  scroll: true,
  scrollSensitivity: 20,
  scrollSpeed: 20,
  sortIndicator: $.ui.sortable.prototype._rearrange,
  tolerance: "intersect",
  zIndex: 1000
	}
});

})(jQuery);

 </p>

Comments

Hide