* partly fixes two issues exposed by bug 34280
[mediawiki.git] / resources / jquery.ui / jquery.ui.sortable.js
blob26ba85f0ecc32f21f97a6ab6430fba354c928d90
1 /*
2  * jQuery UI Sortable 1.8.17
3  *
4  * Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
5  * Dual licensed under the MIT or GPL Version 2 licenses.
6  * http://jquery.org/license
7  *
8  * http://docs.jquery.com/UI/Sortables
9  *
10  * Depends:
11  *      jquery.ui.core.js
12  *      jquery.ui.mouse.js
13  *      jquery.ui.widget.js
14  */
15 (function( $, undefined ) {
17 $.widget("ui.sortable", $.ui.mouse, {
18         widgetEventPrefix: "sort",
19         options: {
20                 appendTo: "parent",
21                 axis: false,
22                 connectWith: false,
23                 containment: false,
24                 cursor: 'auto',
25                 cursorAt: false,
26                 dropOnEmpty: true,
27                 forcePlaceholderSize: false,
28                 forceHelperSize: false,
29                 grid: false,
30                 handle: false,
31                 helper: "original",
32                 items: '> *',
33                 opacity: false,
34                 placeholder: false,
35                 revert: false,
36                 scroll: true,
37                 scrollSensitivity: 20,
38                 scrollSpeed: 20,
39                 scope: "default",
40                 tolerance: "intersect",
41                 zIndex: 1000
42         },
43         _create: function() {
45                 var o = this.options;
46                 this.containerCache = {};
47                 this.element.addClass("ui-sortable");
49                 //Get the items
50                 this.refresh();
52                 //Let's determine if the items are being displayed horizontally
53                 this.floating = this.items.length ? o.axis === 'x' || (/left|right/).test(this.items[0].item.css('float')) || (/inline|table-cell/).test(this.items[0].item.css('display')) : false;
55                 //Let's determine the parent's offset
56                 this.offset = this.element.offset();
58                 //Initialize mouse events for interaction
59                 this._mouseInit();
61         },
63         destroy: function() {
64                 this.element
65                         .removeClass("ui-sortable ui-sortable-disabled");
66                 this._mouseDestroy();
68                 for ( var i = this.items.length - 1; i >= 0; i-- )
69                         this.items[i].item.removeData(this.widgetName + "-item");
71                 return this;
72         },
74         _setOption: function(key, value){
75                 if ( key === "disabled" ) {
76                         this.options[ key ] = value;
77         
78                         this.widget()
79                                 [ value ? "addClass" : "removeClass"]( "ui-sortable-disabled" );
80                 } else {
81                         // Don't call widget base _setOption for disable as it adds ui-state-disabled class
82                         $.Widget.prototype._setOption.apply(this, arguments);
83                 }
84         },
86         _mouseCapture: function(event, overrideHandle) {
87                 var that = this;
89                 if (this.reverting) {
90                         return false;
91                 }
93                 if(this.options.disabled || this.options.type == 'static') return false;
95                 //We have to refresh the items data once first
96                 this._refreshItems(event);
98                 //Find out if the clicked node (or one of its parents) is a actual item in this.items
99                 var currentItem = null, self = this, nodes = $(event.target).parents().each(function() {
100                         if($.data(this, that.widgetName + '-item') == self) {
101                                 currentItem = $(this);
102                                 return false;
103                         }
104                 });
105                 if($.data(event.target, that.widgetName + '-item') == self) currentItem = $(event.target);
107                 if(!currentItem) return false;
108                 if(this.options.handle && !overrideHandle) {
109                         var validHandle = false;
111                         $(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
112                         if(!validHandle) return false;
113                 }
115                 this.currentItem = currentItem;
116                 this._removeCurrentsFromItems();
117                 return true;
119         },
121         _mouseStart: function(event, overrideHandle, noActivation) {
123                 var o = this.options, self = this;
124                 this.currentContainer = this;
126                 //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
127                 this.refreshPositions();
129                 //Create and append the visible helper
130                 this.helper = this._createHelper(event);
132                 //Cache the helper size
133                 this._cacheHelperProportions();
135                 /*
136                  * - Position generation -
137                  * This block generates everything position related - it's the core of draggables.
138                  */
140                 //Cache the margins of the original element
141                 this._cacheMargins();
143                 //Get the next scrolling parent
144                 this.scrollParent = this.helper.scrollParent();
146                 //The element's absolute position on the page minus margins
147                 this.offset = this.currentItem.offset();
148                 this.offset = {
149                         top: this.offset.top - this.margins.top,
150                         left: this.offset.left - this.margins.left
151                 };
153                 // Only after we got the offset, we can change the helper's position to absolute
154                 // TODO: Still need to figure out a way to make relative sorting possible
155                 this.helper.css("position", "absolute");
156                 this.cssPosition = this.helper.css("position");
158                 $.extend(this.offset, {
159                         click: { //Where the click happened, relative to the element
160                                 left: event.pageX - this.offset.left,
161                                 top: event.pageY - this.offset.top
162                         },
163                         parent: this._getParentOffset(),
164                         relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
165                 });
167                 //Generate the original position
168                 this.originalPosition = this._generatePosition(event);
169                 this.originalPageX = event.pageX;
170                 this.originalPageY = event.pageY;
172                 //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
173                 (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
175                 //Cache the former DOM position
176                 this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
178                 //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
179                 if(this.helper[0] != this.currentItem[0]) {
180                         this.currentItem.hide();
181                 }
183                 //Create the placeholder
184                 this._createPlaceholder();
186                 //Set a containment if given in the options
187                 if(o.containment)
188                         this._setContainment();
190                 if(o.cursor) { // cursor option
191                         if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor");
192                         $('body').css("cursor", o.cursor);
193                 }
195                 if(o.opacity) { // opacity option
196                         if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity");
197                         this.helper.css("opacity", o.opacity);
198                 }
200                 if(o.zIndex) { // zIndex option
201                         if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex");
202                         this.helper.css("zIndex", o.zIndex);
203                 }
205                 //Prepare scrolling
206                 if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML')
207                         this.overflowOffset = this.scrollParent.offset();
209                 //Call callbacks
210                 this._trigger("start", event, this._uiHash());
212                 //Recache the helper size
213                 if(!this._preserveHelperProportions)
214                         this._cacheHelperProportions();
217                 //Post 'activate' events to possible containers
218                 if(!noActivation) {
219                          for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, self._uiHash(this)); }
220                 }
222                 //Prepare possible droppables
223                 if($.ui.ddmanager)
224                         $.ui.ddmanager.current = this;
226                 if ($.ui.ddmanager && !o.dropBehaviour)
227                         $.ui.ddmanager.prepareOffsets(this, event);
229                 this.dragging = true;
231                 this.helper.addClass("ui-sortable-helper");
232                 this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
233                 return true;
235         },
237         _mouseDrag: function(event) {
239                 //Compute the helpers position
240                 this.position = this._generatePosition(event);
241                 this.positionAbs = this._convertPositionTo("absolute");
243                 if (!this.lastPositionAbs) {
244                         this.lastPositionAbs = this.positionAbs;
245                 }
247                 //Do scrolling
248                 if(this.options.scroll) {
249                         var o = this.options, scrolled = false;
250                         if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {
252                                 if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
253                                         this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
254                                 else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity)
255                                         this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
257                                 if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
258                                         this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
259                                 else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity)
260                                         this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
262                         } else {
264                                 if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
265                                         scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
266                                 else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
267                                         scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
269                                 if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
270                                         scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
271                                 else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
272                                         scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
274                         }
276                         if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
277                                 $.ui.ddmanager.prepareOffsets(this, event);
278                 }
280                 //Regenerate the absolute position used for position checks
281                 this.positionAbs = this._convertPositionTo("absolute");
283                 //Set the helper position
284                 if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
285                 if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
287                 //Rearrange
288                 for (var i = this.items.length - 1; i >= 0; i--) {
290                         //Cache variables and intersection, continue if no intersection
291                         var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
292                         if (!intersection) continue;
294                         if(itemElement != this.currentItem[0] //cannot intersect with itself
295                                 &&      this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
296                                 &&      !$.ui.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
297                                 && (this.options.type == 'semi-dynamic' ? !$.ui.contains(this.element[0], itemElement) : true)
298                                 //&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container
299                         ) {
301                                 this.direction = intersection == 1 ? "down" : "up";
303                                 if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
304                                         this._rearrange(event, item);
305                                 } else {
306                                         break;
307                                 }
309                                 this._trigger("change", event, this._uiHash());
310                                 break;
311                         }
312                 }
314                 //Post events to containers
315                 this._contactContainers(event);
317                 //Interconnect with droppables
318                 if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);
320                 //Call callbacks
321                 this._trigger('sort', event, this._uiHash());
323                 this.lastPositionAbs = this.positionAbs;
324                 return false;
326         },
328         _mouseStop: function(event, noPropagation) {
330                 if(!event) return;
332                 //If we are using droppables, inform the manager about the drop
333                 if ($.ui.ddmanager && !this.options.dropBehaviour)
334                         $.ui.ddmanager.drop(this, event);
336                 if(this.options.revert) {
337                         var self = this;
338                         var cur = self.placeholder.offset();
340                         self.reverting = true;
342                         $(this.helper).animate({
343                                 left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
344                                 top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
345                         }, parseInt(this.options.revert, 10) || 500, function() {
346                                 self._clear(event);
347                         });
348                 } else {
349                         this._clear(event, noPropagation);
350                 }
352                 return false;
354         },
356         cancel: function() {
358                 var self = this;
360                 if(this.dragging) {
362                         this._mouseUp({ target: null });
364                         if(this.options.helper == "original")
365                                 this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
366                         else
367                                 this.currentItem.show();
369                         //Post deactivating events to containers
370                         for (var i = this.containers.length - 1; i >= 0; i--){
371                                 this.containers[i]._trigger("deactivate", null, self._uiHash(this));
372                                 if(this.containers[i].containerCache.over) {
373                                         this.containers[i]._trigger("out", null, self._uiHash(this));
374                                         this.containers[i].containerCache.over = 0;
375                                 }
376                         }
378                 }
380                 if (this.placeholder) {
381                         //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
382                         if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
383                         if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove();
385                         $.extend(this, {
386                                 helper: null,
387                                 dragging: false,
388                                 reverting: false,
389                                 _noFinalSort: null
390                         });
392                         if(this.domPosition.prev) {
393                                 $(this.domPosition.prev).after(this.currentItem);
394                         } else {
395                                 $(this.domPosition.parent).prepend(this.currentItem);
396                         }
397                 }
399                 return this;
401         },
403         serialize: function(o) {
405                 var items = this._getItemsAsjQuery(o && o.connected);
406                 var str = []; o = o || {};
408                 $(items).each(function() {
409                         var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
410                         if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
411                 });
413                 if(!str.length && o.key) {
414                         str.push(o.key + '=');
415                 }
417                 return str.join('&');
419         },
421         toArray: function(o) {
423                 var items = this._getItemsAsjQuery(o && o.connected);
424                 var ret = []; o = o || {};
426                 items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
427                 return ret;
429         },
431         /* Be careful with the following core functions */
432         _intersectsWith: function(item) {
434                 var x1 = this.positionAbs.left,
435                         x2 = x1 + this.helperProportions.width,
436                         y1 = this.positionAbs.top,
437                         y2 = y1 + this.helperProportions.height;
439                 var l = item.left,
440                         r = l + item.width,
441                         t = item.top,
442                         b = t + item.height;
444                 var dyClick = this.offset.click.top,
445                         dxClick = this.offset.click.left;
447                 var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;
449                 if(        this.options.tolerance == "pointer"
450                         || this.options.forcePointerForContainers
451                         || (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
452                 ) {
453                         return isOverElement;
454                 } else {
456                         return (l < x1 + (this.helperProportions.width / 2) // Right Half
457                                 && x2 - (this.helperProportions.width / 2) < r // Left Half
458                                 && t < y1 + (this.helperProportions.height / 2) // Bottom Half
459                                 && y2 - (this.helperProportions.height / 2) < b ); // Top Half
461                 }
462         },
464         _intersectsWithPointer: function(item) {
466                 var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
467                         isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
468                         isOverElement = isOverElementHeight && isOverElementWidth,
469                         verticalDirection = this._getDragVerticalDirection(),
470                         horizontalDirection = this._getDragHorizontalDirection();
472                 if (!isOverElement)
473                         return false;
475                 return this.floating ?
476                         ( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
477                         : ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );
479         },
481         _intersectsWithSides: function(item) {
483                 var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
484                         isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
485                         verticalDirection = this._getDragVerticalDirection(),
486                         horizontalDirection = this._getDragHorizontalDirection();
488                 if (this.floating && horizontalDirection) {
489                         return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
490                 } else {
491                         return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf));
492                 }
494         },
496         _getDragVerticalDirection: function() {
497                 var delta = this.positionAbs.top - this.lastPositionAbs.top;
498                 return delta != 0 && (delta > 0 ? "down" : "up");
499         },
501         _getDragHorizontalDirection: function() {
502                 var delta = this.positionAbs.left - this.lastPositionAbs.left;
503                 return delta != 0 && (delta > 0 ? "right" : "left");
504         },
506         refresh: function(event) {
507                 this._refreshItems(event);
508                 this.refreshPositions();
509                 return this;
510         },
512         _connectWith: function() {
513                 var options = this.options;
514                 return options.connectWith.constructor == String
515                         ? [options.connectWith]
516                         : options.connectWith;
517         },
518         
519         _getItemsAsjQuery: function(connected) {
521                 var self = this;
522                 var items = [];
523                 var queries = [];
524                 var connectWith = this._connectWith();
526                 if(connectWith && connected) {
527                         for (var i = connectWith.length - 1; i >= 0; i--){
528                                 var cur = $(connectWith[i]);
529                                 for (var j = cur.length - 1; j >= 0; j--){
530                                         var inst = $.data(cur[j], this.widgetName);
531                                         if(inst && inst != this && !inst.options.disabled) {
532                                                 queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), inst]);
533                                         }
534                                 };
535                         };
536                 }
538                 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(".ui-sortable-helper").not('.ui-sortable-placeholder'), this]);
540                 for (var i = queries.length - 1; i >= 0; i--){
541                         queries[i][0].each(function() {
542                                 items.push(this);
543                         });
544                 };
546                 return $(items);
548         },
550         _removeCurrentsFromItems: function() {
552                 var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
554                 for (var i=0; i < this.items.length; i++) {
556                         for (var j=0; j < list.length; j++) {
557                                 if(list[j] == this.items[i].item[0])
558                                         this.items.splice(i,1);
559                         };
561                 };
563         },
565         _refreshItems: function(event) {
567                 this.items = [];
568                 this.containers = [this];
569                 var items = this.items;
570                 var self = this;
571                 var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];
572                 var connectWith = this._connectWith();
574                 if(connectWith) {
575                         for (var i = connectWith.length - 1; i >= 0; i--){
576                                 var cur = $(connectWith[i]);
577                                 for (var j = cur.length - 1; j >= 0; j--){
578                                         var inst = $.data(cur[j], this.widgetName);
579                                         if(inst && inst != this && !inst.options.disabled) {
580                                                 queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
581                                                 this.containers.push(inst);
582                                         }
583                                 };
584                         };
585                 }
587                 for (var i = queries.length - 1; i >= 0; i--) {
588                         var targetData = queries[i][1];
589                         var _queries = queries[i][0];
591                         for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
592                                 var item = $(_queries[j]);
594                                 item.data(this.widgetName + '-item', targetData); // Data for target checking (mouse manager)
596                                 items.push({
597                                         item: item,
598                                         instance: targetData,
599                                         width: 0, height: 0,
600                                         left: 0, top: 0
601                                 });
602                         };
603                 };
605         },
607         refreshPositions: function(fast) {
609                 //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
610                 if(this.offsetParent && this.helper) {
611                         this.offset.parent = this._getParentOffset();
612                 }
614                 for (var i = this.items.length - 1; i >= 0; i--){
615                         var item = this.items[i];
617                         //We ignore calculating positions of all connected containers when we're not over them
618                         if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0])
619                                 continue;
621                         var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
623                         if (!fast) {
624                                 item.width = t.outerWidth();
625                                 item.height = t.outerHeight();
626                         }
628                         var p = t.offset();
629                         item.left = p.left;
630                         item.top = p.top;
631                 };
633                 if(this.options.custom && this.options.custom.refreshContainers) {
634                         this.options.custom.refreshContainers.call(this);
635                 } else {
636                         for (var i = this.containers.length - 1; i >= 0; i--){
637                                 var p = this.containers[i].element.offset();
638                                 this.containers[i].containerCache.left = p.left;
639                                 this.containers[i].containerCache.top = p.top;
640                                 this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
641                                 this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
642                         };
643                 }
645                 return this;
646         },
648         _createPlaceholder: function(that) {
650                 var self = that || this, o = self.options;
652                 if(!o.placeholder || o.placeholder.constructor == String) {
653                         var className = o.placeholder;
654                         o.placeholder = {
655                                 element: function() {
657                                         var el = $(document.createElement(self.currentItem[0].nodeName))
658                                                 .addClass(className || self.currentItem[0].className+" ui-sortable-placeholder")
659                                                 .removeClass("ui-sortable-helper")[0];
661                                         if(!className)
662                                                 el.style.visibility = "hidden";
664                                         return el;
665                                 },
666                                 update: function(container, p) {
668                                         // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
669                                         // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
670                                         if(className && !o.forcePlaceholderSize) return;
672                                         //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
673                                         if(!p.height()) { p.height(self.currentItem.innerHeight() - parseInt(self.currentItem.css('paddingTop')||0, 10) - parseInt(self.currentItem.css('paddingBottom')||0, 10)); };
674                                         if(!p.width()) { p.width(self.currentItem.innerWidth() - parseInt(self.currentItem.css('paddingLeft')||0, 10) - parseInt(self.currentItem.css('paddingRight')||0, 10)); };
675                                 }
676                         };
677                 }
679                 //Create the placeholder
680                 self.placeholder = $(o.placeholder.element.call(self.element, self.currentItem));
682                 //Append it after the actual current item
683                 self.currentItem.after(self.placeholder);
685                 //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
686                 o.placeholder.update(self, self.placeholder);
688         },
690         _contactContainers: function(event) {
691                 
692                 // get innermost container that intersects with item 
693                 var innermostContainer = null, innermostIndex = null;           
694                 
695                 
696                 for (var i = this.containers.length - 1; i >= 0; i--){
698                         // never consider a container that's located within the item itself 
699                         if($.ui.contains(this.currentItem[0], this.containers[i].element[0]))
700                                 continue;
702                         if(this._intersectsWith(this.containers[i].containerCache)) {
704                                 // if we've already found a container and it's more "inner" than this, then continue 
705                                 if(innermostContainer && $.ui.contains(this.containers[i].element[0], innermostContainer.element[0]))
706                                         continue;
708                                 innermostContainer = this.containers[i]; 
709                                 innermostIndex = i;
710                                         
711                         } else {
712                                 // container doesn't intersect. trigger "out" event if necessary 
713                                 if(this.containers[i].containerCache.over) {
714                                         this.containers[i]._trigger("out", event, this._uiHash(this));
715                                         this.containers[i].containerCache.over = 0;
716                                 }
717                         }
719                 }
720                 
721                 // if no intersecting containers found, return 
722                 if(!innermostContainer) return; 
724                 // move the item into the container if it's not there already
725                 if(this.containers.length === 1) {
726                         this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
727                         this.containers[innermostIndex].containerCache.over = 1;
728                 } else if(this.currentContainer != this.containers[innermostIndex]) { 
730                         //When entering a new container, we will find the item with the least distance and append our item near it 
731                         var dist = 10000; var itemWithLeastDistance = null; var base = this.positionAbs[this.containers[innermostIndex].floating ? 'left' : 'top']; 
732                         for (var j = this.items.length - 1; j >= 0; j--) { 
733                                 if(!$.ui.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) continue; 
734                                 var cur = this.items[j][this.containers[innermostIndex].floating ? 'left' : 'top']; 
735                                 if(Math.abs(cur - base) < dist) { 
736                                         dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; 
737                                 } 
738                         } 
740                         if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled 
741                                 return; 
743                         this.currentContainer = this.containers[innermostIndex]; 
744                         itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); 
745                         this._trigger("change", event, this._uiHash()); 
746                         this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); 
748                         //Update the placeholder 
749                         this.options.placeholder.update(this.currentContainer, this.placeholder); 
750                 
751                         this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); 
752                         this.containers[innermostIndex].containerCache.over = 1;
753                 } 
754         
755                 
756         },
758         _createHelper: function(event) {
760                 var o = this.options;
761                 var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem);
763                 if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already
764                         $(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
766                 if(helper[0] == this.currentItem[0])
767                         this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
769                 if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width());
770                 if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height());
772                 return helper;
774         },
776         _adjustOffsetFromHelper: function(obj) {
777                 if (typeof obj == 'string') {
778                         obj = obj.split(' ');
779                 }
780                 if ($.isArray(obj)) {
781                         obj = {left: +obj[0], top: +obj[1] || 0};
782                 }
783                 if ('left' in obj) {
784                         this.offset.click.left = obj.left + this.margins.left;
785                 }
786                 if ('right' in obj) {
787                         this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
788                 }
789                 if ('top' in obj) {
790                         this.offset.click.top = obj.top + this.margins.top;
791                 }
792                 if ('bottom' in obj) {
793                         this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
794                 }
795         },
797         _getParentOffset: function() {
800                 //Get the offsetParent and cache its position
801                 this.offsetParent = this.helper.offsetParent();
802                 var po = this.offsetParent.offset();
804                 // This is a special case where we need to modify a offset calculated on start, since the following happened:
805                 // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
806                 // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
807                 //    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
808                 if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) {
809                         po.left += this.scrollParent.scrollLeft();
810                         po.top += this.scrollParent.scrollTop();
811                 }
813                 if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
814                 || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.browser.msie)) //Ugly IE fix
815                         po = { top: 0, left: 0 };
817                 return {
818                         top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
819                         left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
820                 };
822         },
824         _getRelativeOffset: function() {
826                 if(this.cssPosition == "relative") {
827                         var p = this.currentItem.position();
828                         return {
829                                 top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
830                                 left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
831                         };
832                 } else {
833                         return { top: 0, left: 0 };
834                 }
836         },
838         _cacheMargins: function() {
839                 this.margins = {
840                         left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
841                         top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
842                 };
843         },
845         _cacheHelperProportions: function() {
846                 this.helperProportions = {
847                         width: this.helper.outerWidth(),
848                         height: this.helper.outerHeight()
849                 };
850         },
852         _setContainment: function() {
854                 var o = this.options;
855                 if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
856                 if(o.containment == 'document' || o.containment == 'window') this.containment = [
857                         0 - this.offset.relative.left - this.offset.parent.left,
858                         0 - this.offset.relative.top - this.offset.parent.top,
859                         $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
860                         ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
861                 ];
863                 if(!(/^(document|window|parent)$/).test(o.containment)) {
864                         var ce = $(o.containment)[0];
865                         var co = $(o.containment).offset();
866                         var over = ($(ce).css("overflow") != 'hidden');
868                         this.containment = [
869                                 co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
870                                 co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
871                                 co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
872                                 co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
873                         ];
874                 }
876         },
878         _convertPositionTo: function(d, pos) {
880                 if(!pos) pos = this.position;
881                 var mod = d == "absolute" ? 1 : -1;
882                 var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
884                 return {
885                         top: (
886                                 pos.top                                                                                                                                 // The absolute mouse position
887                                 + this.offset.relative.top * mod                                                                                // Only for relative positioned nodes: Relative offset from element to offset parent
888                                 + this.offset.parent.top * mod                                                                                  // The offsetParent's offset without borders (offset + border)
889                                 - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
890                         ),
891                         left: (
892                                 pos.left                                                                                                                                // The absolute mouse position
893                                 + this.offset.relative.left * mod                                                                               // Only for relative positioned nodes: Relative offset from element to offset parent
894                                 + this.offset.parent.left * mod                                                                                 // The offsetParent's offset without borders (offset + border)
895                                 - ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
896                         )
897                 };
899         },
901         _generatePosition: function(event) {
903                 var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.ui.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
905                 // This is another very weird special case that only happens for relative elements:
906                 // 1. If the css position is relative
907                 // 2. and the scroll parent is the document or similar to the offset parent
908                 // we have to refresh the relative offset during the scroll so there are no jumps
909                 if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
910                         this.offset.relative = this._getRelativeOffset();
911                 }
913                 var pageX = event.pageX;
914                 var pageY = event.pageY;
916                 /*
917                  * - Position constraining -
918                  * Constrain the position to a mix of grid, containment.
919                  */
921                 if(this.originalPosition) { //If we are not dragging yet, we won't check for options
923                         if(this.containment) {
924                                 if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
925                                 if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
926                                 if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
927                                 if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
928                         }
930                         if(o.grid) {
931                                 var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
932                                 pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
934                                 var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
935                                 pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
936                         }
938                 }
940                 return {
941                         top: (
942                                 pageY                                                                                                                           // The absolute mouse position
943                                 - this.offset.click.top                                                                                                 // Click offset (relative to the element)
944                                 - this.offset.relative.top                                                                                              // Only for relative positioned nodes: Relative offset from element to offset parent
945                                 - this.offset.parent.top                                                                                                // The offsetParent's offset without borders (offset + border)
946                                 + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
947                         ),
948                         left: (
949                                 pageX                                                                                                                           // The absolute mouse position
950                                 - this.offset.click.left                                                                                                // Click offset (relative to the element)
951                                 - this.offset.relative.left                                                                                             // Only for relative positioned nodes: Relative offset from element to offset parent
952                                 - this.offset.parent.left                                                                                               // The offsetParent's offset without borders (offset + border)
953                                 + ($.browser.safari && this.cssPosition == 'fixed' ? 0 : ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
954                         )
955                 };
957         },
959         _rearrange: function(event, i, a, hardRefresh) {
961                 a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));
963                 //Various things done here to improve the performance:
964                 // 1. we create a setTimeout, that calls refreshPositions
965                 // 2. on the instance, we have a counter variable, that get's higher after every append
966                 // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
967                 // 4. this lets only the last addition to the timeout stack through
968                 this.counter = this.counter ? ++this.counter : 1;
969                 var self = this, counter = this.counter;
971                 window.setTimeout(function() {
972                         if(counter == self.counter) self.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
973                 },0);
975         },
977         _clear: function(event, noPropagation) {
979                 this.reverting = false;
980                 // We delay all events that have to be triggered to after the point where the placeholder has been removed and
981                 // everything else normalized again
982                 var delayedTriggers = [], self = this;
984                 // We first have to update the dom position of the actual currentItem
985                 // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
986                 if(!this._noFinalSort && this.currentItem.parent().length) this.placeholder.before(this.currentItem);
987                 this._noFinalSort = null;
989                 if(this.helper[0] == this.currentItem[0]) {
990                         for(var i in this._storedCSS) {
991                                 if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = '';
992                         }
993                         this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
994                 } else {
995                         this.currentItem.show();
996                 }
998                 if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
999                 if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
1000                 if(!$.ui.contains(this.element[0], this.currentItem[0])) { //Node was moved out of the current element
1001                         if(!noPropagation) delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
1002                         for (var i = this.containers.length - 1; i >= 0; i--){
1003                                 if($.ui.contains(this.containers[i].element[0], this.currentItem[0]) && !noPropagation) {
1004                                         delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
1005                                         delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.containers[i]));
1006                                 }
1007                         };
1008                 };
1010                 //Post events to containers
1011                 for (var i = this.containers.length - 1; i >= 0; i--){
1012                         if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
1013                         if(this.containers[i].containerCache.over) {
1014                                 delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); };  }).call(this, this.containers[i]));
1015                                 this.containers[i].containerCache.over = 0;
1016                         }
1017                 }
1019                 //Do what was originally in plugins
1020                 if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor
1021                 if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset opacity
1022                 if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index
1024                 this.dragging = false;
1025                 if(this.cancelHelperRemoval) {
1026                         if(!noPropagation) {
1027                                 this._trigger("beforeStop", event, this._uiHash());
1028                                 for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
1029                                 this._trigger("stop", event, this._uiHash());
1030                         }
1031                         return false;
1032                 }
1034                 if(!noPropagation) this._trigger("beforeStop", event, this._uiHash());
1036                 //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
1037                 this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
1039                 if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null;
1041                 if(!noPropagation) {
1042                         for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
1043                         this._trigger("stop", event, this._uiHash());
1044                 }
1046                 this.fromOutside = false;
1047                 return true;
1049         },
1051         _trigger: function() {
1052                 if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
1053                         this.cancel();
1054                 }
1055         },
1057         _uiHash: function(inst) {
1058                 var self = inst || this;
1059                 return {
1060                         helper: self.helper,
1061                         placeholder: self.placeholder || $([]),
1062                         position: self.position,
1063                         originalPosition: self.originalPosition,
1064                         offset: self.positionAbs,
1065                         item: self.currentItem,
1066                         sender: inst ? inst.element : null
1067                 };
1068         }
1072 $.extend($.ui.sortable, {
1073         version: "1.8.17"
1076 })(jQuery);