use touch start events for controls on touch devices
[reveal.js.git] / js / reveal.js
1 /*!
2  * reveal.js
3  * http://lab.hakim.se/reveal-js
4  * MIT licensed
5  *
6  * Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se
7  */
8 var Reveal = (function(){
9
10         'use strict';
11
12         var SLIDES_SELECTOR = '.reveal .slides section',
13                 HORIZONTAL_SLIDES_SELECTOR = '.reveal .slides>section',
14                 VERTICAL_SLIDES_SELECTOR = '.reveal .slides>section.present>section',
15
16                 // Configurations defaults, can be overridden at initialization time
17                 config = {
18                         // Display controls in the bottom right corner
19                         controls: true,
20
21                         // Display a presentation progress bar
22                         progress: true,
23
24                         // Push each slide change to the browser history
25                         history: false,
26
27                         // Enable keyboard shortcuts for navigation
28                         keyboard: true,
29
30                         // Enable the slide overview mode
31                         overview: true,
32
33                         // Vertical centering of slides
34                         center: true,
35
36                         // Loop the presentation
37                         loop: false,
38
39                         // Experimental support for RTL
40                         rtl: false,
41
42                         // Number of milliseconds between automatically proceeding to the
43                         // next slide, disabled when set to 0, this value can be overwritten
44                         // by using a data-autoslide attribute on your slides
45                         autoSlide: 0,
46
47                         // Enable slide navigation via mouse wheel
48                         mouseWheel: false,
49
50                         // Apply a 3D roll to links on hover
51                         rollingLinks: true,
52
53                         // Transition style (see /css/theme)
54                         theme: null,
55
56                         // Transition style
57                         transition: 'default', // default/cube/page/concave/zoom/linear/none
58
59                         // Script dependencies to load
60                         dependencies: []
61                 },
62
63                 // Stores if the next slide should be shown automatically
64                 // after n milliseconds
65                 autoSlide = config.autoSlide,
66
67                 // The horizontal and verical index of the currently active slide
68                 indexh = 0,
69                 indexv = 0,
70
71                 // The previous and current slide HTML elements
72                 previousSlide,
73                 currentSlide,
74
75                 // Slides may hold a data-state attribute which we pick up and apply
76                 // as a class to the body. This list contains the combined state of
77                 // all current slides.
78                 state = [],
79
80                 // Cached references to DOM elements
81                 dom = {},
82
83                 // Detect support for CSS 3D transforms
84                 supports3DTransforms =  'WebkitPerspective' in document.body.style ||
85                                                                 'MozPerspective' in document.body.style ||
86                                                                 'msPerspective' in document.body.style ||
87                                                                 'OPerspective' in document.body.style ||
88                                                                 'perspective' in document.body.style,
89
90                 supports2DTransforms =  'WebkitTransform' in document.body.style ||
91                                                                 'MozTransform' in document.body.style ||
92                                                                 'msTransform' in document.body.style ||
93                                                                 'OTransform' in document.body.style ||
94                                                                 'transform' in document.body.style,
95
96                 // Throttles mouse wheel navigation
97                 mouseWheelTimeout = 0,
98
99                 // An interval used to automatically move on to the next slide
100                 autoSlideTimeout = 0,
101
102                 // Delays updates to the URL due to a Chrome thumbnailer bug
103                 writeURLTimeout = 0,
104
105                 // Holds information about the currently ongoing touch input
106                 touch = {
107                         startX: 0,
108                         startY: 0,
109                         startSpan: 0,
110                         startCount: 0,
111                         handled: false,
112                         threshold: 80
113                 };
114
115         /**
116          * Starts up the presentation if the client is capable.
117          */
118         function initialize( options ) {
119                 if( ( !supports2DTransforms && !supports3DTransforms ) ) {
120                         document.body.setAttribute( 'class', 'no-transforms' );
121
122                         // If the browser doesn't support core features we won't be
123                         // using JavaScript to control the presentation
124                         return;
125                 }
126
127                 // Force a layout when the whole page, incl fonts, has loaded
128                 window.addEventListener( 'load', layout, false );
129
130                 // Copy options over to our config object
131                 extend( config, options );
132
133                 // Hide the address bar in mobile browsers
134                 hideAddressBar();
135
136                 // Loads the dependencies and continues to #start() once done
137                 load();
138
139         }
140
141         /**
142          * Finds and stores references to DOM elements which are
143          * required by the presentation. If a required element is
144          * not found, it is created.
145          */
146         function setupDOM() {
147                 // Cache references to key DOM elements
148                 dom.theme = document.querySelector( '#theme' );
149                 dom.wrapper = document.querySelector( '.reveal' );
150                 dom.slides = document.querySelector( '.reveal .slides' );
151
152                 // Progress bar
153                 if( !dom.wrapper.querySelector( '.progress' ) && config.progress ) {
154                         var progressElement = document.createElement( 'div' );
155                         progressElement.classList.add( 'progress' );
156                         progressElement.innerHTML = '<span></span>';
157                         dom.wrapper.appendChild( progressElement );
158                 }
159
160                 // Arrow controls
161                 if( !dom.wrapper.querySelector( '.controls' ) && config.controls ) {
162                         var controlsElement = document.createElement( 'aside' );
163                         controlsElement.classList.add( 'controls' );
164                         controlsElement.innerHTML = '<div class="navigate-left"></div>' +
165                                                                                 '<div class="navigate-right"></div>' +
166                                                                                 '<div class="navigate-up"></div>' +
167                                                                                 '<div class="navigate-down"></div>';
168                         dom.wrapper.appendChild( controlsElement );
169                 }
170
171                 // Presentation background element
172                 if( !dom.wrapper.querySelector( '.state-background' ) ) {
173                         var backgroundElement = document.createElement( 'div' );
174                         backgroundElement.classList.add( 'state-background' );
175                         dom.wrapper.appendChild( backgroundElement );
176                 }
177
178                 // Overlay graphic which is displayed during the paused mode
179                 if( !dom.wrapper.querySelector( '.pause-overlay' ) ) {
180                         var pausedElement = document.createElement( 'div' );
181                         pausedElement.classList.add( 'pause-overlay' );
182                         dom.wrapper.appendChild( pausedElement );
183                 }
184
185                 // Cache references to elements
186                 dom.progress = document.querySelector( '.reveal .progress' );
187                 dom.progressbar = document.querySelector( '.reveal .progress span' );
188
189                 if ( config.controls ) {
190                         dom.controls = document.querySelector( '.reveal .controls' );
191
192                         // There can be multiple instances of controls throughout the page
193                         dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
194                         dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
195                         dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
196                         dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
197                         dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
198                         dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
199                 }
200         }
201
202         /**
203          * Hides the address bar if we're on a mobile device.
204          */
205         function hideAddressBar() {
206                 if( navigator.userAgent.match( /(iphone|ipod)/i ) ) {
207                         // Give the page some scrollable overflow
208                         document.documentElement.style.overflow = 'scroll';
209                         document.body.style.height = '120%';
210
211                         // Events that should trigger the address bar to hide
212                         window.addEventListener( 'load', removeAddressBar, false );
213                         window.addEventListener( 'orientationchange', removeAddressBar, false );
214                 }
215         }
216
217         /**
218          * Loads the dependencies of reveal.js. Dependencies are
219          * defined via the configuration option 'dependencies'
220          * and will be loaded prior to starting/binding reveal.js.
221          * Some dependencies may have an 'async' flag, if so they
222          * will load after reveal.js has been started up.
223          */
224         function load() {
225                 var scripts = [],
226                         scriptsAsync = [];
227
228                 for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
229                         var s = config.dependencies[i];
230
231                         // Load if there's no condition or the condition is truthy
232                         if( !s.condition || s.condition() ) {
233                                 if( s.async ) {
234                                         scriptsAsync.push( s.src );
235                                 }
236                                 else {
237                                         scripts.push( s.src );
238                                 }
239
240                                 // Extension may contain callback functions
241                                 if( typeof s.callback === 'function' ) {
242                                         head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], s.callback );
243                                 }
244                         }
245                 }
246
247                 // Called once synchronous scritps finish loading
248                 function proceed() {
249                         if( scriptsAsync.length ) {
250                                 // Load asynchronous scripts
251                                 head.js.apply( null, scriptsAsync );
252                         }
253
254                         start();
255                 }
256
257                 if( scripts.length ) {
258                         head.ready( proceed );
259
260                         // Load synchronous scripts
261                         head.js.apply( null, scripts );
262                 }
263                 else {
264                         proceed();
265                 }
266         }
267
268         /**
269          * Starts up reveal.js by binding input events and navigating
270          * to the current URL deeplink if there is one.
271          */
272         function start() {
273                 // Make sure we've got all the DOM elements we need
274                 setupDOM();
275
276                 // Subscribe to input
277                 addEventListeners();
278
279                 // Updates the presentation to match the current configuration values
280                 configure();
281
282                 // Force an initial layout, will thereafter be invoked as the window
283                 // is resized
284                 layout();
285
286                 // Read the initial hash
287                 readURL();
288
289                 // Start auto-sliding if it's enabled
290                 cueAutoSlide();
291
292                 // Notify listeners that the presentation is ready but use a 1ms
293                 // timeout to ensure it's not fired synchronously after #initialize()
294                 setTimeout( function() {
295                         dispatchEvent( 'ready', {
296                                 'indexh': indexh,
297                                 'indexv': indexv,
298                                 'currentSlide': currentSlide
299                         } );
300                 }, 1 );
301         }
302
303         /**
304          * Applies the configuration settings from the config object.
305          */
306         function configure() {
307                 if( supports3DTransforms === false ) {
308                         config.transition = 'linear';
309                 }
310
311                 if( config.controls && dom.controls ) {
312                         dom.controls.style.display = 'block';
313                 }
314
315                 if( config.progress && dom.progress ) {
316                         dom.progress.style.display = 'block';
317                 }
318
319                 if( config.transition !== 'default' ) {
320                         dom.wrapper.classList.add( config.transition );
321                 }
322
323                 if( config.rtl ) {
324                         dom.wrapper.classList.add( 'rtl' );
325                 }
326
327                 if( config.center ) {
328                         dom.wrapper.classList.add( 'center' );
329                 }
330
331                 if( config.mouseWheel ) {
332                         document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
333                         document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
334                 }
335
336                 // 3D links
337                 if( config.rollingLinks ) {
338                         linkify();
339                 }
340
341                 // Load the theme in the config, if it's not already loaded
342                 if( config.theme && dom.theme ) {
343                         var themeURL = dom.theme.getAttribute( 'href' );
344                         var themeFinder = /[^\/]*?(?=\.css)/;
345                         var themeName = themeURL.match(themeFinder)[0];
346
347                         if(  config.theme !== themeName ) {
348                                 themeURL = themeURL.replace(themeFinder, config.theme);
349                                 dom.theme.setAttribute( 'href', themeURL );
350                         }
351                 }
352         }
353
354         /**
355          * Binds all event listeners.
356          */
357         function addEventListeners() {
358                 document.addEventListener( 'touchstart', onDocumentTouchStart, false );
359                 document.addEventListener( 'touchmove', onDocumentTouchMove, false );
360                 document.addEventListener( 'touchend', onDocumentTouchEnd, false );
361                 window.addEventListener( 'hashchange', onWindowHashChange, false );
362                 window.addEventListener( 'resize', onWindowResize, false );
363
364                 if( config.keyboard ) {
365                         document.addEventListener( 'keydown', onDocumentKeyDown, false );
366                 }
367
368                 if ( config.progress && dom.progress ) {
369                         dom.progress.addEventListener( 'click', preventAndForward( onProgressClick ), false );
370                 }
371
372                 if ( config.controls && dom.controls ) {
373                         var actionEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
374                         dom.controlsLeft.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateLeft ), false ); } );
375                         dom.controlsRight.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateRight ), false ); } );
376                         dom.controlsUp.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateUp ), false ); } );
377                         dom.controlsDown.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateDown ), false ); } );
378                         dom.controlsPrev.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigatePrev ), false ); } );
379                         dom.controlsNext.forEach( function( el ) { el.addEventListener( actionEvent, preventAndForward( navigateNext ), false ); } );
380                 }
381         }
382
383         /**
384          * Unbinds all event listeners.
385          */
386         function removeEventListeners() {
387                 document.removeEventListener( 'keydown', onDocumentKeyDown, false );
388                 document.removeEventListener( 'touchstart', onDocumentTouchStart, false );
389                 document.removeEventListener( 'touchmove', onDocumentTouchMove, false );
390                 document.removeEventListener( 'touchend', onDocumentTouchEnd, false );
391                 window.removeEventListener( 'hashchange', onWindowHashChange, false );
392                 window.removeEventListener( 'resize', onWindowResize, false );
393
394                 if ( config.progress && dom.progress ) {
395                         dom.progress.removeEventListener( 'click', preventAndForward( onProgressClick ), false );
396                 }
397
398                 if ( config.controls && dom.controls ) {
399                         var actionEvent = 'ontouchstart' in window ? 'touchstart' : 'click';
400                         dom.controlsLeft.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateLeft ), false ); } );
401                         dom.controlsRight.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateRight ), false ); } );
402                         dom.controlsUp.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateUp ), false ); } );
403                         dom.controlsDown.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateDown ), false ); } );
404                         dom.controlsPrev.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigatePrev ), false ); } );
405                         dom.controlsNext.forEach( function( el ) { el.removeEventListener( actionEvent, preventAndForward( navigateNext ), false ); } );
406                 }
407         }
408
409         /**
410          * Extend object a with the properties of object b.
411          * If there's a conflict, object b takes precedence.
412          */
413         function extend( a, b ) {
414                 for( var i in b ) {
415                         a[ i ] = b[ i ];
416                 }
417         }
418
419         /**
420          * Converts the target object to an array.
421          */
422         function toArray( o ) {
423                 return Array.prototype.slice.call( o );
424         }
425
426         function each( targets, method, args ) {
427                 targets.forEach( function( el ) {
428                         el[method].apply( el, args );
429                 } );
430         }
431
432         /**
433          * Measures the distance in pixels between point a
434          * and point b.
435          *
436          * @param {Object} a point with x/y properties
437          * @param {Object} b point with x/y properties
438          */
439         function distanceBetween( a, b ) {
440                 var dx = a.x - b.x,
441                         dy = a.y - b.y;
442
443                 return Math.sqrt( dx*dx + dy*dy );
444         }
445
446         /**
447          * Prevents an events defaults behavior calls the
448          * specified delegate.
449          *
450          * @param {Function} delegate The method to call
451          * after the wrapper has been executed
452          */
453         function preventAndForward( delegate ) {
454                 return function( event ) {
455                         event.preventDefault();
456                         delegate.call( null, event );
457                 };
458         }
459
460         /**
461          * Causes the address bar to hide on mobile devices,
462          * more vertical space ftw.
463          */
464         function removeAddressBar() {
465                 setTimeout( function() {
466                         window.scrollTo( 0, 1 );
467                 }, 0 );
468         }
469
470         /**
471          * Dispatches an event of the specified type from the
472          * reveal DOM element.
473          */
474         function dispatchEvent( type, properties ) {
475                 var event = document.createEvent( "HTMLEvents", 1, 2 );
476                 event.initEvent( type, true, true );
477                 extend( event, properties );
478                 dom.wrapper.dispatchEvent( event );
479         }
480
481         /**
482          * Wrap all links in 3D goodness.
483          */
484         function linkify() {
485                 if( supports3DTransforms && !( 'msPerspective' in document.body.style ) ) {
486                         var nodes = document.querySelectorAll( SLIDES_SELECTOR + ' a:not(.image)' );
487
488                         for( var i = 0, len = nodes.length; i < len; i++ ) {
489                                 var node = nodes[i];
490
491                                 if( node.textContent && !node.querySelector( 'img' ) && ( !node.className || !node.classList.contains( node, 'roll' ) ) ) {
492                                         node.classList.add( 'roll' );
493                                         node.innerHTML = '<span data-title="'+ node.text +'">' + node.innerHTML + '</span>';
494                                 }
495                         }
496                 }
497         }
498
499         /**
500          * Applies JavaScript-controlled layout rules to the
501          * presentation.
502          */
503         function layout() {
504
505                 if( config.center ) {
506
507                         // Select all slides, vertical and horizontal
508                         var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
509
510                         // Determine the minimum top offset for slides
511                         var minTop = -dom.wrapper.offsetHeight / 2;
512
513                         for( var i = 0, len = slides.length; i < len; i++ ) {
514                                 var slide = slides[ i ];
515
516                                 // Don't bother update invisible slides
517                                 if( slide.style.display === 'none' ) {
518                                         continue;
519                                 }
520
521                                 // Vertical stacks are not centered since their section 
522                                 // children will be
523                                 if( slide.classList.contains( 'stack' ) ) {
524                                         slide.style.top = 0;
525                                 }
526                                 else {
527                                         slide.style.top = Math.max( - ( slide.offsetHeight / 2 ) - 20, minTop ) + 'px';
528                                 }
529                         }
530
531                 }
532
533         }
534
535         /**
536          * Stores the vertical index of a stack so that the same 
537          * vertical slide can be selected when navigating to and 
538          * from the stack.
539          * 
540          * @param {HTMLElement} stack The vertical stack element
541          * @param {int} v Index to memorize
542          */
543         function setPreviousVerticalIndex( stack, v ) {
544                 if( stack ) {
545                         stack.setAttribute( 'data-previous-indexv', v || 0 );
546                 }
547         }
548
549         /**
550          * Retrieves the vertical index which was stored using 
551          * #setPreviousVerticalIndex() or 0 if no previous index
552          * exists.
553          *
554          * @param {HTMLElement} stack The vertical stack element
555          */
556         function getPreviousVerticalIndex( stack ) {
557                 if( stack && stack.classList.contains( 'stack' ) ) {
558                         return parseInt( stack.getAttribute( 'data-previous-indexv' ) || 0, 10 );
559                 }
560
561                 return 0;
562         }
563
564         /**
565          * Displays the overview of slides (quick nav) by
566          * scaling down and arranging all slide elements.
567          *
568          * Experimental feature, might be dropped if perf
569          * can't be improved.
570          */
571         function activateOverview() {
572
573                 // Only proceed if enabled in config
574                 if( config.overview ) {
575
576                         dom.wrapper.classList.add( 'overview' );
577
578                         var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
579
580                         for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
581                                 var hslide = horizontalSlides[i],
582                                         htransform = 'translateZ(-2500px) translate(' + ( ( i - indexh ) * 105 ) + '%, 0%)';
583
584                                 hslide.setAttribute( 'data-index-h', i );
585                                 hslide.style.display = 'block';
586                                 hslide.style.WebkitTransform = htransform;
587                                 hslide.style.MozTransform = htransform;
588                                 hslide.style.msTransform = htransform;
589                                 hslide.style.OTransform = htransform;
590                                 hslide.style.transform = htransform;
591
592                                 if( hslide.classList.contains( 'stack' ) ) {
593
594                                         var verticalSlides = hslide.querySelectorAll( 'section' );
595
596                                         for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
597                                                 var verticalIndex = i === indexh ? indexv : getPreviousVerticalIndex( hslide );
598
599                                                 var vslide = verticalSlides[j],
600                                                         vtransform = 'translate(0%, ' + ( ( j - verticalIndex ) * 105 ) + '%)';
601
602                                                 vslide.setAttribute( 'data-index-h', i );
603                                                 vslide.setAttribute( 'data-index-v', j );
604                                                 vslide.style.display = 'block';
605                                                 vslide.style.WebkitTransform = vtransform;
606                                                 vslide.style.MozTransform = vtransform;
607                                                 vslide.style.msTransform = vtransform;
608                                                 vslide.style.OTransform = vtransform;
609                                                 vslide.style.transform = vtransform;
610
611                                                 // Navigate to this slide on click
612                                                 vslide.addEventListener( 'click', onOverviewSlideClicked, true );
613                                         }
614                                         
615                                 }
616                                 else {
617
618                                         // Navigate to this slide on click
619                                         hslide.addEventListener( 'click', onOverviewSlideClicked, true );
620
621                                 }
622                         }
623
624                         layout();
625
626                 }
627
628         }
629
630         /**
631          * Exits the slide overview and enters the currently
632          * active slide.
633          */
634         function deactivateOverview() {
635
636                 // Only proceed if enabled in config
637                 if( config.overview ) {
638
639                         dom.wrapper.classList.remove( 'overview' );
640
641                         // Select all slides
642                         var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
643
644                         for( var i = 0, len = slides.length; i < len; i++ ) {
645                                 var element = slides[i];
646
647                                 // Resets all transforms to use the external styles
648                                 element.style.WebkitTransform = '';
649                                 element.style.MozTransform = '';
650                                 element.style.msTransform = '';
651                                 element.style.OTransform = '';
652                                 element.style.transform = '';
653
654                                 element.removeEventListener( 'click', onOverviewSlideClicked );
655                         }
656
657                         slide( indexh, indexv );
658
659                 }
660         }
661
662         /**
663          * Toggles the slide overview mode on and off.
664          *
665          * @param {Boolean} override Optional flag which overrides the
666          * toggle logic and forcibly sets the desired state. True means
667          * overview is open, false means it's closed.
668          */
669         function toggleOverview( override ) {
670                 if( typeof override === 'boolean' ) {
671                         override ? activateOverview() : deactivateOverview();
672                 }
673                 else {
674                         isOverviewActive() ? deactivateOverview() : activateOverview();
675                 }
676         }
677
678         /**
679          * Checks if the overview is currently active.
680          *
681          * @return {Boolean} true if the overview is active,
682          * false otherwise
683          */
684         function isOverviewActive() {
685                 return dom.wrapper.classList.contains( 'overview' );
686         }
687
688         /**
689          * Handling the fullscreen functionality via the fullscreen API
690          *
691          * @see http://fullscreen.spec.whatwg.org/
692          * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
693          */
694         function enterFullscreen() {
695                 var element = document.body;
696
697                 // Check which implementation is available
698                 var requestMethod = element.requestFullScreen ||
699                                                         element.webkitRequestFullScreen ||
700                                                         element.mozRequestFullScreen ||
701                                                         element.msRequestFullScreen;
702
703                 if( requestMethod ) {
704                         requestMethod.apply( element );
705                 }
706         }
707
708         /**
709          * Enters the paused mode which fades everything on screen to
710          * black.
711          */
712         function pause() {
713                 dom.wrapper.classList.add( 'paused' );
714         }
715
716         /**
717          * Exits from the paused mode.
718          */
719         function resume() {
720                 dom.wrapper.classList.remove( 'paused' );
721         }
722
723         /**
724          * Toggles the paused mode on and off.
725          */
726         function togglePause() {
727                 if( isPaused() ) {
728                         resume();
729                 }
730                 else {
731                         pause();
732                 }
733         }
734
735         /**
736          * Checks if we are currently in the paused mode.
737          */
738         function isPaused() {
739                 return dom.wrapper.classList.contains( 'paused' );
740         }
741
742         /**
743          * Steps from the current point in the presentation to the
744          * slide which matches the specified horizontal and vertical
745          * indices.
746          *
747          * @param {int} h Horizontal index of the target slide
748          * @param {int} v Vertical index of the target slide
749          * @param {int} f Optional index of a fragment within the 
750          * target slide to activate
751          */
752         function slide( h, v, f ) {
753                 // Remember where we were at before
754                 previousSlide = currentSlide;
755
756                 // Query all horizontal slides in the deck
757                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
758                 
759                 // If no vertical index is specified and the upcoming slide is a 
760                 // stack, resume at its previous vertical index
761                 if( v === undefined ) {
762                         v = getPreviousVerticalIndex( horizontalSlides[ h ] );
763                 }
764
765                 // If we were on a vertical stack, remember what vertical index 
766                 // it was on so we can resume at the same position when returning
767                 if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
768                         setPreviousVerticalIndex( previousSlide.parentNode, indexv );
769                 }
770
771                 // Remember the state before this slide
772                 var stateBefore = state.concat();
773
774                 // Reset the state array
775                 state.length = 0;
776
777                 var indexhBefore = indexh,
778                         indexvBefore = indexv;
779
780                 // Activate and transition to the new slide
781                 indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
782                 indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
783
784                 layout();
785
786                 // Apply the new state
787                 stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
788                         // Check if this state existed on the previous slide. If it
789                         // did, we will avoid adding it repeatedly
790                         for( var j = 0; j < stateBefore.length; j++ ) {
791                                 if( stateBefore[j] === state[i] ) {
792                                         stateBefore.splice( j, 1 );
793                                         continue stateLoop;
794                                 }
795                         }
796
797                         document.documentElement.classList.add( state[i] );
798
799                         // Dispatch custom event matching the state's name
800                         dispatchEvent( state[i] );
801                 }
802
803                 // Clean up the remaints of the previous state
804                 while( stateBefore.length ) {
805                         document.documentElement.classList.remove( stateBefore.pop() );
806                 }
807
808                 // If the overview is active, re-activate it to update positions
809                 if( isOverviewActive() ) {
810                         activateOverview();
811                 }
812
813                 // Update the URL hash after a delay since updating it mid-transition
814                 // is likely to cause visual lag
815                 writeURL( 1500 );
816
817                 // Find the current horizontal slide and any possible vertical slides
818                 // within it
819                 var currentHorizontalSlide = horizontalSlides[ indexh ],
820                         currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
821
822                 // Store references to the previous and current slides
823                 currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
824
825                 
826                 // Show fragment, if specified
827                 if( ( indexh !== indexhBefore || indexv !== indexvBefore ) && f ) {
828                         var fragments = currentSlide.querySelectorAll( '.fragment' );
829
830                         toArray( fragments ).forEach( function( fragment, indexf ) {
831                                 if( indexf < f ) {
832                                         fragment.classList.add( 'visible' );
833                                 }
834                                 else {
835                                         fragment.classList.remove( 'visible' );
836                                 }
837                         } );
838                 }
839
840                 // Dispatch an event if the slide changed
841                 if( indexh !== indexhBefore || indexv !== indexvBefore ) {
842                         dispatchEvent( 'slidechanged', {
843                                 'indexh': indexh,
844                                 'indexv': indexv,
845                                 'previousSlide': previousSlide,
846                                 'currentSlide': currentSlide
847                         } );
848                 }
849                 else {
850                         // Ensure that the previous slide is never the same as the current
851                         previousSlide = null;
852                 }
853
854                 // Solves an edge case where the previous slide maintains the
855                 // 'present' class when navigating between adjacent vertical
856                 // stacks
857                 if( previousSlide ) {
858                         previousSlide.classList.remove( 'present' );
859                 }
860
861                 updateControls();
862                 updateProgress();
863         }
864
865         /**
866          * Updates one dimension of slides by showing the slide
867          * with the specified index.
868          *
869          * @param {String} selector A CSS selector that will fetch
870          * the group of slides we are working with
871          * @param {Number} index The index of the slide that should be
872          * shown
873          *
874          * @return {Number} The index of the slide that is now shown,
875          * might differ from the passed in index if it was out of
876          * bounds.
877          */
878         function updateSlides( selector, index ) {
879                 // Select all slides and convert the NodeList result to
880                 // an array
881                 var slides = toArray( document.querySelectorAll( selector ) ),
882                         slidesLength = slides.length;
883
884                 if( slidesLength ) {
885
886                         // Should the index loop?
887                         if( config.loop ) {
888                                 index %= slidesLength;
889
890                                 if( index < 0 ) {
891                                         index = slidesLength + index;
892                                 }
893                         }
894
895                         // Enforce max and minimum index bounds
896                         index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
897
898                         for( var i = 0; i < slidesLength; i++ ) {
899                                 var element = slides[i];
900
901                                 // Optimization; hide all slides that are three or more steps
902                                 // away from the present slide
903                                 if( isOverviewActive() === false ) {
904                                         // The distance loops so that it measures 1 between the first
905                                         // and last slides
906                                         var distance = Math.abs( ( index - i ) % ( slidesLength - 3 ) ) || 0;
907
908                                         element.style.display = distance > 3 ? 'none' : 'block';
909                                 }
910
911                                 slides[i].classList.remove( 'past' );
912                                 slides[i].classList.remove( 'present' );
913                                 slides[i].classList.remove( 'future' );
914
915                                 if( i < index ) {
916                                         // Any element previous to index is given the 'past' class
917                                         slides[i].classList.add( 'past' );
918                                 }
919                                 else if( i > index ) {
920                                         // Any element subsequent to index is given the 'future' class
921                                         slides[i].classList.add( 'future' );
922                                 }
923
924                                 // If this element contains vertical slides
925                                 if( element.querySelector( 'section' ) ) {
926                                         slides[i].classList.add( 'stack' );
927                                 }
928                         }
929
930                         // Mark the current slide as present
931                         slides[index].classList.add( 'present' );
932
933                         // If this slide has a state associated with it, add it
934                         // onto the current state of the deck
935                         var slideState = slides[index].getAttribute( 'data-state' );
936                         if( slideState ) {
937                                 state = state.concat( slideState.split( ' ' ) );
938                         }
939
940                         // If this slide has a data-autoslide attribtue associated use this as
941                         // autoSlide value otherwise use the global configured time
942                         var slideAutoSlide = slides[index].getAttribute( 'data-autoslide' );
943                         if( slideAutoSlide ) {
944                                 autoSlide = parseInt( slideAutoSlide, 10 );
945                         } else {
946                                 autoSlide = config.autoSlide;
947                         }
948
949                 }
950                 else {
951                         // Since there are no slides we can't be anywhere beyond the
952                         // zeroth index
953                         index = 0;
954                 }
955
956                 return index;
957
958         }
959
960         /**
961          * Updates the progress bar to reflect the current slide.
962          */
963         function updateProgress() {
964                 // Update progress if enabled
965                 if( config.progress && dom.progress ) {
966
967                         var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
968
969                         // The number of past and total slides
970                         var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
971                         var pastCount = 0;
972
973                         // Step through all slides and count the past ones
974                         mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
975
976                                 var horizontalSlide = horizontalSlides[i];
977                                 var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
978
979                                 for( var j = 0; j < verticalSlides.length; j++ ) {
980
981                                         // Stop as soon as we arrive at the present
982                                         if( verticalSlides[j].classList.contains( 'present' ) ) {
983                                                 break mainLoop;
984                                         }
985
986                                         pastCount++;
987
988                                 }
989
990                                 // Stop as soon as we arrive at the present
991                                 if( horizontalSlide.classList.contains( 'present' ) ) {
992                                         break;
993                                 }
994
995                                 // Don't count the wrapping section for vertical slides
996                                 if( horizontalSlide.classList.contains( 'stack' ) === false ) {
997                                         pastCount++;
998                                 }
999
1000                         }
1001
1002                         dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';
1003
1004                 }
1005         }
1006
1007         /**
1008          * Updates the state of all control/navigation arrows.
1009          */
1010         function updateControls() {
1011                 if ( config.controls && dom.controls ) {
1012
1013                         var routes = availableRoutes();
1014
1015                         // Remove the 'enabled' class from all directions
1016                         dom.controlsLeft.concat( dom.controlsRight )
1017                                                         .concat( dom.controlsUp )
1018                                                         .concat( dom.controlsDown )
1019                                                         .concat( dom.controlsPrev )
1020                                                         .concat( dom.controlsNext ).forEach( function( node ) {
1021                                 node.classList.remove( 'enabled' );
1022                         } );
1023
1024                         // Add the 'enabled' class to the available routes
1025                         if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' );     } );
1026                         if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1027                         if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1028                         if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1029
1030                         // Prev/next buttons
1031                         if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1032                         if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1033
1034                 }
1035         }
1036
1037         /**
1038          * Determine what available routes there are for navigation.
1039          *
1040          * @return {Object} containing four booleans: left/right/up/down
1041          */
1042         function availableRoutes() {
1043                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
1044                         verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
1045
1046                 return {
1047                         left: indexh > 0,
1048                         right: indexh < horizontalSlides.length - 1,
1049                         up: indexv > 0,
1050                         down: indexv < verticalSlides.length - 1
1051                 };
1052         }
1053
1054         /**
1055          * Reads the current URL (hash) and navigates accordingly.
1056          */
1057         function readURL() {
1058                 var hash = window.location.hash;
1059
1060                 // Attempt to parse the hash as either an index or name
1061                 var bits = hash.slice( 2 ).split( '/' ),
1062                         name = hash.replace( /#|\//gi, '' );
1063
1064                 // If the first bit is invalid and there is a name we can
1065                 // assume that this is a named link
1066                 if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
1067                         // Find the slide with the specified name
1068                         var element = document.querySelector( '#' + name );
1069
1070                         if( element ) {
1071                                 // Find the position of the named slide and navigate to it
1072                                 var indices = Reveal.getIndices( element );
1073                                 slide( indices.h, indices.v );
1074                         }
1075                         // If the slide doesn't exist, navigate to the current slide
1076                         else {
1077                                 slide( indexh, indexv );
1078                         }
1079                 }
1080                 else {
1081                         // Read the index components of the hash
1082                         var h = parseInt( bits[0], 10 ) || 0,
1083                                 v = parseInt( bits[1], 10 ) || 0;
1084
1085                         slide( h, v );
1086                 }
1087         }
1088
1089         /**
1090          * Updates the page URL (hash) to reflect the current
1091          * state.
1092          *
1093          * @param {Number} delay The time in ms to wait before 
1094          * writing the hash
1095          */
1096         function writeURL( delay ) {
1097                 if( config.history ) {
1098
1099                         // Make sure there's never more than one timeout running
1100                         clearTimeout( writeURLTimeout );
1101
1102                         // If a delay is specified, timeout this call
1103                         if( typeof delay === 'number' ) {
1104                                 writeURLTimeout = setTimeout( writeURL, delay );
1105                         }
1106                         else {
1107                                 var url = '/';
1108
1109                                 // If the current slide has an ID, use that as a named link
1110                                 if( currentSlide && typeof currentSlide.getAttribute( 'id' ) === 'string' ) {
1111                                         url = '/' + currentSlide.getAttribute( 'id' );
1112                                 }
1113                                 // Otherwise use the /h/v index
1114                                 else {
1115                                         if( indexh > 0 || indexv > 0 ) url += indexh;
1116                                         if( indexv > 0 ) url += '/' + indexv;
1117                                 }
1118
1119                                 window.location.hash = url;
1120                         }
1121                 }
1122         }
1123
1124         /**
1125          * Retrieves the h/v location of the current, or specified,
1126          * slide.
1127          *
1128          * @param {HTMLElement} slide If specified, the returned
1129          * index will be for this slide rather than the currently
1130          * active one
1131          *
1132          * @return {Object} { h: <int>, v: <int> }
1133          */
1134         function getIndices( slide ) {
1135                 // By default, return the current indices
1136                 var h = indexh,
1137                         v = indexv;
1138
1139                 // If a slide is specified, return the indices of that slide
1140                 if( slide ) {
1141                         var isVertical = !!slide.parentNode.nodeName.match( /section/gi );
1142                         var slideh = isVertical ? slide.parentNode : slide;
1143
1144                         // Select all horizontal slides
1145                         var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1146
1147                         // Now that we know which the horizontal slide is, get its index
1148                         h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
1149
1150                         // If this is a vertical slide, grab the vertical index
1151                         if( isVertical ) {
1152                                 v = Math.max( toArray( slide.parentNode.children ).indexOf( slide ), 0 );
1153                         }
1154                 }
1155
1156                 return { h: h, v: v };
1157         }
1158
1159         /**
1160          * Navigate to the next slide fragment.
1161          *
1162          * @return {Boolean} true if there was a next fragment,
1163          * false otherwise
1164          */
1165         function nextFragment() {
1166                 // Vertical slides:
1167                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1168                         var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
1169                         if( verticalFragments.length ) {
1170                                 verticalFragments[0].classList.add( 'visible' );
1171
1172                                 // Notify subscribers of the change
1173                                 dispatchEvent( 'fragmentshown', { fragment: verticalFragments[0] } );
1174                                 return true;
1175                         }
1176                 }
1177                 // Horizontal slides:
1178                 else {
1179                         var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
1180                         if( horizontalFragments.length ) {
1181                                 horizontalFragments[0].classList.add( 'visible' );
1182
1183                                 // Notify subscribers of the change
1184                                 dispatchEvent( 'fragmentshown', { fragment: horizontalFragments[0] } );
1185                                 return true;
1186                         }
1187                 }
1188
1189                 return false;
1190         }
1191
1192         /**
1193          * Navigate to the previous slide fragment.
1194          *
1195          * @return {Boolean} true if there was a previous fragment,
1196          * false otherwise
1197          */
1198         function previousFragment() {
1199                 // Vertical slides:
1200                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1201                         var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment.visible' );
1202                         if( verticalFragments.length ) {
1203                                 verticalFragments[ verticalFragments.length - 1 ].classList.remove( 'visible' );
1204
1205                                 // Notify subscribers of the change
1206                                 dispatchEvent( 'fragmenthidden', { fragment: verticalFragments[ verticalFragments.length - 1 ] } );
1207                                 return true;
1208                         }
1209                 }
1210                 // Horizontal slides:
1211                 else {
1212                         var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment.visible' );
1213                         if( horizontalFragments.length ) {
1214                                 horizontalFragments[ horizontalFragments.length - 1 ].classList.remove( 'visible' );
1215
1216                                 // Notify subscribers of the change
1217                                 dispatchEvent( 'fragmenthidden', { fragment: horizontalFragments[ horizontalFragments.length - 1 ] } );
1218                                 return true;
1219                         }
1220                 }
1221
1222                 return false;
1223         }
1224
1225         /**
1226          * Cues a new automated slide if enabled in the config.
1227          */
1228         function cueAutoSlide() {
1229                 clearTimeout( autoSlideTimeout );
1230
1231                 // Cue the next auto-slide if enabled
1232                 if( autoSlide ) {
1233                         autoSlideTimeout = setTimeout( navigateNext, autoSlide );
1234                 }
1235         }
1236
1237         function navigateLeft() {
1238                 // Prioritize hiding fragments
1239                 if( availableRoutes().left && isOverviewActive() || previousFragment() === false ) {
1240                         slide( indexh - 1 );
1241                 }
1242         }
1243
1244         function navigateRight() {
1245                 // Prioritize revealing fragments
1246                 if( availableRoutes().right && isOverviewActive() || nextFragment() === false ) {
1247                         slide( indexh + 1 );
1248                 }
1249         }
1250
1251         function navigateUp() {
1252                 // Prioritize hiding fragments
1253                 if( availableRoutes().up && isOverviewActive() || previousFragment() === false ) {
1254                         slide( indexh, indexv - 1 );
1255                 }
1256         }
1257
1258         function navigateDown() {
1259                 // Prioritize revealing fragments
1260                 if( availableRoutes().down && isOverviewActive() || nextFragment() === false ) {
1261                         slide( indexh, indexv + 1 );
1262                 }
1263         }
1264
1265         /**
1266          * Navigates backwards, prioritized in the following order:
1267          * 1) Previous fragment
1268          * 2) Previous vertical slide
1269          * 3) Previous horizontal slide
1270          */
1271         function navigatePrev() {
1272                 // Prioritize revealing fragments
1273                 if( previousFragment() === false ) {
1274                         if( availableRoutes().up ) {
1275                                 navigateUp();
1276                         }
1277                         else {
1278                                 // Fetch the previous horizontal slide, if there is one
1279                                 var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
1280
1281                                 if( previousSlide ) {
1282                                         indexv = ( previousSlide.querySelectorAll( 'section' ).length + 1 ) || undefined;
1283                                         indexh --;
1284                                         slide();
1285                                 }
1286                         }
1287                 }
1288         }
1289
1290         /**
1291          * Same as #navigatePrev() but navigates forwards.
1292          */
1293         function navigateNext() {
1294                 // Prioritize revealing fragments
1295                 if( nextFragment() === false ) {
1296                         availableRoutes().down ? navigateDown() : navigateRight();
1297                 }
1298
1299                 // If auto-sliding is enabled we need to cue up
1300                 // another timeout
1301                 cueAutoSlide();
1302         }
1303
1304
1305         // --------------------------------------------------------------------//
1306         // ----------------------------- EVENTS -------------------------------//
1307         // --------------------------------------------------------------------//
1308
1309
1310         /**
1311          * Handler for the document level 'keydown' event.
1312          *
1313          * @param {Object} event
1314          */
1315         function onDocumentKeyDown( event ) {
1316                 // Check if there's a focused element that could be using 
1317                 // the keyboard
1318                 var activeElement = document.activeElement;
1319                 var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
1320
1321                 // Disregard the event if there's a focused element or a 
1322                 // keyboard modifier key is present
1323                 if ( hasFocus || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;
1324
1325                 var triggered = true;
1326
1327                 switch( event.keyCode ) {
1328                         // p, page up
1329                         case 80: case 33: navigatePrev(); break;
1330                         // n, page down
1331                         case 78: case 34: navigateNext(); break;
1332                         // h, left
1333                         case 72: case 37: navigateLeft(); break;
1334                         // l, right
1335                         case 76: case 39: navigateRight(); break;
1336                         // k, up
1337                         case 75: case 38: navigateUp(); break;
1338                         // j, down
1339                         case 74: case 40: navigateDown(); break;
1340                         // home
1341                         case 36: slide( 0 ); break;
1342                         // end
1343                         case 35: slide( Number.MAX_VALUE ); break;
1344                         // space
1345                         case 32: isOverviewActive() ? deactivateOverview() : navigateNext(); break;
1346                         // return
1347                         case 13: isOverviewActive() ? deactivateOverview() : triggered = false; break;
1348                         // b, period
1349                         case 66: case 190: togglePause(); break;
1350                         // f
1351                         case 70: enterFullscreen(); break;
1352                         default:
1353                                 triggered = false;
1354                 }
1355
1356                 // If the input resulted in a triggered action we should prevent
1357                 // the browsers default behavior
1358                 if( triggered ) {
1359                         event.preventDefault();
1360                 }
1361                 else if ( event.keyCode === 27 && supports3DTransforms ) {
1362                         toggleOverview();
1363
1364                         event.preventDefault();
1365                 }
1366
1367                 // If auto-sliding is enabled we need to cue up
1368                 // another timeout
1369                 cueAutoSlide();
1370
1371         }
1372
1373         /**
1374          * Handler for the document level 'touchstart' event,
1375          * enables support for swipe and pinch gestures.
1376          */
1377         function onDocumentTouchStart( event ) {
1378                 touch.startX = event.touches[0].clientX;
1379                 touch.startY = event.touches[0].clientY;
1380                 touch.startCount = event.touches.length;
1381
1382                 // If there's two touches we need to memorize the distance
1383                 // between those two points to detect pinching
1384                 if( event.touches.length === 2 && config.overview ) {
1385                         touch.startSpan = distanceBetween( {
1386                                 x: event.touches[1].clientX,
1387                                 y: event.touches[1].clientY
1388                         }, {
1389                                 x: touch.startX,
1390                                 y: touch.startY
1391                         } );
1392                 }
1393         }
1394
1395         /**
1396          * Handler for the document level 'touchmove' event.
1397          */
1398         function onDocumentTouchMove( event ) {
1399                 // Each touch should only trigger one action
1400                 if( !touch.handled ) {
1401                         var currentX = event.touches[0].clientX;
1402                         var currentY = event.touches[0].clientY;
1403
1404                         // If the touch started off with two points and still has
1405                         // two active touches; test for the pinch gesture
1406                         if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
1407
1408                                 // The current distance in pixels between the two touch points
1409                                 var currentSpan = distanceBetween( {
1410                                         x: event.touches[1].clientX,
1411                                         y: event.touches[1].clientY
1412                                 }, {
1413                                         x: touch.startX,
1414                                         y: touch.startY
1415                                 } );
1416
1417                                 // If the span is larger than the desire amount we've got
1418                                 // ourselves a pinch
1419                                 if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
1420                                         touch.handled = true;
1421
1422                                         if( currentSpan < touch.startSpan ) {
1423                                                 activateOverview();
1424                                         }
1425                                         else {
1426                                                 deactivateOverview();
1427                                         }
1428                                 }
1429
1430                                 event.preventDefault();
1431
1432                         }
1433                         // There was only one touch point, look for a swipe
1434                         else if( event.touches.length === 1 && touch.startCount !== 2 ) {
1435
1436                                 var deltaX = currentX - touch.startX,
1437                                         deltaY = currentY - touch.startY;
1438
1439                                 if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1440                                         touch.handled = true;
1441                                         navigateLeft();
1442                                 }
1443                                 else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1444                                         touch.handled = true;
1445                                         navigateRight();
1446                                 }
1447                                 else if( deltaY > touch.threshold ) {
1448                                         touch.handled = true;
1449                                         navigateUp();
1450                                 }
1451                                 else if( deltaY < -touch.threshold ) {
1452                                         touch.handled = true;
1453                                         navigateDown();
1454                                 }
1455
1456                                 event.preventDefault();
1457
1458                         }
1459                 }
1460                 // There's a bug with swiping on some Android devices unless
1461                 // the default action is always prevented
1462                 else if( navigator.userAgent.match( /android/gi ) ) {
1463                         event.preventDefault();
1464                 }
1465         }
1466
1467         /**
1468          * Handler for the document level 'touchend' event.
1469          */
1470         function onDocumentTouchEnd( event ) {
1471                 touch.handled = false;
1472         }
1473
1474         /**
1475          * Handles mouse wheel scrolling, throttled to avoid skipping
1476          * multiple slides.
1477          */
1478         function onDocumentMouseScroll( event ){
1479                 clearTimeout( mouseWheelTimeout );
1480
1481                 mouseWheelTimeout = setTimeout( function() {
1482                         var delta = event.detail || -event.wheelDelta;
1483                         if( delta > 0 ) {
1484                                 navigateNext();
1485                         }
1486                         else {
1487                                 navigatePrev();
1488                         }
1489                 }, 100 );
1490         }
1491
1492         /**
1493          * Clicking on the progress bar results in a navigation to the
1494          * closest approximate horizontal slide using this equation:
1495          *
1496          * ( clickX / presentationWidth ) * numberOfSlides
1497          */
1498         function onProgressClick( event ) {
1499                 var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
1500                 var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
1501
1502                 slide( slideIndex );
1503         }
1504
1505         /**
1506          * Handler for the window level 'hashchange' event.
1507          */
1508         function onWindowHashChange( event ) {
1509                 readURL();
1510         }
1511
1512         /**
1513          * Handler for the window level 'resize' event.
1514          */
1515         function onWindowResize( event ) {
1516                 layout();
1517         }
1518
1519         /**
1520          * Invoked when a slide is and we're in the overview.
1521          */
1522         function onOverviewSlideClicked( event ) {
1523                 // TODO There's a bug here where the event listeners are not
1524                 // removed after deactivating the overview.
1525                 if( isOverviewActive() ) {
1526                         event.preventDefault();
1527
1528                         deactivateOverview();
1529
1530                         var h = parseInt( event.target.getAttribute( 'data-index-h' ), 10 ),
1531                                 v = parseInt( event.target.getAttribute( 'data-index-v' ), 10 );
1532
1533                         slide( h, v );
1534                 }
1535         }
1536
1537
1538         // --------------------------------------------------------------------//
1539         // ------------------------------- API --------------------------------//
1540         // --------------------------------------------------------------------//
1541
1542
1543         return {
1544                 initialize: initialize,
1545
1546                 // Navigation methods
1547                 slide: slide,
1548                 left: navigateLeft,
1549                 right: navigateRight,
1550                 up: navigateUp,
1551                 down: navigateDown,
1552                 prev: navigatePrev,
1553                 next: navigateNext,
1554                 prevFragment: previousFragment,
1555                 nextFragment: nextFragment,
1556
1557                 // Deprecated aliases
1558                 navigateTo: slide,
1559                 navigateLeft: navigateLeft,
1560                 navigateRight: navigateRight,
1561                 navigateUp: navigateUp,
1562                 navigateDown: navigateDown,
1563                 navigatePrev: navigatePrev,
1564                 navigateNext: navigateNext,
1565
1566                 // Toggles the overview mode on/off
1567                 toggleOverview: toggleOverview,
1568
1569                 // Adds or removes all internal event listeners (such as keyboard)
1570                 addEventListeners: addEventListeners,
1571                 removeEventListeners: removeEventListeners,
1572
1573                 // Returns the indices of the current, or specified, slide
1574                 getIndices: getIndices,
1575
1576                 // Returns the previous slide element, may be null
1577                 getPreviousSlide: function() {
1578                         return previousSlide;
1579                 },
1580
1581                 // Returns the current slide element
1582                 getCurrentSlide: function() {
1583                         return currentSlide;
1584                 },
1585
1586                 // Helper method, retrieves query string as a key/value hash
1587                 getQueryHash: function() {
1588                         var query = {};
1589
1590                         location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
1591                                 query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
1592                         } );
1593
1594                         return query;
1595                 },
1596
1597                 // Forward event binding to the reveal DOM element
1598                 addEventListener: function( type, listener, useCapture ) {
1599                         if( 'addEventListener' in window ) {
1600                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
1601                         }
1602                 },
1603                 removeEventListener: function( type, listener, useCapture ) {
1604                         if( 'addEventListener' in window ) {
1605                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
1606                         }
1607                 }
1608         };
1609
1610 })();