remove extra whitespace
[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          * @param {int} o Optional origin for use in multimaster environments
1023          */
1024         function slide( h, v, f, o ) {
1025
1026                 // Remember where we were at before
1027                 previousSlide = currentSlide;
1028
1029                 // Query all horizontal slides in the deck
1030                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
1031
1032                 // If no vertical index is specified and the upcoming slide is a
1033                 // stack, resume at its previous vertical index
1034                 if( v === undefined ) {
1035                         v = getPreviousVerticalIndex( horizontalSlides[ h ] );
1036                 }
1037
1038                 // If we were on a vertical stack, remember what vertical index
1039                 // it was on so we can resume at the same position when returning
1040                 if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
1041                         setPreviousVerticalIndex( previousSlide.parentNode, indexv );
1042                 }
1043
1044                 // Remember the state before this slide
1045                 var stateBefore = state.concat();
1046
1047                 // Reset the state array
1048                 state.length = 0;
1049
1050                 var indexhBefore = indexh,
1051                         indexvBefore = indexv;
1052
1053                 // Activate and transition to the new slide
1054                 indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
1055                 indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
1056
1057                 layout();
1058
1059                 // Apply the new state
1060                 stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
1061                         // Check if this state existed on the previous slide. If it
1062                         // did, we will avoid adding it repeatedly
1063                         for( var j = 0; j < stateBefore.length; j++ ) {
1064                                 if( stateBefore[j] === state[i] ) {
1065                                         stateBefore.splice( j, 1 );
1066                                         continue stateLoop;
1067                                 }
1068                         }
1069
1070                         document.documentElement.classList.add( state[i] );
1071
1072                         // Dispatch custom event matching the state's name
1073                         dispatchEvent( state[i] );
1074                 }
1075
1076                 // Clean up the remains of the previous state
1077                 while( stateBefore.length ) {
1078                         document.documentElement.classList.remove( stateBefore.pop() );
1079                 }
1080
1081                 // If the overview is active, re-activate it to update positions
1082                 if( isOverview() ) {
1083                         activateOverview();
1084                 }
1085
1086                 // Update the URL hash after a delay since updating it mid-transition
1087                 // is likely to cause visual lag
1088                 writeURL( 1500 );
1089
1090                 // Find the current horizontal slide and any possible vertical slides
1091                 // within it
1092                 var currentHorizontalSlide = horizontalSlides[ indexh ],
1093                         currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
1094
1095                 // Store references to the previous and current slides
1096                 currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
1097
1098
1099                 // Show fragment, if specified
1100                 if( typeof f !== 'undefined' ) {
1101                         var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
1102
1103                         toArray( fragments ).forEach( function( fragment, indexf ) {
1104                                 if( indexf < f ) {
1105                                         fragment.classList.add( 'visible' );
1106                                 }
1107                                 else {
1108                                         fragment.classList.remove( 'visible' );
1109                                 }
1110                         } );
1111                 }
1112
1113                 // Dispatch an event if the slide changed
1114                 if( indexh !== indexhBefore || indexv !== indexvBefore ) {
1115                         dispatchEvent( 'slidechanged', {
1116                                 'indexh': indexh,
1117                                 'indexv': indexv,
1118                                 'previousSlide': previousSlide,
1119                                 'currentSlide': currentSlide,
1120                                 'origin': o
1121                         } );
1122                 }
1123                 else {
1124                         // Ensure that the previous slide is never the same as the current
1125                         previousSlide = null;
1126                 }
1127
1128                 // Solves an edge case where the previous slide maintains the
1129                 // 'present' class when navigating between adjacent vertical
1130                 // stacks
1131                 if( previousSlide ) {
1132                         previousSlide.classList.remove( 'present' );
1133
1134                         // Reset all slides upon navigate to home
1135                         // Issue: #285
1136                         if ( document.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) {
1137                                 // Launch async task
1138                                 setTimeout( function () {
1139                                         var slides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i;
1140                                         for( i in slides ) {
1141                                                 if( slides[i] ) {
1142                                                         // Reset stack
1143                                                         setPreviousVerticalIndex( slides[i], 0 );
1144                                                 }
1145                                         }
1146                                 }, 0 );
1147                         }
1148                 }
1149
1150                 updateControls();
1151                 updateProgress();
1152
1153         }
1154
1155         /**
1156          * Updates one dimension of slides by showing the slide
1157          * with the specified index.
1158          *
1159          * @param {String} selector A CSS selector that will fetch
1160          * the group of slides we are working with
1161          * @param {Number} index The index of the slide that should be
1162          * shown
1163          *
1164          * @return {Number} The index of the slide that is now shown,
1165          * might differ from the passed in index if it was out of
1166          * bounds.
1167          */
1168         function updateSlides( selector, index ) {
1169
1170                 // Select all slides and convert the NodeList result to
1171                 // an array
1172                 var slides = toArray( document.querySelectorAll( selector ) ),
1173                         slidesLength = slides.length;
1174
1175                 if( slidesLength ) {
1176
1177                         // Should the index loop?
1178                         if( config.loop ) {
1179                                 index %= slidesLength;
1180
1181                                 if( index < 0 ) {
1182                                         index = slidesLength + index;
1183                                 }
1184                         }
1185
1186                         // Enforce max and minimum index bounds
1187                         index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
1188
1189                         for( var i = 0; i < slidesLength; i++ ) {
1190                                 var element = slides[i];
1191
1192                                 // Optimization; hide all slides that are three or more steps
1193                                 // away from the present slide
1194                                 if( isOverview() === false ) {
1195                                         // The distance loops so that it measures 1 between the first
1196                                         // and last slides
1197                                         var distance = Math.abs( ( index - i ) % ( slidesLength - 3 ) ) || 0;
1198
1199                                         element.style.display = distance > 3 ? 'none' : 'block';
1200                                 }
1201
1202                                 slides[i].classList.remove( 'past' );
1203                                 slides[i].classList.remove( 'present' );
1204                                 slides[i].classList.remove( 'future' );
1205
1206                                 if( i < index ) {
1207                                         // Any element previous to index is given the 'past' class
1208                                         slides[i].classList.add( 'past' );
1209                                 }
1210                                 else if( i > index ) {
1211                                         // Any element subsequent to index is given the 'future' class
1212                                         slides[i].classList.add( 'future' );
1213                                 }
1214
1215                                 // If this element contains vertical slides
1216                                 if( element.querySelector( 'section' ) ) {
1217                                         slides[i].classList.add( 'stack' );
1218                                 }
1219                         }
1220
1221                         // Mark the current slide as present
1222                         slides[index].classList.add( 'present' );
1223
1224                         // If this slide has a state associated with it, add it
1225                         // onto the current state of the deck
1226                         var slideState = slides[index].getAttribute( 'data-state' );
1227                         if( slideState ) {
1228                                 state = state.concat( slideState.split( ' ' ) );
1229                         }
1230
1231                         // If this slide has a data-autoslide attribtue associated use this as
1232                         // autoSlide value otherwise use the global configured time
1233                         var slideAutoSlide = slides[index].getAttribute( 'data-autoslide' );
1234                         if( slideAutoSlide ) {
1235                                 autoSlide = parseInt( slideAutoSlide, 10 );
1236                         }
1237                         else {
1238                                 autoSlide = config.autoSlide;
1239                         }
1240
1241                 }
1242                 else {
1243                         // Since there are no slides we can't be anywhere beyond the
1244                         // zeroth index
1245                         index = 0;
1246                 }
1247
1248                 return index;
1249
1250         }
1251
1252         /**
1253          * Updates the progress bar to reflect the current slide.
1254          */
1255         function updateProgress() {
1256
1257                 // Update progress if enabled
1258                 if( config.progress && dom.progress ) {
1259
1260                         var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1261
1262                         // The number of past and total slides
1263                         var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
1264                         var pastCount = 0;
1265
1266                         // Step through all slides and count the past ones
1267                         mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
1268
1269                                 var horizontalSlide = horizontalSlides[i];
1270                                 var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
1271
1272                                 for( var j = 0; j < verticalSlides.length; j++ ) {
1273
1274                                         // Stop as soon as we arrive at the present
1275                                         if( verticalSlides[j].classList.contains( 'present' ) ) {
1276                                                 break mainLoop;
1277                                         }
1278
1279                                         pastCount++;
1280
1281                                 }
1282
1283                                 // Stop as soon as we arrive at the present
1284                                 if( horizontalSlide.classList.contains( 'present' ) ) {
1285                                         break;
1286                                 }
1287
1288                                 // Don't count the wrapping section for vertical slides
1289                                 if( horizontalSlide.classList.contains( 'stack' ) === false ) {
1290                                         pastCount++;
1291                                 }
1292
1293                         }
1294
1295                         dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';
1296
1297                 }
1298
1299         }
1300
1301         /**
1302          * Updates the state of all control/navigation arrows.
1303          */
1304         function updateControls() {
1305
1306                 if ( config.controls && dom.controls ) {
1307
1308                         var routes = availableRoutes();
1309
1310                         // Remove the 'enabled' class from all directions
1311                         dom.controlsLeft.concat( dom.controlsRight )
1312                                                         .concat( dom.controlsUp )
1313                                                         .concat( dom.controlsDown )
1314                                                         .concat( dom.controlsPrev )
1315                                                         .concat( dom.controlsNext ).forEach( function( node ) {
1316                                 node.classList.remove( 'enabled' );
1317                         } );
1318
1319                         // Add the 'enabled' class to the available routes
1320                         if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' );     } );
1321                         if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1322                         if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1323                         if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1324
1325                         // Prev/next buttons
1326                         if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1327                         if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1328
1329                 }
1330
1331         }
1332
1333         /**
1334          * Determine what available routes there are for navigation.
1335          *
1336          * @return {Object} containing four booleans: left/right/up/down
1337          */
1338         function availableRoutes() {
1339
1340                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
1341                         verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
1342
1343                 return {
1344                         left: indexh > 0 || config.loop,
1345                         right: indexh < horizontalSlides.length - 1 || config.loop,
1346                         up: indexv > 0,
1347                         down: indexv < verticalSlides.length - 1
1348                 };
1349
1350         }
1351
1352         /**
1353          * Reads the current URL (hash) and navigates accordingly.
1354          */
1355         function readURL() {
1356
1357                 var hash = window.location.hash;
1358
1359                 // Attempt to parse the hash as either an index or name
1360                 var bits = hash.slice( 2 ).split( '/' ),
1361                         name = hash.replace( /#|\//gi, '' );
1362
1363                 // If the first bit is invalid and there is a name we can
1364                 // assume that this is a named link
1365                 if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
1366                         // Find the slide with the specified name
1367                         var element = document.querySelector( '#' + name );
1368
1369                         if( element ) {
1370                                 // Find the position of the named slide and navigate to it
1371                                 var indices = Reveal.getIndices( element );
1372                                 slide( indices.h, indices.v );
1373                         }
1374                         // If the slide doesn't exist, navigate to the current slide
1375                         else {
1376                                 slide( indexh, indexv );
1377                         }
1378                 }
1379                 else {
1380                         // Read the index components of the hash
1381                         var h = parseInt( bits[0], 10 ) || 0,
1382                                 v = parseInt( bits[1], 10 ) || 0;
1383
1384                         slide( h, v );
1385                 }
1386
1387         }
1388
1389         /**
1390          * Updates the page URL (hash) to reflect the current
1391          * state.
1392          *
1393          * @param {Number} delay The time in ms to wait before
1394          * writing the hash
1395          */
1396         function writeURL( delay ) {
1397
1398                 if( config.history ) {
1399
1400                         // Make sure there's never more than one timeout running
1401                         clearTimeout( writeURLTimeout );
1402
1403                         // If a delay is specified, timeout this call
1404                         if( typeof delay === 'number' ) {
1405                                 writeURLTimeout = setTimeout( writeURL, delay );
1406                         }
1407                         else {
1408                                 var url = '/';
1409
1410                                 // If the current slide has an ID, use that as a named link
1411                                 if( currentSlide && typeof currentSlide.getAttribute( 'id' ) === 'string' ) {
1412                                         url = '/' + currentSlide.getAttribute( 'id' );
1413                                 }
1414                                 // Otherwise use the /h/v index
1415                                 else {
1416                                         if( indexh > 0 || indexv > 0 ) url += indexh;
1417                                         if( indexv > 0 ) url += '/' + indexv;
1418                                 }
1419
1420                                 window.location.hash = url;
1421                         }
1422                 }
1423
1424         }
1425
1426         /**
1427          * Retrieves the h/v location of the current, or specified,
1428          * slide.
1429          *
1430          * @param {HTMLElement} slide If specified, the returned
1431          * index will be for this slide rather than the currently
1432          * active one
1433          *
1434          * @return {Object} { h: <int>, v: <int> }
1435          */
1436         function getIndices( slide ) {
1437
1438                 // By default, return the current indices
1439                 var h = indexh,
1440                         v = indexv;
1441
1442                 // If a slide is specified, return the indices of that slide
1443                 if( slide ) {
1444                         var isVertical = !!slide.parentNode.nodeName.match( /section/gi );
1445                         var slideh = isVertical ? slide.parentNode : slide;
1446
1447                         // Select all horizontal slides
1448                         var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1449
1450                         // Now that we know which the horizontal slide is, get its index
1451                         h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
1452
1453                         // If this is a vertical slide, grab the vertical index
1454                         if( isVertical ) {
1455                                 v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
1456                         }
1457                 }
1458
1459                 return { h: h, v: v };
1460
1461         }
1462
1463         /**
1464          * Navigate to the next slide fragment.
1465          *
1466          * @return {Boolean} true if there was a next fragment,
1467          * false otherwise
1468          */
1469         function nextFragment() {
1470
1471                 // Vertical slides:
1472                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1473                         var verticalFragments = sortFragments( document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' ) );
1474
1475                         if( verticalFragments.length ) {
1476                                 verticalFragments[0].classList.add( 'visible' );
1477
1478                                 // Notify subscribers of the change
1479                                 dispatchEvent( 'fragmentshown', { fragment: verticalFragments[0] } );
1480                                 return true;
1481                         }
1482                 }
1483                 // Horizontal slides:
1484                 else {
1485                         var horizontalFragments = sortFragments( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' ) );
1486
1487                         if( horizontalFragments.length ) {
1488                                 horizontalFragments[0].classList.add( 'visible' );
1489
1490                                 // Notify subscribers of the change
1491                                 dispatchEvent( 'fragmentshown', { fragment: horizontalFragments[0] } );
1492                                 return true;
1493                         }
1494                 }
1495
1496                 return false;
1497
1498         }
1499
1500         /**
1501          * Navigate to the previous slide fragment.
1502          *
1503          * @return {Boolean} true if there was a previous fragment,
1504          * false otherwise
1505          */
1506         function previousFragment() {
1507
1508                 // Vertical slides:
1509                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1510                         var verticalFragments = sortFragments( document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment.visible' ) );
1511
1512                         if( verticalFragments.length ) {
1513                                 verticalFragments[ verticalFragments.length - 1 ].classList.remove( 'visible' );
1514
1515                                 // Notify subscribers of the change
1516                                 dispatchEvent( 'fragmenthidden', { fragment: verticalFragments[ verticalFragments.length - 1 ] } );
1517                                 return true;
1518                         }
1519                 }
1520                 // Horizontal slides:
1521                 else {
1522                         var horizontalFragments = sortFragments( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment.visible' ) );
1523
1524                         if( horizontalFragments.length ) {
1525                                 horizontalFragments[ horizontalFragments.length - 1 ].classList.remove( 'visible' );
1526
1527                                 // Notify subscribers of the change
1528                                 dispatchEvent( 'fragmenthidden', { fragment: horizontalFragments[ horizontalFragments.length - 1 ] } );
1529                                 return true;
1530                         }
1531                 }
1532
1533                 return false;
1534
1535         }
1536
1537         /**
1538          * Cues a new automated slide if enabled in the config.
1539          */
1540         function cueAutoSlide() {
1541
1542                 clearTimeout( autoSlideTimeout );
1543
1544                 // Cue the next auto-slide if enabled
1545                 if( autoSlide && !isPaused() && !isOverview() ) {
1546                         autoSlideTimeout = setTimeout( navigateNext, autoSlide );
1547                 }
1548
1549         }
1550
1551         /**
1552          * Cancels any ongoing request to auto-slide.
1553          */
1554         function cancelAutoSlide() {
1555
1556                 clearTimeout( autoSlideTimeout );
1557
1558         }
1559
1560         function navigateLeft() {
1561
1562                 // Prioritize hiding fragments
1563                 if( availableRoutes().left && ( isOverview() || previousFragment() === false ) ) {
1564                         slide( indexh - 1 );
1565                 }
1566
1567         }
1568
1569         function navigateRight() {
1570
1571                 // Prioritize revealing fragments
1572                 if( availableRoutes().right && ( isOverview() || nextFragment() === false ) ) {
1573                         slide( indexh + 1 );
1574                 }
1575
1576         }
1577
1578         function navigateUp() {
1579
1580                 // Prioritize hiding fragments
1581                 if( availableRoutes().up && isOverview() || previousFragment() === false ) {
1582                         slide( indexh, indexv - 1 );
1583                 }
1584
1585         }
1586
1587         function navigateDown() {
1588
1589                 // Prioritize revealing fragments
1590                 if( availableRoutes().down && isOverview() || nextFragment() === false ) {
1591                         slide( indexh, indexv + 1 );
1592                 }
1593
1594         }
1595
1596         /**
1597          * Navigates backwards, prioritized in the following order:
1598          * 1) Previous fragment
1599          * 2) Previous vertical slide
1600          * 3) Previous horizontal slide
1601          */
1602         function navigatePrev() {
1603
1604                 // Prioritize revealing fragments
1605                 if( previousFragment() === false ) {
1606                         if( availableRoutes().up ) {
1607                                 navigateUp();
1608                         }
1609                         else {
1610                                 // Fetch the previous horizontal slide, if there is one
1611                                 var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
1612
1613                                 if( previousSlide ) {
1614                                         indexv = ( previousSlide.querySelectorAll( 'section' ).length + 1 ) || undefined;
1615                                         indexh --;
1616                                         slide();
1617                                 }
1618                         }
1619                 }
1620
1621         }
1622
1623         /**
1624          * Same as #navigatePrev() but navigates forwards.
1625          */
1626         function navigateNext() {
1627
1628                 // Prioritize revealing fragments
1629                 if( nextFragment() === false ) {
1630                         availableRoutes().down ? navigateDown() : navigateRight();
1631                 }
1632
1633                 // If auto-sliding is enabled we need to cue up
1634                 // another timeout
1635                 cueAutoSlide();
1636
1637         }
1638
1639
1640         // --------------------------------------------------------------------//
1641         // ----------------------------- EVENTS -------------------------------//
1642         // --------------------------------------------------------------------//
1643
1644
1645         /**
1646          * Handler for the document level 'keydown' event.
1647          *
1648          * @param {Object} event
1649          */
1650         function onDocumentKeyDown( event ) {
1651
1652                 // Check if there's a focused element that could be using
1653                 // the keyboard
1654                 var activeElement = document.activeElement;
1655                 var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
1656
1657                 // Disregard the event if there's a focused element or a
1658                 // keyboard modifier key is present
1659                 if( hasFocus || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;
1660
1661                 var triggered = true;
1662
1663                 // while paused only allow "unpausing" keyboard events (b and .)
1664                 if( isPaused() && [66,190,191].indexOf( event.keyCode ) === -1 ) {
1665                         return false;
1666                 }
1667
1668                 switch( event.keyCode ) {
1669                         // p, page up
1670                         case 80: case 33: navigatePrev(); break;
1671                         // n, page down
1672                         case 78: case 34: navigateNext(); break;
1673                         // h, left
1674                         case 72: case 37: navigateLeft(); break;
1675                         // l, right
1676                         case 76: case 39: navigateRight(); break;
1677                         // k, up
1678                         case 75: case 38: navigateUp(); break;
1679                         // j, down
1680                         case 74: case 40: navigateDown(); break;
1681                         // home
1682                         case 36: slide( 0 ); break;
1683                         // end
1684                         case 35: slide( Number.MAX_VALUE ); break;
1685                         // space
1686                         case 32: isOverview() ? deactivateOverview() : navigateNext(); break;
1687                         // return
1688                         case 13: isOverview() ? deactivateOverview() : triggered = false; break;
1689                         // b, period, Logitech presenter tools "black screen" button
1690                         case 66: case 190: case 191: togglePause(); break;
1691                         // f
1692                         case 70: enterFullscreen(); break;
1693                         default:
1694                                 triggered = false;
1695                 }
1696
1697                 // If the input resulted in a triggered action we should prevent
1698                 // the browsers default behavior
1699                 if( triggered ) {
1700                         event.preventDefault();
1701                 }
1702                 else if ( event.keyCode === 27 && supports3DTransforms ) {
1703                         toggleOverview();
1704
1705                         event.preventDefault();
1706                 }
1707
1708                 // If auto-sliding is enabled we need to cue up
1709                 // another timeout
1710                 cueAutoSlide();
1711
1712         }
1713
1714         /**
1715          * Handler for the 'touchstart' event, enables support for
1716          * swipe and pinch gestures.
1717          */
1718         function onTouchStart( event ) {
1719
1720                 touch.startX = event.touches[0].clientX;
1721                 touch.startY = event.touches[0].clientY;
1722                 touch.startCount = event.touches.length;
1723
1724                 // If there's two touches we need to memorize the distance
1725                 // between those two points to detect pinching
1726                 if( event.touches.length === 2 && config.overview ) {
1727                         touch.startSpan = distanceBetween( {
1728                                 x: event.touches[1].clientX,
1729                                 y: event.touches[1].clientY
1730                         }, {
1731                                 x: touch.startX,
1732                                 y: touch.startY
1733                         } );
1734                 }
1735
1736         }
1737
1738         /**
1739          * Handler for the 'touchmove' event.
1740          */
1741         function onTouchMove( event ) {
1742
1743                 // Each touch should only trigger one action
1744                 if( !touch.handled ) {
1745                         var currentX = event.touches[0].clientX;
1746                         var currentY = event.touches[0].clientY;
1747
1748                         // If the touch started off with two points and still has
1749                         // two active touches; test for the pinch gesture
1750                         if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
1751
1752                                 // The current distance in pixels between the two touch points
1753                                 var currentSpan = distanceBetween( {
1754                                         x: event.touches[1].clientX,
1755                                         y: event.touches[1].clientY
1756                                 }, {
1757                                         x: touch.startX,
1758                                         y: touch.startY
1759                                 } );
1760
1761                                 // If the span is larger than the desire amount we've got
1762                                 // ourselves a pinch
1763                                 if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
1764                                         touch.handled = true;
1765
1766                                         if( currentSpan < touch.startSpan ) {
1767                                                 activateOverview();
1768                                         }
1769                                         else {
1770                                                 deactivateOverview();
1771                                         }
1772                                 }
1773
1774                                 event.preventDefault();
1775
1776                         }
1777                         // There was only one touch point, look for a swipe
1778                         else if( event.touches.length === 1 && touch.startCount !== 2 ) {
1779
1780                                 var deltaX = currentX - touch.startX,
1781                                         deltaY = currentY - touch.startY;
1782
1783                                 if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1784                                         touch.handled = true;
1785                                         navigateLeft();
1786                                 }
1787                                 else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1788                                         touch.handled = true;
1789                                         navigateRight();
1790                                 }
1791                                 else if( deltaY > touch.threshold ) {
1792                                         touch.handled = true;
1793                                         navigateUp();
1794                                 }
1795                                 else if( deltaY < -touch.threshold ) {
1796                                         touch.handled = true;
1797                                         navigateDown();
1798                                 }
1799
1800                                 event.preventDefault();
1801
1802                         }
1803                 }
1804                 // There's a bug with swiping on some Android devices unless
1805                 // the default action is always prevented
1806                 else if( navigator.userAgent.match( /android/gi ) ) {
1807                         event.preventDefault();
1808                 }
1809
1810         }
1811
1812         /**
1813          * Handler for the 'touchend' event.
1814          */
1815         function onTouchEnd( event ) {
1816
1817                 touch.handled = false;
1818
1819         }
1820
1821         /**
1822          * Convert pointer down to touch start.
1823          */
1824         function onPointerDown( event ) {
1825
1826                 if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
1827                         event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
1828                         onTouchStart( event );
1829                 }
1830
1831         }
1832
1833         /**
1834          * Convert pointer move to touch move.
1835          */
1836         function onPointerMove( event ) {
1837
1838                 if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
1839                         event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
1840                         onTouchMove( event );
1841                 }
1842
1843         }
1844
1845         /**
1846          * Convert pointer up to touch end.
1847          */
1848         function onPointerUp( event ) {
1849
1850                 if( event.pointerType === event.MSPOINTER_TYPE_TOUCH ) {
1851                         event.touches = [{ clientX: event.clientX, clientY: event.clientY }];
1852                         onTouchEnd( event );
1853                 }
1854
1855         }
1856
1857         /**
1858          * Handles mouse wheel scrolling, throttled to avoid skipping
1859          * multiple slides.
1860          */
1861         function onDocumentMouseScroll( event ) {
1862
1863                 clearTimeout( mouseWheelTimeout );
1864
1865                 mouseWheelTimeout = setTimeout( function() {
1866                         var delta = event.detail || -event.wheelDelta;
1867                         if( delta > 0 ) {
1868                                 navigateNext();
1869                         }
1870                         else {
1871                                 navigatePrev();
1872                         }
1873                 }, 100 );
1874
1875         }
1876
1877         /**
1878          * Clicking on the progress bar results in a navigation to the
1879          * closest approximate horizontal slide using this equation:
1880          *
1881          * ( clickX / presentationWidth ) * numberOfSlides
1882          */
1883         function onProgressClicked( event ) {
1884
1885                 event.preventDefault();
1886
1887                 var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
1888                 var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
1889
1890                 slide( slideIndex );
1891
1892         }
1893
1894         /**
1895          * Event handler for navigation control buttons.
1896          */
1897         function onNavigateLeftClicked( event ) { event.preventDefault(); navigateLeft(); }
1898         function onNavigateRightClicked( event ) { event.preventDefault(); navigateRight(); }
1899         function onNavigateUpClicked( event ) { event.preventDefault(); navigateUp(); }
1900         function onNavigateDownClicked( event ) { event.preventDefault(); navigateDown(); }
1901         function onNavigatePrevClicked( event ) { event.preventDefault(); navigatePrev(); }
1902         function onNavigateNextClicked( event ) { event.preventDefault(); navigateNext(); }
1903
1904         /**
1905          * Handler for the window level 'hashchange' event.
1906          */
1907         function onWindowHashChange( event ) {
1908
1909                 readURL();
1910
1911         }
1912
1913         /**
1914          * Handler for the window level 'resize' event.
1915          */
1916         function onWindowResize( event ) {
1917
1918                 layout();
1919
1920         }
1921
1922         /**
1923          * Invoked when a slide is and we're in the overview.
1924          */
1925         function onOverviewSlideClicked( event ) {
1926
1927                 // TODO There's a bug here where the event listeners are not
1928                 // removed after deactivating the overview.
1929                 if( eventsAreBound && isOverview() ) {
1930                         event.preventDefault();
1931
1932                         var element = event.target;
1933
1934                         while( element && !element.nodeName.match( /section/gi ) ) {
1935                                 element = element.parentNode;
1936                         }
1937
1938                         if( element && !element.classList.contains( 'disabled' ) ) {
1939
1940                                 deactivateOverview();
1941
1942                                 if( element.nodeName.match( /section/gi ) ) {
1943                                         var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
1944                                                 v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
1945
1946                                         slide( h, v );
1947                                 }
1948
1949                         }
1950                 }
1951
1952         }
1953
1954
1955         // --------------------------------------------------------------------//
1956         // ------------------------------- API --------------------------------//
1957         // --------------------------------------------------------------------//
1958
1959
1960         return {
1961                 initialize: initialize,
1962                 configure: configure,
1963
1964                 // Navigation methods
1965                 slide: slide,
1966                 left: navigateLeft,
1967                 right: navigateRight,
1968                 up: navigateUp,
1969                 down: navigateDown,
1970                 prev: navigatePrev,
1971                 next: navigateNext,
1972                 prevFragment: previousFragment,
1973                 nextFragment: nextFragment,
1974
1975                 // Deprecated aliases
1976                 navigateTo: slide,
1977                 navigateLeft: navigateLeft,
1978                 navigateRight: navigateRight,
1979                 navigateUp: navigateUp,
1980                 navigateDown: navigateDown,
1981                 navigatePrev: navigatePrev,
1982                 navigateNext: navigateNext,
1983
1984                 // Forces an update in slide layout
1985                 layout: layout,
1986
1987                 // Toggles the overview mode on/off
1988                 toggleOverview: toggleOverview,
1989
1990                 // Toggles the "black screen" mode on/off
1991                 togglePause: togglePause,
1992
1993                 // State checks
1994                 isOverview: isOverview,
1995                 isPaused: isPaused,
1996
1997                 // Adds or removes all internal event listeners (such as keyboard)
1998                 addEventListeners: addEventListeners,
1999                 removeEventListeners: removeEventListeners,
2000
2001                 // Returns the indices of the current, or specified, slide
2002                 getIndices: getIndices,
2003
2004                 // Returns the slide at the specified index, y is optional
2005                 getSlide: function( x, y ) {
2006                         var horizontalSlide = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
2007                         var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
2008
2009                         if( typeof y !== 'undefined' ) {
2010                                 return verticalSlides ? verticalSlides[ y ] : undefined;
2011                         }
2012
2013                         return horizontalSlide;
2014                 },
2015
2016                 // Returns the previous slide element, may be null
2017                 getPreviousSlide: function() {
2018                         return previousSlide;
2019                 },
2020
2021                 // Returns the current slide element
2022                 getCurrentSlide: function() {
2023                         return currentSlide;
2024                 },
2025
2026                 // Returns the current scale of the presentation content
2027                 getScale: function() {
2028                         return scale;
2029                 },
2030
2031                 // Returns the current configuration object
2032                 getConfig: function() {
2033                         return config;
2034                 },
2035
2036                 // Helper method, retrieves query string as a key/value hash
2037                 getQueryHash: function() {
2038                         var query = {};
2039
2040                         location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
2041                                 query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
2042                         } );
2043
2044                         return query;
2045                 },
2046
2047                 // Returns true if we're currently on the first slide
2048                 isFirstSlide: function() {
2049                         return document.querySelector( SLIDES_SELECTOR + '.past' ) == null ? true : false;
2050                 },
2051
2052                 // Returns true if we're currently on the last slide
2053                 isLastSlide: function() {
2054                         if( currentSlide && currentSlide.classList.contains( '.stack' ) ) {
2055                                 return currentSlide.querySelector( SLIDES_SELECTOR + '.future' ) == null ? true : false;
2056                         }
2057                         else {
2058                                 return document.querySelector( SLIDES_SELECTOR + '.future' ) == null ? true : false;
2059                         }
2060                 },
2061
2062                 // Forward event binding to the reveal DOM element
2063                 addEventListener: function( type, listener, useCapture ) {
2064                         if( 'addEventListener' in window ) {
2065                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
2066                         }
2067                 },
2068                 removeEventListener: function( type, listener, useCapture ) {
2069                         if( 'addEventListener' in window ) {
2070                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
2071                         }
2072                 }
2073         };
2074
2075 })();