UPDATE 4.4.0.0
[phpmyadmin.git] / js / jquery / src / jquery-ui / sortable.js
blob948fda3a4553630188d225da8e8b2fd6db0b96f7
1 /*!
2  * jQuery UI Sortable 1.11.2
3  * http://jqueryui.com
4  *
5  * Copyright 2014 jQuery Foundation and other contributors
6  * Released under the MIT license.
7  * http://jquery.org/license
8  *
9  * http://api.jqueryui.com/sortable/
10  */
11 (function( factory ) {
12         if ( typeof define === "function" && define.amd ) {
14                 // AMD. Register as an anonymous module.
15                 define([
16                         "jquery",
17                         "./core",
18                         "./mouse",
19                         "./widget"
20                 ], factory );
21         } else {
23                 // Browser globals
24                 factory( jQuery );
25         }
26 }(function( $ ) {
28 return $.widget("ui.sortable", $.ui.mouse, {
29         version: "1.11.2",
30         widgetEventPrefix: "sort",
31         ready: false,
32         options: {
33                 appendTo: "parent",
34                 axis: false,
35                 connectWith: false,
36                 containment: false,
37                 cursor: "auto",
38                 cursorAt: false,
39                 dropOnEmpty: true,
40                 forcePlaceholderSize: false,
41                 forceHelperSize: false,
42                 grid: false,
43                 handle: false,
44                 helper: "original",
45                 items: "> *",
46                 opacity: false,
47                 placeholder: false,
48                 revert: false,
49                 scroll: true,
50                 scrollSensitivity: 20,
51                 scrollSpeed: 20,
52                 scope: "default",
53                 tolerance: "intersect",
54                 zIndex: 1000,
56                 // callbacks
57                 activate: null,
58                 beforeStop: null,
59                 change: null,
60                 deactivate: null,
61                 out: null,
62                 over: null,
63                 receive: null,
64                 remove: null,
65                 sort: null,
66                 start: null,
67                 stop: null,
68                 update: null
69         },
71         _isOverAxis: function( x, reference, size ) {
72                 return ( x >= reference ) && ( x < ( reference + size ) );
73         },
75         _isFloating: function( item ) {
76                 return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
77         },
79         _create: function() {
81                 var o = this.options;
82                 this.containerCache = {};
83                 this.element.addClass("ui-sortable");
85                 //Get the items
86                 this.refresh();
88                 //Let's determine if the items are being displayed horizontally
89                 this.floating = this.items.length ? o.axis === "x" || this._isFloating(this.items[0].item) : false;
91                 //Let's determine the parent's offset
92                 this.offset = this.element.offset();
94                 //Initialize mouse events for interaction
95                 this._mouseInit();
97                 this._setHandleClassName();
99                 //We're ready to go
100                 this.ready = true;
102         },
104         _setOption: function( key, value ) {
105                 this._super( key, value );
107                 if ( key === "handle" ) {
108                         this._setHandleClassName();
109                 }
110         },
112         _setHandleClassName: function() {
113                 this.element.find( ".ui-sortable-handle" ).removeClass( "ui-sortable-handle" );
114                 $.each( this.items, function() {
115                         ( this.instance.options.handle ?
116                                 this.item.find( this.instance.options.handle ) : this.item )
117                                 .addClass( "ui-sortable-handle" );
118                 });
119         },
121         _destroy: function() {
122                 this.element
123                         .removeClass( "ui-sortable ui-sortable-disabled" )
124                         .find( ".ui-sortable-handle" )
125                                 .removeClass( "ui-sortable-handle" );
126                 this._mouseDestroy();
128                 for ( var i = this.items.length - 1; i >= 0; i-- ) {
129                         this.items[i].item.removeData(this.widgetName + "-item");
130                 }
132                 return this;
133         },
135         _mouseCapture: function(event, overrideHandle) {
136                 var currentItem = null,
137                         validHandle = false,
138                         that = this;
140                 if (this.reverting) {
141                         return false;
142                 }
144                 if(this.options.disabled || this.options.type === "static") {
145                         return false;
146                 }
148                 //We have to refresh the items data once first
149                 this._refreshItems(event);
151                 //Find out if the clicked node (or one of its parents) is a actual item in this.items
152                 $(event.target).parents().each(function() {
153                         if($.data(this, that.widgetName + "-item") === that) {
154                                 currentItem = $(this);
155                                 return false;
156                         }
157                 });
158                 if($.data(event.target, that.widgetName + "-item") === that) {
159                         currentItem = $(event.target);
160                 }
162                 if(!currentItem) {
163                         return false;
164                 }
165                 if(this.options.handle && !overrideHandle) {
166                         $(this.options.handle, currentItem).find("*").addBack().each(function() {
167                                 if(this === event.target) {
168                                         validHandle = true;
169                                 }
170                         });
171                         if(!validHandle) {
172                                 return false;
173                         }
174                 }
176                 this.currentItem = currentItem;
177                 this._removeCurrentsFromItems();
178                 return true;
180         },
182         _mouseStart: function(event, overrideHandle, noActivation) {
184                 var i, body,
185                         o = this.options;
187                 this.currentContainer = this;
189                 //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
190                 this.refreshPositions();
192                 //Create and append the visible helper
193                 this.helper = this._createHelper(event);
195                 //Cache the helper size
196                 this._cacheHelperProportions();
198                 /*
199                  * - Position generation -
200                  * This block generates everything position related - it's the core of draggables.
201                  */
203                 //Cache the margins of the original element
204                 this._cacheMargins();
206                 //Get the next scrolling parent
207                 this.scrollParent = this.helper.scrollParent();
209                 //The element's absolute position on the page minus margins
210                 this.offset = this.currentItem.offset();
211                 this.offset = {
212                         top: this.offset.top - this.margins.top,
213                         left: this.offset.left - this.margins.left
214                 };
216                 $.extend(this.offset, {
217                         click: { //Where the click happened, relative to the element
218                                 left: event.pageX - this.offset.left,
219                                 top: event.pageY - this.offset.top
220                         },
221                         parent: this._getParentOffset(),
222                         relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
223                 });
225                 // Only after we got the offset, we can change the helper's position to absolute
226                 // TODO: Still need to figure out a way to make relative sorting possible
227                 this.helper.css("position", "absolute");
228                 this.cssPosition = this.helper.css("position");
230                 //Generate the original position
231                 this.originalPosition = this._generatePosition(event);
232                 this.originalPageX = event.pageX;
233                 this.originalPageY = event.pageY;
235                 //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
236                 (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
238                 //Cache the former DOM position
239                 this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
241                 //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
242                 if(this.helper[0] !== this.currentItem[0]) {
243                         this.currentItem.hide();
244                 }
246                 //Create the placeholder
247                 this._createPlaceholder();
249                 //Set a containment if given in the options
250                 if(o.containment) {
251                         this._setContainment();
252                 }
254                 if( o.cursor && o.cursor !== "auto" ) { // cursor option
255                         body = this.document.find( "body" );
257                         // support: IE
258                         this.storedCursor = body.css( "cursor" );
259                         body.css( "cursor", o.cursor );
261                         this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
262                 }
264                 if(o.opacity) { // opacity option
265                         if (this.helper.css("opacity")) {
266                                 this._storedOpacity = this.helper.css("opacity");
267                         }
268                         this.helper.css("opacity", o.opacity);
269                 }
271                 if(o.zIndex) { // zIndex option
272                         if (this.helper.css("zIndex")) {
273                                 this._storedZIndex = this.helper.css("zIndex");
274                         }
275                         this.helper.css("zIndex", o.zIndex);
276                 }
278                 //Prepare scrolling
279                 if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
280                         this.overflowOffset = this.scrollParent.offset();
281                 }
283                 //Call callbacks
284                 this._trigger("start", event, this._uiHash());
286                 //Recache the helper size
287                 if(!this._preserveHelperProportions) {
288                         this._cacheHelperProportions();
289                 }
292                 //Post "activate" events to possible containers
293                 if( !noActivation ) {
294                         for ( i = this.containers.length - 1; i >= 0; i-- ) {
295                                 this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
296                         }
297                 }
299                 //Prepare possible droppables
300                 if($.ui.ddmanager) {
301                         $.ui.ddmanager.current = this;
302                 }
304                 if ($.ui.ddmanager && !o.dropBehaviour) {
305                         $.ui.ddmanager.prepareOffsets(this, event);
306                 }
308                 this.dragging = true;
310                 this.helper.addClass("ui-sortable-helper");
311                 this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
312                 return true;
314         },
316         _mouseDrag: function(event) {
317                 var i, item, itemElement, intersection,
318                         o = this.options,
319                         scrolled = false;
321                 //Compute the helpers position
322                 this.position = this._generatePosition(event);
323                 this.positionAbs = this._convertPositionTo("absolute");
325                 if (!this.lastPositionAbs) {
326                         this.lastPositionAbs = this.positionAbs;
327                 }
329                 //Do scrolling
330                 if(this.options.scroll) {
331                         if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
333                                 if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
334                                         this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
335                                 } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
336                                         this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
337                                 }
339                                 if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
340                                         this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
341                                 } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
342                                         this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
343                                 }
345                         } else {
347                                 if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
348                                         scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
349                                 } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
350                                         scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
351                                 }
353                                 if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
354                                         scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
355                                 } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
356                                         scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
357                                 }
359                         }
361                         if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
362                                 $.ui.ddmanager.prepareOffsets(this, event);
363                         }
364                 }
366                 //Regenerate the absolute position used for position checks
367                 this.positionAbs = this._convertPositionTo("absolute");
369                 //Set the helper position
370                 if(!this.options.axis || this.options.axis !== "y") {
371                         this.helper[0].style.left = this.position.left+"px";
372                 }
373                 if(!this.options.axis || this.options.axis !== "x") {
374                         this.helper[0].style.top = this.position.top+"px";
375                 }
377                 //Rearrange
378                 for (i = this.items.length - 1; i >= 0; i--) {
380                         //Cache variables and intersection, continue if no intersection
381                         item = this.items[i];
382                         itemElement = item.item[0];
383                         intersection = this._intersectsWithPointer(item);
384                         if (!intersection) {
385                                 continue;
386                         }
388                         // Only put the placeholder inside the current Container, skip all
389                         // items from other containers. This works because when moving
390                         // an item from one container to another the
391                         // currentContainer is switched before the placeholder is moved.
392                         //
393                         // Without this, moving items in "sub-sortables" can cause
394                         // the placeholder to jitter between the outer and inner container.
395                         if (item.instance !== this.currentContainer) {
396                                 continue;
397                         }
399                         // cannot intersect with itself
400                         // no useless actions that have been done before
401                         // no action if the item moved is the parent of the item checked
402                         if (itemElement !== this.currentItem[0] &&
403                                 this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
404                                 !$.contains(this.placeholder[0], itemElement) &&
405                                 (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
406                         ) {
408                                 this.direction = intersection === 1 ? "down" : "up";
410                                 if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
411                                         this._rearrange(event, item);
412                                 } else {
413                                         break;
414                                 }
416                                 this._trigger("change", event, this._uiHash());
417                                 break;
418                         }
419                 }
421                 //Post events to containers
422                 this._contactContainers(event);
424                 //Interconnect with droppables
425                 if($.ui.ddmanager) {
426                         $.ui.ddmanager.drag(this, event);
427                 }
429                 //Call callbacks
430                 this._trigger("sort", event, this._uiHash());
432                 this.lastPositionAbs = this.positionAbs;
433                 return false;
435         },
437         _mouseStop: function(event, noPropagation) {
439                 if(!event) {
440                         return;
441                 }
443                 //If we are using droppables, inform the manager about the drop
444                 if ($.ui.ddmanager && !this.options.dropBehaviour) {
445                         $.ui.ddmanager.drop(this, event);
446                 }
448                 if(this.options.revert) {
449                         var that = this,
450                                 cur = this.placeholder.offset(),
451                                 axis = this.options.axis,
452                                 animation = {};
454                         if ( !axis || axis === "x" ) {
455                                 animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
456                         }
457                         if ( !axis || axis === "y" ) {
458                                 animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
459                         }
460                         this.reverting = true;
461                         $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
462                                 that._clear(event);
463                         });
464                 } else {
465                         this._clear(event, noPropagation);
466                 }
468                 return false;
470         },
472         cancel: function() {
474                 if(this.dragging) {
476                         this._mouseUp({ target: null });
478                         if(this.options.helper === "original") {
479                                 this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
480                         } else {
481                                 this.currentItem.show();
482                         }
484                         //Post deactivating events to containers
485                         for (var i = this.containers.length - 1; i >= 0; i--){
486                                 this.containers[i]._trigger("deactivate", null, this._uiHash(this));
487                                 if(this.containers[i].containerCache.over) {
488                                         this.containers[i]._trigger("out", null, this._uiHash(this));
489                                         this.containers[i].containerCache.over = 0;
490                                 }
491                         }
493                 }
495                 if (this.placeholder) {
496                         //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
497                         if(this.placeholder[0].parentNode) {
498                                 this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
499                         }
500                         if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
501                                 this.helper.remove();
502                         }
504                         $.extend(this, {
505                                 helper: null,
506                                 dragging: false,
507                                 reverting: false,
508                                 _noFinalSort: null
509                         });
511                         if(this.domPosition.prev) {
512                                 $(this.domPosition.prev).after(this.currentItem);
513                         } else {
514                                 $(this.domPosition.parent).prepend(this.currentItem);
515                         }
516                 }
518                 return this;
520         },
522         serialize: function(o) {
524                 var items = this._getItemsAsjQuery(o && o.connected),
525                         str = [];
526                 o = o || {};
528                 $(items).each(function() {
529                         var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
530                         if (res) {
531                                 str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
532                         }
533                 });
535                 if(!str.length && o.key) {
536                         str.push(o.key + "=");
537                 }
539                 return str.join("&");
541         },
543         toArray: function(o) {
545                 var items = this._getItemsAsjQuery(o && o.connected),
546                         ret = [];
548                 o = o || {};
550                 items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
551                 return ret;
553         },
555         /* Be careful with the following core functions */
556         _intersectsWith: function(item) {
558                 var x1 = this.positionAbs.left,
559                         x2 = x1 + this.helperProportions.width,
560                         y1 = this.positionAbs.top,
561                         y2 = y1 + this.helperProportions.height,
562                         l = item.left,
563                         r = l + item.width,
564                         t = item.top,
565                         b = t + item.height,
566                         dyClick = this.offset.click.top,
567                         dxClick = this.offset.click.left,
568                         isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ),
569                         isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ),
570                         isOverElement = isOverElementHeight && isOverElementWidth;
572                 if ( this.options.tolerance === "pointer" ||
573                         this.options.forcePointerForContainers ||
574                         (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
575                 ) {
576                         return isOverElement;
577                 } else {
579                         return (l < x1 + (this.helperProportions.width / 2) && // Right Half
580                                 x2 - (this.helperProportions.width / 2) < r && // Left Half
581                                 t < y1 + (this.helperProportions.height / 2) && // Bottom Half
582                                 y2 - (this.helperProportions.height / 2) < b ); // Top Half
584                 }
585         },
587         _intersectsWithPointer: function(item) {
589                 var isOverElementHeight = (this.options.axis === "x") || this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
590                         isOverElementWidth = (this.options.axis === "y") || this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
591                         isOverElement = isOverElementHeight && isOverElementWidth,
592                         verticalDirection = this._getDragVerticalDirection(),
593                         horizontalDirection = this._getDragHorizontalDirection();
595                 if (!isOverElement) {
596                         return false;
597                 }
599                 return this.floating ?
600                         ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
601                         : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );
603         },
605         _intersectsWithSides: function(item) {
607                 var isOverBottomHalf = this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
608                         isOverRightHalf = this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
609                         verticalDirection = this._getDragVerticalDirection(),
610                         horizontalDirection = this._getDragHorizontalDirection();
612                 if (this.floating && horizontalDirection) {
613                         return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
614                 } else {
615                         return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
616                 }
618         },
620         _getDragVerticalDirection: function() {
621                 var delta = this.positionAbs.top - this.lastPositionAbs.top;
622                 return delta !== 0 && (delta > 0 ? "down" : "up");
623         },
625         _getDragHorizontalDirection: function() {
626                 var delta = this.positionAbs.left - this.lastPositionAbs.left;
627                 return delta !== 0 && (delta > 0 ? "right" : "left");
628         },
630         refresh: function(event) {
631                 this._refreshItems(event);
632                 this._setHandleClassName();
633                 this.refreshPositions();
634                 return this;
635         },
637         _connectWith: function() {
638                 var options = this.options;
639                 return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
640         },
642         _getItemsAsjQuery: function(connected) {
644                 var i, j, cur, inst,
645                         items = [],
646                         queries = [],
647                         connectWith = this._connectWith();
649                 if(connectWith && connected) {
650                         for (i = connectWith.length - 1; i >= 0; i--){
651                                 cur = $(connectWith[i]);
652                                 for ( j = cur.length - 1; j >= 0; j--){
653                                         inst = $.data(cur[j], this.widgetFullName);
654                                         if(inst && inst !== this && !inst.options.disabled) {
655                                                 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]);
656                                         }
657                                 }
658                         }
659                 }
661                 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]);
663                 function addItems() {
664                         items.push( this );
665                 }
666                 for (i = queries.length - 1; i >= 0; i--){
667                         queries[i][0].each( addItems );
668                 }
670                 return $(items);
672         },
674         _removeCurrentsFromItems: function() {
676                 var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
678                 this.items = $.grep(this.items, function (item) {
679                         for (var j=0; j < list.length; j++) {
680                                 if(list[j] === item.item[0]) {
681                                         return false;
682                                 }
683                         }
684                         return true;
685                 });
687         },
689         _refreshItems: function(event) {
691                 this.items = [];
692                 this.containers = [this];
694                 var i, j, cur, inst, targetData, _queries, item, queriesLength,
695                         items = this.items,
696                         queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
697                         connectWith = this._connectWith();
699                 if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
700                         for (i = connectWith.length - 1; i >= 0; i--){
701                                 cur = $(connectWith[i]);
702                                 for (j = cur.length - 1; j >= 0; j--){
703                                         inst = $.data(cur[j], this.widgetFullName);
704                                         if(inst && inst !== this && !inst.options.disabled) {
705                                                 queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
706                                                 this.containers.push(inst);
707                                         }
708                                 }
709                         }
710                 }
712                 for (i = queries.length - 1; i >= 0; i--) {
713                         targetData = queries[i][1];
714                         _queries = queries[i][0];
716                         for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
717                                 item = $(_queries[j]);
719                                 item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)
721                                 items.push({
722                                         item: item,
723                                         instance: targetData,
724                                         width: 0, height: 0,
725                                         left: 0, top: 0
726                                 });
727                         }
728                 }
730         },
732         refreshPositions: function(fast) {
734                 //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
735                 if(this.offsetParent && this.helper) {
736                         this.offset.parent = this._getParentOffset();
737                 }
739                 var i, item, t, p;
741                 for (i = this.items.length - 1; i >= 0; i--){
742                         item = this.items[i];
744                         //We ignore calculating positions of all connected containers when we're not over them
745                         if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
746                                 continue;
747                         }
749                         t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
751                         if (!fast) {
752                                 item.width = t.outerWidth();
753                                 item.height = t.outerHeight();
754                         }
756                         p = t.offset();
757                         item.left = p.left;
758                         item.top = p.top;
759                 }
761                 if(this.options.custom && this.options.custom.refreshContainers) {
762                         this.options.custom.refreshContainers.call(this);
763                 } else {
764                         for (i = this.containers.length - 1; i >= 0; i--){
765                                 p = this.containers[i].element.offset();
766                                 this.containers[i].containerCache.left = p.left;
767                                 this.containers[i].containerCache.top = p.top;
768                                 this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
769                                 this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
770                         }
771                 }
773                 return this;
774         },
776         _createPlaceholder: function(that) {
777                 that = that || this;
778                 var className,
779                         o = that.options;
781                 if(!o.placeholder || o.placeholder.constructor === String) {
782                         className = o.placeholder;
783                         o.placeholder = {
784                                 element: function() {
786                                         var nodeName = that.currentItem[0].nodeName.toLowerCase(),
787                                                 element = $( "<" + nodeName + ">", that.document[0] )
788                                                         .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
789                                                         .removeClass("ui-sortable-helper");
791                                         if ( nodeName === "tr" ) {
792                                                 that.currentItem.children().each(function() {
793                                                         $( "<td>&#160;</td>", that.document[0] )
794                                                                 .attr( "colspan", $( this ).attr( "colspan" ) || 1 )
795                                                                 .appendTo( element );
796                                                 });
797                                         } else if ( nodeName === "img" ) {
798                                                 element.attr( "src", that.currentItem.attr( "src" ) );
799                                         }
801                                         if ( !className ) {
802                                                 element.css( "visibility", "hidden" );
803                                         }
805                                         return element;
806                                 },
807                                 update: function(container, p) {
809                                         // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
810                                         // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
811                                         if(className && !o.forcePlaceholderSize) {
812                                                 return;
813                                         }
815                                         //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
816                                         if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
817                                         if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
818                                 }
819                         };
820                 }
822                 //Create the placeholder
823                 that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
825                 //Append it after the actual current item
826                 that.currentItem.after(that.placeholder);
828                 //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
829                 o.placeholder.update(that, that.placeholder);
831         },
833         _contactContainers: function(event) {
834                 var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom, floating, axis,
835                         innermostContainer = null,
836                         innermostIndex = null;
838                 // get innermost container that intersects with item
839                 for (i = this.containers.length - 1; i >= 0; i--) {
841                         // never consider a container that's located within the item itself
842                         if($.contains(this.currentItem[0], this.containers[i].element[0])) {
843                                 continue;
844                         }
846                         if(this._intersectsWith(this.containers[i].containerCache)) {
848                                 // if we've already found a container and it's more "inner" than this, then continue
849                                 if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
850                                         continue;
851                                 }
853                                 innermostContainer = this.containers[i];
854                                 innermostIndex = i;
856                         } else {
857                                 // container doesn't intersect. trigger "out" event if necessary
858                                 if(this.containers[i].containerCache.over) {
859                                         this.containers[i]._trigger("out", event, this._uiHash(this));
860                                         this.containers[i].containerCache.over = 0;
861                                 }
862                         }
864                 }
866                 // if no intersecting containers found, return
867                 if(!innermostContainer) {
868                         return;
869                 }
871                 // move the item into the container if it's not there already
872                 if(this.containers.length === 1) {
873                         if (!this.containers[innermostIndex].containerCache.over) {
874                                 this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
875                                 this.containers[innermostIndex].containerCache.over = 1;
876                         }
877                 } else {
879                         //When entering a new container, we will find the item with the least distance and append our item near it
880                         dist = 10000;
881                         itemWithLeastDistance = null;
882                         floating = innermostContainer.floating || this._isFloating(this.currentItem);
883                         posProperty = floating ? "left" : "top";
884                         sizeProperty = floating ? "width" : "height";
885                         axis = floating ? "clientX" : "clientY";
887                         for (j = this.items.length - 1; j >= 0; j--) {
888                                 if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
889                                         continue;
890                                 }
891                                 if(this.items[j].item[0] === this.currentItem[0]) {
892                                         continue;
893                                 }
895                                 cur = this.items[j].item.offset()[posProperty];
896                                 nearBottom = false;
897                                 if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
898                                         nearBottom = true;
899                                 }
901                                 if ( Math.abs( event[ axis ] - cur ) < dist ) {
902                                         dist = Math.abs( event[ axis ] - cur );
903                                         itemWithLeastDistance = this.items[ j ];
904                                         this.direction = nearBottom ? "up": "down";
905                                 }
906                         }
908                         //Check if dropOnEmpty is enabled
909                         if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
910                                 return;
911                         }
913                         if(this.currentContainer === this.containers[innermostIndex]) {
914                                 if ( !this.currentContainer.containerCache.over ) {
915                                         this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
916                                         this.currentContainer.containerCache.over = 1;
917                                 }
918                                 return;
919                         }
921                         itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
922                         this._trigger("change", event, this._uiHash());
923                         this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
924                         this.currentContainer = this.containers[innermostIndex];
926                         //Update the placeholder
927                         this.options.placeholder.update(this.currentContainer, this.placeholder);
929                         this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
930                         this.containers[innermostIndex].containerCache.over = 1;
931                 }
934         },
936         _createHelper: function(event) {
938                 var o = this.options,
939                         helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);
941                 //Add the helper to the DOM if that didn't happen already
942                 if(!helper.parents("body").length) {
943                         $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
944                 }
946                 if(helper[0] === this.currentItem[0]) {
947                         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") };
948                 }
950                 if(!helper[0].style.width || o.forceHelperSize) {
951                         helper.width(this.currentItem.width());
952                 }
953                 if(!helper[0].style.height || o.forceHelperSize) {
954                         helper.height(this.currentItem.height());
955                 }
957                 return helper;
959         },
961         _adjustOffsetFromHelper: function(obj) {
962                 if (typeof obj === "string") {
963                         obj = obj.split(" ");
964                 }
965                 if ($.isArray(obj)) {
966                         obj = {left: +obj[0], top: +obj[1] || 0};
967                 }
968                 if ("left" in obj) {
969                         this.offset.click.left = obj.left + this.margins.left;
970                 }
971                 if ("right" in obj) {
972                         this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
973                 }
974                 if ("top" in obj) {
975                         this.offset.click.top = obj.top + this.margins.top;
976                 }
977                 if ("bottom" in obj) {
978                         this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
979                 }
980         },
982         _getParentOffset: function() {
985                 //Get the offsetParent and cache its position
986                 this.offsetParent = this.helper.offsetParent();
987                 var po = this.offsetParent.offset();
989                 // This is a special case where we need to modify a offset calculated on start, since the following happened:
990                 // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
991                 // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
992                 //    the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
993                 if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
994                         po.left += this.scrollParent.scrollLeft();
995                         po.top += this.scrollParent.scrollTop();
996                 }
998                 // This needs to be actually done for all browsers, since pageX/pageY includes this information
999                 // with an ugly IE fix
1000                 if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
1001                         po = { top: 0, left: 0 };
1002                 }
1004                 return {
1005                         top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
1006                         left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
1007                 };
1009         },
1011         _getRelativeOffset: function() {
1013                 if(this.cssPosition === "relative") {
1014                         var p = this.currentItem.position();
1015                         return {
1016                                 top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
1017                                 left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
1018                         };
1019                 } else {
1020                         return { top: 0, left: 0 };
1021                 }
1023         },
1025         _cacheMargins: function() {
1026                 this.margins = {
1027                         left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
1028                         top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
1029                 };
1030         },
1032         _cacheHelperProportions: function() {
1033                 this.helperProportions = {
1034                         width: this.helper.outerWidth(),
1035                         height: this.helper.outerHeight()
1036                 };
1037         },
1039         _setContainment: function() {
1041                 var ce, co, over,
1042                         o = this.options;
1043                 if(o.containment === "parent") {
1044                         o.containment = this.helper[0].parentNode;
1045                 }
1046                 if(o.containment === "document" || o.containment === "window") {
1047                         this.containment = [
1048                                 0 - this.offset.relative.left - this.offset.parent.left,
1049                                 0 - this.offset.relative.top - this.offset.parent.top,
1050                                 $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
1051                                 ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
1052                         ];
1053                 }
1055                 if(!(/^(document|window|parent)$/).test(o.containment)) {
1056                         ce = $(o.containment)[0];
1057                         co = $(o.containment).offset();
1058                         over = ($(ce).css("overflow") !== "hidden");
1060                         this.containment = [
1061                                 co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
1062                                 co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
1063                                 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,
1064                                 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
1065                         ];
1066                 }
1068         },
1070         _convertPositionTo: function(d, pos) {
1072                 if(!pos) {
1073                         pos = this.position;
1074                 }
1075                 var mod = d === "absolute" ? 1 : -1,
1076                         scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
1077                         scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
1079                 return {
1080                         top: (
1081                                 pos.top +                                                                                                                               // The absolute mouse position
1082                                 this.offset.relative.top * mod +                                                                                // Only for relative positioned nodes: Relative offset from element to offset parent
1083                                 this.offset.parent.top * mod -                                                                                  // The offsetParent's offset without borders (offset + border)
1084                                 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
1085                         ),
1086                         left: (
1087                                 pos.left +                                                                                                                              // The absolute mouse position
1088                                 this.offset.relative.left * mod +                                                                               // Only for relative positioned nodes: Relative offset from element to offset parent
1089                                 this.offset.parent.left * mod   -                                                                               // The offsetParent's offset without borders (offset + border)
1090                                 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
1091                         )
1092                 };
1094         },
1096         _generatePosition: function(event) {
1098                 var top, left,
1099                         o = this.options,
1100                         pageX = event.pageX,
1101                         pageY = event.pageY,
1102                         scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
1104                 // This is another very weird special case that only happens for relative elements:
1105                 // 1. If the css position is relative
1106                 // 2. and the scroll parent is the document or similar to the offset parent
1107                 // we have to refresh the relative offset during the scroll so there are no jumps
1108                 if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
1109                         this.offset.relative = this._getRelativeOffset();
1110                 }
1112                 /*
1113                  * - Position constraining -
1114                  * Constrain the position to a mix of grid, containment.
1115                  */
1117                 if(this.originalPosition) { //If we are not dragging yet, we won't check for options
1119                         if(this.containment) {
1120                                 if(event.pageX - this.offset.click.left < this.containment[0]) {
1121                                         pageX = this.containment[0] + this.offset.click.left;
1122                                 }
1123                                 if(event.pageY - this.offset.click.top < this.containment[1]) {
1124                                         pageY = this.containment[1] + this.offset.click.top;
1125                                 }
1126                                 if(event.pageX - this.offset.click.left > this.containment[2]) {
1127                                         pageX = this.containment[2] + this.offset.click.left;
1128                                 }
1129                                 if(event.pageY - this.offset.click.top > this.containment[3]) {
1130                                         pageY = this.containment[3] + this.offset.click.top;
1131                                 }
1132                         }
1134                         if(o.grid) {
1135                                 top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
1136                                 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;
1138                                 left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
1139                                 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;
1140                         }
1142                 }
1144                 return {
1145                         top: (
1146                                 pageY -                                                                                                                         // The absolute mouse position
1147                                 this.offset.click.top -                                                                                                 // Click offset (relative to the element)
1148                                 this.offset.relative.top        -                                                                                       // Only for relative positioned nodes: Relative offset from element to offset parent
1149                                 this.offset.parent.top +                                                                                                // The offsetParent's offset without borders (offset + border)
1150                                 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
1151                         ),
1152                         left: (
1153                                 pageX -                                                                                                                         // The absolute mouse position
1154                                 this.offset.click.left -                                                                                                // Click offset (relative to the element)
1155                                 this.offset.relative.left       -                                                                                       // Only for relative positioned nodes: Relative offset from element to offset parent
1156                                 this.offset.parent.left +                                                                                               // The offsetParent's offset without borders (offset + border)
1157                                 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
1158                         )
1159                 };
1161         },
1163         _rearrange: function(event, i, a, hardRefresh) {
1165                 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));
1167                 //Various things done here to improve the performance:
1168                 // 1. we create a setTimeout, that calls refreshPositions
1169                 // 2. on the instance, we have a counter variable, that get's higher after every append
1170                 // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
1171                 // 4. this lets only the last addition to the timeout stack through
1172                 this.counter = this.counter ? ++this.counter : 1;
1173                 var counter = this.counter;
1175                 this._delay(function() {
1176                         if(counter === this.counter) {
1177                                 this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
1178                         }
1179                 });
1181         },
1183         _clear: function(event, noPropagation) {
1185                 this.reverting = false;
1186                 // We delay all events that have to be triggered to after the point where the placeholder has been removed and
1187                 // everything else normalized again
1188                 var i,
1189                         delayedTriggers = [];
1191                 // We first have to update the dom position of the actual currentItem
1192                 // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
1193                 if(!this._noFinalSort && this.currentItem.parent().length) {
1194                         this.placeholder.before(this.currentItem);
1195                 }
1196                 this._noFinalSort = null;
1198                 if(this.helper[0] === this.currentItem[0]) {
1199                         for(i in this._storedCSS) {
1200                                 if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
1201                                         this._storedCSS[i] = "";
1202                                 }
1203                         }
1204                         this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
1205                 } else {
1206                         this.currentItem.show();
1207                 }
1209                 if(this.fromOutside && !noPropagation) {
1210                         delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
1211                 }
1212                 if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
1213                         delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
1214                 }
1216                 // Check if the items Container has Changed and trigger appropriate
1217                 // events.
1218                 if (this !== this.currentContainer) {
1219                         if(!noPropagation) {
1220                                 delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
1221                                 delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); };  }).call(this, this.currentContainer));
1222                                 delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this));  }; }).call(this, this.currentContainer));
1223                         }
1224                 }
1227                 //Post events to containers
1228                 function delayEvent( type, instance, container ) {
1229                         return function( event ) {
1230                                 container._trigger( type, event, instance._uiHash( instance ) );
1231                         };
1232                 }
1233                 for (i = this.containers.length - 1; i >= 0; i--){
1234                         if (!noPropagation) {
1235                                 delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
1236                         }
1237                         if(this.containers[i].containerCache.over) {
1238                                 delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
1239                                 this.containers[i].containerCache.over = 0;
1240                         }
1241                 }
1243                 //Do what was originally in plugins
1244                 if ( this.storedCursor ) {
1245                         this.document.find( "body" ).css( "cursor", this.storedCursor );
1246                         this.storedStylesheet.remove();
1247                 }
1248                 if(this._storedOpacity) {
1249                         this.helper.css("opacity", this._storedOpacity);
1250                 }
1251                 if(this._storedZIndex) {
1252                         this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
1253                 }
1255                 this.dragging = false;
1257                 if(!noPropagation) {
1258                         this._trigger("beforeStop", event, this._uiHash());
1259                 }
1261                 //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
1262                 this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
1264                 if ( !this.cancelHelperRemoval ) {
1265                         if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
1266                                 this.helper.remove();
1267                         }
1268                         this.helper = null;
1269                 }
1271                 if(!noPropagation) {
1272                         for (i=0; i < delayedTriggers.length; i++) {
1273                                 delayedTriggers[i].call(this, event);
1274                         } //Trigger all delayed events
1275                         this._trigger("stop", event, this._uiHash());
1276                 }
1278                 this.fromOutside = false;
1279                 return !this.cancelHelperRemoval;
1281         },
1283         _trigger: function() {
1284                 if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
1285                         this.cancel();
1286                 }
1287         },
1289         _uiHash: function(_inst) {
1290                 var inst = _inst || this;
1291                 return {
1292                         helper: inst.helper,
1293                         placeholder: inst.placeholder || $([]),
1294                         position: inst.position,
1295                         originalPosition: inst.originalPosition,
1296                         offset: inst.positionAbs,
1297                         item: inst.currentItem,
1298                         sender: _inst ? _inst.element : null
1299                 };
1300         }
1304 }));