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