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