photoswipe-rails 4.0.8a

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,3698 @@
1
+ /*! PhotoSwipe - v4.0.8 - 2015-05-21
2
+ * http://photoswipe.com
3
+ * Copyright (c) 2015 Dmitry Semenov; */
4
+ (function (root, factory) {
5
+ if (typeof define === 'function' && define.amd) {
6
+ define(factory);
7
+ } else if (typeof exports === 'object') {
8
+ module.exports = factory();
9
+ } else {
10
+ root.PhotoSwipe = factory();
11
+ }
12
+ })(this, function () {
13
+
14
+ 'use strict';
15
+ var PhotoSwipe = function(template, UiClass, items, options){
16
+
17
+ /*>>framework-bridge*/
18
+ /**
19
+ *
20
+ * Set of generic functions used by gallery.
21
+ *
22
+ * You're free to modify anything here as long as functionality is kept.
23
+ *
24
+ */
25
+ var framework = {
26
+ features: null,
27
+ bind: function(target, type, listener, unbind) {
28
+ var methodName = (unbind ? 'remove' : 'add') + 'EventListener';
29
+ type = type.split(' ');
30
+ for(var i = 0; i < type.length; i++) {
31
+ if(type[i]) {
32
+ target[methodName]( type[i], listener, false);
33
+ }
34
+ }
35
+ },
36
+ isArray: function(obj) {
37
+ return (obj instanceof Array);
38
+ },
39
+ createEl: function(classes, tag) {
40
+ var el = document.createElement(tag || 'div');
41
+ if(classes) {
42
+ el.className = classes;
43
+ }
44
+ return el;
45
+ },
46
+ getScrollY: function() {
47
+ var yOffset = window.pageYOffset;
48
+ return yOffset !== undefined ? yOffset : document.documentElement.scrollTop;
49
+ },
50
+ unbind: function(target, type, listener) {
51
+ framework.bind(target,type,listener,true);
52
+ },
53
+ removeClass: function(el, className) {
54
+ var reg = new RegExp('(\\s|^)' + className + '(\\s|$)');
55
+ el.className = el.className.replace(reg, ' ').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
56
+ },
57
+ addClass: function(el, className) {
58
+ if( !framework.hasClass(el,className) ) {
59
+ el.className += (el.className ? ' ' : '') + className;
60
+ }
61
+ },
62
+ hasClass: function(el, className) {
63
+ return el.className && new RegExp('(^|\\s)' + className + '(\\s|$)').test(el.className);
64
+ },
65
+ getChildByClass: function(parentEl, childClassName) {
66
+ var node = parentEl.firstChild;
67
+ while(node) {
68
+ if( framework.hasClass(node, childClassName) ) {
69
+ return node;
70
+ }
71
+ node = node.nextSibling;
72
+ }
73
+ },
74
+ arraySearch: function(array, value, key) {
75
+ var i = array.length;
76
+ while(i--) {
77
+ if(array[i][key] === value) {
78
+ return i;
79
+ }
80
+ }
81
+ return -1;
82
+ },
83
+ extend: function(o1, o2, preventOverwrite) {
84
+ for (var prop in o2) {
85
+ if (o2.hasOwnProperty(prop)) {
86
+ if(preventOverwrite && o1.hasOwnProperty(prop)) {
87
+ continue;
88
+ }
89
+ o1[prop] = o2[prop];
90
+ }
91
+ }
92
+ },
93
+ easing: {
94
+ sine: {
95
+ out: function(k) {
96
+ return Math.sin(k * (Math.PI / 2));
97
+ },
98
+ inOut: function(k) {
99
+ return - (Math.cos(Math.PI * k) - 1) / 2;
100
+ }
101
+ },
102
+ cubic: {
103
+ out: function(k) {
104
+ return --k * k * k + 1;
105
+ }
106
+ }
107
+ /*
108
+ elastic: {
109
+ out: function ( k ) {
110
+
111
+ var s, a = 0.1, p = 0.4;
112
+ if ( k === 0 ) return 0;
113
+ if ( k === 1 ) return 1;
114
+ if ( !a || a < 1 ) { a = 1; s = p / 4; }
115
+ else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
116
+ return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
117
+
118
+ },
119
+ },
120
+ back: {
121
+ out: function ( k ) {
122
+ var s = 1.70158;
123
+ return --k * k * ( ( s + 1 ) * k + s ) + 1;
124
+ }
125
+ }
126
+ */
127
+ },
128
+
129
+ /**
130
+ *
131
+ * @return {object}
132
+ *
133
+ * {
134
+ * raf : request animation frame function
135
+ * caf : cancel animation frame function
136
+ * transfrom : transform property key (with vendor), or null if not supported
137
+ * oldIE : IE8 or below
138
+ * }
139
+ *
140
+ */
141
+ detectFeatures: function() {
142
+ if(framework.features) {
143
+ return framework.features;
144
+ }
145
+ var helperEl = framework.createEl(),
146
+ helperStyle = helperEl.style,
147
+ vendor = '',
148
+ features = {};
149
+
150
+ // IE8 and below
151
+ features.oldIE = document.all && !document.addEventListener;
152
+
153
+ features.touch = 'ontouchstart' in window;
154
+
155
+ if(window.requestAnimationFrame) {
156
+ features.raf = window.requestAnimationFrame;
157
+ features.caf = window.cancelAnimationFrame;
158
+ }
159
+
160
+ features.pointerEvent = navigator.pointerEnabled || navigator.msPointerEnabled;
161
+
162
+ // fix false-positive detection of old Android in new IE
163
+ // (IE11 ua string contains "Android 4.0")
164
+
165
+ if(!features.pointerEvent) {
166
+
167
+ var ua = navigator.userAgent;
168
+
169
+ // Detect if device is iPhone or iPod and if it's older than iOS 8
170
+ // http://stackoverflow.com/a/14223920
171
+ //
172
+ // This detection is made because of buggy top/bottom toolbars
173
+ // that don't trigger window.resize event.
174
+ // For more info refer to _isFixedPosition variable in core.js
175
+
176
+ if (/iP(hone|od)/.test(navigator.platform)) {
177
+ var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
178
+ if(v && v.length > 0) {
179
+ v = parseInt(v[1], 10);
180
+ if(v >= 1 && v < 8 ) {
181
+ features.isOldIOSPhone = true;
182
+ }
183
+ }
184
+ }
185
+
186
+ // Detect old Android (before KitKat)
187
+ // due to bugs related to position:fixed
188
+ // http://stackoverflow.com/questions/7184573/pick-up-the-android-version-in-the-browser-by-javascript
189
+
190
+ var match = ua.match(/Android\s([0-9\.]*)/);
191
+ var androidversion = match ? match[1] : 0;
192
+ androidversion = parseFloat(androidversion);
193
+ if(androidversion >= 1 ) {
194
+ if(androidversion < 4.4) {
195
+ features.isOldAndroid = true; // for fixed position bug & performance
196
+ }
197
+ features.androidVersion = androidversion; // for touchend bug
198
+ }
199
+ features.isMobileOpera = /opera mini|opera mobi/i.test(ua);
200
+
201
+ // p.s. yes, yes, UA sniffing is bad, propose your solution for above bugs.
202
+ }
203
+
204
+ var styleChecks = ['transform', 'perspective', 'animationName'],
205
+ vendors = ['', 'webkit','Moz','ms','O'],
206
+ styleCheckItem,
207
+ styleName;
208
+
209
+ for(var i = 0; i < 4; i++) {
210
+ vendor = vendors[i];
211
+
212
+ for(var a = 0; a < 3; a++) {
213
+ styleCheckItem = styleChecks[a];
214
+
215
+ // uppercase first letter of property name, if vendor is present
216
+ styleName = vendor + (vendor ?
217
+ styleCheckItem.charAt(0).toUpperCase() + styleCheckItem.slice(1) :
218
+ styleCheckItem);
219
+
220
+ if(!features[styleCheckItem] && styleName in helperStyle ) {
221
+ features[styleCheckItem] = styleName;
222
+ }
223
+ }
224
+
225
+ if(vendor && !features.raf) {
226
+ vendor = vendor.toLowerCase();
227
+ features.raf = window[vendor+'RequestAnimationFrame'];
228
+ if(features.raf) {
229
+ features.caf = window[vendor+'CancelAnimationFrame'] ||
230
+ window[vendor+'CancelRequestAnimationFrame'];
231
+ }
232
+ }
233
+ }
234
+
235
+ if(!features.raf) {
236
+ var lastTime = 0;
237
+ features.raf = function(fn) {
238
+ var currTime = new Date().getTime();
239
+ var timeToCall = Math.max(0, 16 - (currTime - lastTime));
240
+ var id = window.setTimeout(function() { fn(currTime + timeToCall); }, timeToCall);
241
+ lastTime = currTime + timeToCall;
242
+ return id;
243
+ };
244
+ features.caf = function(id) { clearTimeout(id); };
245
+ }
246
+
247
+ // Detect SVG support
248
+ features.svg = !!document.createElementNS &&
249
+ !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;
250
+
251
+ framework.features = features;
252
+
253
+ return features;
254
+ }
255
+ };
256
+
257
+ framework.detectFeatures();
258
+
259
+ // Override addEventListener for old versions of IE
260
+ if(framework.features.oldIE) {
261
+
262
+ framework.bind = function(target, type, listener, unbind) {
263
+
264
+ type = type.split(' ');
265
+
266
+ var methodName = (unbind ? 'detach' : 'attach') + 'Event',
267
+ evName,
268
+ _handleEv = function() {
269
+ listener.handleEvent.call(listener);
270
+ };
271
+
272
+ for(var i = 0; i < type.length; i++) {
273
+ evName = type[i];
274
+ if(evName) {
275
+
276
+ if(typeof listener === 'object' && listener.handleEvent) {
277
+ if(!unbind) {
278
+ listener['oldIE' + evName] = _handleEv;
279
+ } else {
280
+ if(!listener['oldIE' + evName]) {
281
+ return false;
282
+ }
283
+ }
284
+
285
+ target[methodName]( 'on' + evName, listener['oldIE' + evName]);
286
+ } else {
287
+ target[methodName]( 'on' + evName, listener);
288
+ }
289
+
290
+ }
291
+ }
292
+ };
293
+
294
+ }
295
+
296
+ /*>>framework-bridge*/
297
+
298
+ /*>>core*/
299
+ //function(template, UiClass, items, options)
300
+
301
+ var self = this;
302
+
303
+ /**
304
+ * Static vars, don't change unless you know what you're doing.
305
+ */
306
+ var DOUBLE_TAP_RADIUS = 25,
307
+ NUM_HOLDERS = 3;
308
+
309
+ /**
310
+ * Options
311
+ */
312
+ var _options = {
313
+ allowPanToNext:true,
314
+ spacing: 0.12,
315
+ bgOpacity: 1,
316
+ mouseUsed: false,
317
+ loop: true,
318
+ pinchToClose: true,
319
+ closeOnScroll: true,
320
+ closeOnVerticalDrag: true,
321
+ verticalDragRange: 0.6,
322
+ hideAnimationDuration: 333,
323
+ showAnimationDuration: 333,
324
+ showHideOpacity: false,
325
+ focus: true,
326
+ escKey: true,
327
+ arrowKeys: true,
328
+ mainScrollEndFriction: 0.35,
329
+ panEndFriction: 0.35,
330
+ isClickableElement: function(el) {
331
+ return el.tagName === 'A';
332
+ },
333
+ getDoubleTapZoom: function(isMouseClick, item) {
334
+ if(isMouseClick) {
335
+ return 1;
336
+ } else {
337
+ return item.initialZoomLevel < 0.7 ? 1 : 1.5;
338
+ }
339
+ },
340
+ maxSpreadZoom: 2,
341
+ modal: true,
342
+
343
+ // not fully implemented yet
344
+ scaleMode: 'fit', // TODO
345
+ alwaysFadeIn: false // TODO
346
+ };
347
+ framework.extend(_options, options);
348
+
349
+
350
+ /**
351
+ * Private helper variables & functions
352
+ */
353
+
354
+ var _getEmptyPoint = function() {
355
+ return {x:0,y:0};
356
+ };
357
+
358
+ var _isOpen,
359
+ _isDestroying,
360
+ _closedByScroll,
361
+ _currentItemIndex,
362
+ _containerStyle,
363
+ _containerShiftIndex,
364
+ _currPanDist = _getEmptyPoint(),
365
+ _startPanOffset = _getEmptyPoint(),
366
+ _panOffset = _getEmptyPoint(),
367
+ _upMoveEvents, // drag move, drag end & drag cancel events array
368
+ _downEvents, // drag start events array
369
+ _globalEventHandlers,
370
+ _viewportSize = {},
371
+ _currZoomLevel,
372
+ _startZoomLevel,
373
+ _translatePrefix,
374
+ _translateSufix,
375
+ _updateSizeInterval,
376
+ _itemsNeedUpdate,
377
+ _currPositionIndex = 0,
378
+ _offset = {},
379
+ _slideSize = _getEmptyPoint(), // size of slide area, including spacing
380
+ _itemHolders,
381
+ _prevItemIndex,
382
+ _indexDiff = 0, // difference of indexes since last content update
383
+ _dragStartEvent,
384
+ _dragMoveEvent,
385
+ _dragEndEvent,
386
+ _dragCancelEvent,
387
+ _transformKey,
388
+ _pointerEventEnabled,
389
+ _isFixedPosition = true,
390
+ _likelyTouchDevice,
391
+ _modules = [],
392
+ _requestAF,
393
+ _cancelAF,
394
+ _initalClassName,
395
+ _initalWindowScrollY,
396
+ _oldIE,
397
+ _currentWindowScrollY,
398
+ _features,
399
+ _windowVisibleSize = {},
400
+
401
+ // Registers PhotoSWipe module (History, Controller ...)
402
+ _registerModule = function(name, module) {
403
+ framework.extend(self, module.publicMethods);
404
+ _modules.push(name);
405
+ },
406
+
407
+ _getLoopedId = function(index) {
408
+ var numSlides = _getNumItems();
409
+ if(index > numSlides - 1) {
410
+ return index - numSlides;
411
+ } else if(index < 0) {
412
+ return numSlides + index;
413
+ }
414
+ return index;
415
+ },
416
+
417
+ // Micro bind/trigger
418
+ _listeners = {},
419
+ _listen = function(name, fn) {
420
+ if(!_listeners[name]) {
421
+ _listeners[name] = [];
422
+ }
423
+ return _listeners[name].push(fn);
424
+ },
425
+ _shout = function(name) {
426
+ var listeners = _listeners[name];
427
+
428
+ if(listeners) {
429
+ var args = Array.prototype.slice.call(arguments);
430
+ args.shift();
431
+
432
+ for(var i = 0; i < listeners.length; i++) {
433
+ listeners[i].apply(self, args);
434
+ }
435
+ }
436
+ },
437
+
438
+ _getCurrentTime = function() {
439
+ return new Date().getTime();
440
+ },
441
+ _applyBgOpacity = function(opacity) {
442
+ _bgOpacity = opacity;
443
+ self.bg.style.opacity = opacity * _options.bgOpacity;
444
+ },
445
+
446
+ _applyZoomTransform = function(styleObj,x,y,zoom) {
447
+ styleObj[_transformKey] = _translatePrefix + x + 'px, ' + y + 'px' + _translateSufix + ' scale(' + zoom + ')';
448
+ },
449
+ _applyCurrentZoomPan = function() {
450
+ if(_currZoomElementStyle) {
451
+ _applyZoomTransform(_currZoomElementStyle, _panOffset.x, _panOffset.y, _currZoomLevel);
452
+ }
453
+ },
454
+ _applyZoomPanToItem = function(item) {
455
+ if(item.container) {
456
+ _applyZoomTransform(item.container.style,
457
+ item.initialPosition.x,
458
+ item.initialPosition.y,
459
+ item.initialZoomLevel);
460
+ }
461
+ },
462
+ _setTranslateX = function(x, elStyle) {
463
+ elStyle[_transformKey] = _translatePrefix + x + 'px, 0px' + _translateSufix;
464
+ },
465
+ _moveMainScroll = function(x, dragging) {
466
+
467
+ if(!_options.loop && dragging) {
468
+ // if of current item during scroll (float)
469
+ var newSlideIndexOffset = _currentItemIndex + (_slideSize.x * _currPositionIndex - x)/_slideSize.x;
470
+ var delta = Math.round(x - _mainScrollPos.x);
471
+
472
+ if( (newSlideIndexOffset < 0 && delta > 0) ||
473
+ (newSlideIndexOffset >= _getNumItems()-1 && delta < 0) ) {
474
+ x = _mainScrollPos.x + delta * _options.mainScrollEndFriction;
475
+ }
476
+ }
477
+
478
+ _mainScrollPos.x = x;
479
+ _setTranslateX(x, _containerStyle);
480
+ },
481
+ _calculatePanOffset = function(axis, zoomLevel) {
482
+ var m = _midZoomPoint[axis] - _offset[axis];
483
+ return _startPanOffset[axis] + _currPanDist[axis] + m - m * ( zoomLevel / _startZoomLevel );
484
+ },
485
+
486
+ _equalizePoints = function(p1, p2) {
487
+ p1.x = p2.x;
488
+ p1.y = p2.y;
489
+ if(p2.id) {
490
+ p1.id = p2.id;
491
+ }
492
+ },
493
+ _roundPoint = function(p) {
494
+ p.x = Math.round(p.x);
495
+ p.y = Math.round(p.y);
496
+ },
497
+
498
+ _mouseMoveTimeout = null,
499
+ _onFirstMouseMove = function() {
500
+ // Wait until mouse move event is fired at least twice during 100ms
501
+ // We do this, because some mobile browsers trigger it on touchstart
502
+ if(_mouseMoveTimeout ) {
503
+ framework.unbind(document, 'mousemove', _onFirstMouseMove);
504
+ framework.addClass(template, 'pswp--has_mouse');
505
+ _options.mouseUsed = true;
506
+ _shout('mouseUsed');
507
+ }
508
+ _mouseMoveTimeout = setTimeout(function() {
509
+ _mouseMoveTimeout = null;
510
+ }, 100);
511
+ },
512
+
513
+ _bindEvents = function() {
514
+ framework.bind(document, 'keydown', self);
515
+
516
+ if(_features.transform) {
517
+ // don't bind click event in browsers that don't support transform (mostly IE8)
518
+ framework.bind(self.scrollWrap, 'click', self);
519
+ }
520
+
521
+
522
+ if(!_options.mouseUsed) {
523
+ framework.bind(document, 'mousemove', _onFirstMouseMove);
524
+ }
525
+
526
+ framework.bind(window, 'resize scroll', self);
527
+
528
+ _shout('bindEvents');
529
+ },
530
+
531
+ _unbindEvents = function() {
532
+ framework.unbind(window, 'resize', self);
533
+ framework.unbind(window, 'scroll', _globalEventHandlers.scroll);
534
+ framework.unbind(document, 'keydown', self);
535
+ framework.unbind(document, 'mousemove', _onFirstMouseMove);
536
+
537
+ if(_features.transform) {
538
+ framework.unbind(self.scrollWrap, 'click', self);
539
+ }
540
+
541
+ if(_isDragging) {
542
+ framework.unbind(window, _upMoveEvents, self);
543
+ }
544
+
545
+ _shout('unbindEvents');
546
+ },
547
+
548
+ _calculatePanBounds = function(zoomLevel, update) {
549
+ var bounds = _calculateItemSize( self.currItem, _viewportSize, zoomLevel );
550
+ if(update) {
551
+ _currPanBounds = bounds;
552
+ }
553
+ return bounds;
554
+ },
555
+
556
+ _getMinZoomLevel = function(item) {
557
+ if(!item) {
558
+ item = self.currItem;
559
+ }
560
+ return item.initialZoomLevel;
561
+ },
562
+ _getMaxZoomLevel = function(item) {
563
+ if(!item) {
564
+ item = self.currItem;
565
+ }
566
+ return item.w > 0 ? _options.maxSpreadZoom : 1;
567
+ },
568
+
569
+ // Return true if offset is out of the bounds
570
+ _modifyDestPanOffset = function(axis, destPanBounds, destPanOffset, destZoomLevel) {
571
+ if(destZoomLevel === self.currItem.initialZoomLevel) {
572
+ destPanOffset[axis] = self.currItem.initialPosition[axis];
573
+ return true;
574
+ } else {
575
+ destPanOffset[axis] = _calculatePanOffset(axis, destZoomLevel);
576
+
577
+ if(destPanOffset[axis] > destPanBounds.min[axis]) {
578
+ destPanOffset[axis] = destPanBounds.min[axis];
579
+ return true;
580
+ } else if(destPanOffset[axis] < destPanBounds.max[axis] ) {
581
+ destPanOffset[axis] = destPanBounds.max[axis];
582
+ return true;
583
+ }
584
+ }
585
+ return false;
586
+ },
587
+
588
+ _setupTransforms = function() {
589
+
590
+ if(_transformKey) {
591
+ // setup 3d transforms
592
+ var allow3dTransform = _features.perspective && !_likelyTouchDevice;
593
+ _translatePrefix = 'translate' + (allow3dTransform ? '3d(' : '(');
594
+ _translateSufix = _features.perspective ? ', 0px)' : ')';
595
+ return;
596
+ }
597
+
598
+ // Override zoom/pan/move functions in case old browser is used (most likely IE)
599
+ // (so they use left/top/width/height, instead of CSS transform)
600
+
601
+ _transformKey = 'left';
602
+ framework.addClass(template, 'pswp--ie');
603
+
604
+ _setTranslateX = function(x, elStyle) {
605
+ elStyle.left = x + 'px';
606
+ };
607
+ _applyZoomPanToItem = function(item) {
608
+
609
+ var zoomRatio = item.fitRatio > 1 ? 1 : item.fitRatio,
610
+ s = item.container.style,
611
+ w = zoomRatio * item.w,
612
+ h = zoomRatio * item.h;
613
+
614
+ s.width = w + 'px';
615
+ s.height = h + 'px';
616
+ s.left = item.initialPosition.x + 'px';
617
+ s.top = item.initialPosition.y + 'px';
618
+
619
+ };
620
+ _applyCurrentZoomPan = function() {
621
+ if(_currZoomElementStyle) {
622
+
623
+ var s = _currZoomElementStyle,
624
+ item = self.currItem,
625
+ zoomRatio = item.fitRatio > 1 ? 1 : item.fitRatio,
626
+ w = zoomRatio * item.w,
627
+ h = zoomRatio * item.h;
628
+
629
+ s.width = w + 'px';
630
+ s.height = h + 'px';
631
+
632
+
633
+ s.left = _panOffset.x + 'px';
634
+ s.top = _panOffset.y + 'px';
635
+ }
636
+
637
+ };
638
+ },
639
+
640
+ _onKeyDown = function(e) {
641
+ var keydownAction = '';
642
+ if(_options.escKey && e.keyCode === 27) {
643
+ keydownAction = 'close';
644
+ } else if(_options.arrowKeys) {
645
+ if(e.keyCode === 37) {
646
+ keydownAction = 'prev';
647
+ } else if(e.keyCode === 39) {
648
+ keydownAction = 'next';
649
+ }
650
+ }
651
+
652
+ if(keydownAction) {
653
+ // don't do anything if special key pressed to prevent from overriding default browser actions
654
+ // e.g. in Chrome on Mac cmd+arrow-left returns to previous page
655
+ if( !e.ctrlKey && !e.altKey && !e.shiftKey && !e.metaKey ) {
656
+ if(e.preventDefault) {
657
+ e.preventDefault();
658
+ } else {
659
+ e.returnValue = false;
660
+ }
661
+ self[keydownAction]();
662
+ }
663
+ }
664
+ },
665
+
666
+ _onGlobalClick = function(e) {
667
+ if(!e) {
668
+ return;
669
+ }
670
+
671
+ // don't allow click event to pass through when triggering after drag or some other gesture
672
+ if(_moved || _zoomStarted || _mainScrollAnimating || _verticalDragInitiated) {
673
+ e.preventDefault();
674
+ e.stopPropagation();
675
+ }
676
+ },
677
+
678
+ _updatePageScrollOffset = function() {
679
+ self.setScrollOffset(0, framework.getScrollY());
680
+ };
681
+
682
+
683
+
684
+
685
+
686
+
687
+
688
+ // Micro animation engine
689
+ var _animations = {},
690
+ _numAnimations = 0,
691
+ _stopAnimation = function(name) {
692
+ if(_animations[name]) {
693
+ if(_animations[name].raf) {
694
+ _cancelAF( _animations[name].raf );
695
+ }
696
+ _numAnimations--;
697
+ delete _animations[name];
698
+ }
699
+ },
700
+ _registerStartAnimation = function(name) {
701
+ if(_animations[name]) {
702
+ _stopAnimation(name);
703
+ }
704
+ if(!_animations[name]) {
705
+ _numAnimations++;
706
+ _animations[name] = {};
707
+ }
708
+ },
709
+ _stopAllAnimations = function() {
710
+ for (var prop in _animations) {
711
+
712
+ if( _animations.hasOwnProperty( prop ) ) {
713
+ _stopAnimation(prop);
714
+ }
715
+
716
+ }
717
+ },
718
+ _animateProp = function(name, b, endProp, d, easingFn, onUpdate, onComplete) {
719
+ var startAnimTime = _getCurrentTime(), t;
720
+ _registerStartAnimation(name);
721
+
722
+ var animloop = function(){
723
+ if ( _animations[name] ) {
724
+
725
+ t = _getCurrentTime() - startAnimTime; // time diff
726
+ //b - beginning (start prop)
727
+ //d - anim duration
728
+
729
+ if ( t >= d ) {
730
+ _stopAnimation(name);
731
+ onUpdate(endProp);
732
+ if(onComplete) {
733
+ onComplete();
734
+ }
735
+ return;
736
+ }
737
+ onUpdate( (endProp - b) * easingFn(t/d) + b );
738
+
739
+ _animations[name].raf = _requestAF(animloop);
740
+ }
741
+ };
742
+ animloop();
743
+ };
744
+
745
+
746
+
747
+ var publicMethods = {
748
+
749
+ // make a few local variables and functions public
750
+ shout: _shout,
751
+ listen: _listen,
752
+ viewportSize: _viewportSize,
753
+ options: _options,
754
+
755
+ isMainScrollAnimating: function() {
756
+ return _mainScrollAnimating;
757
+ },
758
+ getZoomLevel: function() {
759
+ return _currZoomLevel;
760
+ },
761
+ getCurrentIndex: function() {
762
+ return _currentItemIndex;
763
+ },
764
+ isDragging: function() {
765
+ return _isDragging;
766
+ },
767
+ isZooming: function() {
768
+ return _isZooming;
769
+ },
770
+ setScrollOffset: function(x,y) {
771
+ _offset.x = x;
772
+ _currentWindowScrollY = _offset.y = y;
773
+ _shout('updateScrollOffset', _offset);
774
+ },
775
+ applyZoomPan: function(zoomLevel,panX,panY) {
776
+ _panOffset.x = panX;
777
+ _panOffset.y = panY;
778
+ _currZoomLevel = zoomLevel;
779
+ _applyCurrentZoomPan();
780
+ },
781
+
782
+ init: function() {
783
+
784
+ if(_isOpen || _isDestroying) {
785
+ return;
786
+ }
787
+
788
+ var i;
789
+
790
+ self.framework = framework; // basic function
791
+ self.template = template; // root DOM element of PhotoSwipe
792
+ self.bg = framework.getChildByClass(template, 'pswp__bg');
793
+
794
+ _initalClassName = template.className;
795
+ _isOpen = true;
796
+
797
+ _features = framework.detectFeatures();
798
+ _requestAF = _features.raf;
799
+ _cancelAF = _features.caf;
800
+ _transformKey = _features.transform;
801
+ _oldIE = _features.oldIE;
802
+
803
+ self.scrollWrap = framework.getChildByClass(template, 'pswp__scroll-wrap');
804
+ self.container = framework.getChildByClass(self.scrollWrap, 'pswp__container');
805
+
806
+ _containerStyle = self.container.style; // for fast access
807
+
808
+ // Objects that hold slides (there are only 3 in DOM)
809
+ self.itemHolders = _itemHolders = [
810
+ {el:self.container.children[0] , wrap:0, index: -1},
811
+ {el:self.container.children[1] , wrap:0, index: -1},
812
+ {el:self.container.children[2] , wrap:0, index: -1}
813
+ ];
814
+
815
+ // hide nearby item holders until initial zoom animation finishes (to avoid extra Paints)
816
+ _itemHolders[0].el.style.display = _itemHolders[2].el.style.display = 'none';
817
+
818
+ _setupTransforms();
819
+
820
+ // Setup global events
821
+ _globalEventHandlers = {
822
+ resize: self.updateSize,
823
+ scroll: _updatePageScrollOffset,
824
+ keydown: _onKeyDown,
825
+ click: _onGlobalClick
826
+ };
827
+
828
+ // disable show/hide effects on old browsers that don't support CSS animations or transforms,
829
+ // old IOS, Android and Opera mobile. Blackberry seems to work fine, even older models.
830
+ var oldPhone = _features.isOldIOSPhone || _features.isOldAndroid || _features.isMobileOpera;
831
+ if(!_features.animationName || !_features.transform || oldPhone) {
832
+ _options.showAnimationDuration = _options.hideAnimationDuration = 0;
833
+ }
834
+
835
+ // init modules
836
+ for(i = 0; i < _modules.length; i++) {
837
+ self['init' + _modules[i]]();
838
+ }
839
+
840
+ // init
841
+ if(UiClass) {
842
+ var ui = self.ui = new UiClass(self, framework);
843
+ ui.init();
844
+ }
845
+
846
+ _shout('firstUpdate');
847
+ _currentItemIndex = _currentItemIndex || _options.index || 0;
848
+ // validate index
849
+ if( isNaN(_currentItemIndex) || _currentItemIndex < 0 || _currentItemIndex >= _getNumItems() ) {
850
+ _currentItemIndex = 0;
851
+ }
852
+ self.currItem = _getItemAt( _currentItemIndex );
853
+
854
+
855
+ if(_features.isOldIOSPhone || _features.isOldAndroid) {
856
+ _isFixedPosition = false;
857
+ }
858
+
859
+ template.setAttribute('aria-hidden', 'false');
860
+ if(_options.modal) {
861
+ if(!_isFixedPosition) {
862
+ template.style.position = 'absolute';
863
+ template.style.top = framework.getScrollY() + 'px';
864
+ } else {
865
+ template.style.position = 'fixed';
866
+ }
867
+ }
868
+
869
+ if(_currentWindowScrollY === undefined) {
870
+ _shout('initialLayout');
871
+ _currentWindowScrollY = _initalWindowScrollY = framework.getScrollY();
872
+ }
873
+
874
+ // add classes to root element of PhotoSwipe
875
+ var rootClasses = 'pswp--open ';
876
+ if(_options.mainClass) {
877
+ rootClasses += _options.mainClass + ' ';
878
+ }
879
+ if(_options.showHideOpacity) {
880
+ rootClasses += 'pswp--animate_opacity ';
881
+ }
882
+ rootClasses += _likelyTouchDevice ? 'pswp--touch' : 'pswp--notouch';
883
+ rootClasses += _features.animationName ? ' pswp--css_animation' : '';
884
+ rootClasses += _features.svg ? ' pswp--svg' : '';
885
+ framework.addClass(template, rootClasses);
886
+
887
+ self.updateSize();
888
+
889
+ // initial update
890
+ _containerShiftIndex = -1;
891
+ _indexDiff = null;
892
+ for(i = 0; i < NUM_HOLDERS; i++) {
893
+ _setTranslateX( (i+_containerShiftIndex) * _slideSize.x, _itemHolders[i].el.style);
894
+ }
895
+
896
+ if(!_oldIE) {
897
+ framework.bind(self.scrollWrap, _downEvents, self); // no dragging for old IE
898
+ }
899
+
900
+ _listen('initialZoomInEnd', function() {
901
+ self.setContent(_itemHolders[0], _currentItemIndex-1);
902
+ self.setContent(_itemHolders[2], _currentItemIndex+1);
903
+
904
+ _itemHolders[0].el.style.display = _itemHolders[2].el.style.display = 'block';
905
+
906
+ if(_options.focus) {
907
+ // focus causes layout,
908
+ // which causes lag during the animation,
909
+ // that's why we delay it untill the initial zoom transition ends
910
+ template.focus();
911
+ }
912
+
913
+
914
+ _bindEvents();
915
+ });
916
+
917
+ // set content for center slide (first time)
918
+ self.setContent(_itemHolders[1], _currentItemIndex);
919
+
920
+ self.updateCurrItem();
921
+
922
+ _shout('afterInit');
923
+
924
+ if(!_isFixedPosition) {
925
+
926
+ // On all versions of iOS lower than 8.0, we check size of viewport every second.
927
+ //
928
+ // This is done to detect when Safari top & bottom bars appear,
929
+ // as this action doesn't trigger any events (like resize).
930
+ //
931
+ // On iOS8 they fixed this.
932
+ //
933
+ // 10 Nov 2014: iOS 7 usage ~40%. iOS 8 usage 56%.
934
+
935
+ _updateSizeInterval = setInterval(function() {
936
+ if(!_numAnimations && !_isDragging && !_isZooming && (_currZoomLevel === self.currItem.initialZoomLevel) ) {
937
+ self.updateSize();
938
+ }
939
+ }, 1000);
940
+ }
941
+
942
+ framework.addClass(template, 'pswp--visible');
943
+ },
944
+
945
+ // Closes the gallery, then destroy it
946
+ close: function() {
947
+ if(!_isOpen) {
948
+ return;
949
+ }
950
+
951
+ _isOpen = false;
952
+ _isDestroying = true;
953
+ _shout('close');
954
+ _unbindEvents();
955
+
956
+ _showOrHide( self.currItem, null, true, self.destroy);
957
+ },
958
+
959
+ // destroys gallery (unbinds events, cleans up intervals and timeouts to avoid memory leaks)
960
+ destroy: function() {
961
+ _shout('destroy');
962
+
963
+ if(_showOrHideTimeout) {
964
+ clearTimeout(_showOrHideTimeout);
965
+ }
966
+
967
+ template.setAttribute('aria-hidden', 'true');
968
+ template.className = _initalClassName;
969
+
970
+ if(_updateSizeInterval) {
971
+ clearInterval(_updateSizeInterval);
972
+ }
973
+
974
+ framework.unbind(self.scrollWrap, _downEvents, self);
975
+
976
+ // we unbind lost event at the end, as closing animation may depend on it
977
+ framework.unbind(window, 'scroll', self);
978
+
979
+ _stopDragUpdateLoop();
980
+
981
+ _stopAllAnimations();
982
+
983
+ _listeners = null;
984
+ },
985
+
986
+ /**
987
+ * Pan image to position
988
+ * @param {Number} x
989
+ * @param {Number} y
990
+ * @param {Boolean} force Will ignore bounds if set to true.
991
+ */
992
+ panTo: function(x,y,force) {
993
+ if(!force) {
994
+ if(x > _currPanBounds.min.x) {
995
+ x = _currPanBounds.min.x;
996
+ } else if(x < _currPanBounds.max.x) {
997
+ x = _currPanBounds.max.x;
998
+ }
999
+
1000
+ if(y > _currPanBounds.min.y) {
1001
+ y = _currPanBounds.min.y;
1002
+ } else if(y < _currPanBounds.max.y) {
1003
+ y = _currPanBounds.max.y;
1004
+ }
1005
+ }
1006
+
1007
+ _panOffset.x = x;
1008
+ _panOffset.y = y;
1009
+ _applyCurrentZoomPan();
1010
+ },
1011
+
1012
+ handleEvent: function (e) {
1013
+ e = e || window.event;
1014
+ if(_globalEventHandlers[e.type]) {
1015
+ _globalEventHandlers[e.type](e);
1016
+ }
1017
+ },
1018
+
1019
+
1020
+ goTo: function(index) {
1021
+
1022
+ index = _getLoopedId(index);
1023
+
1024
+ var diff = index - _currentItemIndex;
1025
+ _indexDiff = diff;
1026
+
1027
+ _currentItemIndex = index;
1028
+ self.currItem = _getItemAt( _currentItemIndex );
1029
+ _currPositionIndex -= diff;
1030
+
1031
+ _moveMainScroll(_slideSize.x * _currPositionIndex);
1032
+
1033
+
1034
+ _stopAllAnimations();
1035
+ _mainScrollAnimating = false;
1036
+
1037
+ self.updateCurrItem();
1038
+ },
1039
+ next: function() {
1040
+ self.goTo( _currentItemIndex + 1);
1041
+ },
1042
+ prev: function() {
1043
+ self.goTo( _currentItemIndex - 1);
1044
+ },
1045
+
1046
+ // update current zoom/pan objects
1047
+ updateCurrZoomItem: function(emulateSetContent) {
1048
+ if(emulateSetContent) {
1049
+ _shout('beforeChange', 0);
1050
+ }
1051
+
1052
+ // itemHolder[1] is middle (current) item
1053
+ if(_itemHolders[1].el.children.length) {
1054
+ var zoomElement = _itemHolders[1].el.children[0];
1055
+ if( framework.hasClass(zoomElement, 'pswp__zoom-wrap') ) {
1056
+ _currZoomElementStyle = zoomElement.style;
1057
+ } else {
1058
+ _currZoomElementStyle = null;
1059
+ }
1060
+ } else {
1061
+ _currZoomElementStyle = null;
1062
+ }
1063
+
1064
+ _currPanBounds = self.currItem.bounds;
1065
+ _startZoomLevel = _currZoomLevel = self.currItem.initialZoomLevel;
1066
+
1067
+ _panOffset.x = _currPanBounds.center.x;
1068
+ _panOffset.y = _currPanBounds.center.y;
1069
+
1070
+ if(emulateSetContent) {
1071
+ _shout('afterChange');
1072
+ }
1073
+ },
1074
+
1075
+
1076
+ invalidateCurrItems: function() {
1077
+ _itemsNeedUpdate = true;
1078
+ for(var i = 0; i < NUM_HOLDERS; i++) {
1079
+ if( _itemHolders[i].item ) {
1080
+ _itemHolders[i].item.needsUpdate = true;
1081
+ }
1082
+ }
1083
+ },
1084
+
1085
+ updateCurrItem: function(beforeAnimation) {
1086
+
1087
+ if(_indexDiff === 0) {
1088
+ return;
1089
+ }
1090
+
1091
+ var diffAbs = Math.abs(_indexDiff),
1092
+ tempHolder;
1093
+
1094
+ if(beforeAnimation && diffAbs < 2) {
1095
+ return;
1096
+ }
1097
+
1098
+
1099
+ self.currItem = _getItemAt( _currentItemIndex );
1100
+
1101
+ _shout('beforeChange', _indexDiff);
1102
+
1103
+ if(diffAbs >= NUM_HOLDERS) {
1104
+ _containerShiftIndex += _indexDiff + (_indexDiff > 0 ? -NUM_HOLDERS : NUM_HOLDERS);
1105
+ diffAbs = NUM_HOLDERS;
1106
+ }
1107
+ for(var i = 0; i < diffAbs; i++) {
1108
+ if(_indexDiff > 0) {
1109
+ tempHolder = _itemHolders.shift();
1110
+ _itemHolders[NUM_HOLDERS-1] = tempHolder; // move first to last
1111
+
1112
+ _containerShiftIndex++;
1113
+ _setTranslateX( (_containerShiftIndex+2) * _slideSize.x, tempHolder.el.style);
1114
+ self.setContent(tempHolder, _currentItemIndex - diffAbs + i + 1 + 1);
1115
+ } else {
1116
+ tempHolder = _itemHolders.pop();
1117
+ _itemHolders.unshift( tempHolder ); // move last to first
1118
+
1119
+ _containerShiftIndex--;
1120
+ _setTranslateX( _containerShiftIndex * _slideSize.x, tempHolder.el.style);
1121
+ self.setContent(tempHolder, _currentItemIndex + diffAbs - i - 1 - 1);
1122
+ }
1123
+
1124
+ }
1125
+
1126
+ // reset zoom/pan on previous item
1127
+ if(_currZoomElementStyle && Math.abs(_indexDiff) === 1) {
1128
+
1129
+ var prevItem = _getItemAt(_prevItemIndex);
1130
+ if(prevItem.initialZoomLevel !== _currZoomLevel) {
1131
+ _calculateItemSize(prevItem , _viewportSize );
1132
+ _applyZoomPanToItem( prevItem );
1133
+ }
1134
+
1135
+ }
1136
+
1137
+ // reset diff after update
1138
+ _indexDiff = 0;
1139
+
1140
+ self.updateCurrZoomItem();
1141
+
1142
+ _prevItemIndex = _currentItemIndex;
1143
+
1144
+ _shout('afterChange');
1145
+
1146
+ },
1147
+
1148
+
1149
+
1150
+ updateSize: function(force) {
1151
+
1152
+ if(!_isFixedPosition && _options.modal) {
1153
+ var windowScrollY = framework.getScrollY();
1154
+ if(_currentWindowScrollY !== windowScrollY) {
1155
+ template.style.top = windowScrollY + 'px';
1156
+ _currentWindowScrollY = windowScrollY;
1157
+ }
1158
+ if(!force && _windowVisibleSize.x === window.innerWidth && _windowVisibleSize.y === window.innerHeight) {
1159
+ return;
1160
+ }
1161
+ _windowVisibleSize.x = window.innerWidth;
1162
+ _windowVisibleSize.y = window.innerHeight;
1163
+
1164
+ //template.style.width = _windowVisibleSize.x + 'px';
1165
+ template.style.height = _windowVisibleSize.y + 'px';
1166
+ }
1167
+
1168
+
1169
+
1170
+ _viewportSize.x = self.scrollWrap.clientWidth;
1171
+ _viewportSize.y = self.scrollWrap.clientHeight;
1172
+
1173
+ _updatePageScrollOffset();
1174
+
1175
+ _slideSize.x = _viewportSize.x + Math.round(_viewportSize.x * _options.spacing);
1176
+ _slideSize.y = _viewportSize.y;
1177
+
1178
+ _moveMainScroll(_slideSize.x * _currPositionIndex);
1179
+
1180
+ _shout('beforeResize'); // even may be used for example to switch image sources
1181
+
1182
+
1183
+ // don't re-calculate size on inital size update
1184
+ if(_containerShiftIndex !== undefined) {
1185
+
1186
+ var holder,
1187
+ item,
1188
+ hIndex;
1189
+
1190
+ for(var i = 0; i < NUM_HOLDERS; i++) {
1191
+ holder = _itemHolders[i];
1192
+ _setTranslateX( (i+_containerShiftIndex) * _slideSize.x, holder.el.style);
1193
+
1194
+ hIndex = _currentItemIndex+i-1;
1195
+
1196
+ if(_options.loop && _getNumItems() > 2) {
1197
+ hIndex = _getLoopedId(hIndex);
1198
+ }
1199
+
1200
+ // update zoom level on items and refresh source (if needsUpdate)
1201
+ item = _getItemAt( hIndex );
1202
+
1203
+ // re-render gallery item if `needsUpdate`,
1204
+ // or doesn't have `bounds` (entirely new slide object)
1205
+ if( item && (_itemsNeedUpdate || item.needsUpdate || !item.bounds) ) {
1206
+
1207
+ self.cleanSlide( item );
1208
+
1209
+ self.setContent( holder, hIndex );
1210
+
1211
+ // if "center" slide
1212
+ if(i === 1) {
1213
+ self.currItem = item;
1214
+ self.updateCurrZoomItem(true);
1215
+ }
1216
+
1217
+ item.needsUpdate = false;
1218
+
1219
+ } else if(holder.index === -1 && hIndex >= 0) {
1220
+ // add content first time
1221
+ self.setContent( holder, hIndex );
1222
+ }
1223
+ if(item && item.container) {
1224
+ _calculateItemSize(item, _viewportSize);
1225
+ _applyZoomPanToItem( item );
1226
+ }
1227
+
1228
+ }
1229
+ _itemsNeedUpdate = false;
1230
+ }
1231
+
1232
+ _startZoomLevel = _currZoomLevel = self.currItem.initialZoomLevel;
1233
+ _currPanBounds = self.currItem.bounds;
1234
+
1235
+ if(_currPanBounds) {
1236
+ _panOffset.x = _currPanBounds.center.x;
1237
+ _panOffset.y = _currPanBounds.center.y;
1238
+ _applyCurrentZoomPan();
1239
+ }
1240
+
1241
+ _shout('resize');
1242
+ },
1243
+
1244
+ // Zoom current item to
1245
+ zoomTo: function(destZoomLevel, centerPoint, speed, easingFn, updateFn) {
1246
+ /*
1247
+ if(destZoomLevel === 'fit') {
1248
+ destZoomLevel = self.currItem.fitRatio;
1249
+ } else if(destZoomLevel === 'fill') {
1250
+ destZoomLevel = self.currItem.fillRatio;
1251
+ }
1252
+ */
1253
+
1254
+ if(centerPoint) {
1255
+ _startZoomLevel = _currZoomLevel;
1256
+ _midZoomPoint.x = Math.abs(centerPoint.x) - _panOffset.x ;
1257
+ _midZoomPoint.y = Math.abs(centerPoint.y) - _panOffset.y ;
1258
+ _equalizePoints(_startPanOffset, _panOffset);
1259
+ }
1260
+
1261
+ var destPanBounds = _calculatePanBounds(destZoomLevel, false),
1262
+ destPanOffset = {};
1263
+
1264
+ _modifyDestPanOffset('x', destPanBounds, destPanOffset, destZoomLevel);
1265
+ _modifyDestPanOffset('y', destPanBounds, destPanOffset, destZoomLevel);
1266
+
1267
+ var initialZoomLevel = _currZoomLevel;
1268
+ var initialPanOffset = {
1269
+ x: _panOffset.x,
1270
+ y: _panOffset.y
1271
+ };
1272
+
1273
+ _roundPoint(destPanOffset);
1274
+
1275
+ // _startZoomLevel = destZoomLevel;
1276
+ var onUpdate = function(now) {
1277
+ if(now === 1) {
1278
+ _currZoomLevel = destZoomLevel;
1279
+ _panOffset.x = destPanOffset.x;
1280
+ _panOffset.y = destPanOffset.y;
1281
+ } else {
1282
+ _currZoomLevel = (destZoomLevel - initialZoomLevel) * now + initialZoomLevel;
1283
+ _panOffset.x = (destPanOffset.x - initialPanOffset.x) * now + initialPanOffset.x;
1284
+ _panOffset.y = (destPanOffset.y - initialPanOffset.y) * now + initialPanOffset.y;
1285
+ }
1286
+
1287
+ if(updateFn) {
1288
+ updateFn(now);
1289
+ }
1290
+
1291
+ _applyCurrentZoomPan();
1292
+ };
1293
+
1294
+ if(speed) {
1295
+ _animateProp('customZoomTo', 0, 1, speed, easingFn || framework.easing.sine.inOut, onUpdate);
1296
+ } else {
1297
+ onUpdate(1);
1298
+ }
1299
+ }
1300
+
1301
+
1302
+ };
1303
+
1304
+
1305
+ /*>>core*/
1306
+
1307
+ /*>>gestures*/
1308
+ /**
1309
+ * Mouse/touch/pointer event handlers.
1310
+ *
1311
+ * separated from @core.js for readability
1312
+ */
1313
+
1314
+ var MIN_SWIPE_DISTANCE = 30,
1315
+ DIRECTION_CHECK_OFFSET = 10; // amount of pixels to drag to determine direction of swipe
1316
+
1317
+ var _gestureStartTime,
1318
+ _gestureCheckSpeedTime,
1319
+
1320
+ // pool of objects that are used during dragging of zooming
1321
+ p = {}, // first point
1322
+ p2 = {}, // second point (for zoom gesture)
1323
+ delta = {},
1324
+ _currPoint = {},
1325
+ _startPoint = {},
1326
+ _currPointers = [],
1327
+ _startMainScrollPos = {},
1328
+ _releaseAnimData,
1329
+ _posPoints = [], // array of points during dragging, used to determine type of gesture
1330
+ _tempPoint = {},
1331
+
1332
+ _isZoomingIn,
1333
+ _verticalDragInitiated,
1334
+ _oldAndroidTouchEndTimeout,
1335
+ _currZoomedItemIndex = 0,
1336
+ _centerPoint = _getEmptyPoint(),
1337
+ _lastReleaseTime = 0,
1338
+ _isDragging, // at least one pointer is down
1339
+ _isMultitouch, // at least two _pointers are down
1340
+ _zoomStarted, // zoom level changed during zoom gesture
1341
+ _moved,
1342
+ _dragAnimFrame,
1343
+ _mainScrollShifted,
1344
+ _currentPoints, // array of current touch points
1345
+ _isZooming,
1346
+ _currPointsDistance,
1347
+ _startPointsDistance,
1348
+ _currPanBounds,
1349
+ _mainScrollPos = _getEmptyPoint(),
1350
+ _currZoomElementStyle,
1351
+ _mainScrollAnimating, // true, if animation after swipe gesture is running
1352
+ _midZoomPoint = _getEmptyPoint(),
1353
+ _currCenterPoint = _getEmptyPoint(),
1354
+ _direction,
1355
+ _isFirstMove,
1356
+ _opacityChanged,
1357
+ _bgOpacity,
1358
+ _wasOverInitialZoom,
1359
+
1360
+ _isEqualPoints = function(p1, p2) {
1361
+ return p1.x === p2.x && p1.y === p2.y;
1362
+ },
1363
+ _isNearbyPoints = function(touch0, touch1) {
1364
+ return Math.abs(touch0.x - touch1.x) < DOUBLE_TAP_RADIUS && Math.abs(touch0.y - touch1.y) < DOUBLE_TAP_RADIUS;
1365
+ },
1366
+ _calculatePointsDistance = function(p1, p2) {
1367
+ _tempPoint.x = Math.abs( p1.x - p2.x );
1368
+ _tempPoint.y = Math.abs( p1.y - p2.y );
1369
+ return Math.sqrt(_tempPoint.x * _tempPoint.x + _tempPoint.y * _tempPoint.y);
1370
+ },
1371
+ _stopDragUpdateLoop = function() {
1372
+ if(_dragAnimFrame) {
1373
+ _cancelAF(_dragAnimFrame);
1374
+ _dragAnimFrame = null;
1375
+ }
1376
+ },
1377
+ _dragUpdateLoop = function() {
1378
+ if(_isDragging) {
1379
+ _dragAnimFrame = _requestAF(_dragUpdateLoop);
1380
+ _renderMovement();
1381
+ }
1382
+ },
1383
+ _canPan = function() {
1384
+ return !(_options.scaleMode === 'fit' && _currZoomLevel === self.currItem.initialZoomLevel);
1385
+ },
1386
+
1387
+ // find the closest parent DOM element
1388
+ _closestElement = function(el, fn) {
1389
+ if(!el) {
1390
+ return false;
1391
+ }
1392
+
1393
+ // don't search elements above pswp__scroll-wrap
1394
+ if(el.className && el.className.indexOf('pswp__scroll-wrap') > -1 ) {
1395
+ return false;
1396
+ }
1397
+
1398
+ if( fn(el) ) {
1399
+ return el;
1400
+ }
1401
+
1402
+ return _closestElement(el.parentNode, fn);
1403
+ },
1404
+
1405
+ _preventObj = {},
1406
+ _preventDefaultEventBehaviour = function(e, isDown) {
1407
+ _preventObj.prevent = !_closestElement(e.target, _options.isClickableElement);
1408
+
1409
+ _shout('preventDragEvent', e, isDown, _preventObj);
1410
+ return _preventObj.prevent;
1411
+
1412
+ },
1413
+ _convertTouchToPoint = function(touch, p) {
1414
+ p.x = touch.pageX;
1415
+ p.y = touch.pageY;
1416
+ p.id = touch.identifier;
1417
+ return p;
1418
+ },
1419
+ _findCenterOfPoints = function(p1, p2, pCenter) {
1420
+ pCenter.x = (p1.x + p2.x) * 0.5;
1421
+ pCenter.y = (p1.y + p2.y) * 0.5;
1422
+ },
1423
+ _pushPosPoint = function(time, x, y) {
1424
+ if(time - _gestureCheckSpeedTime > 50) {
1425
+ var o = _posPoints.length > 2 ? _posPoints.shift() : {};
1426
+ o.x = x;
1427
+ o.y = y;
1428
+ _posPoints.push(o);
1429
+ _gestureCheckSpeedTime = time;
1430
+ }
1431
+ },
1432
+
1433
+ _calculateVerticalDragOpacityRatio = function() {
1434
+ var yOffset = _panOffset.y - self.currItem.initialPosition.y; // difference between initial and current position
1435
+ return 1 - Math.abs( yOffset / (_viewportSize.y / 2) );
1436
+ },
1437
+
1438
+
1439
+ // points pool, reused during touch events
1440
+ _ePoint1 = {},
1441
+ _ePoint2 = {},
1442
+ _tempPointsArr = [],
1443
+ _tempCounter,
1444
+ _getTouchPoints = function(e) {
1445
+ // clean up previous points, without recreating array
1446
+ while(_tempPointsArr.length > 0) {
1447
+ _tempPointsArr.pop();
1448
+ }
1449
+
1450
+ if(!_pointerEventEnabled) {
1451
+ if(e.type.indexOf('touch') > -1) {
1452
+
1453
+ if(e.touches && e.touches.length > 0) {
1454
+ _tempPointsArr[0] = _convertTouchToPoint(e.touches[0], _ePoint1);
1455
+ if(e.touches.length > 1) {
1456
+ _tempPointsArr[1] = _convertTouchToPoint(e.touches[1], _ePoint2);
1457
+ }
1458
+ }
1459
+
1460
+ } else {
1461
+ _ePoint1.x = e.pageX;
1462
+ _ePoint1.y = e.pageY;
1463
+ _ePoint1.id = '';
1464
+ _tempPointsArr[0] = _ePoint1;//_ePoint1;
1465
+ }
1466
+ } else {
1467
+ _tempCounter = 0;
1468
+ // we can use forEach, as pointer events are supported only in modern browsers
1469
+ _currPointers.forEach(function(p) {
1470
+ if(_tempCounter === 0) {
1471
+ _tempPointsArr[0] = p;
1472
+ } else if(_tempCounter === 1) {
1473
+ _tempPointsArr[1] = p;
1474
+ }
1475
+ _tempCounter++;
1476
+
1477
+ });
1478
+ }
1479
+ return _tempPointsArr;
1480
+ },
1481
+
1482
+ _panOrMoveMainScroll = function(axis, delta) {
1483
+
1484
+ var panFriction,
1485
+ overDiff = 0,
1486
+ newOffset = _panOffset[axis] + delta[axis],
1487
+ startOverDiff,
1488
+ dir = delta[axis] > 0,
1489
+ newMainScrollPosition = _mainScrollPos.x + delta.x,
1490
+ mainScrollDiff = _mainScrollPos.x - _startMainScrollPos.x,
1491
+ newPanPos,
1492
+ newMainScrollPos;
1493
+
1494
+ // calculate fdistance over the bounds and friction
1495
+ if(newOffset > _currPanBounds.min[axis] || newOffset < _currPanBounds.max[axis]) {
1496
+ panFriction = _options.panEndFriction;
1497
+ // Linear increasing of friction, so at 1/4 of viewport it's at max value.
1498
+ // Looks not as nice as was expected. Left for history.
1499
+ // panFriction = (1 - (_panOffset[axis] + delta[axis] + panBounds.min[axis]) / (_viewportSize[axis] / 4) );
1500
+ } else {
1501
+ panFriction = 1;
1502
+ }
1503
+
1504
+ newOffset = _panOffset[axis] + delta[axis] * panFriction;
1505
+
1506
+ // move main scroll or start panning
1507
+ if(_options.allowPanToNext || _currZoomLevel === self.currItem.initialZoomLevel) {
1508
+
1509
+
1510
+ if(!_currZoomElementStyle) {
1511
+
1512
+ newMainScrollPos = newMainScrollPosition;
1513
+
1514
+ } else if(_direction === 'h' && axis === 'x' && !_zoomStarted ) {
1515
+
1516
+ if(dir) {
1517
+ if(newOffset > _currPanBounds.min[axis]) {
1518
+ panFriction = _options.panEndFriction;
1519
+ overDiff = _currPanBounds.min[axis] - newOffset;
1520
+ startOverDiff = _currPanBounds.min[axis] - _startPanOffset[axis];
1521
+ }
1522
+
1523
+ // drag right
1524
+ if( (startOverDiff <= 0 || mainScrollDiff < 0) && _getNumItems() > 1 ) {
1525
+ newMainScrollPos = newMainScrollPosition;
1526
+ if(mainScrollDiff < 0 && newMainScrollPosition > _startMainScrollPos.x) {
1527
+ newMainScrollPos = _startMainScrollPos.x;
1528
+ }
1529
+ } else {
1530
+ if(_currPanBounds.min.x !== _currPanBounds.max.x) {
1531
+ newPanPos = newOffset;
1532
+ }
1533
+
1534
+ }
1535
+
1536
+ } else {
1537
+
1538
+ if(newOffset < _currPanBounds.max[axis] ) {
1539
+ panFriction =_options.panEndFriction;
1540
+ overDiff = newOffset - _currPanBounds.max[axis];
1541
+ startOverDiff = _startPanOffset[axis] - _currPanBounds.max[axis];
1542
+ }
1543
+
1544
+ if( (startOverDiff <= 0 || mainScrollDiff > 0) && _getNumItems() > 1 ) {
1545
+ newMainScrollPos = newMainScrollPosition;
1546
+
1547
+ if(mainScrollDiff > 0 && newMainScrollPosition < _startMainScrollPos.x) {
1548
+ newMainScrollPos = _startMainScrollPos.x;
1549
+ }
1550
+
1551
+ } else {
1552
+ if(_currPanBounds.min.x !== _currPanBounds.max.x) {
1553
+ newPanPos = newOffset;
1554
+ }
1555
+ }
1556
+
1557
+ }
1558
+
1559
+
1560
+ //
1561
+ }
1562
+
1563
+ if(axis === 'x') {
1564
+
1565
+ if(newMainScrollPos !== undefined) {
1566
+ _moveMainScroll(newMainScrollPos, true);
1567
+ if(newMainScrollPos === _startMainScrollPos.x) {
1568
+ _mainScrollShifted = false;
1569
+ } else {
1570
+ _mainScrollShifted = true;
1571
+ }
1572
+ }
1573
+
1574
+ if(_currPanBounds.min.x !== _currPanBounds.max.x) {
1575
+ if(newPanPos !== undefined) {
1576
+ _panOffset.x = newPanPos;
1577
+ } else if(!_mainScrollShifted) {
1578
+ _panOffset.x += delta.x * panFriction;
1579
+ }
1580
+ }
1581
+
1582
+ return newMainScrollPos !== undefined;
1583
+ }
1584
+
1585
+ }
1586
+
1587
+ if(!_mainScrollAnimating) {
1588
+
1589
+ if(!_mainScrollShifted) {
1590
+ if(_currZoomLevel > self.currItem.fitRatio) {
1591
+ _panOffset[axis] += delta[axis] * panFriction;
1592
+
1593
+ }
1594
+ }
1595
+
1596
+
1597
+ }
1598
+
1599
+ },
1600
+
1601
+ // Pointerdown/touchstart/mousedown handler
1602
+ _onDragStart = function(e) {
1603
+
1604
+ // Allow dragging only via left mouse button.
1605
+ // As this handler is not added in IE8 - we ignore e.which
1606
+ //
1607
+ // http://www.quirksmode.org/js/events_properties.html
1608
+ // https://developer.mozilla.org/en-US/docs/Web/API/event.button
1609
+ if(e.type === 'mousedown' && e.button > 0 ) {
1610
+ return;
1611
+ }
1612
+
1613
+ if(_initialZoomRunning) {
1614
+ e.preventDefault();
1615
+ return;
1616
+ }
1617
+
1618
+ if(_oldAndroidTouchEndTimeout && e.type === 'mousedown') {
1619
+ return;
1620
+ }
1621
+
1622
+ if(_preventDefaultEventBehaviour(e, true)) {
1623
+ e.preventDefault();
1624
+ }
1625
+
1626
+
1627
+
1628
+ _shout('pointerDown');
1629
+
1630
+ if(_pointerEventEnabled) {
1631
+ var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id');
1632
+ if(pointerIndex < 0) {
1633
+ pointerIndex = _currPointers.length;
1634
+ }
1635
+ _currPointers[pointerIndex] = {x:e.pageX, y:e.pageY, id: e.pointerId};
1636
+ }
1637
+
1638
+
1639
+
1640
+ var startPointsList = _getTouchPoints(e),
1641
+ numPoints = startPointsList.length;
1642
+
1643
+ _currentPoints = null;
1644
+
1645
+ _stopAllAnimations();
1646
+
1647
+ // init drag
1648
+ if(!_isDragging || numPoints === 1) {
1649
+
1650
+
1651
+
1652
+ _isDragging = _isFirstMove = true;
1653
+ framework.bind(window, _upMoveEvents, self);
1654
+
1655
+ _isZoomingIn =
1656
+ _wasOverInitialZoom =
1657
+ _opacityChanged =
1658
+ _verticalDragInitiated =
1659
+ _mainScrollShifted =
1660
+ _moved =
1661
+ _isMultitouch =
1662
+ _zoomStarted = false;
1663
+
1664
+ _direction = null;
1665
+
1666
+ _shout('firstTouchStart', startPointsList);
1667
+
1668
+ _equalizePoints(_startPanOffset, _panOffset);
1669
+
1670
+ _currPanDist.x = _currPanDist.y = 0;
1671
+ _equalizePoints(_currPoint, startPointsList[0]);
1672
+ _equalizePoints(_startPoint, _currPoint);
1673
+
1674
+ //_equalizePoints(_startMainScrollPos, _mainScrollPos);
1675
+ _startMainScrollPos.x = _slideSize.x * _currPositionIndex;
1676
+
1677
+ _posPoints = [{
1678
+ x: _currPoint.x,
1679
+ y: _currPoint.y
1680
+ }];
1681
+
1682
+ _gestureCheckSpeedTime = _gestureStartTime = _getCurrentTime();
1683
+
1684
+ //_mainScrollAnimationEnd(true);
1685
+ _calculatePanBounds( _currZoomLevel, true );
1686
+
1687
+ // Start rendering
1688
+ _stopDragUpdateLoop();
1689
+ _dragUpdateLoop();
1690
+
1691
+ }
1692
+
1693
+ // init zoom
1694
+ if(!_isZooming && numPoints > 1 && !_mainScrollAnimating && !_mainScrollShifted) {
1695
+ _startZoomLevel = _currZoomLevel;
1696
+ _zoomStarted = false; // true if zoom changed at least once
1697
+
1698
+ _isZooming = _isMultitouch = true;
1699
+ _currPanDist.y = _currPanDist.x = 0;
1700
+
1701
+ _equalizePoints(_startPanOffset, _panOffset);
1702
+
1703
+ _equalizePoints(p, startPointsList[0]);
1704
+ _equalizePoints(p2, startPointsList[1]);
1705
+
1706
+ _findCenterOfPoints(p, p2, _currCenterPoint);
1707
+
1708
+ _midZoomPoint.x = Math.abs(_currCenterPoint.x) - _panOffset.x;
1709
+ _midZoomPoint.y = Math.abs(_currCenterPoint.y) - _panOffset.y;
1710
+ _currPointsDistance = _startPointsDistance = _calculatePointsDistance(p, p2);
1711
+ }
1712
+
1713
+
1714
+ },
1715
+
1716
+ // Pointermove/touchmove/mousemove handler
1717
+ _onDragMove = function(e) {
1718
+
1719
+ e.preventDefault();
1720
+
1721
+ if(_pointerEventEnabled) {
1722
+ var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id');
1723
+ if(pointerIndex > -1) {
1724
+ var p = _currPointers[pointerIndex];
1725
+ p.x = e.pageX;
1726
+ p.y = e.pageY;
1727
+ }
1728
+ }
1729
+
1730
+ if(_isDragging) {
1731
+ var touchesList = _getTouchPoints(e);
1732
+ if(!_direction && !_moved && !_isZooming) {
1733
+ var diff = Math.abs(touchesList[0].x - _currPoint.x) - Math.abs(touchesList[0].y - _currPoint.y);
1734
+ // check the direction of movement
1735
+ if(Math.abs(diff) >= DIRECTION_CHECK_OFFSET) {
1736
+ _direction = diff > 0 ? 'h' : 'v';
1737
+ _currentPoints = touchesList;
1738
+ }
1739
+ } else {
1740
+ _currentPoints = touchesList;
1741
+ }
1742
+ }
1743
+ },
1744
+ //
1745
+ _renderMovement = function() {
1746
+
1747
+ if(!_currentPoints) {
1748
+ return;
1749
+ }
1750
+
1751
+ var numPoints = _currentPoints.length;
1752
+
1753
+ if(numPoints === 0) {
1754
+ return;
1755
+ }
1756
+
1757
+ _equalizePoints(p, _currentPoints[0]);
1758
+
1759
+ delta.x = p.x - _currPoint.x;
1760
+ delta.y = p.y - _currPoint.y;
1761
+
1762
+ if(_isZooming && numPoints > 1) {
1763
+ // Handle behaviour for more than 1 point
1764
+
1765
+ _currPoint.x = p.x;
1766
+ _currPoint.y = p.y;
1767
+
1768
+ // check if one of two points changed
1769
+ if( !delta.x && !delta.y && _isEqualPoints(_currentPoints[1], p2) ) {
1770
+ return;
1771
+ }
1772
+
1773
+ _equalizePoints(p2, _currentPoints[1]);
1774
+
1775
+
1776
+ if(!_zoomStarted) {
1777
+ _zoomStarted = true;
1778
+ _shout('zoomGestureStarted');
1779
+ }
1780
+
1781
+ // Distance between two points
1782
+ var pointsDistance = _calculatePointsDistance(p,p2);
1783
+
1784
+ var zoomLevel = _calculateZoomLevel(pointsDistance);
1785
+
1786
+ // slightly over the of initial zoom level
1787
+ if(zoomLevel > self.currItem.initialZoomLevel + self.currItem.initialZoomLevel / 15) {
1788
+ _wasOverInitialZoom = true;
1789
+ }
1790
+
1791
+ // Apply the friction if zoom level is out of the bounds
1792
+ var zoomFriction = 1,
1793
+ minZoomLevel = _getMinZoomLevel(),
1794
+ maxZoomLevel = _getMaxZoomLevel();
1795
+
1796
+ if ( zoomLevel < minZoomLevel ) {
1797
+
1798
+ if(_options.pinchToClose && !_wasOverInitialZoom && _startZoomLevel <= self.currItem.initialZoomLevel) {
1799
+ // fade out background if zooming out
1800
+ var minusDiff = minZoomLevel - zoomLevel;
1801
+ var percent = 1 - minusDiff / (minZoomLevel / 1.2);
1802
+
1803
+ _applyBgOpacity(percent);
1804
+ _shout('onPinchClose', percent);
1805
+ _opacityChanged = true;
1806
+ } else {
1807
+ zoomFriction = (minZoomLevel - zoomLevel) / minZoomLevel;
1808
+ if(zoomFriction > 1) {
1809
+ zoomFriction = 1;
1810
+ }
1811
+ zoomLevel = minZoomLevel - zoomFriction * (minZoomLevel / 3);
1812
+ }
1813
+
1814
+ } else if ( zoomLevel > maxZoomLevel ) {
1815
+ // 1.5 - extra zoom level above the max. E.g. if max is x6, real max 6 + 1.5 = 7.5
1816
+ zoomFriction = (zoomLevel - maxZoomLevel) / ( minZoomLevel * 6 );
1817
+ if(zoomFriction > 1) {
1818
+ zoomFriction = 1;
1819
+ }
1820
+ zoomLevel = maxZoomLevel + zoomFriction * minZoomLevel;
1821
+ }
1822
+
1823
+ if(zoomFriction < 0) {
1824
+ zoomFriction = 0;
1825
+ }
1826
+
1827
+ // distance between touch points after friction is applied
1828
+ _currPointsDistance = pointsDistance;
1829
+
1830
+ // _centerPoint - The point in the middle of two pointers
1831
+ _findCenterOfPoints(p, p2, _centerPoint);
1832
+
1833
+ // paning with two pointers pressed
1834
+ _currPanDist.x += _centerPoint.x - _currCenterPoint.x;
1835
+ _currPanDist.y += _centerPoint.y - _currCenterPoint.y;
1836
+ _equalizePoints(_currCenterPoint, _centerPoint);
1837
+
1838
+ _panOffset.x = _calculatePanOffset('x', zoomLevel);
1839
+ _panOffset.y = _calculatePanOffset('y', zoomLevel);
1840
+
1841
+ _isZoomingIn = zoomLevel > _currZoomLevel;
1842
+ _currZoomLevel = zoomLevel;
1843
+ _applyCurrentZoomPan();
1844
+
1845
+ } else {
1846
+
1847
+ // handle behaviour for one point (dragging or panning)
1848
+
1849
+ if(!_direction) {
1850
+ return;
1851
+ }
1852
+
1853
+ if(_isFirstMove) {
1854
+ _isFirstMove = false;
1855
+
1856
+ // subtract drag distance that was used during the detection direction
1857
+
1858
+ if( Math.abs(delta.x) >= DIRECTION_CHECK_OFFSET) {
1859
+ delta.x -= _currentPoints[0].x - _startPoint.x;
1860
+ }
1861
+
1862
+ if( Math.abs(delta.y) >= DIRECTION_CHECK_OFFSET) {
1863
+ delta.y -= _currentPoints[0].y - _startPoint.y;
1864
+ }
1865
+ }
1866
+
1867
+ _currPoint.x = p.x;
1868
+ _currPoint.y = p.y;
1869
+
1870
+ // do nothing if pointers position hasn't changed
1871
+ if(delta.x === 0 && delta.y === 0) {
1872
+ return;
1873
+ }
1874
+
1875
+ if(_direction === 'v' && _options.closeOnVerticalDrag) {
1876
+ if(!_canPan()) {
1877
+
1878
+ _currPanDist.y += delta.y;
1879
+ _panOffset.y += delta.y;
1880
+
1881
+ var opacityRatio = _calculateVerticalDragOpacityRatio();
1882
+
1883
+ _verticalDragInitiated = true;
1884
+ _shout('onVerticalDrag', opacityRatio);
1885
+
1886
+ _applyBgOpacity(opacityRatio);
1887
+ _applyCurrentZoomPan();
1888
+ return ;
1889
+ }
1890
+ }
1891
+
1892
+ _pushPosPoint(_getCurrentTime(), p.x, p.y);
1893
+
1894
+ _moved = true;
1895
+ _currPanBounds = self.currItem.bounds;
1896
+
1897
+ var mainScrollChanged = _panOrMoveMainScroll('x', delta);
1898
+ if(!mainScrollChanged) {
1899
+ _panOrMoveMainScroll('y', delta);
1900
+
1901
+ _roundPoint(_panOffset);
1902
+ _applyCurrentZoomPan();
1903
+ }
1904
+
1905
+ }
1906
+
1907
+ },
1908
+
1909
+ // Pointerup/pointercancel/touchend/touchcancel/mouseup event handler
1910
+ _onDragRelease = function(e) {
1911
+
1912
+ if(_features.isOldAndroid ) {
1913
+
1914
+ if(_oldAndroidTouchEndTimeout && e.type === 'mouseup') {
1915
+ return;
1916
+ }
1917
+
1918
+ // on Android (v4.1, 4.2, 4.3 & possibly older)
1919
+ // ghost mousedown/up event isn't preventable via e.preventDefault,
1920
+ // which causes fake mousedown event
1921
+ // so we block mousedown/up for 600ms
1922
+ if( e.type.indexOf('touch') > -1 ) {
1923
+ clearTimeout(_oldAndroidTouchEndTimeout);
1924
+ _oldAndroidTouchEndTimeout = setTimeout(function() {
1925
+ _oldAndroidTouchEndTimeout = 0;
1926
+ }, 600);
1927
+ }
1928
+
1929
+ }
1930
+
1931
+ _shout('pointerUp');
1932
+
1933
+ if(_preventDefaultEventBehaviour(e, false)) {
1934
+ e.preventDefault();
1935
+ }
1936
+
1937
+ var releasePoint;
1938
+
1939
+ if(_pointerEventEnabled) {
1940
+ var pointerIndex = framework.arraySearch(_currPointers, e.pointerId, 'id');
1941
+
1942
+ if(pointerIndex > -1) {
1943
+ releasePoint = _currPointers.splice(pointerIndex, 1)[0];
1944
+
1945
+ if(navigator.pointerEnabled) {
1946
+ releasePoint.type = e.pointerType || 'mouse';
1947
+ } else {
1948
+ var MSPOINTER_TYPES = {
1949
+ 4: 'mouse', // event.MSPOINTER_TYPE_MOUSE
1950
+ 2: 'touch', // event.MSPOINTER_TYPE_TOUCH
1951
+ 3: 'pen' // event.MSPOINTER_TYPE_PEN
1952
+ };
1953
+ releasePoint.type = MSPOINTER_TYPES[e.pointerType];
1954
+
1955
+ if(!releasePoint.type) {
1956
+ releasePoint.type = e.pointerType || 'mouse';
1957
+ }
1958
+ }
1959
+
1960
+ }
1961
+ }
1962
+
1963
+ var touchList = _getTouchPoints(e),
1964
+ gestureType,
1965
+ numPoints = touchList.length;
1966
+
1967
+ if(e.type === 'mouseup') {
1968
+ numPoints = 0;
1969
+ }
1970
+
1971
+ // Do nothing if there were 3 touch points or more
1972
+ if(numPoints === 2) {
1973
+ _currentPoints = null;
1974
+ return true;
1975
+ }
1976
+
1977
+ // if second pointer released
1978
+ if(numPoints === 1) {
1979
+ _equalizePoints(_startPoint, touchList[0]);
1980
+ }
1981
+
1982
+
1983
+ // pointer hasn't moved, send "tap release" point
1984
+ if(numPoints === 0 && !_direction && !_mainScrollAnimating) {
1985
+ if(!releasePoint) {
1986
+ if(e.type === 'mouseup') {
1987
+ releasePoint = {x: e.pageX, y: e.pageY, type:'mouse'};
1988
+ } else if(e.changedTouches && e.changedTouches[0]) {
1989
+ releasePoint = {x: e.changedTouches[0].pageX, y: e.changedTouches[0].pageY, type:'touch'};
1990
+ }
1991
+ }
1992
+
1993
+ _shout('touchRelease', e, releasePoint);
1994
+ }
1995
+
1996
+ // Difference in time between releasing of two last touch points (zoom gesture)
1997
+ var releaseTimeDiff = -1;
1998
+
1999
+ // Gesture completed, no pointers left
2000
+ if(numPoints === 0) {
2001
+ _isDragging = false;
2002
+ framework.unbind(window, _upMoveEvents, self);
2003
+
2004
+ _stopDragUpdateLoop();
2005
+
2006
+ if(_isZooming) {
2007
+ // Two points released at the same time
2008
+ releaseTimeDiff = 0;
2009
+ } else if(_lastReleaseTime !== -1) {
2010
+ releaseTimeDiff = _getCurrentTime() - _lastReleaseTime;
2011
+ }
2012
+ }
2013
+ _lastReleaseTime = numPoints === 1 ? _getCurrentTime() : -1;
2014
+
2015
+ if(releaseTimeDiff !== -1 && releaseTimeDiff < 150) {
2016
+ gestureType = 'zoom';
2017
+ } else {
2018
+ gestureType = 'swipe';
2019
+ }
2020
+
2021
+ if(_isZooming && numPoints < 2) {
2022
+ _isZooming = false;
2023
+
2024
+ // Only second point released
2025
+ if(numPoints === 1) {
2026
+ gestureType = 'zoomPointerUp';
2027
+ }
2028
+ _shout('zoomGestureEnded');
2029
+ }
2030
+
2031
+ _currentPoints = null;
2032
+ if(!_moved && !_zoomStarted && !_mainScrollAnimating && !_verticalDragInitiated) {
2033
+ // nothing to animate
2034
+ return;
2035
+ }
2036
+
2037
+ _stopAllAnimations();
2038
+
2039
+
2040
+ if(!_releaseAnimData) {
2041
+ _releaseAnimData = _initDragReleaseAnimationData();
2042
+ }
2043
+
2044
+ _releaseAnimData.calculateSwipeSpeed('x');
2045
+
2046
+
2047
+ if(_verticalDragInitiated) {
2048
+
2049
+ var opacityRatio = _calculateVerticalDragOpacityRatio();
2050
+
2051
+ if(opacityRatio < _options.verticalDragRange) {
2052
+ self.close();
2053
+ } else {
2054
+ var initalPanY = _panOffset.y,
2055
+ initialBgOpacity = _bgOpacity;
2056
+
2057
+ _animateProp('verticalDrag', 0, 1, 300, framework.easing.cubic.out, function(now) {
2058
+
2059
+ _panOffset.y = (self.currItem.initialPosition.y - initalPanY) * now + initalPanY;
2060
+
2061
+ _applyBgOpacity( (1 - initialBgOpacity) * now + initialBgOpacity );
2062
+ _applyCurrentZoomPan();
2063
+ });
2064
+
2065
+ _shout('onVerticalDrag', 1);
2066
+ }
2067
+
2068
+ return;
2069
+ }
2070
+
2071
+
2072
+ // main scroll
2073
+ if( (_mainScrollShifted || _mainScrollAnimating) && numPoints === 0) {
2074
+ var itemChanged = _finishSwipeMainScrollGesture(gestureType, _releaseAnimData);
2075
+ if(itemChanged) {
2076
+ return;
2077
+ }
2078
+ gestureType = 'zoomPointerUp';
2079
+ }
2080
+
2081
+ // prevent zoom/pan animation when main scroll animation runs
2082
+ if(_mainScrollAnimating) {
2083
+ return;
2084
+ }
2085
+
2086
+ // Complete simple zoom gesture (reset zoom level if it's out of the bounds)
2087
+ if(gestureType !== 'swipe') {
2088
+ _completeZoomGesture();
2089
+ return;
2090
+ }
2091
+
2092
+ // Complete pan gesture if main scroll is not shifted, and it's possible to pan current image
2093
+ if(!_mainScrollShifted && _currZoomLevel > self.currItem.fitRatio) {
2094
+ _completePanGesture(_releaseAnimData);
2095
+ }
2096
+ },
2097
+
2098
+
2099
+ // Returns object with data about gesture
2100
+ // It's created only once and then reused
2101
+ _initDragReleaseAnimationData = function() {
2102
+ // temp local vars
2103
+ var lastFlickDuration,
2104
+ tempReleasePos;
2105
+
2106
+ // s = this
2107
+ var s = {
2108
+ lastFlickOffset: {},
2109
+ lastFlickDist: {},
2110
+ lastFlickSpeed: {},
2111
+ slowDownRatio: {},
2112
+ slowDownRatioReverse: {},
2113
+ speedDecelerationRatio: {},
2114
+ speedDecelerationRatioAbs: {},
2115
+ distanceOffset: {},
2116
+ backAnimDestination: {},
2117
+ backAnimStarted: {},
2118
+ calculateSwipeSpeed: function(axis) {
2119
+
2120
+
2121
+ if( _posPoints.length > 1) {
2122
+ lastFlickDuration = _getCurrentTime() - _gestureCheckSpeedTime + 50;
2123
+ tempReleasePos = _posPoints[_posPoints.length-2][axis];
2124
+ } else {
2125
+ lastFlickDuration = _getCurrentTime() - _gestureStartTime; // total gesture duration
2126
+ tempReleasePos = _startPoint[axis];
2127
+ }
2128
+ s.lastFlickOffset[axis] = _currPoint[axis] - tempReleasePos;
2129
+ s.lastFlickDist[axis] = Math.abs(s.lastFlickOffset[axis]);
2130
+ if(s.lastFlickDist[axis] > 20) {
2131
+ s.lastFlickSpeed[axis] = s.lastFlickOffset[axis] / lastFlickDuration;
2132
+ } else {
2133
+ s.lastFlickSpeed[axis] = 0;
2134
+ }
2135
+ if( Math.abs(s.lastFlickSpeed[axis]) < 0.1 ) {
2136
+ s.lastFlickSpeed[axis] = 0;
2137
+ }
2138
+
2139
+ s.slowDownRatio[axis] = 0.95;
2140
+ s.slowDownRatioReverse[axis] = 1 - s.slowDownRatio[axis];
2141
+ s.speedDecelerationRatio[axis] = 1;
2142
+ },
2143
+
2144
+ calculateOverBoundsAnimOffset: function(axis, speed) {
2145
+ if(!s.backAnimStarted[axis]) {
2146
+
2147
+ if(_panOffset[axis] > _currPanBounds.min[axis]) {
2148
+ s.backAnimDestination[axis] = _currPanBounds.min[axis];
2149
+
2150
+ } else if(_panOffset[axis] < _currPanBounds.max[axis]) {
2151
+ s.backAnimDestination[axis] = _currPanBounds.max[axis];
2152
+ }
2153
+
2154
+ if(s.backAnimDestination[axis] !== undefined) {
2155
+ s.slowDownRatio[axis] = 0.7;
2156
+ s.slowDownRatioReverse[axis] = 1 - s.slowDownRatio[axis];
2157
+ if(s.speedDecelerationRatioAbs[axis] < 0.05) {
2158
+
2159
+ s.lastFlickSpeed[axis] = 0;
2160
+ s.backAnimStarted[axis] = true;
2161
+
2162
+ _animateProp('bounceZoomPan'+axis,_panOffset[axis],
2163
+ s.backAnimDestination[axis],
2164
+ speed || 300,
2165
+ framework.easing.sine.out,
2166
+ function(pos) {
2167
+ _panOffset[axis] = pos;
2168
+ _applyCurrentZoomPan();
2169
+ }
2170
+ );
2171
+
2172
+ }
2173
+ }
2174
+ }
2175
+ },
2176
+
2177
+ // Reduces the speed by slowDownRatio (per 10ms)
2178
+ calculateAnimOffset: function(axis) {
2179
+ if(!s.backAnimStarted[axis]) {
2180
+ s.speedDecelerationRatio[axis] = s.speedDecelerationRatio[axis] * (s.slowDownRatio[axis] +
2181
+ s.slowDownRatioReverse[axis] -
2182
+ s.slowDownRatioReverse[axis] * s.timeDiff / 10);
2183
+
2184
+ s.speedDecelerationRatioAbs[axis] = Math.abs(s.lastFlickSpeed[axis] * s.speedDecelerationRatio[axis]);
2185
+ s.distanceOffset[axis] = s.lastFlickSpeed[axis] * s.speedDecelerationRatio[axis] * s.timeDiff;
2186
+ _panOffset[axis] += s.distanceOffset[axis];
2187
+
2188
+ }
2189
+ },
2190
+
2191
+ panAnimLoop: function() {
2192
+ if ( _animations.zoomPan ) {
2193
+ _animations.zoomPan.raf = _requestAF(s.panAnimLoop);
2194
+
2195
+ s.now = _getCurrentTime();
2196
+ s.timeDiff = s.now - s.lastNow;
2197
+ s.lastNow = s.now;
2198
+
2199
+ s.calculateAnimOffset('x');
2200
+ s.calculateAnimOffset('y');
2201
+
2202
+ _applyCurrentZoomPan();
2203
+
2204
+ s.calculateOverBoundsAnimOffset('x');
2205
+ s.calculateOverBoundsAnimOffset('y');
2206
+
2207
+
2208
+ if (s.speedDecelerationRatioAbs.x < 0.05 && s.speedDecelerationRatioAbs.y < 0.05) {
2209
+
2210
+ // round pan position
2211
+ _panOffset.x = Math.round(_panOffset.x);
2212
+ _panOffset.y = Math.round(_panOffset.y);
2213
+ _applyCurrentZoomPan();
2214
+
2215
+ _stopAnimation('zoomPan');
2216
+ return;
2217
+ }
2218
+ }
2219
+
2220
+ }
2221
+ };
2222
+ return s;
2223
+ },
2224
+
2225
+ _completePanGesture = function(animData) {
2226
+ // calculate swipe speed for Y axis (paanning)
2227
+ animData.calculateSwipeSpeed('y');
2228
+
2229
+ _currPanBounds = self.currItem.bounds;
2230
+
2231
+ animData.backAnimDestination = {};
2232
+ animData.backAnimStarted = {};
2233
+
2234
+ // Avoid acceleration animation if speed is too low
2235
+ if(Math.abs(animData.lastFlickSpeed.x) <= 0.05 && Math.abs(animData.lastFlickSpeed.y) <= 0.05 ) {
2236
+ animData.speedDecelerationRatioAbs.x = animData.speedDecelerationRatioAbs.y = 0;
2237
+
2238
+ // Run pan drag release animation. E.g. if you drag image and release finger without momentum.
2239
+ animData.calculateOverBoundsAnimOffset('x');
2240
+ animData.calculateOverBoundsAnimOffset('y');
2241
+ return true;
2242
+ }
2243
+
2244
+ // Animation loop that controls the acceleration after pan gesture ends
2245
+ _registerStartAnimation('zoomPan');
2246
+ animData.lastNow = _getCurrentTime();
2247
+ animData.panAnimLoop();
2248
+ },
2249
+
2250
+
2251
+ _finishSwipeMainScrollGesture = function(gestureType, _releaseAnimData) {
2252
+ var itemChanged;
2253
+ if(!_mainScrollAnimating) {
2254
+ _currZoomedItemIndex = _currentItemIndex;
2255
+ }
2256
+
2257
+
2258
+
2259
+ var itemsDiff;
2260
+
2261
+ if(gestureType === 'swipe') {
2262
+ var totalShiftDist = _currPoint.x - _startPoint.x,
2263
+ isFastLastFlick = _releaseAnimData.lastFlickDist.x < 10;
2264
+
2265
+ // if container is shifted for more than MIN_SWIPE_DISTANCE,
2266
+ // and last flick gesture was in right direction
2267
+ if(totalShiftDist > MIN_SWIPE_DISTANCE &&
2268
+ (isFastLastFlick || _releaseAnimData.lastFlickOffset.x > 20) ) {
2269
+ // go to prev item
2270
+ itemsDiff = -1;
2271
+ } else if(totalShiftDist < -MIN_SWIPE_DISTANCE &&
2272
+ (isFastLastFlick || _releaseAnimData.lastFlickOffset.x < -20) ) {
2273
+ // go to next item
2274
+ itemsDiff = 1;
2275
+ }
2276
+ }
2277
+
2278
+ var nextCircle;
2279
+
2280
+ if(itemsDiff) {
2281
+
2282
+ _currentItemIndex += itemsDiff;
2283
+
2284
+ if(_currentItemIndex < 0) {
2285
+ _currentItemIndex = _options.loop ? _getNumItems()-1 : 0;
2286
+ nextCircle = true;
2287
+ } else if(_currentItemIndex >= _getNumItems()) {
2288
+ _currentItemIndex = _options.loop ? 0 : _getNumItems()-1;
2289
+ nextCircle = true;
2290
+ }
2291
+
2292
+ if(!nextCircle || _options.loop) {
2293
+ _indexDiff += itemsDiff;
2294
+ _currPositionIndex -= itemsDiff;
2295
+ itemChanged = true;
2296
+ }
2297
+
2298
+
2299
+
2300
+ }
2301
+
2302
+ var animateToX = _slideSize.x * _currPositionIndex;
2303
+ var animateToDist = Math.abs( animateToX - _mainScrollPos.x );
2304
+ var finishAnimDuration;
2305
+
2306
+
2307
+ if(!itemChanged && animateToX > _mainScrollPos.x !== _releaseAnimData.lastFlickSpeed.x > 0) {
2308
+ // "return to current" duration, e.g. when dragging from slide 0 to -1
2309
+ finishAnimDuration = 333;
2310
+ } else {
2311
+ finishAnimDuration = Math.abs(_releaseAnimData.lastFlickSpeed.x) > 0 ?
2312
+ animateToDist / Math.abs(_releaseAnimData.lastFlickSpeed.x) :
2313
+ 333;
2314
+
2315
+ finishAnimDuration = Math.min(finishAnimDuration, 400);
2316
+ finishAnimDuration = Math.max(finishAnimDuration, 250);
2317
+ }
2318
+
2319
+ if(_currZoomedItemIndex === _currentItemIndex) {
2320
+ itemChanged = false;
2321
+ }
2322
+
2323
+ _mainScrollAnimating = true;
2324
+
2325
+ _shout('mainScrollAnimStart');
2326
+
2327
+ _animateProp('mainScroll', _mainScrollPos.x, animateToX, finishAnimDuration, framework.easing.cubic.out,
2328
+ _moveMainScroll,
2329
+ function() {
2330
+ _stopAllAnimations();
2331
+ _mainScrollAnimating = false;
2332
+ _currZoomedItemIndex = -1;
2333
+
2334
+ if(itemChanged || _currZoomedItemIndex !== _currentItemIndex) {
2335
+ self.updateCurrItem();
2336
+ }
2337
+
2338
+ _shout('mainScrollAnimComplete');
2339
+ }
2340
+ );
2341
+
2342
+ if(itemChanged) {
2343
+ self.updateCurrItem(true);
2344
+ }
2345
+
2346
+ return itemChanged;
2347
+ },
2348
+
2349
+ _calculateZoomLevel = function(touchesDistance) {
2350
+ return 1 / _startPointsDistance * touchesDistance * _startZoomLevel;
2351
+ },
2352
+
2353
+ // Resets zoom if it's out of bounds
2354
+ _completeZoomGesture = function() {
2355
+ var destZoomLevel = _currZoomLevel,
2356
+ minZoomLevel = _getMinZoomLevel(),
2357
+ maxZoomLevel = _getMaxZoomLevel();
2358
+
2359
+ if ( _currZoomLevel < minZoomLevel ) {
2360
+ destZoomLevel = minZoomLevel;
2361
+ } else if ( _currZoomLevel > maxZoomLevel ) {
2362
+ destZoomLevel = maxZoomLevel;
2363
+ }
2364
+
2365
+ var destOpacity = 1,
2366
+ onUpdate,
2367
+ initialOpacity = _bgOpacity;
2368
+
2369
+ if(_opacityChanged && !_isZoomingIn && !_wasOverInitialZoom && _currZoomLevel < minZoomLevel) {
2370
+ //_closedByScroll = true;
2371
+ self.close();
2372
+ return true;
2373
+ }
2374
+
2375
+ if(_opacityChanged) {
2376
+ onUpdate = function(now) {
2377
+
2378
+ _applyBgOpacity( (destOpacity - initialOpacity) * now + initialOpacity );
2379
+
2380
+ };
2381
+ }
2382
+
2383
+ self.zoomTo(destZoomLevel, 0, 300, framework.easing.cubic.out, onUpdate);
2384
+ return true;
2385
+ };
2386
+
2387
+
2388
+ _registerModule('Gestures', {
2389
+ publicMethods: {
2390
+
2391
+ initGestures: function() {
2392
+
2393
+ // helper function that builds touch/pointer/mouse events
2394
+ var addEventNames = function(pref, down, move, up, cancel) {
2395
+ _dragStartEvent = pref + down;
2396
+ _dragMoveEvent = pref + move;
2397
+ _dragEndEvent = pref + up;
2398
+ if(cancel) {
2399
+ _dragCancelEvent = pref + cancel;
2400
+ } else {
2401
+ _dragCancelEvent = '';
2402
+ }
2403
+ };
2404
+
2405
+ _pointerEventEnabled = _features.pointerEvent;
2406
+ if(_pointerEventEnabled && _features.touch) {
2407
+ // we don't need touch events, if browser supports pointer events
2408
+ _features.touch = false;
2409
+ }
2410
+
2411
+ if(_pointerEventEnabled) {
2412
+ if(navigator.pointerEnabled) {
2413
+ addEventNames('pointer', 'down', 'move', 'up', 'cancel');
2414
+ } else {
2415
+ // IE10 pointer events are case-sensitive
2416
+ addEventNames('MSPointer', 'Down', 'Move', 'Up', 'Cancel');
2417
+ }
2418
+ } else if(_features.touch) {
2419
+ addEventNames('touch', 'start', 'move', 'end', 'cancel');
2420
+ _likelyTouchDevice = true;
2421
+ } else {
2422
+ addEventNames('mouse', 'down', 'move', 'up');
2423
+ }
2424
+
2425
+ _upMoveEvents = _dragMoveEvent + ' ' + _dragEndEvent + ' ' + _dragCancelEvent;
2426
+ _downEvents = _dragStartEvent;
2427
+
2428
+ if(_pointerEventEnabled && !_likelyTouchDevice) {
2429
+ _likelyTouchDevice = (navigator.maxTouchPoints > 1) || (navigator.msMaxTouchPoints > 1);
2430
+ }
2431
+ // make variable public
2432
+ self.likelyTouchDevice = _likelyTouchDevice;
2433
+
2434
+ _globalEventHandlers[_dragStartEvent] = _onDragStart;
2435
+ _globalEventHandlers[_dragMoveEvent] = _onDragMove;
2436
+ _globalEventHandlers[_dragEndEvent] = _onDragRelease; // the Kraken
2437
+
2438
+ if(_dragCancelEvent) {
2439
+ _globalEventHandlers[_dragCancelEvent] = _globalEventHandlers[_dragEndEvent];
2440
+ }
2441
+
2442
+ // Bind mouse events on device with detected hardware touch support, in case it supports multiple types of input.
2443
+ if(_features.touch) {
2444
+ _downEvents += ' mousedown';
2445
+ _upMoveEvents += ' mousemove mouseup';
2446
+ _globalEventHandlers.mousedown = _globalEventHandlers[_dragStartEvent];
2447
+ _globalEventHandlers.mousemove = _globalEventHandlers[_dragMoveEvent];
2448
+ _globalEventHandlers.mouseup = _globalEventHandlers[_dragEndEvent];
2449
+ }
2450
+
2451
+ if(!_likelyTouchDevice) {
2452
+ // don't allow pan to next slide from zoomed state on Desktop
2453
+ _options.allowPanToNext = false;
2454
+ }
2455
+ }
2456
+
2457
+ }
2458
+ });
2459
+
2460
+
2461
+ /*>>gestures*/
2462
+
2463
+ /*>>show-hide-transition*/
2464
+ /**
2465
+ * show-hide-transition.js:
2466
+ *
2467
+ * Manages initial opening or closing transition.
2468
+ *
2469
+ * If you're not planning to use transition for gallery at all,
2470
+ * you may set options hideAnimationDuration and showAnimationDuration to 0,
2471
+ * and just delete startAnimation function.
2472
+ *
2473
+ */
2474
+
2475
+
2476
+ var _showOrHideTimeout,
2477
+ _showOrHide = function(item, img, out, completeFn) {
2478
+
2479
+ if(_showOrHideTimeout) {
2480
+ clearTimeout(_showOrHideTimeout);
2481
+ }
2482
+
2483
+ _initialZoomRunning = true;
2484
+ _initialContentSet = true;
2485
+
2486
+ // dimensions of small thumbnail {x:,y:,w:}.
2487
+ // Height is optional, as calculated based on large image.
2488
+ var thumbBounds;
2489
+ if(item.initialLayout) {
2490
+ thumbBounds = item.initialLayout;
2491
+ item.initialLayout = null;
2492
+ } else {
2493
+ thumbBounds = _options.getThumbBoundsFn && _options.getThumbBoundsFn(_currentItemIndex);
2494
+ }
2495
+
2496
+ var duration = out ? _options.hideAnimationDuration : _options.showAnimationDuration;
2497
+
2498
+ var onComplete = function() {
2499
+ _stopAnimation('initialZoom');
2500
+ if(!out) {
2501
+ _applyBgOpacity(1);
2502
+ if(img) {
2503
+ img.style.display = 'block';
2504
+ }
2505
+ framework.addClass(template, 'pswp--animated-in');
2506
+ _shout('initialZoom' + (out ? 'OutEnd' : 'InEnd'));
2507
+ } else {
2508
+ self.template.removeAttribute('style');
2509
+ self.bg.removeAttribute('style');
2510
+ }
2511
+
2512
+ if(completeFn) {
2513
+ completeFn();
2514
+ }
2515
+ _initialZoomRunning = false;
2516
+ };
2517
+
2518
+ // if bounds aren't provided, just open gallery without animation
2519
+ if(!duration || !thumbBounds || thumbBounds.x === undefined) {
2520
+
2521
+ var finishWithoutAnimation = function() {
2522
+ _shout('initialZoom' + (out ? 'Out' : 'In') );
2523
+
2524
+ _currZoomLevel = item.initialZoomLevel;
2525
+ _equalizePoints(_panOffset, item.initialPosition );
2526
+ _applyCurrentZoomPan();
2527
+
2528
+ // no transition
2529
+ template.style.opacity = out ? 0 : 1;
2530
+ _applyBgOpacity(1);
2531
+
2532
+ onComplete();
2533
+ };
2534
+ finishWithoutAnimation();
2535
+
2536
+ return;
2537
+ }
2538
+
2539
+ var startAnimation = function() {
2540
+ var closeWithRaf = _closedByScroll,
2541
+ fadeEverything = !self.currItem.src || self.currItem.loadError || _options.showHideOpacity;
2542
+
2543
+ // apply hw-acceleration to image
2544
+ if(item.miniImg) {
2545
+ item.miniImg.style.webkitBackfaceVisibility = 'hidden';
2546
+ }
2547
+
2548
+ if(!out) {
2549
+ _currZoomLevel = thumbBounds.w / item.w;
2550
+ _panOffset.x = thumbBounds.x;
2551
+ _panOffset.y = thumbBounds.y - _initalWindowScrollY;
2552
+
2553
+ self[fadeEverything ? 'template' : 'bg'].style.opacity = 0.001;
2554
+ _applyCurrentZoomPan();
2555
+ }
2556
+
2557
+ _registerStartAnimation('initialZoom');
2558
+
2559
+ if(out && !closeWithRaf) {
2560
+ framework.removeClass(template, 'pswp--animated-in');
2561
+ }
2562
+
2563
+ if(fadeEverything) {
2564
+ if(out) {
2565
+ framework[ (closeWithRaf ? 'remove' : 'add') + 'Class' ](template, 'pswp--animate_opacity');
2566
+ } else {
2567
+ setTimeout(function() {
2568
+ framework.addClass(template, 'pswp--animate_opacity');
2569
+ }, 30);
2570
+ }
2571
+ }
2572
+
2573
+ _showOrHideTimeout = setTimeout(function() {
2574
+
2575
+ _shout('initialZoom' + (out ? 'Out' : 'In') );
2576
+
2577
+
2578
+ if(!out) {
2579
+
2580
+ // "in" animation always uses CSS transitions (instead of rAF).
2581
+ // CSS transition work faster here,
2582
+ // as developer may also want to animate other things,
2583
+ // like ui on top of sliding area, which can be animated just via CSS
2584
+
2585
+ _currZoomLevel = item.initialZoomLevel;
2586
+ _equalizePoints(_panOffset, item.initialPosition );
2587
+ _applyCurrentZoomPan();
2588
+ _applyBgOpacity(1);
2589
+
2590
+ if(fadeEverything) {
2591
+ template.style.opacity = 1;
2592
+ } else {
2593
+ _applyBgOpacity(1);
2594
+ }
2595
+
2596
+ _showOrHideTimeout = setTimeout(onComplete, duration + 20);
2597
+ } else {
2598
+
2599
+ // "out" animation uses rAF only when PhotoSwipe is closed by browser scroll, to recalculate position
2600
+ var destZoomLevel = thumbBounds.w / item.w,
2601
+ initialPanOffset = {
2602
+ x: _panOffset.x,
2603
+ y: _panOffset.y
2604
+ },
2605
+ initialZoomLevel = _currZoomLevel,
2606
+ initalBgOpacity = _bgOpacity,
2607
+ onUpdate = function(now) {
2608
+
2609
+ if(now === 1) {
2610
+ _currZoomLevel = destZoomLevel;
2611
+ _panOffset.x = thumbBounds.x;
2612
+ _panOffset.y = thumbBounds.y - _currentWindowScrollY;
2613
+ } else {
2614
+ _currZoomLevel = (destZoomLevel - initialZoomLevel) * now + initialZoomLevel;
2615
+ _panOffset.x = (thumbBounds.x - initialPanOffset.x) * now + initialPanOffset.x;
2616
+ _panOffset.y = (thumbBounds.y - _currentWindowScrollY - initialPanOffset.y) * now + initialPanOffset.y;
2617
+ }
2618
+
2619
+ _applyCurrentZoomPan();
2620
+ if(fadeEverything) {
2621
+ template.style.opacity = 1 - now;
2622
+ } else {
2623
+ _applyBgOpacity( initalBgOpacity - now * initalBgOpacity );
2624
+ }
2625
+ };
2626
+
2627
+ if(closeWithRaf) {
2628
+ _animateProp('initialZoom', 0, 1, duration, framework.easing.cubic.out, onUpdate, onComplete);
2629
+ } else {
2630
+ onUpdate(1);
2631
+ _showOrHideTimeout = setTimeout(onComplete, duration + 20);
2632
+ }
2633
+ }
2634
+
2635
+ }, out ? 25 : 90); // Main purpose of this delay is to give browser time to paint and
2636
+ // create composite layers of PhotoSwipe UI parts (background, controls, caption, arrows).
2637
+ // Which avoids lag at the beginning of scale transition.
2638
+ };
2639
+ startAnimation();
2640
+
2641
+
2642
+ };
2643
+
2644
+ /*>>show-hide-transition*/
2645
+
2646
+ /*>>items-controller*/
2647
+ /**
2648
+ *
2649
+ * Controller manages gallery items, their dimensions, and their content.
2650
+ *
2651
+ */
2652
+
2653
+ var _items,
2654
+ _tempPanAreaSize = {},
2655
+ _imagesToAppendPool = [],
2656
+ _initialContentSet,
2657
+ _initialZoomRunning,
2658
+ _controllerDefaultOptions = {
2659
+ index: 0,
2660
+ errorMsg: '<div class="pswp__error-msg"><a href="%url%" target="_blank">The image</a> could not be loaded.</div>',
2661
+ forceProgressiveLoading: false, // TODO
2662
+ preload: [1,1],
2663
+ getNumItemsFn: function() {
2664
+ return _items.length;
2665
+ }
2666
+ };
2667
+
2668
+
2669
+ var _getItemAt,
2670
+ _getNumItems,
2671
+ _initialIsLoop,
2672
+ _getZeroBounds = function() {
2673
+ return {
2674
+ center:{x:0,y:0},
2675
+ max:{x:0,y:0},
2676
+ min:{x:0,y:0}
2677
+ };
2678
+ },
2679
+ _calculateSingleItemPanBounds = function(item, realPanElementW, realPanElementH ) {
2680
+ var bounds = item.bounds;
2681
+
2682
+ // position of element when it's centered
2683
+ bounds.center.x = Math.round((_tempPanAreaSize.x - realPanElementW) / 2);
2684
+ bounds.center.y = Math.round((_tempPanAreaSize.y - realPanElementH) / 2) + item.vGap.top;
2685
+
2686
+ // maximum pan position
2687
+ bounds.max.x = (realPanElementW > _tempPanAreaSize.x) ?
2688
+ Math.round(_tempPanAreaSize.x - realPanElementW) :
2689
+ bounds.center.x;
2690
+
2691
+ bounds.max.y = (realPanElementH > _tempPanAreaSize.y) ?
2692
+ Math.round(_tempPanAreaSize.y - realPanElementH) + item.vGap.top :
2693
+ bounds.center.y;
2694
+
2695
+ // minimum pan position
2696
+ bounds.min.x = (realPanElementW > _tempPanAreaSize.x) ? 0 : bounds.center.x;
2697
+ bounds.min.y = (realPanElementH > _tempPanAreaSize.y) ? item.vGap.top : bounds.center.y;
2698
+ },
2699
+ _calculateItemSize = function(item, viewportSize, zoomLevel) {
2700
+
2701
+ if (item.src && !item.loadError) {
2702
+ var isInitial = !zoomLevel;
2703
+
2704
+ if(isInitial) {
2705
+ if(!item.vGap) {
2706
+ item.vGap = {top:0,bottom:0};
2707
+ }
2708
+ // allows overriding vertical margin for individual items
2709
+ _shout('parseVerticalMargin', item);
2710
+ }
2711
+
2712
+
2713
+ _tempPanAreaSize.x = viewportSize.x;
2714
+ _tempPanAreaSize.y = viewportSize.y - item.vGap.top - item.vGap.bottom;
2715
+
2716
+ if (isInitial) {
2717
+ var hRatio = _tempPanAreaSize.x / item.w;
2718
+ var vRatio = _tempPanAreaSize.y / item.h;
2719
+
2720
+ item.fitRatio = hRatio < vRatio ? hRatio : vRatio;
2721
+ //item.fillRatio = hRatio > vRatio ? hRatio : vRatio;
2722
+
2723
+ var scaleMode = _options.scaleMode;
2724
+
2725
+ if (scaleMode === 'orig') {
2726
+ zoomLevel = 1;
2727
+ } else if (scaleMode === 'fit') {
2728
+ zoomLevel = item.fitRatio;
2729
+ }
2730
+
2731
+ if (zoomLevel > 1) {
2732
+ zoomLevel = 1;
2733
+ }
2734
+
2735
+ item.initialZoomLevel = zoomLevel;
2736
+
2737
+ if(!item.bounds) {
2738
+ // reuse bounds object
2739
+ item.bounds = _getZeroBounds();
2740
+ }
2741
+ }
2742
+
2743
+ if(!zoomLevel) {
2744
+ return;
2745
+ }
2746
+
2747
+ _calculateSingleItemPanBounds(item, item.w * zoomLevel, item.h * zoomLevel);
2748
+
2749
+ if (isInitial && zoomLevel === item.initialZoomLevel) {
2750
+ item.initialPosition = item.bounds.center;
2751
+ }
2752
+
2753
+ return item.bounds;
2754
+ } else {
2755
+ item.w = item.h = 0;
2756
+ item.initialZoomLevel = item.fitRatio = 1;
2757
+ item.bounds = _getZeroBounds();
2758
+ item.initialPosition = item.bounds.center;
2759
+
2760
+ // if it's not image, we return zero bounds (content is not zoomable)
2761
+ return item.bounds;
2762
+ }
2763
+ return false;
2764
+ },
2765
+
2766
+
2767
+
2768
+
2769
+ _appendImage = function(index, item, baseDiv, img, preventAnimation, keepPlaceholder) {
2770
+
2771
+
2772
+ if(item.loadError) {
2773
+ return;
2774
+ }
2775
+
2776
+ var animate,
2777
+ isSwiping = self.isDragging() && !self.isZooming(),
2778
+ slideMightBeVisible = index === _currentItemIndex || self.isMainScrollAnimating() || isSwiping;
2779
+
2780
+ // fade in loaded image only when current holder is active, or might be visible
2781
+ if(!preventAnimation && (_likelyTouchDevice || _options.alwaysFadeIn) && slideMightBeVisible) {
2782
+ animate = true;
2783
+ }
2784
+
2785
+ if(img) {
2786
+ if(animate) {
2787
+ img.style.opacity = 0;
2788
+ }
2789
+
2790
+ item.imageAppended = true;
2791
+ _setImageSize(img, item.w, item.h);
2792
+
2793
+ baseDiv.appendChild(img);
2794
+
2795
+ if(animate) {
2796
+ setTimeout(function() {
2797
+ img.style.opacity = 1;
2798
+ if(keepPlaceholder) {
2799
+ setTimeout(function() {
2800
+ // hide image placeholder "behind"
2801
+ if(item && item.loaded && item.placeholder) {
2802
+ item.placeholder.style.display = 'none';
2803
+ item.placeholder = null;
2804
+ }
2805
+ }, 500);
2806
+ }
2807
+ }, 50);
2808
+ }
2809
+ }
2810
+ },
2811
+
2812
+
2813
+
2814
+ _preloadImage = function(item) {
2815
+ item.loading = true;
2816
+ item.loaded = false;
2817
+ var img = item.img = framework.createEl('pswp__img', 'img');
2818
+ var onComplete = function() {
2819
+ item.loading = false;
2820
+ item.loaded = true;
2821
+
2822
+ if(item.loadComplete) {
2823
+ item.loadComplete(item);
2824
+ } else {
2825
+ item.img = null; // no need to store image object
2826
+ }
2827
+ img.onload = img.onerror = null;
2828
+ img = null;
2829
+ };
2830
+ img.onload = onComplete;
2831
+ img.onerror = function() {
2832
+ item.loadError = true;
2833
+ onComplete();
2834
+ };
2835
+
2836
+ img.src = item.src;// + '?a=' + Math.random();
2837
+
2838
+ return img;
2839
+ },
2840
+ _checkForError = function(item, cleanUp) {
2841
+ if(item.src && item.loadError && item.container) {
2842
+
2843
+ if(cleanUp) {
2844
+ item.container.innerHTML = '';
2845
+ }
2846
+
2847
+ item.container.innerHTML = _options.errorMsg.replace('%url%', item.src );
2848
+ return true;
2849
+
2850
+ }
2851
+ },
2852
+ _setImageSize = function(img, w, h) {
2853
+ img.style.width = w + 'px';
2854
+ img.style.height = h + 'px';
2855
+ },
2856
+ _appendImagesPool = function() {
2857
+
2858
+ if(_imagesToAppendPool.length) {
2859
+ var poolItem;
2860
+
2861
+ for(var i = 0; i < _imagesToAppendPool.length; i++) {
2862
+ poolItem = _imagesToAppendPool[i];
2863
+ if( poolItem.holder.index === poolItem.index ) {
2864
+ _appendImage(poolItem.index, poolItem.item, poolItem.baseDiv, poolItem.img);
2865
+ }
2866
+ }
2867
+ _imagesToAppendPool = [];
2868
+ }
2869
+ };
2870
+
2871
+
2872
+
2873
+ _registerModule('Controller', {
2874
+
2875
+ publicMethods: {
2876
+
2877
+ lazyLoadItem: function(index) {
2878
+ index = _getLoopedId(index);
2879
+ var item = _getItemAt(index);
2880
+
2881
+ if(!item || item.loaded || item.loading) {
2882
+ return;
2883
+ }
2884
+
2885
+ _shout('gettingData', index, item);
2886
+
2887
+ if (!item.src) {
2888
+ return;
2889
+ }
2890
+
2891
+ _preloadImage(item);
2892
+ },
2893
+ initController: function() {
2894
+ framework.extend(_options, _controllerDefaultOptions, true);
2895
+ self.items = _items = items;
2896
+ _getItemAt = self.getItemAt;
2897
+ _getNumItems = _options.getNumItemsFn; //self.getNumItems;
2898
+
2899
+
2900
+
2901
+ _initialIsLoop = _options.loop;
2902
+ if(_getNumItems() < 3) {
2903
+ _options.loop = false; // disable loop if less then 3 items
2904
+ }
2905
+
2906
+ _listen('beforeChange', function(diff) {
2907
+
2908
+ var p = _options.preload,
2909
+ isNext = diff === null ? true : (diff > 0),
2910
+ preloadBefore = Math.min(p[0], _getNumItems() ),
2911
+ preloadAfter = Math.min(p[1], _getNumItems() ),
2912
+ i;
2913
+
2914
+
2915
+ for(i = 1; i <= (isNext ? preloadAfter : preloadBefore); i++) {
2916
+ self.lazyLoadItem(_currentItemIndex+i);
2917
+ }
2918
+ for(i = 1; i <= (isNext ? preloadBefore : preloadAfter); i++) {
2919
+ self.lazyLoadItem(_currentItemIndex-i);
2920
+ }
2921
+ });
2922
+
2923
+ _listen('initialLayout', function() {
2924
+ self.currItem.initialLayout = _options.getThumbBoundsFn && _options.getThumbBoundsFn(_currentItemIndex);
2925
+ });
2926
+
2927
+ _listen('mainScrollAnimComplete', _appendImagesPool);
2928
+ _listen('initialZoomInEnd', _appendImagesPool);
2929
+
2930
+
2931
+
2932
+ _listen('destroy', function() {
2933
+ var item;
2934
+ for(var i = 0; i < _items.length; i++) {
2935
+ item = _items[i];
2936
+ // remove reference to DOM elements, for GC
2937
+ if(item.container) {
2938
+ item.container = null;
2939
+ }
2940
+ if(item.placeholder) {
2941
+ item.placeholder = null;
2942
+ }
2943
+ if(item.img) {
2944
+ item.img = null;
2945
+ }
2946
+ if(item.preloader) {
2947
+ item.preloader = null;
2948
+ }
2949
+ if(item.loadError) {
2950
+ item.loaded = item.loadError = false;
2951
+ }
2952
+ }
2953
+ _imagesToAppendPool = null;
2954
+ });
2955
+ },
2956
+
2957
+
2958
+ getItemAt: function(index) {
2959
+ if (index >= 0) {
2960
+ return _items[index] !== undefined ? _items[index] : false;
2961
+ }
2962
+ return false;
2963
+ },
2964
+
2965
+ allowProgressiveImg: function() {
2966
+ // 1. Progressive image loading isn't working on webkit/blink
2967
+ // when hw-acceleration (e.g. translateZ) is applied to IMG element.
2968
+ // That's why in PhotoSwipe parent element gets zoom transform, not image itself.
2969
+ //
2970
+ // 2. Progressive image loading sometimes blinks in webkit/blink when applying animation to parent element.
2971
+ // That's why it's disabled on touch devices (mainly because of swipe transition)
2972
+ //
2973
+ // 3. Progressive image loading sometimes doesn't work in IE (up to 11).
2974
+
2975
+ // Don't allow progressive loading on non-large touch devices
2976
+ return _options.forceProgressiveLoading || !_likelyTouchDevice || _options.mouseUsed || screen.width > 1200;
2977
+ // 1200 - to eliminate touch devices with large screen (like Chromebook Pixel)
2978
+ },
2979
+
2980
+ setContent: function(holder, index) {
2981
+
2982
+ if(_options.loop) {
2983
+ index = _getLoopedId(index);
2984
+ }
2985
+
2986
+ var prevItem = self.getItemAt(holder.index);
2987
+ if(prevItem) {
2988
+ prevItem.container = null;
2989
+ }
2990
+
2991
+ var item = self.getItemAt(index),
2992
+ img;
2993
+
2994
+ if(!item) {
2995
+ holder.el.innerHTML = '';
2996
+ return;
2997
+ }
2998
+
2999
+ // allow to override data
3000
+ _shout('gettingData', index, item);
3001
+
3002
+ holder.index = index;
3003
+ holder.item = item;
3004
+
3005
+ // base container DIV is created only once for each of 3 holders
3006
+ var baseDiv = item.container = framework.createEl('pswp__zoom-wrap');
3007
+
3008
+
3009
+
3010
+ if(!item.src && item.html) {
3011
+ if(item.html.tagName) {
3012
+ baseDiv.appendChild(item.html);
3013
+ } else {
3014
+ baseDiv.innerHTML = item.html;
3015
+ }
3016
+ }
3017
+
3018
+ _checkForError(item);
3019
+
3020
+ if(item.src && !item.loadError && !item.loaded) {
3021
+
3022
+ item.loadComplete = function(item) {
3023
+
3024
+ // gallery closed before image finished loading
3025
+ if(!_isOpen) {
3026
+ return;
3027
+ }
3028
+
3029
+ // Apply hw-acceleration only after image is loaded.
3030
+ // This is webkit progressive image loading bugfix.
3031
+ // https://bugs.webkit.org/show_bug.cgi?id=108630
3032
+ // https://code.google.com/p/chromium/issues/detail?id=404547
3033
+ if(item.img) {
3034
+ item.img.style.webkitBackfaceVisibility = 'hidden';
3035
+ }
3036
+
3037
+ // check if holder hasn't changed while image was loading
3038
+ if(holder && holder.index === index ) {
3039
+ if( _checkForError(item, true) ) {
3040
+ item.loadComplete = item.img = null;
3041
+ _calculateItemSize(item, _viewportSize);
3042
+ _applyZoomPanToItem(item);
3043
+
3044
+ if(holder.index === _currentItemIndex) {
3045
+ // recalculate dimensions
3046
+ self.updateCurrZoomItem();
3047
+ }
3048
+ return;
3049
+ }
3050
+ if( !item.imageAppended ) {
3051
+ if(_features.transform && (_mainScrollAnimating || _initialZoomRunning) ) {
3052
+ _imagesToAppendPool.push({
3053
+ item:item,
3054
+ baseDiv:baseDiv,
3055
+ img:item.img,
3056
+ index:index,
3057
+ holder:holder
3058
+ });
3059
+ } else {
3060
+ _appendImage(index, item, baseDiv, item.img, _mainScrollAnimating || _initialZoomRunning);
3061
+ }
3062
+ } else {
3063
+ // remove preloader & mini-img
3064
+ if(!_initialZoomRunning && item.placeholder) {
3065
+ item.placeholder.style.display = 'none';
3066
+ item.placeholder = null;
3067
+ }
3068
+ }
3069
+ }
3070
+
3071
+ item.loadComplete = null;
3072
+ item.img = null; // no need to store image element after it's added
3073
+
3074
+ _shout('imageLoadComplete', index, item);
3075
+ };
3076
+
3077
+ if(framework.features.transform) {
3078
+
3079
+ var placeholderClassName = 'pswp__img pswp__img--placeholder';
3080
+ placeholderClassName += (item.msrc ? '' : ' pswp__img--placeholder--blank');
3081
+
3082
+ var placeholder = framework.createEl(placeholderClassName, item.msrc ? 'img' : '');
3083
+ if(item.msrc) {
3084
+ placeholder.src = item.msrc;
3085
+ }
3086
+
3087
+ _setImageSize(placeholder, item.w, item.h);
3088
+
3089
+ baseDiv.appendChild(placeholder);
3090
+ item.placeholder = placeholder;
3091
+
3092
+ }
3093
+
3094
+
3095
+
3096
+
3097
+ if(!item.loading) {
3098
+ _preloadImage(item);
3099
+ }
3100
+
3101
+
3102
+ if( self.allowProgressiveImg() ) {
3103
+ // just append image
3104
+ if(!_initialContentSet && _features.transform) {
3105
+ _imagesToAppendPool.push({
3106
+ item:item,
3107
+ baseDiv:baseDiv,
3108
+ img:item.img,
3109
+ index:index,
3110
+ holder:holder
3111
+ });
3112
+ } else {
3113
+ _appendImage(index, item, baseDiv, item.img, true, true);
3114
+ }
3115
+ }
3116
+
3117
+ } else if(item.src && !item.loadError) {
3118
+ // image object is created every time, due to bugs of image loading & delay when switching images
3119
+ img = framework.createEl('pswp__img', 'img');
3120
+ img.style.webkitBackfaceVisibility = 'hidden';
3121
+ img.style.opacity = 1;
3122
+ img.src = item.src;
3123
+ _setImageSize(img, item.w, item.h);
3124
+ _appendImage(index, item, baseDiv, img, true);
3125
+ }
3126
+
3127
+ _calculateItemSize(item, _viewportSize);
3128
+
3129
+ if(!_initialContentSet && index === _currentItemIndex) {
3130
+ _currZoomElementStyle = baseDiv.style;
3131
+ _showOrHide(item, (img ||item.img) );
3132
+ } else {
3133
+ _applyZoomPanToItem(item);
3134
+ }
3135
+
3136
+ holder.el.innerHTML = '';
3137
+ holder.el.appendChild(baseDiv);
3138
+ },
3139
+
3140
+ cleanSlide: function( item ) {
3141
+ if(item.img ) {
3142
+ item.img.onload = item.img.onerror = null;
3143
+ }
3144
+ item.loaded = item.loading = item.img = item.imageAppended = false;
3145
+ }
3146
+
3147
+ }
3148
+ });
3149
+
3150
+ /*>>items-controller*/
3151
+
3152
+ /*>>tap*/
3153
+ /**
3154
+ * tap.js:
3155
+ *
3156
+ * Displatches tap and double-tap events.
3157
+ *
3158
+ */
3159
+
3160
+ var tapTimer,
3161
+ tapReleasePoint = {},
3162
+ _dispatchTapEvent = function(origEvent, releasePoint, pointerType) {
3163
+ var e = document.createEvent( 'CustomEvent' ),
3164
+ eDetail = {
3165
+ origEvent:origEvent,
3166
+ target:origEvent.target,
3167
+ releasePoint: releasePoint,
3168
+ pointerType:pointerType || 'touch'
3169
+ };
3170
+
3171
+ e.initCustomEvent( 'pswpTap', true, true, eDetail );
3172
+ origEvent.target.dispatchEvent(e);
3173
+ };
3174
+
3175
+ _registerModule('Tap', {
3176
+ publicMethods: {
3177
+ initTap: function() {
3178
+ _listen('firstTouchStart', self.onTapStart);
3179
+ _listen('touchRelease', self.onTapRelease);
3180
+ _listen('destroy', function() {
3181
+ tapReleasePoint = {};
3182
+ tapTimer = null;
3183
+ });
3184
+ },
3185
+ onTapStart: function(touchList) {
3186
+ if(touchList.length > 1) {
3187
+ clearTimeout(tapTimer);
3188
+ tapTimer = null;
3189
+ }
3190
+ },
3191
+ onTapRelease: function(e, releasePoint) {
3192
+ if(!releasePoint) {
3193
+ return;
3194
+ }
3195
+
3196
+ if(!_moved && !_isMultitouch && !_numAnimations) {
3197
+ var p0 = releasePoint;
3198
+ if(tapTimer) {
3199
+ clearTimeout(tapTimer);
3200
+ tapTimer = null;
3201
+
3202
+ // Check if taped on the same place
3203
+ if ( _isNearbyPoints(p0, tapReleasePoint) ) {
3204
+ _shout('doubleTap', p0);
3205
+ return;
3206
+ }
3207
+ }
3208
+
3209
+ if(releasePoint.type === 'mouse') {
3210
+ _dispatchTapEvent(e, releasePoint, 'mouse');
3211
+ return;
3212
+ }
3213
+
3214
+ var clickedTagName = e.target.tagName.toUpperCase();
3215
+ // avoid double tap delay on buttons and elements that have class pswp__single-tap
3216
+ if(clickedTagName === 'BUTTON' || framework.hasClass(e.target, 'pswp__single-tap') ) {
3217
+ _dispatchTapEvent(e, releasePoint);
3218
+ return;
3219
+ }
3220
+
3221
+ _equalizePoints(tapReleasePoint, p0);
3222
+
3223
+ tapTimer = setTimeout(function() {
3224
+ _dispatchTapEvent(e, releasePoint);
3225
+ tapTimer = null;
3226
+ }, 300);
3227
+ }
3228
+ }
3229
+ }
3230
+ });
3231
+
3232
+ /*>>tap*/
3233
+
3234
+ /*>>desktop-zoom*/
3235
+ /**
3236
+ *
3237
+ * desktop-zoom.js:
3238
+ *
3239
+ * - Binds mousewheel event for paning zoomed image.
3240
+ * - Manages "dragging", "zoomed-in", "zoom-out" classes.
3241
+ * (which are used for cursors and zoom icon)
3242
+ * - Adds toggleDesktopZoom function.
3243
+ *
3244
+ */
3245
+
3246
+ var _wheelDelta;
3247
+
3248
+ _registerModule('DesktopZoom', {
3249
+
3250
+ publicMethods: {
3251
+
3252
+ initDesktopZoom: function() {
3253
+
3254
+ if(_oldIE) {
3255
+ // no zoom for old IE (<=8)
3256
+ return;
3257
+ }
3258
+
3259
+ if(_likelyTouchDevice) {
3260
+ // if detected hardware touch support, we wait until mouse is used,
3261
+ // and only then apply desktop-zoom features
3262
+ _listen('mouseUsed', function() {
3263
+ self.setupDesktopZoom();
3264
+ });
3265
+ } else {
3266
+ self.setupDesktopZoom(true);
3267
+ }
3268
+
3269
+ },
3270
+
3271
+ setupDesktopZoom: function(onInit) {
3272
+
3273
+ _wheelDelta = {};
3274
+
3275
+ var events = 'wheel mousewheel DOMMouseScroll';
3276
+
3277
+ _listen('bindEvents', function() {
3278
+ framework.bind(template, events, self.handleMouseWheel);
3279
+ });
3280
+
3281
+ _listen('unbindEvents', function() {
3282
+ if(_wheelDelta) {
3283
+ framework.unbind(template, events, self.handleMouseWheel);
3284
+ }
3285
+ });
3286
+
3287
+ self.mouseZoomedIn = false;
3288
+
3289
+ var hasDraggingClass,
3290
+ updateZoomable = function() {
3291
+ if(self.mouseZoomedIn) {
3292
+ framework.removeClass(template, 'pswp--zoomed-in');
3293
+ self.mouseZoomedIn = false;
3294
+ }
3295
+ if(_currZoomLevel < 1) {
3296
+ framework.addClass(template, 'pswp--zoom-allowed');
3297
+ } else {
3298
+ framework.removeClass(template, 'pswp--zoom-allowed');
3299
+ }
3300
+ removeDraggingClass();
3301
+ },
3302
+ removeDraggingClass = function() {
3303
+ if(hasDraggingClass) {
3304
+ framework.removeClass(template, 'pswp--dragging');
3305
+ hasDraggingClass = false;
3306
+ }
3307
+ };
3308
+
3309
+ _listen('resize' , updateZoomable);
3310
+ _listen('afterChange' , updateZoomable);
3311
+ _listen('pointerDown', function() {
3312
+ if(self.mouseZoomedIn) {
3313
+ hasDraggingClass = true;
3314
+ framework.addClass(template, 'pswp--dragging');
3315
+ }
3316
+ });
3317
+ _listen('pointerUp', removeDraggingClass);
3318
+
3319
+ if(!onInit) {
3320
+ updateZoomable();
3321
+ }
3322
+
3323
+ },
3324
+
3325
+ handleMouseWheel: function(e) {
3326
+
3327
+ if(_currZoomLevel <= self.currItem.fitRatio) {
3328
+ if( _options.modal ) {
3329
+
3330
+ if ( !_options.closeOnScroll ) {
3331
+ e.preventDefault();
3332
+ } else if( _transformKey && Math.abs(e.deltaY) > 2 ) {
3333
+ // close PhotoSwipe
3334
+ // if browser supports transforms & scroll changed enough
3335
+ _closedByScroll = true;
3336
+ self.close();
3337
+ }
3338
+
3339
+ }
3340
+ return true;
3341
+ }
3342
+
3343
+ // allow just one event to fire
3344
+ e.stopPropagation();
3345
+
3346
+ // https://developer.mozilla.org/en-US/docs/Web/Events/wheel
3347
+ _wheelDelta.x = 0;
3348
+
3349
+ if('deltaX' in e) {
3350
+ if(e.deltaMode === 1 /* DOM_DELTA_LINE */) {
3351
+ // 18 - average line height
3352
+ _wheelDelta.x = e.deltaX * 18;
3353
+ _wheelDelta.y = e.deltaY * 18;
3354
+ } else {
3355
+ _wheelDelta.x = e.deltaX;
3356
+ _wheelDelta.y = e.deltaY;
3357
+ }
3358
+ } else if('wheelDelta' in e) {
3359
+ if(e.wheelDeltaX) {
3360
+ _wheelDelta.x = -0.16 * e.wheelDeltaX;
3361
+ }
3362
+ if(e.wheelDeltaY) {
3363
+ _wheelDelta.y = -0.16 * e.wheelDeltaY;
3364
+ } else {
3365
+ _wheelDelta.y = -0.16 * e.wheelDelta;
3366
+ }
3367
+ } else if('detail' in e) {
3368
+ _wheelDelta.y = e.detail;
3369
+ } else {
3370
+ return;
3371
+ }
3372
+
3373
+ _calculatePanBounds(_currZoomLevel, true);
3374
+
3375
+ var newPanX = _panOffset.x - _wheelDelta.x,
3376
+ newPanY = _panOffset.y - _wheelDelta.y;
3377
+
3378
+ // only prevent scrolling in nonmodal mode when not at edges
3379
+ if (_options.modal ||
3380
+ (
3381
+ newPanX <= _currPanBounds.min.x && newPanX >= _currPanBounds.max.x &&
3382
+ newPanY <= _currPanBounds.min.y && newPanY >= _currPanBounds.max.y
3383
+ ) ) {
3384
+ e.preventDefault();
3385
+ }
3386
+
3387
+ // TODO: use rAF instead of mousewheel?
3388
+ self.panTo(newPanX, newPanY);
3389
+ },
3390
+
3391
+ toggleDesktopZoom: function(centerPoint) {
3392
+ centerPoint = centerPoint || {x:_viewportSize.x/2 + _offset.x, y:_viewportSize.y/2 + _offset.y };
3393
+
3394
+ var doubleTapZoomLevel = _options.getDoubleTapZoom(true, self.currItem);
3395
+ var zoomOut = _currZoomLevel === doubleTapZoomLevel;
3396
+
3397
+ self.mouseZoomedIn = !zoomOut;
3398
+
3399
+ self.zoomTo(zoomOut ? self.currItem.initialZoomLevel : doubleTapZoomLevel, centerPoint, 333);
3400
+ framework[ (!zoomOut ? 'add' : 'remove') + 'Class'](template, 'pswp--zoomed-in');
3401
+ }
3402
+
3403
+ }
3404
+ });
3405
+
3406
+
3407
+ /*>>desktop-zoom*/
3408
+
3409
+ /*>>history*/
3410
+ /**
3411
+ *
3412
+ * history.js:
3413
+ *
3414
+ * - Back button to close gallery.
3415
+ *
3416
+ * - Unique URL for each slide: example.com/&pid=1&gid=3
3417
+ * (where PID is picture index, and GID and gallery index)
3418
+ *
3419
+ * - Switch URL when slides change.
3420
+ *
3421
+ */
3422
+
3423
+
3424
+ var _historyDefaultOptions = {
3425
+ history: true,
3426
+ galleryUID: 1
3427
+ };
3428
+
3429
+ var _historyUpdateTimeout,
3430
+ _hashChangeTimeout,
3431
+ _hashAnimCheckTimeout,
3432
+ _hashChangedByScript,
3433
+ _hashChangedByHistory,
3434
+ _hashReseted,
3435
+ _initialHash,
3436
+ _historyChanged,
3437
+ _closedFromURL,
3438
+ _urlChangedOnce,
3439
+ _windowLoc,
3440
+
3441
+ _supportsPushState,
3442
+
3443
+ _getHash = function() {
3444
+ return _windowLoc.hash.substring(1);
3445
+ },
3446
+ _cleanHistoryTimeouts = function() {
3447
+
3448
+ if(_historyUpdateTimeout) {
3449
+ clearTimeout(_historyUpdateTimeout);
3450
+ }
3451
+
3452
+ if(_hashAnimCheckTimeout) {
3453
+ clearTimeout(_hashAnimCheckTimeout);
3454
+ }
3455
+ },
3456
+
3457
+ // pid - Picture index
3458
+ // gid - Gallery index
3459
+ _parseItemIndexFromURL = function() {
3460
+ var hash = _getHash(),
3461
+ params = {};
3462
+
3463
+ if(hash.length < 5) { // pid=1
3464
+ return params;
3465
+ }
3466
+
3467
+ var i, vars = hash.split('&');
3468
+ for (i = 0; i < vars.length; i++) {
3469
+ if(!vars[i]) {
3470
+ continue;
3471
+ }
3472
+ var pair = vars[i].split('=');
3473
+ if(pair.length < 2) {
3474
+ continue;
3475
+ }
3476
+ params[pair[0]] = pair[1];
3477
+ }
3478
+ if(_options.galleryPIDs) {
3479
+ // detect custom pid in hash and search for it among the items collection
3480
+ var searchfor = params.pid;
3481
+ params.pid = 0; // if custom pid cannot be found, fallback to the first item
3482
+ for(i = 0; i < _items.length; i++) {
3483
+ if(_items[i].pid === searchfor) {
3484
+ params.pid = i;
3485
+ break;
3486
+ }
3487
+ }
3488
+ } else {
3489
+ params.pid = parseInt(params.pid,10)-1;
3490
+ }
3491
+ if( params.pid < 0 ) {
3492
+ params.pid = 0;
3493
+ }
3494
+ return params;
3495
+ },
3496
+ _updateHash = function() {
3497
+
3498
+ if(_hashAnimCheckTimeout) {
3499
+ clearTimeout(_hashAnimCheckTimeout);
3500
+ }
3501
+
3502
+
3503
+ if(_numAnimations || _isDragging) {
3504
+ // changing browser URL forces layout/paint in some browsers, which causes noticable lag during animation
3505
+ // that's why we update hash only when no animations running
3506
+ _hashAnimCheckTimeout = setTimeout(_updateHash, 500);
3507
+ return;
3508
+ }
3509
+
3510
+ if(_hashChangedByScript) {
3511
+ clearTimeout(_hashChangeTimeout);
3512
+ } else {
3513
+ _hashChangedByScript = true;
3514
+ }
3515
+
3516
+
3517
+ var pid = (_currentItemIndex + 1);
3518
+ var item = _getItemAt( _currentItemIndex );
3519
+ if(item.hasOwnProperty('pid')) {
3520
+ // carry forward any custom pid assigned to the item
3521
+ pid = item.pid;
3522
+ }
3523
+ var newHash = _initialHash + '&' + 'gid=' + _options.galleryUID + '&' + 'pid=' + pid;
3524
+
3525
+ if(!_historyChanged) {
3526
+ if(_windowLoc.hash.indexOf(newHash) === -1) {
3527
+ _urlChangedOnce = true;
3528
+ }
3529
+ // first time - add new hisory record, then just replace
3530
+ }
3531
+
3532
+ var newURL = _windowLoc.href.split('#')[0] + '#' + newHash;
3533
+
3534
+ if( _supportsPushState ) {
3535
+
3536
+ if('#' + newHash !== window.location.hash) {
3537
+ history[_historyChanged ? 'replaceState' : 'pushState']('', document.title, newURL);
3538
+ }
3539
+
3540
+ } else {
3541
+ if(_historyChanged) {
3542
+ _windowLoc.replace( newURL );
3543
+ } else {
3544
+ _windowLoc.hash = newHash;
3545
+ }
3546
+ }
3547
+
3548
+
3549
+
3550
+ _historyChanged = true;
3551
+ _hashChangeTimeout = setTimeout(function() {
3552
+ _hashChangedByScript = false;
3553
+ }, 60);
3554
+ };
3555
+
3556
+
3557
+
3558
+
3559
+
3560
+ _registerModule('History', {
3561
+
3562
+
3563
+
3564
+ publicMethods: {
3565
+ initHistory: function() {
3566
+
3567
+ framework.extend(_options, _historyDefaultOptions, true);
3568
+
3569
+ if( !_options.history ) {
3570
+ return;
3571
+ }
3572
+
3573
+
3574
+ _windowLoc = window.location;
3575
+ _urlChangedOnce = false;
3576
+ _closedFromURL = false;
3577
+ _historyChanged = false;
3578
+ _initialHash = _getHash();
3579
+ _supportsPushState = ('pushState' in history);
3580
+
3581
+
3582
+ if(_initialHash.indexOf('gid=') > -1) {
3583
+ _initialHash = _initialHash.split('&gid=')[0];
3584
+ _initialHash = _initialHash.split('?gid=')[0];
3585
+ }
3586
+
3587
+
3588
+ _listen('afterChange', self.updateURL);
3589
+ _listen('unbindEvents', function() {
3590
+ framework.unbind(window, 'hashchange', self.onHashChange);
3591
+ });
3592
+
3593
+
3594
+ var returnToOriginal = function() {
3595
+ _hashReseted = true;
3596
+ if(!_closedFromURL) {
3597
+
3598
+ if(_urlChangedOnce) {
3599
+ history.back();
3600
+ } else {
3601
+
3602
+ if(_initialHash) {
3603
+ _windowLoc.hash = _initialHash;
3604
+ } else {
3605
+ if (_supportsPushState) {
3606
+
3607
+ // remove hash from url without refreshing it or scrolling to top
3608
+ history.pushState('', document.title, _windowLoc.pathname + _windowLoc.search );
3609
+ } else {
3610
+ _windowLoc.hash = '';
3611
+ }
3612
+ }
3613
+ }
3614
+
3615
+ }
3616
+
3617
+ _cleanHistoryTimeouts();
3618
+ };
3619
+
3620
+
3621
+ _listen('unbindEvents', function() {
3622
+ if(_closedByScroll) {
3623
+ // if PhotoSwipe is closed by scroll, we go "back" before the closing animation starts
3624
+ // this is done to keep the scroll position
3625
+ returnToOriginal();
3626
+ }
3627
+ });
3628
+ _listen('destroy', function() {
3629
+ if(!_hashReseted) {
3630
+ returnToOriginal();
3631
+ }
3632
+ });
3633
+ _listen('firstUpdate', function() {
3634
+ _currentItemIndex = _parseItemIndexFromURL().pid;
3635
+ });
3636
+
3637
+
3638
+
3639
+
3640
+ var index = _initialHash.indexOf('pid=');
3641
+ if(index > -1) {
3642
+ _initialHash = _initialHash.substring(0, index);
3643
+ if(_initialHash.slice(-1) === '&') {
3644
+ _initialHash = _initialHash.slice(0, -1);
3645
+ }
3646
+ }
3647
+
3648
+
3649
+ setTimeout(function() {
3650
+ if(_isOpen) { // hasn't destroyed yet
3651
+ framework.bind(window, 'hashchange', self.onHashChange);
3652
+ }
3653
+ }, 40);
3654
+
3655
+ },
3656
+ onHashChange: function() {
3657
+
3658
+ if(_getHash() === _initialHash) {
3659
+
3660
+ _closedFromURL = true;
3661
+ self.close();
3662
+ return;
3663
+ }
3664
+ if(!_hashChangedByScript) {
3665
+
3666
+ _hashChangedByHistory = true;
3667
+ self.goTo( _parseItemIndexFromURL().pid );
3668
+ _hashChangedByHistory = false;
3669
+ }
3670
+
3671
+ },
3672
+ updateURL: function() {
3673
+
3674
+ // Delay the update of URL, to avoid lag during transition,
3675
+ // and to not to trigger actions like "refresh page sound" or "blinking favicon" to often
3676
+
3677
+ _cleanHistoryTimeouts();
3678
+
3679
+
3680
+ if(_hashChangedByHistory) {
3681
+ return;
3682
+ }
3683
+
3684
+ if(!_historyChanged) {
3685
+ _updateHash(); // first time
3686
+ } else {
3687
+ _historyUpdateTimeout = setTimeout(_updateHash, 800);
3688
+ }
3689
+ }
3690
+
3691
+ }
3692
+ });
3693
+
3694
+
3695
+ /*>>history*/
3696
+ framework.extend(self, publicMethods); };
3697
+ return PhotoSwipe;
3698
+ });