blindfolded attempt at ie10 touch (#300)
[reveal.js.git] / js / reveal.js
1 /*!
2  * reveal.js
3  * http://lab.hakim.se/reveal-js
4  * MIT licensed
5  *
6  * Copyright (C) 2013 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                 HOME_SLIDE_SELECTOR = '.reveal .slides>section:first-child',
16
17                 // Configurations defaults, can be overridden at initialization time
18                 config = {
19
20                         // The "normal" size of the presentation, aspect ratio will be preserved
21                         // when the presentation is scaled to fit different resolutions
22                         width: 960,
23                         height: 700,
24
25                         // Factor of the display size that should remain empty around the content
26                         margin: 0.1,
27
28                         // Bounds for smallest/largest possible scale to apply to content
29                         minScale: 0.2,
30                         maxScale: 1.0,
31
32                         // Display controls in the bottom right corner
33                         controls: true,
34
35                         // Display a presentation progress bar
36                         progress: true,
37
38                         // Push each slide change to the browser history
39                         history: false,
40
41                         // Enable keyboard shortcuts for navigation
42                         keyboard: true,
43
44                         // Enable the slide overview mode
45                         overview: true,
46
47                         // Vertical centring of slides
48                         center: true,
49
50                         // Enables touch navigation on devices with touch input
51                         touch: true,
52
53                         // Loop the presentation
54                         loop: false,
55
56                         // Change the presentation direction to be RTL
57                         rtl: false,
58
59                         // Number of milliseconds between automatically proceeding to the
60                         // next slide, disabled when set to 0, this value can be overwritten
61                         // by using a data-autoslide attribute on your slides
62                         autoSlide: 0,
63
64                         // Enable slide navigation via mouse wheel
65                         mouseWheel: false,
66
67                         // Apply a 3D roll to links on hover
68                         rollingLinks: true,
69
70                         // Theme (see /css/theme)
71                         theme: null,
72
73                         // Transition style
74                         transition: 'default', // default/cube/page/concave/zoom/linear/fade/none
75
76                         // Script dependencies to load
77                         dependencies: []
78                 },
79
80                 // The current auto-slide duration
81                 autoSlide = 0,
82
83                 // The horizontal and vertical index of the currently active slide
84                 indexh = 0,
85                 indexv = 0,
86
87                 // The previous and current slide HTML elements
88                 previousSlide,
89                 currentSlide,
90
91                 // Slides may hold a data-state attribute which we pick up and apply
92                 // as a class to the body. This list contains the combined state of
93                 // all current slides.
94                 state = [],
95
96                 // The current scale of the presentation (see width/height config)
97                 scale = 1,
98
99                 // Cached references to DOM elements
100                 dom = {},
101
102                 // Detect support for CSS 3D transforms
103                 supports3DTransforms =  'WebkitPerspective' in document.body.style ||
104                                                                 'MozPerspective' in document.body.style ||
105                                                                 'msPerspective' in document.body.style ||
106                                                                 'OPerspective' in document.body.style ||
107                                                                 'perspective' in document.body.style,
108
109                 // Detect support for CSS 2D transforms
110                 supports2DTransforms =  'WebkitTransform' in document.body.style ||
111                                                                 'MozTransform' in document.body.style ||
112                                                                 'msTransform' in document.body.style ||
113                                                                 'OTransform' in document.body.style ||
114                                                                 'transform' in document.body.style,
115
116                 // Throttles mouse wheel navigation
117                 mouseWheelTimeout = 0,
118
119                 // An interval used to automatically move on to the next slide
120                 autoSlideTimeout = 0,
121
122                 // Delays updates to the URL due to a Chrome thumbnailer bug
123                 writeURLTimeout = 0,
124
125                 // A delay used to activate the overview mode
126                 activateOverviewTimeout = 0,
127
128                 // A delay used to deactivate the overview mode
129                 deactivateOverviewTimeout = 0,
130
131                 // Flags if the interaction event listeners are bound
132                 eventsAreBound = false,
133
134                 // Holds information about the currently ongoing touch input
135                 touch = {
136                         startX: 0,
137                         startY: 0,
138                         startSpan: 0,
139                         startCount: 0,
140                         handled: false,
141                         threshold: 80
142                 };
143
144         /**
145          * Starts up the presentation if the client is capable.
146          */
147         function initialize( options ) {
148
149                 if( !supports2DTransforms && !supports3DTransforms ) {
150                         document.body.setAttribute( 'class', 'no-transforms' );
151
152                         // If the browser doesn't support core features we won't be
153                         // using JavaScript to control the presentation
154                         return;
155                 }
156
157                 // Force a layout when the whole page, incl fonts, has loaded
158                 window.addEventListener( 'load', layout, false );
159
160                 // Copy options over to our config object
161                 extend( config, options );
162
163                 // Hide the address bar in mobile browsers
164                 hideAddressBar();
165
166                 // Loads the dependencies and continues to #start() once done
167                 load();
168
169         }
170
171         /**
172          * Finds and stores references to DOM elements which are
173          * required by the presentation. If a required element is
174          * not found, it is created.
175          */
176         function setupDOM() {
177
178                 // Cache references to key DOM elements
179                 dom.theme = document.querySelector( '#theme' );
180                 dom.wrapper = document.querySelector( '.reveal' );
181                 dom.slides = document.querySelector( '.reveal .slides' );
182
183                 // Progress bar
184                 if( !dom.wrapper.querySelector( '.progress' ) && config.progress ) {
185                         var progressElement = document.createElement( 'div' );
186                         progressElement.classList.add( 'progress' );
187                         progressElement.innerHTML = '<span></span>';
188                         dom.wrapper.appendChild( progressElement );
189                 }
190
191                 // Arrow controls
192                 if( !dom.wrapper.querySelector( '.controls' ) && config.controls ) {
193                         var controlsElement = document.createElement( 'aside' );
194                         controlsElement.classList.add( 'controls' );
195                         controlsElement.innerHTML = '<div class="navigate-left"></div>' +
196                                                                                 '<div class="navigate-right"></div>' +
197                                                                                 '<div class="navigate-up"></div>' +
198                                                                                 '<div class="navigate-down"></div>';
199                         dom.wrapper.appendChild( controlsElement );
200                 }
201
202                 // Presentation background element
203                 if( !dom.wrapper.querySelector( '.state-background' ) ) {
204                         var backgroundElement = document.createElement( 'div' );
205                         backgroundElement.classList.add( 'state-background' );
206                         dom.wrapper.appendChild( backgroundElement );
207                 }
208
209                 // Overlay graphic which is displayed during the paused mode
210                 if( !dom.wrapper.querySelector( '.pause-overlay' ) ) {
211                         var pausedElement = document.createElement( 'div' );
212                         pausedElement.classList.add( 'pause-overlay' );
213                         dom.wrapper.appendChild( pausedElement );
214                 }
215
216                 // Cache references to elements
217                 dom.progress = document.querySelector( '.reveal .progress' );
218                 dom.progressbar = document.querySelector( '.reveal .progress span' );
219
220                 if ( config.controls ) {
221                         dom.controls = document.querySelector( '.reveal .controls' );
222
223                         // There can be multiple instances of controls throughout the page
224                         dom.controlsLeft = toArray( document.querySelectorAll( '.navigate-left' ) );
225                         dom.controlsRight = toArray( document.querySelectorAll( '.navigate-right' ) );
226                         dom.controlsUp = toArray( document.querySelectorAll( '.navigate-up' ) );
227                         dom.controlsDown = toArray( document.querySelectorAll( '.navigate-down' ) );
228                         dom.controlsPrev = toArray( document.querySelectorAll( '.navigate-prev' ) );
229                         dom.controlsNext = toArray( document.querySelectorAll( '.navigate-next' ) );
230                 }
231
232         }
233
234         /**
235          * Hides the address bar if we're on a mobile device.
236          */
237         function hideAddressBar() {
238
239                 if( /iphone|ipod|android/gi.test( navigator.userAgent ) && !/crios/gi.test( navigator.userAgent ) ) {
240                         // Events that should trigger the address bar to hide
241                         window.addEventListener( 'load', removeAddressBar, false );
242                         window.addEventListener( 'orientationchange', removeAddressBar, false );
243                 }
244
245         }
246
247         /**
248          * Loads the dependencies of reveal.js. Dependencies are
249          * defined via the configuration option 'dependencies'
250          * and will be loaded prior to starting/binding reveal.js.
251          * Some dependencies may have an 'async' flag, if so they
252          * will load after reveal.js has been started up.
253          */
254         function load() {
255
256                 var scripts = [],
257                         scriptsAsync = [];
258
259                 for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
260                         var s = config.dependencies[i];
261
262                         // Load if there's no condition or the condition is truthy
263                         if( !s.condition || s.condition() ) {
264                                 if( s.async ) {
265                                         scriptsAsync.push( s.src );
266                                 }
267                                 else {
268                                         scripts.push( s.src );
269                                 }
270
271                                 // Extension may contain callback functions
272                                 if( typeof s.callback === 'function' ) {
273                                         head.ready( s.src.match( /([\w\d_\-]*)\.?js$|[^\\\/]*$/i )[0], s.callback );
274                                 }
275                         }
276                 }
277
278                 // Called once synchronous scripts finish loading
279                 function proceed() {
280                         if( scriptsAsync.length ) {
281                                 // Load asynchronous scripts
282                                 head.js.apply( null, scriptsAsync );
283                         }
284
285                         start();
286                 }
287
288                 if( scripts.length ) {
289                         head.ready( proceed );
290
291                         // Load synchronous scripts
292                         head.js.apply( null, scripts );
293                 }
294                 else {
295                         proceed();
296                 }
297
298         }
299
300         /**
301          * Starts up reveal.js by binding input events and navigating
302          * to the current URL deeplink if there is one.
303          */
304         function start() {
305
306                 // Make sure we've got all the DOM elements we need
307                 setupDOM();
308
309                 // Subscribe to input
310                 addEventListeners();
311
312                 // Updates the presentation to match the current configuration values
313                 configure();
314
315                 // Read the initial hash
316                 readURL();
317
318                 // Notify listeners that the presentation is ready but use a 1ms
319                 // timeout to ensure it's not fired synchronously after #initialize()
320                 setTimeout( function() {
321                         dispatchEvent( 'ready', {
322                                 'indexh': indexh,
323                                 'indexv': indexv,
324                                 'currentSlide': currentSlide
325                         } );
326                 }, 1 );
327
328         }
329
330         /**
331          * Applies the configuration settings from the config object.
332          */
333         function configure( options ) {
334
335                 dom.wrapper.classList.remove( config.transition );
336
337                 // New config options may be passed when this method
338                 // is invoked through the API after initialization
339                 if( typeof options === 'object' ) extend( config, options );
340
341                 // Force linear transition based on browser capabilities
342                 if( supports3DTransforms === false ) config.transition = 'linear';
343
344                 dom.wrapper.classList.add( config.transition );
345
346                 if( dom.controls ) {
347                         dom.controls.style.display = ( config.controls && dom.controls ) ? 'block' : 'none';
348                 }
349
350                 if( dom.progress ) {
351                         dom.progress.style.display = ( config.progress && dom.progress ) ? 'block' : 'none';
352                 }
353
354                 if( config.rtl ) {
355                         dom.wrapper.classList.add( 'rtl' );
356                 }
357                 else {
358                         dom.wrapper.classList.remove( 'rtl' );
359                 }
360
361                 if( config.center ) {
362                         dom.wrapper.classList.add( 'center' );
363                 }
364                 else {
365                         dom.wrapper.classList.remove( 'center' );
366                 }
367
368                 if( config.mouseWheel ) {
369                         document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
370                         document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
371                 }
372                 else {
373                         document.removeEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
374                         document.removeEventListener( 'mousewheel', onDocumentMouseScroll, false );
375                 }
376
377                 // 3D links
378                 if( config.rollingLinks ) {
379                         enable3DLinks();
380                 }
381                 else {
382                         disable3DLinks();
383                 }
384
385                 // Load the theme in the config, if it's not already loaded
386                 if( config.theme && dom.theme ) {
387                         var themeURL = dom.theme.getAttribute( 'href' );
388                         var themeFinder = /[^\/]*?(?=\.css)/;
389                         var themeName = themeURL.match(themeFinder)[0];
390
391                         if(  config.theme !== themeName ) {
392                                 themeURL = themeURL.replace(themeFinder, config.theme);
393                                 dom.theme.setAttribute( 'href', themeURL );
394                         }
395                 }
396
397                 // Force a layout to make sure the current config is accounted for
398                 layout();
399
400                 // Reflect the current autoSlide value
401                 autoSlide = config.autoSlide;
402
403                 // Start auto-sliding if it's enabled
404                 cueAutoSlide();
405
406         }
407
408         /**
409          * Binds all event listeners.
410          */
411         function addEventListeners() {
412
413                 eventsAreBound = true;
414
415                 window.addEventListener( 'hashchange', onWindowHashChange, false );
416                 window.addEventListener( 'resize', onWindowResize, false );
417
418                 if( config.touch ) {
419                         dom.wrapper.addEventListener( 'touchstart', onTouchStart, false );
420                         dom.wrapper.addEventListener( 'touchmove', onTouchMove, false );
421                         dom.wrapper.addEventListener( 'touchend', onTouchEnd, false );
422
423                         // Support pointer-style touch interaction as well
424                         if( window.navigator.msPointerEnabled ) {
425                                 dom.wrapper.addEventListener( 'MSPointerDown', onPointerDown, false );
426                                 dom.wrapper.addEventListener( 'MSPointerMove', onPointerMove, false );
427                                 dom.wrapper.addEventListener( 'MSPointerUp', onPointerUp, false );
428                         }
429                 }
430
431                 if( config.keyboard ) {
432                         document.addEventListener( 'keydown', onDocumentKeyDown, false );
433                 }
434
435                 if ( config.progress && dom.progress ) {
436                         dom.progress.addEventListener( 'click', onProgressClicked, false );
437                 }
438
439                 if ( config.controls && dom.controls ) {
440                         [ 'touchstart', 'click' ].forEach( function( eventName ) {
441                                 dom.controlsLeft.forEach( function( el ) { el.addEventListener( eventName, onNavigateLeftClicked, false ); } );
442                                 dom.controlsRight.forEach( function( el ) { el.addEventListener( eventName, onNavigateRightClicked, false ); } );
443                                 dom.controlsUp.forEach( function( el ) { el.addEventListener( eventName, onNavigateUpClicked, false ); } );
444                                 dom.controlsDown.forEach( function( el ) { el.addEventListener( eventName, onNavigateDownClicked, false ); } );
445                                 dom.controlsPrev.forEach( function( el ) { el.addEventListener( eventName, onNavigatePrevClicked, false ); } );
446                                 dom.controlsNext.forEach( function( el ) { el.addEventListener( eventName, onNavigateNextClicked, false ); } );
447                         } );
448                 }
449
450         }
451
452         /**
453          * Unbinds all event listeners.
454          */
455         function removeEventListeners() {
456
457                 eventsAreBound = false;
458
459                 document.removeEventListener( 'keydown', onDocumentKeyDown, false );
460                 window.removeEventListener( 'hashchange', onWindowHashChange, false );
461                 window.removeEventListener( 'resize', onWindowResize, false );
462
463                 if( config.touch ) {
464                         dom.wrapper.removeEventListener( 'touchstart', onTouchStart, false );
465                         dom.wrapper.removeEventListener( 'touchmove', onTouchMove, false );
466                         dom.wrapper.removeEventListener( 'touchend', onTouchEnd, false );
467
468                         if( window.navigator.msPointerEnabled ) {
469                                 dom.wrapper.removeEventListener( 'MSPointerDown', onPointerDown, false );
470                                 dom.wrapper.removeEventListener( 'MSPointerMove', onPointerMove, false );
471                                 dom.wrapper.removeEventListener( 'MSPointerUp', onPointerUp, false );
472                         }
473                 }
474
475                 if ( config.progress && dom.progress ) {
476                         dom.progress.removeEventListener( 'click', onProgressClicked, false );
477                 }
478
479                 if ( config.controls && dom.controls ) {
480                         [ 'touchstart', 'click' ].forEach( function( eventName ) {
481                                 dom.controlsLeft.forEach( function( el ) { el.removeEventListener( eventName, onNavigateLeftClicked, false ); } );
482                                 dom.controlsRight.forEach( function( el ) { el.removeEventListener( eventName, onNavigateRightClicked, false ); } );
483                                 dom.controlsUp.forEach( function( el ) { el.removeEventListener( eventName, onNavigateUpClicked, false ); } );
484                                 dom.controlsDown.forEach( function( el ) { el.removeEventListener( eventName, onNavigateDownClicked, false ); } );
485                                 dom.controlsPrev.forEach( function( el ) { el.removeEventListener( eventName, onNavigatePrevClicked, false ); } );
486                                 dom.controlsNext.forEach( function( el ) { el.removeEventListener( eventName, onNavigateNextClicked, false ); } );
487                         } );
488                 }
489
490         }
491
492         /**
493          * Extend object a with the properties of object b.
494          * If there's a conflict, object b takes precedence.
495          */
496         function extend( a, b ) {
497
498                 for( var i in b ) {
499                         a[ i ] = b[ i ];
500                 }
501
502         }
503
504         /**
505          * Converts the target object to an array.
506          */
507         function toArray( o ) {
508
509                 return Array.prototype.slice.call( o );
510
511         }
512
513         /**
514          * Measures the distance in pixels between point a
515          * and point b.
516          *
517          * @param {Object} a point with x/y properties
518          * @param {Object} b point with x/y properties
519          */
520         function distanceBetween( a, b ) {
521
522                 var dx = a.x - b.x,
523                         dy = a.y - b.y;
524
525                 return Math.sqrt( dx*dx + dy*dy );
526
527         }
528
529         /**
530          * Causes the address bar to hide on mobile devices,
531          * more vertical space ftw.
532          */
533         function removeAddressBar() {
534
535                 if( window.orientation === 0 ) {
536                         document.documentElement.style.overflow = 'scroll';
537                         document.body.style.height = '120%';
538                 }
539                 else {
540                         document.documentElement.style.overflow = '';
541                         document.body.style.height = '100%';
542                 }
543
544                 setTimeout( function() {
545                         window.scrollTo( 0, 1 );
546                 }, 10 );
547
548         }
549
550         /**
551          * Dispatches an event of the specified type from the
552          * reveal DOM element.
553          */
554         function dispatchEvent( type, properties ) {
555
556                 var event = document.createEvent( "HTMLEvents", 1, 2 );
557                 event.initEvent( type, true, true );
558                 extend( event, properties );
559                 dom.wrapper.dispatchEvent( event );
560
561         }
562
563         /**
564          * Wrap all links in 3D goodness.
565          */
566         function enable3DLinks() {
567
568                 if( supports3DTransforms && !( 'msPerspective' in document.body.style ) ) {
569                         var anchors = document.querySelectorAll( SLIDES_SELECTOR + ' a:not(.image)' );
570
571                         for( var i = 0, len = anchors.length; i < len; i++ ) {
572                                 var anchor = anchors[i];
573
574                                 if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) {
575                                         var span = document.createElement('span');
576                                         span.setAttribute('data-title', anchor.text);
577                                         span.innerHTML = anchor.innerHTML;
578
579                                         anchor.classList.add( 'roll' );
580                                         anchor.innerHTML = '';
581                                         anchor.appendChild(span);
582                                 }
583                         }
584                 }
585
586         }
587
588         /**
589          * Unwrap all 3D links.
590          */
591         function disable3DLinks() {
592
593                 var anchors = document.querySelectorAll( SLIDES_SELECTOR + ' a.roll' );
594
595                 for( var i = 0, len = anchors.length; i < len; i++ ) {
596                         var anchor = anchors[i];
597                         var span = anchor.querySelector( 'span' );
598
599                         if( span ) {
600                                 anchor.classList.remove( 'roll' );
601                                 anchor.innerHTML = span.innerHTML;
602                         }
603                 }
604
605         }
606
607         /**
608          * Return a sorted fragments list, ordered by an increasing
609          * "data-fragment-index" attribute.
610          *
611          * Fragments will be revealed in the order that they are returned by
612          * this function, so you can use the index attributes to control the 
613          * order of fragment appearance.
614          *
615          * To maintain a sensible default fragment order, fragments are presumed
616          * to be passed in document order. This function adds a "fragment-index"
617          * attribute to each node if such an attribute is not already present,
618          * and sets that attribute to an integer value which is the position of
619          * the fragment within the fragments list.
620          */
621         function sortFragments( fragments ) {
622
623                 var a = toArray( fragments );
624
625                 a.forEach( function( el, idx ) {
626                         if( !el.hasAttribute( 'data-fragment-index' ) ) {
627                                 el.setAttribute( 'data-fragment-index', idx );
628                         }
629                 } );
630
631                 a.sort( function( l, r ) {
632                         return l.getAttribute( 'data-fragment-index' ) - r.getAttribute( 'data-fragment-index');
633                 } );
634
635                 return a
636
637         }
638
639         /**
640          * Applies JavaScript-controlled layout rules to the
641          * presentation.
642          */
643         function layout() {
644
645                 if( dom.wrapper ) {
646
647                         // Available space to scale within
648                         var availableWidth = dom.wrapper.offsetWidth,
649                                 availableHeight = dom.wrapper.offsetHeight;
650
651                         // Reduce available space by margin
652                         availableWidth -= ( availableHeight * config.margin );
653                         availableHeight -= ( availableHeight * config.margin );
654
655                         // Dimensions of the content
656                         var slideWidth = config.width,
657                                 slideHeight = config.height;
658
659                         // Slide width may be a percentage of available width
660                         if( typeof slideWidth === 'string' && /%$/.test( slideWidth ) ) {
661                                 slideWidth = parseInt( slideWidth, 10 ) / 100 * availableWidth;
662                         }
663
664                         // Slide height may be a percentage of available height
665                         if( typeof slideHeight === 'string' && /%$/.test( slideHeight ) ) {
666                                 slideHeight = parseInt( slideHeight, 10 ) / 100 * availableHeight;
667                         }
668
669                         dom.slides.style.width = slideWidth + 'px';
670                         dom.slides.style.height = slideHeight + 'px';
671
672                         // Determine scale of content to fit within available space
673                         scale = Math.min( availableWidth / slideWidth, availableHeight / slideHeight );
674
675                         // Respect max/min scale settings
676                         scale = Math.max( scale, config.minScale );
677                         scale = Math.min( scale, config.maxScale );
678
679                         // Prefer applying scale via zoom since Chrome blurs scaled content
680                         // with nested transforms
681                         if( typeof dom.slides.style.zoom !== 'undefined' && !navigator.userAgent.match( /(iphone|ipod|ipad|android)/gi ) ) {
682                                 dom.slides.style.zoom = scale;
683                         }
684                         // Apply scale transform as a fallback
685                         else {
686                                 var transform = 'translate(-50%, -50%) scale('+ scale +') translate(50%, 50%)';
687
688                                 dom.slides.style.WebkitTransform = transform;
689                                 dom.slides.style.MozTransform = transform;
690                                 dom.slides.style.msTransform = transform;
691                                 dom.slides.style.OTransform = transform;
692                                 dom.slides.style.transform = transform;
693                         }
694
695                         // Select all slides, vertical and horizontal
696                         var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
697
698                         for( var i = 0, len = slides.length; i < len; i++ ) {
699                                 var slide = slides[ i ];
700
701                                 // Don't bother updating invisible slides
702                                 if( slide.style.display === 'none' ) {
703                                         continue;
704                                 }
705
706                                 if( config.center ) {
707                                         // Vertical stacks are not centred since their section
708                                         // children will be
709                                         if( slide.classList.contains( 'stack' ) ) {
710                                                 slide.style.top = 0;
711                                         }
712                                         else {
713                                                 slide.style.top = Math.max( - ( slide.offsetHeight / 2 ) - 20, -slideHeight / 2 ) + 'px';
714                                         }
715                                 }
716                                 else {
717                                         slide.style.top = '';
718                                 }
719
720                         }
721
722                 }
723
724         }
725
726         /**
727          * Stores the vertical index of a stack so that the same
728          * vertical slide can be selected when navigating to and
729          * from the stack.
730          *
731          * @param {HTMLElement} stack The vertical stack element
732          * @param {int} v Index to memorize
733          */
734         function setPreviousVerticalIndex( stack, v ) {
735
736                 if( typeof stack === 'object' && typeof stack.setAttribute === 'function' ) {
737                         stack.setAttribute( 'data-previous-indexv', v || 0 );
738                 }
739
740         }
741
742         /**
743          * Retrieves the vertical index which was stored using
744          * #setPreviousVerticalIndex() or 0 if no previous index
745          * exists.
746          *
747          * @param {HTMLElement} stack The vertical stack element
748          */
749         function getPreviousVerticalIndex( stack ) {
750
751                 if( typeof stack === 'object' && typeof stack.setAttribute === 'function' && stack.classList.contains( 'stack' ) ) {
752                         return parseInt( stack.getAttribute( 'data-previous-indexv' ) || 0, 10 );
753                 }
754
755                 return 0;
756
757         }
758
759         /**
760          * Displays the overview of slides (quick nav) by
761          * scaling down and arranging all slide elements.
762          *
763          * Experimental feature, might be dropped if perf
764          * can't be improved.
765          */
766         function activateOverview() {
767
768                 // Only proceed if enabled in config
769                 if( config.overview ) {
770
771                         // Don't auto-slide while in overview mode
772                         cancelAutoSlide();
773
774                         var wasActive = dom.wrapper.classList.contains( 'overview' );
775
776                         dom.wrapper.classList.add( 'overview' );
777                         dom.wrapper.classList.remove( 'exit-overview' );
778
779                         clearTimeout( activateOverviewTimeout );
780                         clearTimeout( deactivateOverviewTimeout );
781
782                         // Not the pretties solution, but need to let the overview
783                         // class apply first so that slides are measured accurately
784                         // before we can position them
785                         activateOverviewTimeout = setTimeout( function(){
786
787                                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
788
789                                 for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
790                                         var hslide = horizontalSlides[i],
791                                                 htransform = 'translateZ(-2500px) translate(' + ( ( i - indexh ) * 105 ) + '%, 0%)';
792
793                                         hslide.setAttribute( 'data-index-h', i );
794                                         hslide.style.display = 'block';
795                                         hslide.style.WebkitTransform = htransform;
796                                         hslide.style.MozTransform = htransform;
797                                         hslide.style.msTransform = htransform;
798                                         hslide.style.OTransform = htransform;
799                                         hslide.style.transform = htransform;
800
801                                         if( hslide.classList.contains( 'stack' ) ) {
802
803                                                 var verticalSlides = hslide.querySelectorAll( 'section' );
804
805                                                 for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
806                                                         var verticalIndex = i === indexh ? indexv : getPreviousVerticalIndex( hslide );
807
808                                                         var vslide = verticalSlides[j],
809                                                                 vtransform = 'translate(0%, ' + ( ( j - verticalIndex ) * 105 ) + '%)';
810
811                                                         vslide.setAttribute( 'data-index-h', i );
812                                                         vslide.setAttribute( 'data-index-v', j );
813                                                         vslide.style.display = 'block';
814                                                         vslide.style.WebkitTransform = vtransform;
815                                                         vslide.style.MozTransform = vtransform;
816                                                         vslide.style.msTransform = vtransform;
817                                                         vslide.style.OTransform = vtransform;
818                                                         vslide.style.transform = vtransform;
819
820                                                         // Navigate to this slide on click
821                                                         vslide.addEventListener( 'click', onOverviewSlideClicked, true );
822                                                 }
823
824                                         }
825                                         else {
826
827                                                 // Navigate to this slide on click
828                                                 hslide.addEventListener( 'click', onOverviewSlideClicked, true );
829
830                                         }
831                                 }
832
833                                 layout();
834
835                                 if( !wasActive ) {
836                                         // Notify observers of the overview showing
837                                         dispatchEvent( 'overviewshown', {
838                                                 'indexh': indexh,
839                                                 'indexv': indexv,
840                                                 'currentSlide': currentSlide
841                                         } );
842                                 }
843
844                         }, 10 );
845
846                 }
847
848         }
849
850         /**
851          * Exits the slide overview and enters the currently
852          * active slide.
853          */
854         function deactivateOverview() {
855
856                 // Only proceed if enabled in config
857                 if( config.overview ) {
858
859                         clearTimeout( activateOverviewTimeout );
860                         clearTimeout( deactivateOverviewTimeout );
861
862                         dom.wrapper.classList.remove( 'overview' );
863
864                         // Temporarily add a class so that transitions can do different things
865                         // depending on whether they are exiting/entering overview, or just
866                         // moving from slide to slide
867                         dom.wrapper.classList.add( 'exit-overview' );
868
869                         deactivateOverviewTimeout = setTimeout( function () {
870                                 dom.wrapper.classList.remove( 'exit-overview' );
871                         }, 10);
872
873                         // Select all slides
874                         var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
875
876                         for( var i = 0, len = slides.length; i < len; i++ ) {
877                                 var element = slides[i];
878
879                                 element.style.display = '';
880
881                                 // Resets all transforms to use the external styles
882                                 element.style.WebkitTransform = '';
883                                 element.style.MozTransform = '';
884                                 element.style.msTransform = '';
885                                 element.style.OTransform = '';
886                                 element.style.transform = '';
887
888                                 element.removeEventListener( 'click', onOverviewSlideClicked, true );
889                         }
890
891                         slide( indexh, indexv );
892
893                         cueAutoSlide();
894
895                         // Notify observers of the overview hiding
896                         dispatchEvent( 'overviewhidden', {
897                                 'indexh': indexh,
898                                 'indexv': indexv,
899                                 'currentSlide': currentSlide
900                         } );
901
902                 }
903         }
904
905         /**
906          * Toggles the slide overview mode on and off.
907          *
908          * @param {Boolean} override Optional flag which overrides the
909          * toggle logic and forcibly sets the desired state. True means
910          * overview is open, false means it's closed.
911          */
912         function toggleOverview( override ) {
913
914                 if( typeof override === 'boolean' ) {
915                         override ? activateOverview() : deactivateOverview();
916                 }
917                 else {
918                         isOverview() ? deactivateOverview() : activateOverview();
919                 }
920
921         }
922
923         /**
924          * Checks if the overview is currently active.
925          *
926          * @return {Boolean} true if the overview is active,
927          * false otherwise
928          */
929         function isOverview() {
930
931                 return dom.wrapper.classList.contains( 'overview' );
932
933         }
934
935         /**
936          * Handling the fullscreen functionality via the fullscreen API
937          *
938          * @see http://fullscreen.spec.whatwg.org/
939          * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
940          */
941         function enterFullscreen() {
942
943                 var element = document.body;
944
945                 // Check which implementation is available
946                 var requestMethod = element.requestFullScreen ||
947                                                         element.webkitRequestFullScreen ||
948                                                         element.mozRequestFullScreen ||
949                                                         element.msRequestFullScreen;
950
951                 if( requestMethod ) {
952                         requestMethod.apply( element );
953                 }
954
955         }
956
957         /**
958          * Enters the paused mode which fades everything on screen to
959          * black.
960          */
961         function pause() {
962
963                 var wasPaused = dom.wrapper.classList.contains( 'paused' );
964
965                 cancelAutoSlide();
966                 dom.wrapper.classList.add( 'paused' );
967
968                 if( wasPaused === false ) {
969                         dispatchEvent( 'paused' );
970                 }
971
972         }
973
974         /**
975          * Exits from the paused mode.
976          */
977         function resume() {
978
979                 var wasPaused = dom.wrapper.classList.contains( 'paused' );
980
981                 cueAutoSlide();
982                 dom.wrapper.classList.remove( 'paused' );
983
984                 if( wasPaused ) {
985                         dispatchEvent( 'resumed' );
986                 }
987
988         }
989
990         /**
991          * Toggles the paused mode on and off.
992          */
993         function togglePause() {
994
995                 if( isPaused() ) {
996                         resume();
997                 }
998                 else {
999                         pause();
1000                 }
1001
1002         }
1003
1004         /**
1005          * Checks if we are currently in the paused mode.
1006          */
1007         function isPaused() {
1008
1009                 return dom.wrapper.classList.contains( 'paused' );
1010
1011         }
1012
1013         /**
1014          * Steps from the current point in the presentation to the
1015          * slide which matches the specified horizontal and vertical
1016          * indices.
1017          *
1018          * @param {int} h Horizontal index of the target slide
1019          * @param {int} v Vertical index of the target slide
1020          * @param {int} f Optional index of a fragment within the
1021          * target slide to activate
1022          */
1023         function slide( h, v, f ) {
1024
1025                 // Remember where we were at before
1026                 previousSlide = currentSlide;
1027
1028                 // Query all horizontal slides in the deck
1029                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
1030
1031                 // If no vertical index is specified and the upcoming slide is a
1032                 // stack, resume at its previous vertical index
1033                 if( v === undefined ) {
1034                         v = getPreviousVerticalIndex( horizontalSlides[ h ] );
1035                 }
1036
1037                 // If we were on a vertical stack, remember what vertical index
1038                 // it was on so we can resume at the same position when returning
1039                 if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
1040                         setPreviousVerticalIndex( previousSlide.parentNode, indexv );
1041                 }
1042
1043                 // Remember the state before this slide
1044                 var stateBefore = state.concat();
1045
1046                 // Reset the state array
1047                 state.length = 0;
1048
1049                 var indexhBefore = indexh,
1050                         indexvBefore = indexv;
1051
1052                 // Activate and transition to the new slide
1053                 indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
1054                 indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
1055
1056                 layout();
1057
1058                 // Apply the new state
1059                 stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
1060                         // Check if this state existed on the previous slide. If it
1061                         // did, we will avoid adding it repeatedly
1062                         for( var j = 0; j < stateBefore.length; j++ ) {
1063                                 if( stateBefore[j] === state[i] ) {
1064                                         stateBefore.splice( j, 1 );
1065                                         continue stateLoop;
1066                                 }
1067                         }
1068
1069                         document.documentElement.classList.add( state[i] );
1070
1071                         // Dispatch custom event matching the state's name
1072                         dispatchEvent( state[i] );
1073                 }
1074
1075                 // Clean up the remains of the previous state
1076                 while( stateBefore.length ) {
1077                         document.documentElement.classList.remove( stateBefore.pop() );
1078                 }
1079
1080                 // If the overview is active, re-activate it to update positions
1081                 if( isOverview() ) {
1082                         activateOverview();
1083                 }
1084
1085                 // Update the URL hash after a delay since updating it mid-transition
1086                 // is likely to cause visual lag
1087                 writeURL( 1500 );
1088
1089                 // Find the current horizontal slide and any possible vertical slides
1090                 // within it
1091                 var currentHorizontalSlide = horizontalSlides[ indexh ],
1092                         currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
1093
1094                 // Store references to the previous and current slides
1095                 currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
1096
1097
1098                 // Show fragment, if specified
1099                 if( typeof f !== 'undefined' ) {
1100                         var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
1101
1102                         toArray( fragments ).forEach( function( fragment, indexf ) {
1103                                 if( indexf < f ) {
1104                                         fragment.classList.add( 'visible' );
1105                                 }
1106                                 else {
1107                                         fragment.classList.remove( 'visible' );
1108                                 }
1109                         } );
1110                 }
1111
1112                 // Dispatch an event if the slide changed
1113                 if( indexh !== indexhBefore || indexv !== indexvBefore ) {
1114                         dispatchEvent( 'slidechanged', {
1115                                 'indexh': indexh,
1116                                 'indexv': indexv,
1117                                 'previousSlide': previousSlide,
1118                                 'currentSlide': currentSlide
1119                         } );
1120                 }
1121                 else {
1122                         // Ensure that the previous slide is never the same as the current
1123                         previousSlide = null;
1124                 }
1125
1126                 // Solves an edge case where the previous slide maintains the
1127                 // 'present' class when navigating between adjacent vertical
1128                 // stacks
1129                 if( previousSlide ) {
1130                         previousSlide.classList.remove( 'present' );
1131
1132                         // Reset all slides upon navigate to home
1133                         // Issue: #285
1134                         if ( document.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) {
1135                                 // Launch async task
1136                                 setTimeout( function () {
1137                                         var slides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i;
1138                                         for( i in slides ) {
1139                                                 if( slides[i] ) {
1140                                                         // Reset stack
1141                                                         setPreviousVerticalIndex( slides[i], 0 );
1142                                                 }
1143                                         }
1144                                 }, 0 );
1145                         }
1146                 }
1147
1148                 updateControls();
1149                 updateProgress();
1150
1151         }
1152
1153         /**
1154          * Updates one dimension of slides by showing the slide
1155          * with the specified index.
1156          *
1157          * @param {String} selector A CSS selector that will fetch
1158          * the group of slides we are working with
1159          * @param {Number} index The index of the slide that should be
1160          * shown
1161          *
1162          * @return {Number} The index of the slide that is now shown,
1163          * might differ from the passed in index if it was out of
1164          * bounds.
1165          */
1166         function updateSlides( selector, index ) {
1167
1168                 // Select all slides and convert the NodeList result to
1169                 // an array
1170                 var slides = toArray( document.querySelectorAll( selector ) ),
1171                         slidesLength = slides.length;
1172
1173                 if( slidesLength ) {
1174
1175                         // Should the index loop?
1176                         if( config.loop ) {
1177                                 index %= slidesLength;
1178
1179                                 if( index < 0 ) {
1180                                         index = slidesLength + index;
1181                                 }
1182                         }
1183
1184                         // Enforce max and minimum index bounds
1185                         index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
1186
1187                         for( var i = 0; i < slidesLength; i++ ) {
1188                                 var element = slides[i];
1189
1190                                 // Optimization; hide all slides that are three or more steps
1191                                 // away from the present slide
1192                                 if( isOverview() === false ) {
1193                                         // The distance loops so that it measures 1 between the first
1194                                         // and last slides
1195                                         var distance = Math.abs( ( index - i ) % ( slidesLength - 3 ) ) || 0;
1196
1197                                         element.style.display = distance > 3 ? 'none' : 'block';
1198                                 }
1199
1200                                 slides[i].classList.remove( 'past' );
1201                                 slides[i].classList.remove( 'present' );
1202                                 slides[i].classList.remove( 'future' );
1203
1204                                 if( i < index ) {
1205                                         // Any element previous to index is given the 'past' class
1206                                         slides[i].classList.add( 'past' );
1207                                 }
1208                                 else if( i > index ) {
1209                                         // Any element subsequent to index is given the 'future' class
1210                                         slides[i].classList.add( 'future' );
1211                                 }
1212
1213                                 // If this element contains vertical slides
1214                                 if( element.querySelector( 'section' ) ) {
1215                                         slides[i].classList.add( 'stack' );
1216                                 }
1217                         }
1218
1219                         // Mark the current slide as present
1220                         slides[index].classList.add( 'present' );
1221
1222                         // If this slide has a state associated with it, add it
1223                         // onto the current state of the deck
1224                         var slideState = slides[index].getAttribute( 'data-state' );
1225                         if( slideState ) {
1226                                 state = state.concat( slideState.split( ' ' ) );
1227                         }
1228
1229                         // If this slide has a data-autoslide attribtue associated use this as
1230                         // autoSlide value otherwise use the global configured time
1231                         var slideAutoSlide = slides[index].getAttribute( 'data-autoslide' );
1232                         if( slideAutoSlide ) {
1233                                 autoSlide = parseInt( slideAutoSlide, 10 );
1234                         }
1235                         else {
1236                                 autoSlide = config.autoSlide;
1237                         }
1238
1239                 }
1240                 else {
1241                         // Since there are no slides we can't be anywhere beyond the
1242                         // zeroth index
1243                         index = 0;
1244                 }
1245
1246                 return index;
1247
1248         }
1249
1250         /**
1251          * Updates the progress bar to reflect the current slide.
1252          */
1253         function updateProgress() {
1254
1255                 // Update progress if enabled
1256                 if( config.progress && dom.progress ) {
1257
1258                         var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1259
1260                         // The number of past and total slides
1261                         var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
1262                         var pastCount = 0;
1263
1264                         // Step through all slides and count the past ones
1265                         mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
1266
1267                                 var horizontalSlide = horizontalSlides[i];
1268                                 var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
1269
1270                                 for( var j = 0; j < verticalSlides.length; j++ ) {
1271
1272                                         // Stop as soon as we arrive at the present
1273                                         if( verticalSlides[j].classList.contains( 'present' ) ) {
1274                                                 break mainLoop;
1275                                         }
1276
1277                                         pastCount++;
1278
1279                                 }
1280
1281                                 // Stop as soon as we arrive at the present
1282                                 if( horizontalSlide.classList.contains( 'present' ) ) {
1283                                         break;
1284                                 }
1285
1286                                 // Don't count the wrapping section for vertical slides
1287                                 if( horizontalSlide.classList.contains( 'stack' ) === false ) {
1288                                         pastCount++;
1289                                 }
1290
1291                         }
1292
1293                         dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';
1294
1295                 }
1296
1297         }
1298
1299         /**
1300          * Updates the state of all control/navigation arrows.
1301          */
1302         function updateControls() {
1303
1304                 if ( config.controls && dom.controls ) {
1305
1306                         var routes = availableRoutes();
1307
1308                         // Remove the 'enabled' class from all directions
1309                         dom.controlsLeft.concat( dom.controlsRight )
1310                                                         .concat( dom.controlsUp )
1311                                                         .concat( dom.controlsDown )
1312                                                         .concat( dom.controlsPrev )
1313                                                         .concat( dom.controlsNext ).forEach( function( node ) {
1314                                 node.classList.remove( 'enabled' );
1315                         } );
1316
1317                         // Add the 'enabled' class to the available routes
1318                         if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' );     } );
1319                         if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1320                         if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1321                         if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1322
1323                         // Prev/next buttons
1324                         if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1325                         if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1326
1327                 }
1328
1329         }
1330
1331         /**
1332          * Determine what available routes there are for navigation.
1333          *
1334          * @return {Object} containing four booleans: left/right/up/down
1335          */
1336         function availableRoutes() {
1337
1338                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
1339                         verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
1340
1341                 return {
1342                         left: indexh > 0 || config.loop,
1343                         right: indexh < horizontalSlides.length - 1 || config.loop,
1344                         up: indexv > 0,
1345                         down: indexv < verticalSlides.length - 1
1346                 };
1347
1348         }
1349
1350         /**
1351          * Reads the current URL (hash) and navigates accordingly.
1352          */
1353         function readURL() {
1354
1355                 var hash = window.location.hash;
1356
1357                 // Attempt to parse the hash as either an index or name
1358                 var bits = hash.slice( 2 ).split( '/' ),
1359                         name = hash.replace( /#|\//gi, '' );
1360
1361                 // If the first bit is invalid and there is a name we can
1362                 // assume that this is a named link
1363                 if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
1364                         // Find the slide with the specified name
1365                         var element = document.querySelector( '#' + name );
1366
1367                         if( element ) {
1368                                 // Find the position of the named slide and navigate to it
1369                                 var indices = Reveal.getIndices( element );
1370                                 slide( indices.h, indices.v );
1371                         }
1372                         // If the slide doesn't exist, navigate to the current slide
1373                         else {
1374                                 slide( indexh, indexv );
1375                         }
1376                 }
1377                 else {
1378                         // Read the index components of the hash
1379                         var h = parseInt( bits[0], 10 ) || 0,
1380                                 v = parseInt( bits[1], 10 ) || 0;
1381
1382                         slide( h, v );
1383                 }
1384
1385         }
1386
1387         /**
1388          * Updates the page URL (hash) to reflect the current
1389          * state.
1390          *
1391          * @param {Number} delay The time in ms to wait before
1392          * writing the hash
1393          */
1394         function writeURL( delay ) {
1395
1396                 if( config.history ) {
1397
1398                         // Make sure there's never more than one timeout running
1399                         clearTimeout( writeURLTimeout );
1400
1401                         // If a delay is specified, timeout this call
1402                         if( typeof delay === 'number' ) {
1403                                 writeURLTimeout = setTimeout( writeURL, delay );
1404                         }
1405                         else {
1406                                 var url = '/';
1407
1408                                 // If the current slide has an ID, use that as a named link
1409                                 if( currentSlide && typeof currentSlide.getAttribute( 'id' ) === 'string' ) {
1410                                         url = '/' + currentSlide.getAttribute( 'id' );
1411                                 }
1412                                 // Otherwise use the /h/v index
1413                                 else {
1414                                         if( indexh > 0 || indexv > 0 ) url += indexh;
1415                                         if( indexv > 0 ) url += '/' + indexv;
1416                                 }
1417
1418                                 window.location.hash = url;
1419                         }
1420                 }
1421
1422         }
1423
1424         /**
1425          * Retrieves the h/v location of the current, or specified,
1426          * slide.
1427          *
1428          * @param {HTMLElement} slide If specified, the returned
1429          * index will be for this slide rather than the currently
1430          * active one
1431          *
1432          * @return {Object} { h: <int>, v: <int> }
1433          */
1434         function getIndices( slide ) {
1435
1436                 // By default, return the current indices
1437                 var h = indexh,
1438                         v = indexv;
1439
1440                 // If a slide is specified, return the indices of that slide
1441                 if( slide ) {
1442                         var isVertical = !!slide.parentNode.nodeName.match( /section/gi );
1443                         var slideh = isVertical ? slide.parentNode : slide;
1444
1445                         // Select all horizontal slides
1446                         var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1447
1448                         // Now that we know which the horizontal slide is, get its index
1449                         h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
1450
1451                         // If this is a vertical slide, grab the vertical index
1452                         if( isVertical ) {
1453                                 v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
1454                         }
1455                 }
1456
1457                 return { h: h, v: v };
1458
1459         }
1460
1461         /**
1462          * Navigate to the next slide fragment.
1463          *
1464          * @return {Boolean} true if there was a next fragment,
1465          * false otherwise
1466          */
1467         function nextFragment() {
1468
1469                 // Vertical slides:
1470                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1471                         var verticalFragments = sortFragments( document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' ) );
1472
1473                         if( verticalFragments.length ) {
1474                                 verticalFragments[0].classList.add( 'visible' );
1475
1476                                 // Notify subscribers of the change
1477                                 dispatchEvent( 'fragmentshown', { fragment: verticalFragments[0] } );
1478                                 return true;
1479                         }
1480                 }
1481                 // Horizontal slides:
1482                 else {
1483                         var horizontalFragments = sortFragments( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' ) );
1484
1485                         if( horizontalFragments.length ) {
1486                                 horizontalFragments[0].classList.add( 'visible' );
1487
1488                                 // Notify subscribers of the change
1489                                 dispatchEvent( 'fragmentshown', { fragment: horizontalFragments[0] } );
1490                                 return true;
1491                         }
1492                 }
1493
1494                 return false;
1495
1496         }
1497
1498         /**
1499          * Navigate to the previous slide fragment.
1500          *
1501          * @return {Boolean} true if there was a previous fragment,
1502          * false otherwise
1503          */
1504         function previousFragment() {
1505
1506                 // Vertical slides:
1507                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1508                         var verticalFragments = sortFragments( document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment.visible' ) );
1509
1510                         if( verticalFragments.length ) {
1511                                 verticalFragments[ verticalFragments.length - 1 ].classList.remove( 'visible' );
1512
1513                                 // Notify subscribers of the change
1514                                 dispatchEvent( 'fragmenthidden', { fragment: verticalFragments[ verticalFragments.length - 1 ] } );
1515                                 return true;
1516                         }
1517                 }
1518                 // Horizontal slides:
1519                 else {
1520                         var horizontalFragments = sortFragments( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment.visible' ) );
1521
1522                         if( horizontalFragments.length ) {
1523                                 horizontalFragments[ horizontalFragments.length - 1 ].classList.remove( 'visible' );
1524
1525                                 // Notify subscribers of the change
1526                                 dispatchEvent( 'fragmenthidden', { fragment: horizontalFragments[ horizontalFragments.length - 1 ] } );
1527                                 return true;
1528                         }
1529                 }
1530
1531                 return false;
1532
1533         }
1534
1535         /**
1536          * Cues a new automated slide if enabled in the config.
1537          */
1538         function cueAutoSlide() {
1539
1540                 clearTimeout( autoSlideTimeout );
1541
1542                 // Cue the next auto-slide if enabled
1543                 if( autoSlide && !isPaused() && !isOverview() ) {
1544                         autoSlideTimeout = setTimeout( navigateNext, autoSlide );
1545                 }
1546
1547         }
1548
1549         /**
1550          * Cancels any ongoing request to auto-slide.
1551          */
1552         function cancelAutoSlide() {
1553
1554                 clearTimeout( autoSlideTimeout );
1555
1556         }
1557
1558         function navigateLeft() {
1559
1560                 // Prioritize hiding fragments
1561                 if( availableRoutes().left && ( isOverview() || previousFragment() === false ) ) {
1562                         slide( indexh - 1 );
1563                 }
1564
1565         }
1566
1567         function navigateRight() {
1568
1569                 // Prioritize revealing fragments
1570                 if( availableRoutes().right && ( isOverview() || nextFragment() === false ) ) {
1571                         slide( indexh + 1 );
1572                 }
1573
1574         }
1575
1576         function navigateUp() {
1577
1578                 // Prioritize hiding fragments
1579                 if( availableRoutes().up && isOverview() || previousFragment() === false ) {
1580                         slide( indexh, indexv - 1 );
1581                 }
1582
1583         }
1584
1585         function navigateDown() {
1586
1587                 // Prioritize revealing fragments
1588                 if( availableRoutes().down && isOverview() || nextFragment() === false ) {
1589                         slide( indexh, indexv + 1 );
1590                 }
1591
1592         }
1593
1594         /**
1595          * Navigates backwards, prioritized in the following order:
1596          * 1) Previous fragment
1597          * 2) Previous vertical slide
1598          * 3) Previous horizontal slide
1599          */
1600         function navigatePrev() {
1601
1602                 // Prioritize revealing fragments
1603                 if( previousFragment() === false ) {
1604                         if( availableRoutes().up ) {
1605                                 navigateUp();
1606                         }
1607                         else {
1608                                 // Fetch the previous horizontal slide, if there is one
1609                                 var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
1610
1611                                 if( previousSlide ) {
1612                                         indexv = ( previousSlide.querySelectorAll( 'section' ).length + 1 ) || undefined;
1613                                         indexh --;
1614                                         slide();
1615                                 }
1616                         }
1617                 }
1618
1619         }
1620
1621         /**
1622          * Same as #navigatePrev() but navigates forwards.
1623          */
1624         function navigateNext() {
1625
1626                 // Prioritize revealing fragments
1627                 if( nextFragment() === false ) {
1628                         availableRoutes().down ? navigateDown() : navigateRight();
1629                 }
1630
1631                 // If auto-sliding is enabled we need to cue up
1632                 // another timeout
1633                 cueAutoSlide();
1634
1635         }
1636
1637
1638         // --------------------------------------------------------------------//
1639         // ----------------------------- EVENTS -------------------------------//
1640         // --------------------------------------------------------------------//
1641
1642
1643         /**
1644          * Handler for the document level 'keydown' event.
1645          *
1646          * @param {Object} event
1647          */
1648         function onDocumentKeyDown( event ) {
1649
1650                 // Check if there's a focused element that could be using
1651                 // the keyboard
1652                 var activeElement = document.activeElement;
1653                 var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
1654
1655                 // Disregard the event if there's a focused element or a
1656                 // keyboard modifier key is present
1657                 if( hasFocus || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;
1658
1659                 var triggered = true;
1660
1661                 // while paused only allow "unpausing" keyboard events (b and .)
1662                 if( isPaused() && [66,190,191].indexOf( event.keyCode ) === -1 ) {
1663                         return false;
1664                 }
1665
1666                 switch( event.keyCode ) {
1667                         // p, page up
1668                         case 80: case 33: navigatePrev(); break;
1669                         // n, page down
1670                         case 78: case 34: navigateNext(); break;
1671                         // h, left
1672                         case 72: case 37: navigateLeft(); break;
1673                         // l, right
1674                         case 76: case 39: navigateRight(); break;
1675                         // k, up
1676                         case 75: case 38: navigateUp(); break;
1677                         // j, down
1678                         case 74: case 40: navigateDown(); break;
1679                         // home
1680                         case 36: slide( 0 ); break;
1681                         // end
1682                         case 35: slide( Number.MAX_VALUE ); break;
1683                         // space
1684                         case 32: isOverview() ? deactivateOverview() : navigateNext(); break;
1685                         // return
1686                         case 13: isOverview() ? deactivateOverview() : triggered = false; break;
1687                         // b, period, Logitech presenter tools "black screen" button
1688                         case 66: case 190: case 191: togglePause(); break;
1689                         // f
1690                         case 70: enterFullscreen(); break;
1691                         default:
1692                                 triggered = false;
1693                 }
1694
1695                 // If the input resulted in a triggered action we should prevent
1696                 // the browsers default behavior
1697                 if( triggered ) {
1698                         event.preventDefault();
1699                 }
1700                 else if ( event.keyCode === 27 && supports3DTransforms ) {
1701                         toggleOverview();
1702
1703                         event.preventDefault();
1704                 }
1705
1706                 // If auto-sliding is enabled we need to cue up
1707                 // another timeout
1708                 cueAutoSlide();
1709
1710         }
1711
1712         /**
1713          * Handler for the 'touchstart' event, enables support for 
1714          * swipe and pinch gestures.
1715          */
1716         function onTouchStart( event ) {
1717
1718                 touch.startX = event.touches[0].clientX;
1719                 touch.startY = event.touches[0].clientY;
1720                 touch.startCount = event.touches.length;
1721
1722                 // If there's two touches we need to memorize the distance
1723                 // between those two points to detect pinching
1724                 if( event.touches.length === 2 && config.overview ) {
1725                         touch.startSpan = distanceBetween( {
1726                                 x: event.touches[1].clientX,
1727                                 y: event.touches[1].clientY
1728                         }, {
1729                                 x: touch.startX,
1730                                 y: touch.startY
1731                         } );
1732                 }
1733
1734         }
1735
1736         /**
1737          * Handler for the 'touchmove' event.
1738          */
1739         function onTouchMove( event ) {
1740
1741                 // Each touch should only trigger one action
1742                 if( !touch.handled ) {
1743                         var currentX = event.touches[0].clientX;
1744                         var currentY = event.touches[0].clientY;
1745
1746                         // If the touch started off with two points and still has
1747                         // two active touches; test for the pinch gesture
1748                         if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
1749
1750                                 // The current distance in pixels between the two touch points
1751                                 var currentSpan = distanceBetween( {
1752                                         x: event.touches[1].clientX,
1753                                         y: event.touches[1].clientY
1754                                 }, {
1755                                         x: touch.startX,
1756                                         y: touch.startY
1757                                 } );
1758
1759                                 // If the span is larger than the desire amount we've got
1760                                 // ourselves a pinch
1761                                 if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
1762                                         touch.handled = true;
1763
1764                                         if( currentSpan < touch.startSpan ) {
1765                                                 activateOverview();
1766                                         }
1767                                         else {
1768                                                 deactivateOverview();
1769                                         }
1770                                 }
1771
1772                                 event.preventDefault();
1773
1774                         }
1775                         // There was only one touch point, look for a swipe
1776                         else if( event.touches.length === 1 && touch.startCount !== 2 ) {
1777
1778                                 var deltaX = currentX - touch.startX,
1779                                         deltaY = currentY - touch.startY;
1780
1781                                 if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1782                                         touch.handled = true;
1783                                         navigateLeft();
1784                                 }
1785                                 else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1786                                         touch.handled = true;
1787                                         navigateRight();
1788                                 }
1789                                 else if( deltaY > touch.threshold ) {
1790                                         touch.handled = true;
1791                                         navigateUp();
1792                                 }
1793                                 else if( deltaY < -touch.threshold ) {
1794                                         touch.handled = true;
1795                                         navigateDown();
1796                                 }
1797
1798                                 event.preventDefault();
1799
1800                         }
1801                 }
1802                 // There's a bug with swiping on some Android devices unless
1803                 // the default action is always prevented
1804                 else if( navigator.userAgent.match( /android/gi ) ) {
1805                         event.preventDefault();
1806                 }
1807
1808         }
1809
1810         /**
1811          * Handler for the 'touchend' event.
1812          */
1813         function onTouchEnd( event ) {
1814
1815                 touch.handled = false;
1816
1817         }
1818
1819         /**
1820          * Convert pointer down to touch start.
1821          */
1822         function onPointerDown( event ) {
1823
1824                 if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
1825                         event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
1826                         this.onTouchStart( event );
1827                 }
1828
1829         }
1830
1831         /**
1832          * Convert pointer move to touch move.
1833          */
1834         function onPointerMove( event ) {
1835
1836                 if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
1837                         event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
1838                         this.onTouchMove( event );
1839                 }
1840
1841         }
1842
1843         /**
1844          * Convert pointer up to touch end.
1845          */
1846         function onPointerUp( event ) {
1847
1848                 if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
1849                         event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
1850                         this.onTouchEnd( event );
1851                 }
1852
1853         }
1854
1855         /**
1856          * Handles mouse wheel scrolling, throttled to avoid skipping
1857          * multiple slides.
1858          */
1859         function onDocumentMouseScroll( event ) {
1860
1861                 clearTimeout( mouseWheelTimeout );
1862
1863                 mouseWheelTimeout = setTimeout( function() {
1864                         var delta = event.detail || -event.wheelDelta;
1865                         if( delta > 0 ) {
1866                                 navigateNext();
1867                         }
1868                         else {
1869                                 navigatePrev();
1870                         }
1871                 }, 100 );
1872
1873         }
1874
1875         /**
1876          * Clicking on the progress bar results in a navigation to the
1877          * closest approximate horizontal slide using this equation:
1878          *
1879          * ( clickX / presentationWidth ) * numberOfSlides
1880          */
1881         function onProgressClicked( event ) {
1882
1883                 event.preventDefault();
1884
1885                 var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
1886                 var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
1887
1888                 slide( slideIndex );
1889
1890         }
1891
1892         /**
1893          * Event handler for navigation control buttons.
1894          */
1895         function onNavigateLeftClicked( event ) { event.preventDefault(); navigateLeft(); }
1896         function onNavigateRightClicked( event ) { event.preventDefault(); navigateRight(); }
1897         function onNavigateUpClicked( event ) { event.preventDefault(); navigateUp(); }
1898         function onNavigateDownClicked( event ) { event.preventDefault(); navigateDown(); }
1899         function onNavigatePrevClicked( event ) { event.preventDefault(); navigatePrev(); }
1900         function onNavigateNextClicked( event ) { event.preventDefault(); navigateNext(); }
1901
1902         /**
1903          * Handler for the window level 'hashchange' event.
1904          */
1905         function onWindowHashChange( event ) {
1906
1907                 readURL();
1908
1909         }
1910
1911         /**
1912          * Handler for the window level 'resize' event.
1913          */
1914         function onWindowResize( event ) {
1915
1916                 layout();
1917
1918         }
1919
1920         /**
1921          * Invoked when a slide is and we're in the overview.
1922          */
1923         function onOverviewSlideClicked( event ) {
1924
1925                 // TODO There's a bug here where the event listeners are not
1926                 // removed after deactivating the overview.
1927                 if( eventsAreBound && isOverview() ) {
1928                         event.preventDefault();
1929
1930                         var element = event.target;
1931
1932                         while( element && !element.nodeName.match( /section/gi ) ) {
1933                                 element = element.parentNode;
1934                         }
1935
1936                         if( element && !element.classList.contains( 'disabled' ) ) {
1937
1938                                 deactivateOverview();
1939
1940                                 if( element.nodeName.match( /section/gi ) ) {
1941                                         var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
1942                                                 v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
1943
1944                                         slide( h, v );
1945                                 }
1946
1947                         }
1948                 }
1949
1950         }
1951
1952
1953         // --------------------------------------------------------------------//
1954         // ------------------------------- API --------------------------------//
1955         // --------------------------------------------------------------------//
1956
1957
1958         return {
1959                 initialize: initialize,
1960                 configure: configure,
1961
1962                 // Navigation methods
1963                 slide: slide,
1964                 left: navigateLeft,
1965                 right: navigateRight,
1966                 up: navigateUp,
1967                 down: navigateDown,
1968                 prev: navigatePrev,
1969                 next: navigateNext,
1970                 prevFragment: previousFragment,
1971                 nextFragment: nextFragment,
1972
1973                 // Deprecated aliases
1974                 navigateTo: slide,
1975                 navigateLeft: navigateLeft,
1976                 navigateRight: navigateRight,
1977                 navigateUp: navigateUp,
1978                 navigateDown: navigateDown,
1979                 navigatePrev: navigatePrev,
1980                 navigateNext: navigateNext,
1981
1982                 // Forces an update in slide layout
1983                 layout: layout,
1984
1985                 // Toggles the overview mode on/off
1986                 toggleOverview: toggleOverview,
1987
1988                 // Toggles the "black screen" mode on/off
1989                 togglePause: togglePause,
1990
1991                 // State checks
1992                 isOverview: isOverview,
1993                 isPaused: isPaused,
1994
1995                 // Adds or removes all internal event listeners (such as keyboard)
1996                 addEventListeners: addEventListeners,
1997                 removeEventListeners: removeEventListeners,
1998
1999                 // Returns the indices of the current, or specified, slide
2000                 getIndices: getIndices,
2001
2002                 // Returns the slide at the specified index, y is optional
2003                 getSlide: function( x, y ) {
2004                         var horizontalSlide = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
2005                         var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
2006
2007                         if( typeof y !== 'undefined' ) {
2008                                 return verticalSlides ? verticalSlides[ y ] : undefined;
2009                         }
2010
2011                         return horizontalSlide;
2012                 },
2013
2014                 // Returns the previous slide element, may be null
2015                 getPreviousSlide: function() {
2016                         return previousSlide;
2017                 },
2018
2019                 // Returns the current slide element
2020                 getCurrentSlide: function() {
2021                         return currentSlide;
2022                 },
2023
2024                 // Returns the current scale of the presentation content
2025                 getScale: function() {
2026                         return scale;
2027                 },
2028
2029                 // Helper method, retrieves query string as a key/value hash
2030                 getQueryHash: function() {
2031                         var query = {};
2032
2033                         location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
2034                                 query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
2035                         } );
2036
2037                         return query;
2038                 },
2039
2040                 // Returns true if we're currently on the first slide
2041                 isFirstSlide: function() {
2042                         return document.querySelector( SLIDES_SELECTOR + '.past' ) == null ? true : false;
2043                 },
2044
2045                 // Returns true if we're currently on the last slide
2046                 isLastSlide: function() {
2047                         if( currentSlide && currentSlide.classList.contains( '.stack' ) ) {
2048                                 return currentSlide.querySelector( SLIDES_SELECTOR + '.future' ) == null ? true : false;
2049                         }
2050                         else {
2051                                 return document.querySelector( SLIDES_SELECTOR + '.future' ) == null ? true : false;
2052                         }
2053                 },
2054
2055                 // Forward event binding to the reveal DOM element
2056                 addEventListener: function( type, listener, useCapture ) {
2057                         if( 'addEventListener' in window ) {
2058                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
2059                         }
2060                 },
2061                 removeEventListener: function( type, listener, useCapture ) {
2062                         if( 'addEventListener' in window ) {
2063                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
2064                         }
2065                 }
2066         };
2067
2068 })();