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