ux/Iscroll.js
[roojs1] / ux / Iscroll.js
1 /*!
2  * iScroll v4.1.9 ~ Copyright (c) 2011 Matteo Spinelli, http://cubiq.org
3  * Released under MIT license, http://cubiq.org/license
4  */
5
6 namespace('Roo.ux');
7
8 (function(){
9 var m = Math,
10         vendor = (/webkit/i).test(navigator.appVersion) ? 'webkit' :
11                 (/firefox/i).test(navigator.userAgent) ? 'Moz' :
12                 'opera' in window ? 'O' : '',
13
14         // Browser capabilities
15         has3d = 'WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix(),
16         hasTouch = 'ontouchstart' in window,
17         hasTransform = vendor + 'Transform' in document.documentElement.style,
18         isAndroid = (/android/gi).test(navigator.appVersion),
19         isIDevice = (/iphone|ipad/gi).test(navigator.appVersion),
20         isPlaybook = (/playbook/gi).test(navigator.appVersion),
21         hasTransitionEnd = isIDevice || isPlaybook,
22         nextFrame = (function() {
23             return window.requestAnimationFrame
24                         || window.webkitRequestAnimationFrame
25                         || window.mozRequestAnimationFrame
26                         || window.oRequestAnimationFrame
27                         || window.msRequestAnimationFrame
28                         || function(callback) { return setTimeout(callback, 1); }
29         })(),
30         cancelFrame = (function () {
31             return window.cancelRequestAnimationFrame
32                         || window.webkitCancelRequestAnimationFrame
33                         || window.mozCancelRequestAnimationFrame
34                         || window.oCancelRequestAnimationFrame
35                         || window.msCancelRequestAnimationFrame
36                         || clearTimeout
37         })(),
38
39         // Events
40         RESIZE_EV = 'onorientationchange' in window ? 'orientationchange' : 'resize',
41         START_EV = hasTouch ? 'touchstart' : 'mousedown',
42         MOVE_EV = hasTouch ? 'touchmove' : 'mousemove',
43         END_EV = hasTouch ? 'touchend' : 'mouseup',
44         CANCEL_EV = hasTouch ? 'touchcancel' : 'mouseup',
45         WHEEL_EV = vendor == 'Moz' ? 'DOMMouseScroll' : 'mousewheel',
46
47         // Helpers
48         trnOpen = 'translate' + (has3d ? '3d(' : '('),
49         trnClose = has3d ? ',0)' : ')',
50
51         // Constructor
52         Roo.ux.iScroll = function (el, options) {
53                 var that = this,
54                         doc = document,
55                         i;
56
57                 that.wrapper = typeof el == 'object' ? el : doc.getElementById(el);
58                 that.wrapper.style.overflow = 'hidden';
59                 that.scroller = that.wrapper.children[0];
60
61                 // Default options
62                 that.options = {
63                         hScroll: true,
64                         vScroll: true,
65                         bounce: true,
66                         bounceLock: false,
67                         momentum: true,
68                         lockDirection: true,
69                         useTransform: true,
70                         useTransition: false,
71                         topOffset: 0,
72                         checkDOMChanges: false,         // Experimental
73
74                         // Scrollbar
75                         hScrollbar: true,
76                         vScrollbar: true,
77                         fixedScrollbar: isAndroid,
78                         hideScrollbar: isIDevice,
79                         fadeScrollbar: isIDevice && has3d,
80                         scrollbarClass: '',
81
82                         // Zoom
83                         zoom: false,
84                         zoomMin: 1,
85                         zoomMax: 4,
86                         doubleTapZoom: 2,
87                         wheelAction: 'scroll',
88
89                         // Snap
90                         snap: false,
91                         snapThreshold: 1,
92
93                         // Events
94                         onRefresh: null,
95                         onBeforeScrollStart: function (e) { e.preventDefault(); },
96                         onScrollStart: null,
97                         onBeforeScrollMove: null,
98                         onScrollMove: null,
99                         onBeforeScrollEnd: null,
100                         onScrollEnd: null,
101                         onTouchEnd: null,
102                         onDestroy: null,
103                         onZoomStart: null,
104                         onZoom: null,
105                         onZoomEnd: null
106                 };
107
108                 // User defined options
109                 for (i in options) that.options[i] = options[i];
110
111                 // Normalize options
112                 that.options.useTransform = hasTransform ? that.options.useTransform : false;
113                 that.options.hScrollbar = that.options.hScroll && that.options.hScrollbar;
114                 that.options.vScrollbar = that.options.vScroll && that.options.vScrollbar;
115                 that.options.zoom = that.options.useTransform && that.options.zoom;
116                 that.options.useTransition = hasTransitionEnd && that.options.useTransition;
117                 
118                 // Set some default styles
119                 that.scroller.style[vendor + 'TransitionProperty'] = that.options.useTransform ? '-' + vendor.toLowerCase() + '-transform' : 'top left';
120                 that.scroller.style[vendor + 'TransitionDuration'] = '0';
121                 that.scroller.style[vendor + 'TransformOrigin'] = '0 0';
122                 if (that.options.useTransition) that.scroller.style[vendor + 'TransitionTimingFunction'] = 'cubic-bezier(0.33,0.66,0.66,1)';
123                 
124                 if (that.options.useTransform) that.scroller.style[vendor + 'Transform'] = trnOpen + '0,0' + trnClose;
125                 else that.scroller.style.cssText += ';position:absolute;top:0;left:0';
126
127                 if (that.options.useTransition) that.options.fixedScrollbar = true;
128
129                 that.refresh();
130
131                 that._bind(RESIZE_EV, window);
132                 that._bind(START_EV);
133                 if (!hasTouch) {
134                         that._bind('mouseout', that.wrapper);
135                         that._bind(WHEEL_EV);
136                 }
137
138                 if (that.options.checkDOMChanges) that.checkDOMTime = setInterval(function () {
139                         that._checkDOMChanges();
140                 }, 500);
141         };
142
143 // Prototype
144 iScroll.prototype = {
145         enabled: true,
146         x: 0,
147         y: 0,
148         steps: [],
149         scale: 1,
150         currPageX: 0, currPageY: 0,
151         pagesX: [], pagesY: [],
152         aniTime: null,
153         wheelZoomCount: 0,
154         
155         handleEvent: function (e) {
156                 var that = this;
157                 switch(e.type) {
158                         case START_EV:
159                                 if (!hasTouch && e.button !== 0) return;
160                                 that._start(e);
161                                 break;
162                         case MOVE_EV: that._move(e); break;
163                         case END_EV:
164                         case CANCEL_EV: that._end(e); break;
165                         case RESIZE_EV: that._resize(); break;
166                         case WHEEL_EV: that._wheel(e); break;
167                         case 'mouseout': that._mouseout(e); break;
168                         case 'webkitTransitionEnd': that._transitionEnd(e); break;
169                 }
170         },
171         
172         _checkDOMChanges: function () {
173                 if (this.moved || this.zoomed || this.animating ||
174                         (this.scrollerW == this.scroller.offsetWidth * this.scale && this.scrollerH == this.scroller.offsetHeight * this.scale)) return;
175
176                 this.refresh();
177         },
178         
179         _scrollbar: function (dir) {
180                 var that = this,
181                         doc = document,
182                         bar;
183
184                 if (!that[dir + 'Scrollbar']) {
185                         if (that[dir + 'ScrollbarWrapper']) {
186                                 if (hasTransform) that[dir + 'ScrollbarIndicator'].style[vendor + 'Transform'] = '';
187                                 that[dir + 'ScrollbarWrapper'].parentNode.removeChild(that[dir + 'ScrollbarWrapper']);
188                                 that[dir + 'ScrollbarWrapper'] = null;
189                                 that[dir + 'ScrollbarIndicator'] = null;
190                         }
191
192                         return;
193                 }
194
195                 if (!that[dir + 'ScrollbarWrapper']) {
196                         // Create the scrollbar wrapper
197                         bar = doc.createElement('div');
198
199                         if (that.options.scrollbarClass) bar.className = that.options.scrollbarClass + dir.toUpperCase();
200                         else bar.style.cssText = 'position:absolute;z-index:100;' + (dir == 'h' ? 'height:7px;bottom:1px;left:2px;right:' + (that.vScrollbar ? '7' : '2') + 'px' : 'width:7px;bottom:' + (that.hScrollbar ? '7' : '2') + 'px;top:2px;right:1px');
201
202                         bar.style.cssText += ';pointer-events:none;-' + vendor + '-transition-property:opacity;-' + vendor + '-transition-duration:' + (that.options.fadeScrollbar ? '350ms' : '0') + ';overflow:hidden;opacity:' + (that.options.hideScrollbar ? '0' : '1');
203
204                         that.wrapper.appendChild(bar);
205                         that[dir + 'ScrollbarWrapper'] = bar;
206
207                         // Create the scrollbar indicator
208                         bar = doc.createElement('div');
209                         if (!that.options.scrollbarClass) {
210                                 bar.style.cssText = 'position:absolute;z-index:100;background:rgba(0,0,0,0.5);border:1px solid rgba(255,255,255,0.9);-' + vendor + '-background-clip:padding-box;-' + vendor + '-box-sizing:border-box;' + (dir == 'h' ? 'height:100%' : 'width:100%') + ';-' + vendor + '-border-radius:3px;border-radius:3px';
211                         }
212                         bar.style.cssText += ';pointer-events:none;-' + vendor + '-transition-property:-' + vendor + '-transform;-' + vendor + '-transition-timing-function:cubic-bezier(0.33,0.66,0.66,1);-' + vendor + '-transition-duration:0;-' + vendor + '-transform:' + trnOpen + '0,0' + trnClose;
213                         if (that.options.useTransition) bar.style.cssText += ';-' + vendor + '-transition-timing-function:cubic-bezier(0.33,0.66,0.66,1)';
214
215                         that[dir + 'ScrollbarWrapper'].appendChild(bar);
216                         that[dir + 'ScrollbarIndicator'] = bar;
217                 }
218
219                 if (dir == 'h') {
220                         that.hScrollbarSize = that.hScrollbarWrapper.clientWidth;
221                         that.hScrollbarIndicatorSize = m.max(m.round(that.hScrollbarSize * that.hScrollbarSize / that.scrollerW), 8);
222                         that.hScrollbarIndicator.style.width = that.hScrollbarIndicatorSize + 'px';
223                         that.hScrollbarMaxScroll = that.hScrollbarSize - that.hScrollbarIndicatorSize;
224                         that.hScrollbarProp = that.hScrollbarMaxScroll / that.maxScrollX;
225                 } else {
226                         that.vScrollbarSize = that.vScrollbarWrapper.clientHeight;
227                         that.vScrollbarIndicatorSize = m.max(m.round(that.vScrollbarSize * that.vScrollbarSize / that.scrollerH), 8);
228                         that.vScrollbarIndicator.style.height = that.vScrollbarIndicatorSize + 'px';
229                         that.vScrollbarMaxScroll = that.vScrollbarSize - that.vScrollbarIndicatorSize;
230                         that.vScrollbarProp = that.vScrollbarMaxScroll / that.maxScrollY;
231                 }
232
233                 // Reset position
234                 that._scrollbarPos(dir, true);
235         },
236         
237         _resize: function () {
238                 var that = this;
239                 setTimeout(function () { that.refresh(); }, isAndroid ? 200 : 0);
240         },
241         
242         _pos: function (x, y) {
243                 x = this.hScroll ? x : 0;
244                 y = this.vScroll ? y : 0;
245
246                 if (this.options.useTransform) {
247                         this.scroller.style[vendor + 'Transform'] = trnOpen + x + 'px,' + y + 'px' + trnClose + ' scale(' + this.scale + ')';
248                 } else {
249                         x = m.round(x);
250                         y = m.round(y);
251                         this.scroller.style.left = x + 'px';
252                         this.scroller.style.top = y + 'px';
253                 }
254
255                 this.x = x;
256                 this.y = y;
257
258                 this._scrollbarPos('h');
259                 this._scrollbarPos('v');
260         },
261
262         _scrollbarPos: function (dir, hidden) {
263                 var that = this,
264                         pos = dir == 'h' ? that.x : that.y,
265                         size;
266
267                 if (!that[dir + 'Scrollbar']) return;
268
269                 pos = that[dir + 'ScrollbarProp'] * pos;
270
271                 if (pos < 0) {
272                         if (!that.options.fixedScrollbar) {
273                                 size = that[dir + 'ScrollbarIndicatorSize'] + m.round(pos * 3);
274                                 if (size < 8) size = 8;
275                                 that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
276                         }
277                         pos = 0;
278                 } else if (pos > that[dir + 'ScrollbarMaxScroll']) {
279                         if (!that.options.fixedScrollbar) {
280                                 size = that[dir + 'ScrollbarIndicatorSize'] - m.round((pos - that[dir + 'ScrollbarMaxScroll']) * 3);
281                                 if (size < 8) size = 8;
282                                 that[dir + 'ScrollbarIndicator'].style[dir == 'h' ? 'width' : 'height'] = size + 'px';
283                                 pos = that[dir + 'ScrollbarMaxScroll'] + (that[dir + 'ScrollbarIndicatorSize'] - size);
284                         } else {
285                                 pos = that[dir + 'ScrollbarMaxScroll'];
286                         }
287                 }
288
289                 that[dir + 'ScrollbarWrapper'].style[vendor + 'TransitionDelay'] = '0';
290                 that[dir + 'ScrollbarWrapper'].style.opacity = hidden && that.options.hideScrollbar ? '0' : '1';
291                 that[dir + 'ScrollbarIndicator'].style[vendor + 'Transform'] = trnOpen + (dir == 'h' ? pos + 'px,0' : '0,' + pos + 'px') + trnClose;
292         },
293         
294         _start: function (e) {
295                 var that = this,
296                         point = hasTouch ? e.touches[0] : e,
297                         matrix, x, y,
298                         c1, c2;
299
300                 if (!that.enabled) return;
301
302                 if (that.options.onBeforeScrollStart) that.options.onBeforeScrollStart.call(that, e);
303
304                 if (that.options.useTransition || that.options.zoom) that._transitionTime(0);
305
306                 that.moved = false;
307                 that.animating = false;
308                 that.zoomed = false;
309                 that.distX = 0;
310                 that.distY = 0;
311                 that.absDistX = 0;
312                 that.absDistY = 0;
313                 that.dirX = 0;
314                 that.dirY = 0;
315
316                 // Gesture start
317                 if (that.options.zoom && hasTouch && e.touches.length > 1) {
318                         c1 = m.abs(e.touches[0].pageX-e.touches[1].pageX);
319                         c2 = m.abs(e.touches[0].pageY-e.touches[1].pageY);
320                         that.touchesDistStart = m.sqrt(c1 * c1 + c2 * c2);
321
322                         that.originX = m.abs(e.touches[0].pageX + e.touches[1].pageX - that.wrapperOffsetLeft * 2) / 2 - that.x;
323                         that.originY = m.abs(e.touches[0].pageY + e.touches[1].pageY - that.wrapperOffsetTop * 2) / 2 - that.y;
324
325                         if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
326                 }
327
328                 if (that.options.momentum) {
329                         if (that.options.useTransform) {
330                                 // Very lame general purpose alternative to CSSMatrix
331                                 matrix = getComputedStyle(that.scroller, null)[vendor + 'Transform'].replace(/[^0-9-.,]/g, '').split(',');
332                                 x = matrix[4] * 1;
333                                 y = matrix[5] * 1;
334                         } else {
335                                 x = getComputedStyle(that.scroller, null).left.replace(/[^0-9-]/g, '') * 1;
336                                 y = getComputedStyle(that.scroller, null).top.replace(/[^0-9-]/g, '') * 1;
337                         }
338                         
339                         if (x != that.x || y != that.y) {
340                                 if (that.options.useTransition) that._unbind('webkitTransitionEnd');
341                                 else cancelFrame(that.aniTime);
342                                 that.steps = [];
343                                 that._pos(x, y);
344                         }
345                 }
346
347                 that.absStartX = that.x;        // Needed by snap threshold
348                 that.absStartY = that.y;
349
350                 that.startX = that.x;
351                 that.startY = that.y;
352                 that.pointX = point.pageX;
353                 that.pointY = point.pageY;
354
355                 that.startTime = e.timeStamp || (new Date()).getTime();
356
357                 if (that.options.onScrollStart) that.options.onScrollStart.call(that, e);
358
359                 that._bind(MOVE_EV);
360                 that._bind(END_EV);
361                 that._bind(CANCEL_EV);
362         },
363         
364         _move: function (e) {
365                 var that = this,
366                         point = hasTouch ? e.touches[0] : e,
367                         deltaX = point.pageX - that.pointX,
368                         deltaY = point.pageY - that.pointY,
369                         newX = that.x + deltaX,
370                         newY = that.y + deltaY,
371                         c1, c2, scale,
372                         timestamp = e.timeStamp || (new Date()).getTime();
373
374                 if (that.options.onBeforeScrollMove) that.options.onBeforeScrollMove.call(that, e);
375
376                 // Zoom
377                 if (that.options.zoom && hasTouch && e.touches.length > 1) {
378                         c1 = m.abs(e.touches[0].pageX - e.touches[1].pageX);
379                         c2 = m.abs(e.touches[0].pageY - e.touches[1].pageY);
380                         that.touchesDist = m.sqrt(c1*c1+c2*c2);
381
382                         that.zoomed = true;
383
384                         scale = 1 / that.touchesDistStart * that.touchesDist * this.scale;
385
386                         if (scale < that.options.zoomMin) scale = 0.5 * that.options.zoomMin * Math.pow(2.0, scale / that.options.zoomMin);
387                         else if (scale > that.options.zoomMax) scale = 2.0 * that.options.zoomMax * Math.pow(0.5, that.options.zoomMax / scale);
388
389                         that.lastScale = scale / this.scale;
390
391                         newX = this.originX - this.originX * that.lastScale + this.x,
392                         newY = this.originY - this.originY * that.lastScale + this.y;
393
394                         this.scroller.style[vendor + 'Transform'] = trnOpen + newX + 'px,' + newY + 'px' + trnClose + ' scale(' + scale + ')';
395
396                         if (that.options.onZoom) that.options.onZoom.call(that, e);
397                         return;
398                 }
399
400                 that.pointX = point.pageX;
401                 that.pointY = point.pageY;
402
403                 // Slow down if outside of the boundaries
404                 if (newX > 0 || newX < that.maxScrollX) {
405                         newX = that.options.bounce ? that.x + (deltaX / 2) : newX >= 0 || that.maxScrollX >= 0 ? 0 : that.maxScrollX;
406                 }
407                 if (newY > that.minScrollY || newY < that.maxScrollY) { 
408                         newY = that.options.bounce ? that.y + (deltaY / 2) : newY >= that.minScrollY || that.maxScrollY >= 0 ? that.minScrollY : that.maxScrollY;
409                 }
410
411                 if (that.absDistX < 6 && that.absDistY < 6) {
412                         that.distX += deltaX;
413                         that.distY += deltaY;
414                         that.absDistX = m.abs(that.distX);
415                         that.absDistY = m.abs(that.distY);
416
417                         return;
418                 }
419
420                 // Lock direction
421                 if (that.options.lockDirection) {
422                         if (that.absDistX > that.absDistY + 5) {
423                                 newY = that.y;
424                                 deltaY = 0;
425                         } else if (that.absDistY > that.absDistX + 5) {
426                                 newX = that.x;
427                                 deltaX = 0;
428                         }
429                 }
430
431                 that.moved = true;
432                 that._pos(newX, newY);
433                 that.dirX = deltaX > 0 ? -1 : deltaX < 0 ? 1 : 0;
434                 that.dirY = deltaY > 0 ? -1 : deltaY < 0 ? 1 : 0;
435
436                 if (timestamp - that.startTime > 300) {
437                         that.startTime = timestamp;
438                         that.startX = that.x;
439                         that.startY = that.y;
440                 }
441                 
442                 if (that.options.onScrollMove) that.options.onScrollMove.call(that, e);
443         },
444         
445         _end: function (e) {
446                 if (hasTouch && e.touches.length != 0) return;
447
448                 var that = this,
449                         point = hasTouch ? e.changedTouches[0] : e,
450                         target, ev,
451                         momentumX = { dist:0, time:0 },
452                         momentumY = { dist:0, time:0 },
453                         duration = (e.timeStamp || (new Date()).getTime()) - that.startTime,
454                         newPosX = that.x,
455                         newPosY = that.y,
456                         distX, distY,
457                         newDuration,
458                         snap,
459                         scale;
460
461                 that._unbind(MOVE_EV);
462                 that._unbind(END_EV);
463                 that._unbind(CANCEL_EV);
464
465                 if (that.options.onBeforeScrollEnd) that.options.onBeforeScrollEnd.call(that, e);
466
467                 if (that.zoomed) {
468                         scale = that.scale * that.lastScale;
469                         scale = Math.max(that.options.zoomMin, scale);
470                         scale = Math.min(that.options.zoomMax, scale);
471                         that.lastScale = scale / that.scale;
472                         that.scale = scale;
473
474                         that.x = that.originX - that.originX * that.lastScale + that.x;
475                         that.y = that.originY - that.originY * that.lastScale + that.y;
476                         
477                         that.scroller.style[vendor + 'TransitionDuration'] = '200ms';
478                         that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose + ' scale(' + that.scale + ')';
479                         
480                         that.zoomed = false;
481                         that.refresh();
482
483                         if (that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
484                         return;
485                 }
486
487                 if (!that.moved) {
488                         if (hasTouch) {
489                                 if (that.doubleTapTimer && that.options.zoom) {
490                                         // Double tapped
491                                         clearTimeout(that.doubleTapTimer);
492                                         that.doubleTapTimer = null;
493                                         if (that.options.onZoomStart) that.options.onZoomStart.call(that, e);
494                                         that.zoom(that.pointX, that.pointY, that.scale == 1 ? that.options.doubleTapZoom : 1);
495                                         if (that.options.onZoomEnd) {
496                                                 setTimeout(function() {
497                                                         that.options.onZoomEnd.call(that, e);
498                                                 }, 200); // 200 is default zoom duration
499                                         }
500                                 } else {
501                                         that.doubleTapTimer = setTimeout(function () {
502                                                 that.doubleTapTimer = null;
503
504                                                 // Find the last touched element
505                                                 target = point.target;
506                                                 while (target.nodeType != 1) target = target.parentNode;
507
508                                                 if (target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA') {
509                                                         ev = document.createEvent('MouseEvents');
510                                                         ev.initMouseEvent('click', true, true, e.view, 1,
511                                                                 point.screenX, point.screenY, point.clientX, point.clientY,
512                                                                 e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
513                                                                 0, null);
514                                                         ev._fake = true;
515                                                         target.dispatchEvent(ev);
516                                                 }
517                                         }, that.options.zoom ? 250 : 0);
518                                 }
519                         }
520
521                         that._resetPos(200);
522
523                         if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
524                         return;
525                 }
526
527                 if (duration < 300 && that.options.momentum) {
528                         momentumX = newPosX ? that._momentum(newPosX - that.startX, duration, -that.x, that.scrollerW - that.wrapperW + that.x, that.options.bounce ? that.wrapperW : 0) : momentumX;
529                         momentumY = newPosY ? that._momentum(newPosY - that.startY, duration, -that.y, (that.maxScrollY < 0 ? that.scrollerH - that.wrapperH + that.y - that.minScrollY : 0), that.options.bounce ? that.wrapperH : 0) : momentumY;
530
531                         newPosX = that.x + momentumX.dist;
532                         newPosY = that.y + momentumY.dist;
533
534                         if ((that.x > 0 && newPosX > 0) || (that.x < that.maxScrollX && newPosX < that.maxScrollX)) momentumX = { dist:0, time:0 };
535                         if ((that.y > that.minScrollY && newPosY > that.minScrollY) || (that.y < that.maxScrollY && newPosY < that.maxScrollY)) momentumY = { dist:0, time:0 };
536                 }
537
538                 if (momentumX.dist || momentumY.dist) {
539                         newDuration = m.max(m.max(momentumX.time, momentumY.time), 10);
540
541                         // Do we need to snap?
542                         if (that.options.snap) {
543                                 distX = newPosX - that.absStartX;
544                                 distY = newPosY - that.absStartY;
545                                 if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) { that.scrollTo(that.absStartX, that.absStartY, 200); }
546                                 else {
547                                         snap = that._snap(newPosX, newPosY);
548                                         newPosX = snap.x;
549                                         newPosY = snap.y;
550                                         newDuration = m.max(snap.time, newDuration);
551                                 }
552                         }
553
554                         that.scrollTo(m.round(newPosX), m.round(newPosY), newDuration);
555
556                         if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
557                         return;
558                 }
559
560                 // Do we need to snap?
561                 if (that.options.snap) {
562                         distX = newPosX - that.absStartX;
563                         distY = newPosY - that.absStartY;
564                         if (m.abs(distX) < that.options.snapThreshold && m.abs(distY) < that.options.snapThreshold) that.scrollTo(that.absStartX, that.absStartY, 200);
565                         else {
566                                 snap = that._snap(that.x, that.y);
567                                 if (snap.x != that.x || snap.y != that.y) that.scrollTo(snap.x, snap.y, snap.time);
568                         }
569
570                         if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
571                         return;
572                 }
573
574                 that._resetPos(200);
575                 if (that.options.onTouchEnd) that.options.onTouchEnd.call(that, e);
576         },
577         
578         _resetPos: function (time) {
579                 var that = this,
580                         resetX = that.x >= 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x,
581                         resetY = that.y >= that.minScrollY || that.maxScrollY > 0 ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
582
583                 if (resetX == that.x && resetY == that.y) {
584                         if (that.moved) {
585                                 that.moved = false;
586                                 if (that.options.onScrollEnd) that.options.onScrollEnd.call(that);              // Execute custom code on scroll end
587                         }
588
589                         if (that.hScrollbar && that.options.hideScrollbar) {
590                                 if (vendor == 'webkit') that.hScrollbarWrapper.style[vendor + 'TransitionDelay'] = '300ms';
591                                 that.hScrollbarWrapper.style.opacity = '0';
592                         }
593                         if (that.vScrollbar && that.options.hideScrollbar) {
594                                 if (vendor == 'webkit') that.vScrollbarWrapper.style[vendor + 'TransitionDelay'] = '300ms';
595                                 that.vScrollbarWrapper.style.opacity = '0';
596                         }
597
598                         return;
599                 }
600
601                 that.scrollTo(resetX, resetY, time || 0);
602         },
603
604         _wheel: function (e) {
605                 var that = this,
606                         wheelDeltaX, wheelDeltaY,
607                         deltaX, deltaY,
608                         deltaScale;
609
610                 if ('wheelDeltaX' in e) {
611                         wheelDeltaX = e.wheelDeltaX / 12;
612                         wheelDeltaY = e.wheelDeltaY / 12;
613                 } else if ('detail' in e) {
614                         wheelDeltaX = wheelDeltaY = -e.detail * 3;
615                 } else {
616                         wheelDeltaX = wheelDeltaY = -e.wheelDelta;
617                 }
618                 
619                 if (that.options.wheelAction == 'zoom') {
620                         deltaScale = that.scale * Math.pow(2, 1/3 * (wheelDeltaY ? wheelDeltaY / Math.abs(wheelDeltaY) : 0));
621                         if (deltaScale < that.options.zoomMin) deltaScale = that.options.zoomMin;
622                         if (deltaScale > that.options.zoomMax) deltaScale = that.options.zoomMax;
623                         
624                         if (deltaScale != that.scale) {
625                                 if (!that.wheelZoomCount && that.options.onZoomStart) that.options.onZoomStart.call(that, e);
626                                 that.wheelZoomCount++;
627                                 
628                                 that.zoom(e.pageX, e.pageY, deltaScale, 400);
629                                 
630                                 setTimeout(function() {
631                                         that.wheelZoomCount--;
632                                         if (!that.wheelZoomCount && that.options.onZoomEnd) that.options.onZoomEnd.call(that, e);
633                                 }, 400);
634                         }
635                         
636                         return;
637                 }
638                 
639                 deltaX = that.x + wheelDeltaX;
640                 deltaY = that.y + wheelDeltaY;
641
642                 if (deltaX > 0) deltaX = 0;
643                 else if (deltaX < that.maxScrollX) deltaX = that.maxScrollX;
644
645                 if (deltaY > that.minScrollY) deltaY = that.minScrollY;
646                 else if (deltaY < that.maxScrollY) deltaY = that.maxScrollY;
647
648                 that.scrollTo(deltaX, deltaY, 0);
649         },
650         
651         _mouseout: function (e) {
652                 var t = e.relatedTarget;
653
654                 if (!t) {
655                         this._end(e);
656                         return;
657                 }
658
659                 while (t = t.parentNode) if (t == this.wrapper) return;
660                 
661                 this._end(e);
662         },
663
664         _transitionEnd: function (e) {
665                 var that = this;
666
667                 if (e.target != that.scroller) return;
668
669                 that._unbind('webkitTransitionEnd');
670                 
671                 that._startAni();
672         },
673
674
675         /**
676          *
677          * Utilities
678          *
679          */
680         _startAni: function () {
681                 var that = this,
682                         startX = that.x, startY = that.y,
683                         startTime = (new Date).getTime(),
684                         step, easeOut;
685
686                 if (that.animating) return;
687                 
688                 if (!that.steps.length) {
689                         that._resetPos(400);
690                         return;
691                 }
692                 
693                 step = that.steps.shift();
694                 
695                 if (step.x == startX && step.y == startY) step.time = 0;
696
697                 that.animating = true;
698                 that.moved = true;
699                 
700                 if (that.options.useTransition) {
701                         that._transitionTime(step.time);
702                         that._pos(step.x, step.y);
703                         that.animating = false;
704                         if (step.time) that._bind('webkitTransitionEnd');
705                         else that._resetPos(0);
706                         return;
707                 }
708
709                 (function animate () {
710                         var now = (new Date).getTime(),
711                                 newX, newY;
712
713                         if (now >= startTime + step.time) {
714                                 that._pos(step.x, step.y);
715                                 that.animating = false;
716                                 if (that.options.onAnimationEnd) that.options.onAnimationEnd.call(that);                        // Execute custom code on animation end
717                                 that._startAni();
718                                 return;
719                         }
720
721                         now = (now - startTime) / step.time - 1;
722                         easeOut = m.sqrt(1 - now * now);
723                         newX = (step.x - startX) * easeOut + startX;
724                         newY = (step.y - startY) * easeOut + startY;
725                         that._pos(newX, newY);
726                         if (that.animating) that.aniTime = nextFrame(animate);
727                 })();
728         },
729
730         _transitionTime: function (time) {
731                 time += 'ms';
732                 this.scroller.style[vendor + 'TransitionDuration'] = time;
733                 if (this.hScrollbar) this.hScrollbarIndicator.style[vendor + 'TransitionDuration'] = time;
734                 if (this.vScrollbar) this.vScrollbarIndicator.style[vendor + 'TransitionDuration'] = time;
735         },
736
737         _momentum: function (dist, time, maxDistUpper, maxDistLower, size) {
738                 var deceleration = 0.0006,
739                         speed = m.abs(dist) / time,
740                         newDist = (speed * speed) / (2 * deceleration),
741                         newTime = 0, outsideDist = 0;
742
743                 // Proportinally reduce speed if we are outside of the boundaries 
744                 if (dist > 0 && newDist > maxDistUpper) {
745                         outsideDist = size / (6 / (newDist / speed * deceleration));
746                         maxDistUpper = maxDistUpper + outsideDist;
747                         speed = speed * maxDistUpper / newDist;
748                         newDist = maxDistUpper;
749                 } else if (dist < 0 && newDist > maxDistLower) {
750                         outsideDist = size / (6 / (newDist / speed * deceleration));
751                         maxDistLower = maxDistLower + outsideDist;
752                         speed = speed * maxDistLower / newDist;
753                         newDist = maxDistLower;
754                 }
755
756                 newDist = newDist * (dist < 0 ? -1 : 1);
757                 newTime = speed / deceleration;
758
759                 return { dist: newDist, time: m.round(newTime) };
760         },
761
762         _offset: function (el) {
763                 var left = -el.offsetLeft,
764                         top = -el.offsetTop;
765                         
766                 while (el = el.offsetParent) {
767                         left -= el.offsetLeft;
768                         top -= el.offsetTop;
769                 }
770                 
771                 if (el != this.wrapper) {
772                         left *= this.scale;
773                         top *= this.scale;
774                 }
775
776                 return { left: left, top: top };
777         },
778
779         _snap: function (x, y) {
780                 var that = this,
781                         i, l,
782                         page, time,
783                         sizeX, sizeY;
784
785                 // Check page X
786                 page = that.pagesX.length - 1;
787                 for (i=0, l=that.pagesX.length; i<l; i++) {
788                         if (x >= that.pagesX[i]) {
789                                 page = i;
790                                 break;
791                         }
792                 }
793                 if (page == that.currPageX && page > 0 && that.dirX < 0) page--;
794                 x = that.pagesX[page];
795                 sizeX = m.abs(x - that.pagesX[that.currPageX]);
796                 sizeX = sizeX ? m.abs(that.x - x) / sizeX * 500 : 0;
797                 that.currPageX = page;
798
799                 // Check page Y
800                 page = that.pagesY.length-1;
801                 for (i=0; i<page; i++) {
802                         if (y >= that.pagesY[i]) {
803                                 page = i;
804                                 break;
805                         }
806                 }
807                 if (page == that.currPageY && page > 0 && that.dirY < 0) page--;
808                 y = that.pagesY[page];
809                 sizeY = m.abs(y - that.pagesY[that.currPageY]);
810                 sizeY = sizeY ? m.abs(that.y - y) / sizeY * 500 : 0;
811                 that.currPageY = page;
812
813                 // Snap with constant speed (proportional duration)
814                 time = m.round(m.max(sizeX, sizeY)) || 200;
815
816                 return { x: x, y: y, time: time };
817         },
818
819         _bind: function (type, el, bubble) {
820                 (el || this.scroller).addEventListener(type, this, !!bubble);
821         },
822
823         _unbind: function (type, el, bubble) {
824                 (el || this.scroller).removeEventListener(type, this, !!bubble);
825         },
826
827
828         /**
829          *
830          * Public methods
831          *
832          */
833         destroy: function () {
834                 var that = this;
835
836                 that.scroller.style[vendor + 'Transform'] = '';
837
838                 // Remove the scrollbars
839                 that.hScrollbar = false;
840                 that.vScrollbar = false;
841                 that._scrollbar('h');
842                 that._scrollbar('v');
843
844                 // Remove the event listeners
845                 that._unbind(RESIZE_EV, window);
846                 that._unbind(START_EV);
847                 that._unbind(MOVE_EV);
848                 that._unbind(END_EV);
849                 that._unbind(CANCEL_EV);
850                 
851                 if (that.options.hasTouch) {
852                         that._unbind('mouseout', that.wrapper);
853                         that._unbind(WHEEL_EV);
854                 }
855                 
856                 if (that.options.useTransition) that._unbind('webkitTransitionEnd');
857                 
858                 if (that.options.checkDOMChanges) clearInterval(that.checkDOMTime);
859                 
860                 if (that.options.onDestroy) that.options.onDestroy.call(that);
861         },
862
863         refresh: function () {
864                 var that = this,
865                         offset,
866                         i, l,
867                         els,
868                         pos = 0,
869                         page = 0;
870
871                 if (that.scale < that.options.zoomMin) that.scale = that.options.zoomMin;
872                 that.wrapperW = that.wrapper.clientWidth || 1;
873                 that.wrapperH = that.wrapper.clientHeight || 1;
874
875                 that.minScrollY = -that.options.topOffset || 0;
876                 that.scrollerW = m.round(that.scroller.offsetWidth * that.scale);
877                 that.scrollerH = m.round((that.scroller.offsetHeight + that.minScrollY) * that.scale);
878                 that.maxScrollX = that.wrapperW - that.scrollerW;
879                 that.maxScrollY = that.wrapperH - that.scrollerH + that.minScrollY;
880                 that.dirX = 0;
881                 that.dirY = 0;
882
883                 if (that.options.onRefresh) that.options.onRefresh.call(that);
884
885                 that.hScroll = that.options.hScroll && that.maxScrollX < 0;
886                 that.vScroll = that.options.vScroll && (!that.options.bounceLock && !that.hScroll || that.scrollerH > that.wrapperH);
887
888                 that.hScrollbar = that.hScroll && that.options.hScrollbar;
889                 that.vScrollbar = that.vScroll && that.options.vScrollbar && that.scrollerH > that.wrapperH;
890
891                 offset = that._offset(that.wrapper);
892                 that.wrapperOffsetLeft = -offset.left;
893                 that.wrapperOffsetTop = -offset.top;
894
895                 // Prepare snap
896                 if (typeof that.options.snap == 'string') {
897                         that.pagesX = [];
898                         that.pagesY = [];
899                         els = that.scroller.querySelectorAll(that.options.snap);
900                         for (i=0, l=els.length; i<l; i++) {
901                                 pos = that._offset(els[i]);
902                                 pos.left += that.wrapperOffsetLeft;
903                                 pos.top += that.wrapperOffsetTop;
904                                 that.pagesX[i] = pos.left < that.maxScrollX ? that.maxScrollX : pos.left * that.scale;
905                                 that.pagesY[i] = pos.top < that.maxScrollY ? that.maxScrollY : pos.top * that.scale;
906                         }
907                 } else if (that.options.snap) {
908                         that.pagesX = [];
909                         while (pos >= that.maxScrollX) {
910                                 that.pagesX[page] = pos;
911                                 pos = pos - that.wrapperW;
912                                 page++;
913                         }
914                         if (that.maxScrollX%that.wrapperW) that.pagesX[that.pagesX.length] = that.maxScrollX - that.pagesX[that.pagesX.length-1] + that.pagesX[that.pagesX.length-1];
915
916                         pos = 0;
917                         page = 0;
918                         that.pagesY = [];
919                         while (pos >= that.maxScrollY) {
920                                 that.pagesY[page] = pos;
921                                 pos = pos - that.wrapperH;
922                                 page++;
923                         }
924                         if (that.maxScrollY%that.wrapperH) that.pagesY[that.pagesY.length] = that.maxScrollY - that.pagesY[that.pagesY.length-1] + that.pagesY[that.pagesY.length-1];
925                 }
926
927                 // Prepare the scrollbars
928                 that._scrollbar('h');
929                 that._scrollbar('v');
930
931                 if (!that.zoomed) {
932                         that.scroller.style[vendor + 'TransitionDuration'] = '0';
933                         that._resetPos(200);
934                 }
935         },
936
937         scrollTo: function (x, y, time, relative) {
938                 var that = this,
939                         step = x,
940                         i, l;
941
942                 that.stop();
943
944                 if (!step.length) step = [{ x: x, y: y, time: time, relative: relative }];
945                 
946                 for (i=0, l=step.length; i<l; i++) {
947                         if (step[i].relative) { step[i].x = that.x - step[i].x; step[i].y = that.y - step[i].y; }
948                         that.steps.push({ x: step[i].x, y: step[i].y, time: step[i].time || 0 });
949                 }
950
951                 that._startAni();
952         },
953
954         scrollToElement: function (el, time) {
955                 var that = this, pos;
956                 el = el.nodeType ? el : that.scroller.querySelector(el);
957                 if (!el) return;
958
959                 pos = that._offset(el);
960                 pos.left += that.wrapperOffsetLeft;
961                 pos.top += that.wrapperOffsetTop;
962
963                 pos.left = pos.left > 0 ? 0 : pos.left < that.maxScrollX ? that.maxScrollX : pos.left;
964                 pos.top = pos.top > that.minScrollY ? that.minScrollY : pos.top < that.maxScrollY ? that.maxScrollY : pos.top;
965                 time = time === undefined ? m.max(m.abs(pos.left)*2, m.abs(pos.top)*2) : time;
966
967                 that.scrollTo(pos.left, pos.top, time);
968         },
969
970         scrollToPage: function (pageX, pageY, time) {
971                 var that = this, x, y;
972                 
973                 if (that.options.snap) {
974                         pageX = pageX == 'next' ? that.currPageX+1 : pageX == 'prev' ? that.currPageX-1 : pageX;
975                         pageY = pageY == 'next' ? that.currPageY+1 : pageY == 'prev' ? that.currPageY-1 : pageY;
976
977                         pageX = pageX < 0 ? 0 : pageX > that.pagesX.length-1 ? that.pagesX.length-1 : pageX;
978                         pageY = pageY < 0 ? 0 : pageY > that.pagesY.length-1 ? that.pagesY.length-1 : pageY;
979
980                         that.currPageX = pageX;
981                         that.currPageY = pageY;
982                         x = that.pagesX[pageX];
983                         y = that.pagesY[pageY];
984                 } else {
985                         x = -that.wrapperW * pageX;
986                         y = -that.wrapperH * pageY;
987                         if (x < that.maxScrollX) x = that.maxScrollX;
988                         if (y < that.maxScrollY) y = that.maxScrollY;
989                 }
990
991                 that.scrollTo(x, y, time || 400);
992         },
993
994         disable: function () {
995                 this.stop();
996                 this._resetPos(0);
997                 this.enabled = false;
998
999                 // If disabled after touchstart we make sure that there are no left over events
1000                 this._unbind(MOVE_EV);
1001                 this._unbind(END_EV);
1002                 this._unbind(CANCEL_EV);
1003         },
1004         
1005         enable: function () {
1006                 this.enabled = true;
1007         },
1008         
1009         stop: function () {
1010                 if (this.options.useTransition) this._unbind('webkitTransitionEnd');
1011                 else cancelFrame(this.aniTime);
1012                 this.steps = [];
1013                 this.moved = false;
1014                 this.animating = false;
1015         },
1016         
1017         zoom: function (x, y, scale, time) {
1018                 var that = this,
1019                         relScale = scale / that.scale;
1020
1021                 if (!that.options.useTransform) return;
1022
1023                 that.zoomed = true;
1024                 time = time === undefined ? 200 : time;
1025                 x = x - that.wrapperOffsetLeft - that.x;
1026                 y = y - that.wrapperOffsetTop - that.y;
1027                 that.x = x - x * relScale + that.x;
1028                 that.y = y - y * relScale + that.y;
1029
1030                 that.scale = scale;
1031                 that.refresh();
1032
1033                 that.x = that.x > 0 ? 0 : that.x < that.maxScrollX ? that.maxScrollX : that.x;
1034                 that.y = that.y > that.minScrollY ? that.minScrollY : that.y < that.maxScrollY ? that.maxScrollY : that.y;
1035
1036                 that.scroller.style[vendor + 'TransitionDuration'] = time + 'ms';
1037                 that.scroller.style[vendor + 'Transform'] = trnOpen + that.x + 'px,' + that.y + 'px' + trnClose + ' scale(' + scale + ')';
1038                 that.zoomed = false;
1039         },
1040         
1041         isReady: function () {
1042                 return !this.moved && !this.zoomed && !this.animating;
1043         }
1044 };
1045
1046 if (typeof exports !== 'undefined') exports.iScroll = iScroll;
1047 else window.iScroll = iScroll;
1048
1049 })();