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