enable pos-startup config of autoSlide
[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                         document.addEventListener( 'touchstart', onDocumentTouchStart, false );
420                         document.addEventListener( 'touchmove', onDocumentTouchMove, false );
421                         document.addEventListener( 'touchend', onDocumentTouchEnd, false );
422                 }
423
424                 if( config.keyboard ) {
425                         document.addEventListener( 'keydown', onDocumentKeyDown, false );
426                 }
427
428                 if ( config.progress && dom.progress ) {
429                         dom.progress.addEventListener( 'click', onProgressClicked, false );
430                 }
431
432                 if ( config.controls && dom.controls ) {
433                         var actionEvent = 'ontouchstart' in window && window.ontouchstart != null ? 'touchstart' : 'click';
434                         dom.controlsLeft.forEach( function( el ) { el.addEventListener( actionEvent, onNavigateLeftClicked, false ); } );
435                         dom.controlsRight.forEach( function( el ) { el.addEventListener( actionEvent, onNavigateRightClicked, false ); } );
436                         dom.controlsUp.forEach( function( el ) { el.addEventListener( actionEvent, onNavigateUpClicked, false ); } );
437                         dom.controlsDown.forEach( function( el ) { el.addEventListener( actionEvent, onNavigateDownClicked, false ); } );
438                         dom.controlsPrev.forEach( function( el ) { el.addEventListener( actionEvent, onNavigatePrevClicked, false ); } );
439                         dom.controlsNext.forEach( function( el ) { el.addEventListener( actionEvent, onNavigateNextClicked, false ); } );
440                 }
441
442         }
443
444         /**
445          * Unbinds all event listeners.
446          */
447         function removeEventListeners() {
448
449                 eventsAreBound = false;
450
451                 document.removeEventListener( 'keydown', onDocumentKeyDown, false );
452                 window.removeEventListener( 'hashchange', onWindowHashChange, false );
453                 window.removeEventListener( 'resize', onWindowResize, false );
454
455                 if( config.touch ) {
456                         document.removeEventListener( 'touchstart', onDocumentTouchStart, false );
457                         document.removeEventListener( 'touchmove', onDocumentTouchMove, false );
458                         document.removeEventListener( 'touchend', onDocumentTouchEnd, false );
459                 }
460
461                 if ( config.progress && dom.progress ) {
462                         dom.progress.removeEventListener( 'click', onProgressClicked, false );
463                 }
464
465                 if ( config.controls && dom.controls ) {
466                         var actionEvent = 'ontouchstart' in window && window.ontouchstart != null ? 'touchstart' : 'click';
467                         dom.controlsLeft.forEach( function( el ) { el.removeEventListener( actionEvent, onNavigateLeftClicked, false ); } );
468                         dom.controlsRight.forEach( function( el ) { el.removeEventListener( actionEvent, onNavigateRightClicked, false ); } );
469                         dom.controlsUp.forEach( function( el ) { el.removeEventListener( actionEvent, onNavigateUpClicked, false ); } );
470                         dom.controlsDown.forEach( function( el ) { el.removeEventListener( actionEvent, onNavigateDownClicked, false ); } );
471                         dom.controlsPrev.forEach( function( el ) { el.removeEventListener( actionEvent, onNavigatePrevClicked, false ); } );
472                         dom.controlsNext.forEach( function( el ) { el.removeEventListener( actionEvent, onNavigateNextClicked, false ); } );
473                 }
474
475         }
476
477         /**
478          * Extend object a with the properties of object b.
479          * If there's a conflict, object b takes precedence.
480          */
481         function extend( a, b ) {
482
483                 for( var i in b ) {
484                         a[ i ] = b[ i ];
485                 }
486
487         }
488
489         /**
490          * Converts the target object to an array.
491          */
492         function toArray( o ) {
493
494                 return Array.prototype.slice.call( o );
495
496         }
497
498         /**
499          * Measures the distance in pixels between point a
500          * and point b.
501          *
502          * @param {Object} a point with x/y properties
503          * @param {Object} b point with x/y properties
504          */
505         function distanceBetween( a, b ) {
506
507                 var dx = a.x - b.x,
508                         dy = a.y - b.y;
509
510                 return Math.sqrt( dx*dx + dy*dy );
511
512         }
513
514         /**
515          * Causes the address bar to hide on mobile devices,
516          * more vertical space ftw.
517          */
518         function removeAddressBar() {
519
520                 if( window.orientation === 0 ) {
521                         document.documentElement.style.overflow = 'scroll';
522                         document.body.style.height = '120%';
523                 }
524                 else {
525                         document.documentElement.style.overflow = '';
526                         document.body.style.height = '100%';
527                 }
528
529                 setTimeout( function() {
530                         window.scrollTo( 0, 1 );
531                 }, 10 );
532
533         }
534
535         /**
536          * Dispatches an event of the specified type from the
537          * reveal DOM element.
538          */
539         function dispatchEvent( type, properties ) {
540
541                 var event = document.createEvent( "HTMLEvents", 1, 2 );
542                 event.initEvent( type, true, true );
543                 extend( event, properties );
544                 dom.wrapper.dispatchEvent( event );
545
546         }
547
548         /**
549          * Wrap all links in 3D goodness.
550          */
551         function enable3DLinks() {
552
553                 if( supports3DTransforms && !( 'msPerspective' in document.body.style ) ) {
554                         var anchors = document.querySelectorAll( SLIDES_SELECTOR + ' a:not(.image)' );
555
556                         for( var i = 0, len = anchors.length; i < len; i++ ) {
557                                 var anchor = anchors[i];
558
559                                 if( anchor.textContent && !anchor.querySelector( '*' ) && ( !anchor.className || !anchor.classList.contains( anchor, 'roll' ) ) ) {
560                                         var span = document.createElement('span');
561                                         span.setAttribute('data-title', anchor.text);
562                                         span.innerHTML = anchor.innerHTML;
563
564                                         anchor.classList.add( 'roll' );
565                                         anchor.innerHTML = '';
566                                         anchor.appendChild(span);
567                                 }
568                         }
569                 }
570
571         }
572
573         /**
574          * Unwrap all 3D links.
575          */
576         function disable3DLinks() {
577
578                 var anchors = document.querySelectorAll( SLIDES_SELECTOR + ' a.roll' );
579
580                 for( var i = 0, len = anchors.length; i < len; i++ ) {
581                         var anchor = anchors[i];
582                         var span = anchor.querySelector( 'span' );
583
584                         if( span ) {
585                                 anchor.classList.remove( 'roll' );
586                                 anchor.innerHTML = span.innerHTML;
587                         }
588                 }
589
590         }
591
592         /**
593          * Return a sorted fragments list, ordered by an increasing
594          * "data-fragment-index" attribute.
595          *
596          * Fragments will be revealed in the order that they are returned by
597          * this function, so you can use the index attributes to control the 
598          * order of fragment appearance.
599          *
600          * To maintain a sensible default fragment order, fragments are presumed
601          * to be passed in document order. This function adds a "fragment-index"
602          * attribute to each node if such an attribute is not already present,
603          * and sets that attribute to an integer value which is the position of
604          * the fragment within the fragments list.
605          */
606         function sortFragments( fragments ) {
607
608                 var a = toArray( fragments );
609
610                 a.forEach( function( el, idx ) {
611                         if( !el.hasAttribute( 'data-fragment-index' ) ) {
612                                 el.setAttribute( 'data-fragment-index', idx );
613                         }
614                 } );
615
616                 a.sort( function( l, r ) {
617                         return l.getAttribute( 'data-fragment-index' ) - r.getAttribute( 'data-fragment-index');
618                 } );
619
620                 return a
621
622         }
623
624         /**
625          * Applies JavaScript-controlled layout rules to the
626          * presentation.
627          */
628         function layout() {
629
630                 if( dom.wrapper ) {
631
632                         // Available space to scale within
633                         var availableWidth = dom.wrapper.offsetWidth,
634                                 availableHeight = dom.wrapper.offsetHeight;
635
636                         // Reduce available space by margin
637                         availableWidth -= ( availableHeight * config.margin );
638                         availableHeight -= ( availableHeight * config.margin );
639
640                         // Dimensions of the content
641                         var slideWidth = config.width,
642                                 slideHeight = config.height;
643
644                         // Slide width may be a percentage of available width
645                         if( typeof slideWidth === 'string' && /%$/.test( slideWidth ) ) {
646                                 slideWidth = parseInt( slideWidth, 10 ) / 100 * availableWidth;
647                         }
648
649                         // Slide height may be a percentage of available height
650                         if( typeof slideHeight === 'string' && /%$/.test( slideHeight ) ) {
651                                 slideHeight = parseInt( slideHeight, 10 ) / 100 * availableHeight;
652                         }
653
654                         dom.slides.style.width = slideWidth + 'px';
655                         dom.slides.style.height = slideHeight + 'px';
656
657                         // Determine scale of content to fit within available space
658                         scale = Math.min( availableWidth / slideWidth, availableHeight / slideHeight );
659
660                         // Respect max/min scale settings
661                         scale = Math.max( scale, config.minScale );
662                         scale = Math.min( scale, config.maxScale );
663
664                         // Prefer applying scale via zoom since Chrome blurs scaled content
665                         // with nested transforms
666                         if( typeof dom.slides.style.zoom !== 'undefined' && !navigator.userAgent.match( /(iphone|ipod|ipad|android)/gi ) ) {
667                                 dom.slides.style.zoom = scale;
668                         }
669                         // Apply scale transform as a fallback
670                         else {
671                                 var transform = 'translate(-50%, -50%) scale('+ scale +') translate(50%, 50%)';
672
673                                 dom.slides.style.WebkitTransform = transform;
674                                 dom.slides.style.MozTransform = transform;
675                                 dom.slides.style.msTransform = transform;
676                                 dom.slides.style.OTransform = transform;
677                                 dom.slides.style.transform = transform;
678                         }
679
680                         // Select all slides, vertical and horizontal
681                         var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
682
683                         for( var i = 0, len = slides.length; i < len; i++ ) {
684                                 var slide = slides[ i ];
685
686                                 // Don't bother updating invisible slides
687                                 if( slide.style.display === 'none' ) {
688                                         continue;
689                                 }
690
691                                 if( config.center ) {
692                                         // Vertical stacks are not centred since their section
693                                         // children will be
694                                         if( slide.classList.contains( 'stack' ) ) {
695                                                 slide.style.top = 0;
696                                         }
697                                         else {
698                                                 slide.style.top = Math.max( - ( slide.offsetHeight / 2 ) - 20, -slideHeight / 2 ) + 'px';
699                                         }
700                                 }
701                                 else {
702                                         slide.style.top = '';
703                                 }
704
705                         }
706
707                 }
708
709         }
710
711         /**
712          * Stores the vertical index of a stack so that the same
713          * vertical slide can be selected when navigating to and
714          * from the stack.
715          *
716          * @param {HTMLElement} stack The vertical stack element
717          * @param {int} v Index to memorize
718          */
719         function setPreviousVerticalIndex( stack, v ) {
720
721                 if( stack ) {
722                         stack.setAttribute( 'data-previous-indexv', v || 0 );
723                 }
724
725         }
726
727         /**
728          * Retrieves the vertical index which was stored using
729          * #setPreviousVerticalIndex() or 0 if no previous index
730          * exists.
731          *
732          * @param {HTMLElement} stack The vertical stack element
733          */
734         function getPreviousVerticalIndex( stack ) {
735
736                 if( stack && stack.classList.contains( 'stack' ) ) {
737                         return parseInt( stack.getAttribute( 'data-previous-indexv' ) || 0, 10 );
738                 }
739
740                 return 0;
741
742         }
743
744         /**
745          * Displays the overview of slides (quick nav) by
746          * scaling down and arranging all slide elements.
747          *
748          * Experimental feature, might be dropped if perf
749          * can't be improved.
750          */
751         function activateOverview() {
752
753                 // Only proceed if enabled in config
754                 if( config.overview ) {
755
756                         // Don't auto-slide while in overview mode
757                         cancelAutoSlide();
758
759                         var wasActive = dom.wrapper.classList.contains( 'overview' );
760
761                         dom.wrapper.classList.add( 'overview' );
762                         dom.wrapper.classList.remove( 'exit-overview' );
763
764                         clearTimeout( activateOverviewTimeout );
765                         clearTimeout( deactivateOverviewTimeout );
766
767                         // Not the pretties solution, but need to let the overview
768                         // class apply first so that slides are measured accurately
769                         // before we can position them
770                         activateOverviewTimeout = setTimeout( function(){
771
772                                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
773
774                                 for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
775                                         var hslide = horizontalSlides[i],
776                                                 htransform = 'translateZ(-2500px) translate(' + ( ( i - indexh ) * 105 ) + '%, 0%)';
777
778                                         hslide.setAttribute( 'data-index-h', i );
779                                         hslide.style.display = 'block';
780                                         hslide.style.WebkitTransform = htransform;
781                                         hslide.style.MozTransform = htransform;
782                                         hslide.style.msTransform = htransform;
783                                         hslide.style.OTransform = htransform;
784                                         hslide.style.transform = htransform;
785
786                                         if( hslide.classList.contains( 'stack' ) ) {
787
788                                                 var verticalSlides = hslide.querySelectorAll( 'section' );
789
790                                                 for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
791                                                         var verticalIndex = i === indexh ? indexv : getPreviousVerticalIndex( hslide );
792
793                                                         var vslide = verticalSlides[j],
794                                                                 vtransform = 'translate(0%, ' + ( ( j - verticalIndex ) * 105 ) + '%)';
795
796                                                         vslide.setAttribute( 'data-index-h', i );
797                                                         vslide.setAttribute( 'data-index-v', j );
798                                                         vslide.style.display = 'block';
799                                                         vslide.style.WebkitTransform = vtransform;
800                                                         vslide.style.MozTransform = vtransform;
801                                                         vslide.style.msTransform = vtransform;
802                                                         vslide.style.OTransform = vtransform;
803                                                         vslide.style.transform = vtransform;
804
805                                                         // Navigate to this slide on click
806                                                         vslide.addEventListener( 'click', onOverviewSlideClicked, true );
807                                                 }
808
809                                         }
810                                         else {
811
812                                                 // Navigate to this slide on click
813                                                 hslide.addEventListener( 'click', onOverviewSlideClicked, true );
814
815                                         }
816                                 }
817
818                                 layout();
819
820                                 if( !wasActive ) {
821                                         // Notify observers of the overview showing
822                                         dispatchEvent( 'overviewshown', {
823                                                 'indexh': indexh,
824                                                 'indexv': indexv,
825                                                 'currentSlide': currentSlide
826                                         } );
827                                 }
828
829                         }, 10 );
830
831                 }
832
833         }
834
835         /**
836          * Exits the slide overview and enters the currently
837          * active slide.
838          */
839         function deactivateOverview() {
840
841                 // Only proceed if enabled in config
842                 if( config.overview ) {
843
844                         clearTimeout( activateOverviewTimeout );
845                         clearTimeout( deactivateOverviewTimeout );
846
847                         dom.wrapper.classList.remove( 'overview' );
848
849                         // Temporarily add a class so that transitions can do different things
850                         // depending on whether they are exiting/entering overview, or just
851                         // moving from slide to slide
852                         dom.wrapper.classList.add( 'exit-overview' );
853
854                         deactivateOverviewTimeout = setTimeout( function () {
855                                 dom.wrapper.classList.remove( 'exit-overview' );
856                         }, 10);
857
858                         // Select all slides
859                         var slides = toArray( document.querySelectorAll( SLIDES_SELECTOR ) );
860
861                         for( var i = 0, len = slides.length; i < len; i++ ) {
862                                 var element = slides[i];
863
864                                 element.style.display = '';
865
866                                 // Resets all transforms to use the external styles
867                                 element.style.WebkitTransform = '';
868                                 element.style.MozTransform = '';
869                                 element.style.msTransform = '';
870                                 element.style.OTransform = '';
871                                 element.style.transform = '';
872
873                                 element.removeEventListener( 'click', onOverviewSlideClicked, true );
874                         }
875
876                         slide( indexh, indexv );
877
878                         cueAutoSlide();
879
880                         // Notify observers of the overview hiding
881                         dispatchEvent( 'overviewhidden', {
882                                 'indexh': indexh,
883                                 'indexv': indexv,
884                                 'currentSlide': currentSlide
885                         } );
886
887                 }
888         }
889
890         /**
891          * Toggles the slide overview mode on and off.
892          *
893          * @param {Boolean} override Optional flag which overrides the
894          * toggle logic and forcibly sets the desired state. True means
895          * overview is open, false means it's closed.
896          */
897         function toggleOverview( override ) {
898
899                 if( typeof override === 'boolean' ) {
900                         override ? activateOverview() : deactivateOverview();
901                 }
902                 else {
903                         isOverview() ? deactivateOverview() : activateOverview();
904                 }
905
906         }
907
908         /**
909          * Checks if the overview is currently active.
910          *
911          * @return {Boolean} true if the overview is active,
912          * false otherwise
913          */
914         function isOverview() {
915
916                 return dom.wrapper.classList.contains( 'overview' );
917
918         }
919
920         /**
921          * Handling the fullscreen functionality via the fullscreen API
922          *
923          * @see http://fullscreen.spec.whatwg.org/
924          * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
925          */
926         function enterFullscreen() {
927
928                 var element = document.body;
929
930                 // Check which implementation is available
931                 var requestMethod = element.requestFullScreen ||
932                                                         element.webkitRequestFullScreen ||
933                                                         element.mozRequestFullScreen ||
934                                                         element.msRequestFullScreen;
935
936                 if( requestMethod ) {
937                         requestMethod.apply( element );
938                 }
939
940         }
941
942         /**
943          * Enters the paused mode which fades everything on screen to
944          * black.
945          */
946         function pause() {
947
948                 var wasPaused = dom.wrapper.classList.contains( 'paused' );
949
950                 cancelAutoSlide();
951                 dom.wrapper.classList.add( 'paused' );
952
953                 if( wasPaused === false ) {
954                         dispatchEvent( 'paused' );
955                 }
956
957         }
958
959         /**
960          * Exits from the paused mode.
961          */
962         function resume() {
963
964                 var wasPaused = dom.wrapper.classList.contains( 'paused' );
965
966                 cueAutoSlide();
967                 dom.wrapper.classList.remove( 'paused' );
968
969                 if( wasPaused ) {
970                         dispatchEvent( 'resumed' );
971                 }
972
973         }
974
975         /**
976          * Toggles the paused mode on and off.
977          */
978         function togglePause() {
979
980                 if( isPaused() ) {
981                         resume();
982                 }
983                 else {
984                         pause();
985                 }
986
987         }
988
989         /**
990          * Checks if we are currently in the paused mode.
991          */
992         function isPaused() {
993
994                 return dom.wrapper.classList.contains( 'paused' );
995
996         }
997
998         /**
999          * Steps from the current point in the presentation to the
1000          * slide which matches the specified horizontal and vertical
1001          * indices.
1002          *
1003          * @param {int} h Horizontal index of the target slide
1004          * @param {int} v Vertical index of the target slide
1005          * @param {int} f Optional index of a fragment within the
1006          * target slide to activate
1007          */
1008         function slide( h, v, f ) {
1009
1010                 // Remember where we were at before
1011                 previousSlide = currentSlide;
1012
1013                 // Query all horizontal slides in the deck
1014                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
1015
1016                 // If no vertical index is specified and the upcoming slide is a
1017                 // stack, resume at its previous vertical index
1018                 if( v === undefined ) {
1019                         v = getPreviousVerticalIndex( horizontalSlides[ h ] );
1020                 }
1021
1022                 // If we were on a vertical stack, remember what vertical index
1023                 // it was on so we can resume at the same position when returning
1024                 if( previousSlide && previousSlide.parentNode && previousSlide.parentNode.classList.contains( 'stack' ) ) {
1025                         setPreviousVerticalIndex( previousSlide.parentNode, indexv );
1026                 }
1027
1028                 // Remember the state before this slide
1029                 var stateBefore = state.concat();
1030
1031                 // Reset the state array
1032                 state.length = 0;
1033
1034                 var indexhBefore = indexh,
1035                         indexvBefore = indexv;
1036
1037                 // Activate and transition to the new slide
1038                 indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
1039                 indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
1040
1041                 layout();
1042
1043                 // Apply the new state
1044                 stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
1045                         // Check if this state existed on the previous slide. If it
1046                         // did, we will avoid adding it repeatedly
1047                         for( var j = 0; j < stateBefore.length; j++ ) {
1048                                 if( stateBefore[j] === state[i] ) {
1049                                         stateBefore.splice( j, 1 );
1050                                         continue stateLoop;
1051                                 }
1052                         }
1053
1054                         document.documentElement.classList.add( state[i] );
1055
1056                         // Dispatch custom event matching the state's name
1057                         dispatchEvent( state[i] );
1058                 }
1059
1060                 // Clean up the remains of the previous state
1061                 while( stateBefore.length ) {
1062                         document.documentElement.classList.remove( stateBefore.pop() );
1063                 }
1064
1065                 // If the overview is active, re-activate it to update positions
1066                 if( isOverview() ) {
1067                         activateOverview();
1068                 }
1069
1070                 // Update the URL hash after a delay since updating it mid-transition
1071                 // is likely to cause visual lag
1072                 writeURL( 1500 );
1073
1074                 // Find the current horizontal slide and any possible vertical slides
1075                 // within it
1076                 var currentHorizontalSlide = horizontalSlides[ indexh ],
1077                         currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
1078
1079                 // Store references to the previous and current slides
1080                 currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
1081
1082
1083                 // Show fragment, if specified
1084                 if( typeof f !== 'undefined' ) {
1085                         var fragments = sortFragments( currentSlide.querySelectorAll( '.fragment' ) );
1086
1087                         toArray( fragments ).forEach( function( fragment, indexf ) {
1088                                 if( indexf < f ) {
1089                                         fragment.classList.add( 'visible' );
1090                                 }
1091                                 else {
1092                                         fragment.classList.remove( 'visible' );
1093                                 }
1094                         } );
1095                 }
1096
1097                 // Dispatch an event if the slide changed
1098                 if( indexh !== indexhBefore || indexv !== indexvBefore ) {
1099                         dispatchEvent( 'slidechanged', {
1100                                 'indexh': indexh,
1101                                 'indexv': indexv,
1102                                 'previousSlide': previousSlide,
1103                                 'currentSlide': currentSlide
1104                         } );
1105                 }
1106                 else {
1107                         // Ensure that the previous slide is never the same as the current
1108                         previousSlide = null;
1109                 }
1110
1111                 // Solves an edge case where the previous slide maintains the
1112                 // 'present' class when navigating between adjacent vertical
1113                 // stacks
1114                 if( previousSlide ) {
1115                         previousSlide.classList.remove( 'present' );
1116
1117                         // Reset all slides upon navigate to home
1118                         // Issue: #285
1119                         if ( document.querySelector( HOME_SLIDE_SELECTOR ).classList.contains( 'present' ) ) {
1120                                 // Launch async task
1121                                 setTimeout( function () {
1122                                         var slides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.stack') ), i;
1123                                         for( i in slides ) {
1124                                                 if( slides[i] ) {
1125                                                         // Reset stack
1126                                                         setPreviousVerticalIndex( slides[i], 0 );
1127                                                 }
1128                                         }
1129                                 }, 0 );
1130                         }
1131                 }
1132
1133                 updateControls();
1134                 updateProgress();
1135
1136         }
1137
1138         /**
1139          * Updates one dimension of slides by showing the slide
1140          * with the specified index.
1141          *
1142          * @param {String} selector A CSS selector that will fetch
1143          * the group of slides we are working with
1144          * @param {Number} index The index of the slide that should be
1145          * shown
1146          *
1147          * @return {Number} The index of the slide that is now shown,
1148          * might differ from the passed in index if it was out of
1149          * bounds.
1150          */
1151         function updateSlides( selector, index ) {
1152
1153                 // Select all slides and convert the NodeList result to
1154                 // an array
1155                 var slides = toArray( document.querySelectorAll( selector ) ),
1156                         slidesLength = slides.length;
1157
1158                 if( slidesLength ) {
1159
1160                         // Should the index loop?
1161                         if( config.loop ) {
1162                                 index %= slidesLength;
1163
1164                                 if( index < 0 ) {
1165                                         index = slidesLength + index;
1166                                 }
1167                         }
1168
1169                         // Enforce max and minimum index bounds
1170                         index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
1171
1172                         for( var i = 0; i < slidesLength; i++ ) {
1173                                 var element = slides[i];
1174
1175                                 // Optimization; hide all slides that are three or more steps
1176                                 // away from the present slide
1177                                 if( isOverview() === false ) {
1178                                         // The distance loops so that it measures 1 between the first
1179                                         // and last slides
1180                                         var distance = Math.abs( ( index - i ) % ( slidesLength - 3 ) ) || 0;
1181
1182                                         element.style.display = distance > 3 ? 'none' : 'block';
1183                                 }
1184
1185                                 slides[i].classList.remove( 'past' );
1186                                 slides[i].classList.remove( 'present' );
1187                                 slides[i].classList.remove( 'future' );
1188
1189                                 if( i < index ) {
1190                                         // Any element previous to index is given the 'past' class
1191                                         slides[i].classList.add( 'past' );
1192                                 }
1193                                 else if( i > index ) {
1194                                         // Any element subsequent to index is given the 'future' class
1195                                         slides[i].classList.add( 'future' );
1196                                 }
1197
1198                                 // If this element contains vertical slides
1199                                 if( element.querySelector( 'section' ) ) {
1200                                         slides[i].classList.add( 'stack' );
1201                                 }
1202                         }
1203
1204                         // Mark the current slide as present
1205                         slides[index].classList.add( 'present' );
1206
1207                         // If this slide has a state associated with it, add it
1208                         // onto the current state of the deck
1209                         var slideState = slides[index].getAttribute( 'data-state' );
1210                         if( slideState ) {
1211                                 state = state.concat( slideState.split( ' ' ) );
1212                         }
1213
1214                         // If this slide has a data-autoslide attribtue associated use this as
1215                         // autoSlide value otherwise use the global configured time
1216                         var slideAutoSlide = slides[index].getAttribute( 'data-autoslide' );
1217                         if( slideAutoSlide ) {
1218                                 autoSlide = parseInt( slideAutoSlide, 10 );
1219                         }
1220                         else {
1221                                 autoSlide = config.autoSlide;
1222                         }
1223
1224                 }
1225                 else {
1226                         // Since there are no slides we can't be anywhere beyond the
1227                         // zeroth index
1228                         index = 0;
1229                 }
1230
1231                 return index;
1232
1233         }
1234
1235         /**
1236          * Updates the progress bar to reflect the current slide.
1237          */
1238         function updateProgress() {
1239
1240                 // Update progress if enabled
1241                 if( config.progress && dom.progress ) {
1242
1243                         var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1244
1245                         // The number of past and total slides
1246                         var totalCount = document.querySelectorAll( SLIDES_SELECTOR + ':not(.stack)' ).length;
1247                         var pastCount = 0;
1248
1249                         // Step through all slides and count the past ones
1250                         mainLoop: for( var i = 0; i < horizontalSlides.length; i++ ) {
1251
1252                                 var horizontalSlide = horizontalSlides[i];
1253                                 var verticalSlides = toArray( horizontalSlide.querySelectorAll( 'section' ) );
1254
1255                                 for( var j = 0; j < verticalSlides.length; j++ ) {
1256
1257                                         // Stop as soon as we arrive at the present
1258                                         if( verticalSlides[j].classList.contains( 'present' ) ) {
1259                                                 break mainLoop;
1260                                         }
1261
1262                                         pastCount++;
1263
1264                                 }
1265
1266                                 // Stop as soon as we arrive at the present
1267                                 if( horizontalSlide.classList.contains( 'present' ) ) {
1268                                         break;
1269                                 }
1270
1271                                 // Don't count the wrapping section for vertical slides
1272                                 if( horizontalSlide.classList.contains( 'stack' ) === false ) {
1273                                         pastCount++;
1274                                 }
1275
1276                         }
1277
1278                         dom.progressbar.style.width = ( pastCount / ( totalCount - 1 ) ) * window.innerWidth + 'px';
1279
1280                 }
1281
1282         }
1283
1284         /**
1285          * Updates the state of all control/navigation arrows.
1286          */
1287         function updateControls() {
1288
1289                 if ( config.controls && dom.controls ) {
1290
1291                         var routes = availableRoutes();
1292
1293                         // Remove the 'enabled' class from all directions
1294                         dom.controlsLeft.concat( dom.controlsRight )
1295                                                         .concat( dom.controlsUp )
1296                                                         .concat( dom.controlsDown )
1297                                                         .concat( dom.controlsPrev )
1298                                                         .concat( dom.controlsNext ).forEach( function( node ) {
1299                                 node.classList.remove( 'enabled' );
1300                         } );
1301
1302                         // Add the 'enabled' class to the available routes
1303                         if( routes.left ) dom.controlsLeft.forEach( function( el ) { el.classList.add( 'enabled' );     } );
1304                         if( routes.right ) dom.controlsRight.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1305                         if( routes.up ) dom.controlsUp.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1306                         if( routes.down ) dom.controlsDown.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1307
1308                         // Prev/next buttons
1309                         if( routes.left || routes.up ) dom.controlsPrev.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1310                         if( routes.right || routes.down ) dom.controlsNext.forEach( function( el ) { el.classList.add( 'enabled' ); } );
1311
1312                 }
1313
1314         }
1315
1316         /**
1317          * Determine what available routes there are for navigation.
1318          *
1319          * @return {Object} containing four booleans: left/right/up/down
1320          */
1321         function availableRoutes() {
1322
1323                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
1324                         verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
1325
1326                 return {
1327                         left: indexh > 0,
1328                         right: indexh < horizontalSlides.length - 1,
1329                         up: indexv > 0,
1330                         down: indexv < verticalSlides.length - 1
1331                 };
1332
1333         }
1334
1335         /**
1336          * Reads the current URL (hash) and navigates accordingly.
1337          */
1338         function readURL() {
1339
1340                 var hash = window.location.hash;
1341
1342                 // Attempt to parse the hash as either an index or name
1343                 var bits = hash.slice( 2 ).split( '/' ),
1344                         name = hash.replace( /#|\//gi, '' );
1345
1346                 // If the first bit is invalid and there is a name we can
1347                 // assume that this is a named link
1348                 if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
1349                         // Find the slide with the specified name
1350                         var element = document.querySelector( '#' + name );
1351
1352                         if( element ) {
1353                                 // Find the position of the named slide and navigate to it
1354                                 var indices = Reveal.getIndices( element );
1355                                 slide( indices.h, indices.v );
1356                         }
1357                         // If the slide doesn't exist, navigate to the current slide
1358                         else {
1359                                 slide( indexh, indexv );
1360                         }
1361                 }
1362                 else {
1363                         // Read the index components of the hash
1364                         var h = parseInt( bits[0], 10 ) || 0,
1365                                 v = parseInt( bits[1], 10 ) || 0;
1366
1367                         slide( h, v );
1368                 }
1369
1370         }
1371
1372         /**
1373          * Updates the page URL (hash) to reflect the current
1374          * state.
1375          *
1376          * @param {Number} delay The time in ms to wait before
1377          * writing the hash
1378          */
1379         function writeURL( delay ) {
1380
1381                 if( config.history ) {
1382
1383                         // Make sure there's never more than one timeout running
1384                         clearTimeout( writeURLTimeout );
1385
1386                         // If a delay is specified, timeout this call
1387                         if( typeof delay === 'number' ) {
1388                                 writeURLTimeout = setTimeout( writeURL, delay );
1389                         }
1390                         else {
1391                                 var url = '/';
1392
1393                                 // If the current slide has an ID, use that as a named link
1394                                 if( currentSlide && typeof currentSlide.getAttribute( 'id' ) === 'string' ) {
1395                                         url = '/' + currentSlide.getAttribute( 'id' );
1396                                 }
1397                                 // Otherwise use the /h/v index
1398                                 else {
1399                                         if( indexh > 0 || indexv > 0 ) url += indexh;
1400                                         if( indexv > 0 ) url += '/' + indexv;
1401                                 }
1402
1403                                 window.location.hash = url;
1404                         }
1405                 }
1406
1407         }
1408
1409         /**
1410          * Retrieves the h/v location of the current, or specified,
1411          * slide.
1412          *
1413          * @param {HTMLElement} slide If specified, the returned
1414          * index will be for this slide rather than the currently
1415          * active one
1416          *
1417          * @return {Object} { h: <int>, v: <int> }
1418          */
1419         function getIndices( slide ) {
1420
1421                 // By default, return the current indices
1422                 var h = indexh,
1423                         v = indexv;
1424
1425                 // If a slide is specified, return the indices of that slide
1426                 if( slide ) {
1427                         var isVertical = !!slide.parentNode.nodeName.match( /section/gi );
1428                         var slideh = isVertical ? slide.parentNode : slide;
1429
1430                         // Select all horizontal slides
1431                         var horizontalSlides = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1432
1433                         // Now that we know which the horizontal slide is, get its index
1434                         h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
1435
1436                         // If this is a vertical slide, grab the vertical index
1437                         if( isVertical ) {
1438                                 v = Math.max( toArray( slide.parentNode.querySelectorAll( 'section' ) ).indexOf( slide ), 0 );
1439                         }
1440                 }
1441
1442                 return { h: h, v: v };
1443
1444         }
1445
1446         /**
1447          * Navigate to the next slide fragment.
1448          *
1449          * @return {Boolean} true if there was a next fragment,
1450          * false otherwise
1451          */
1452         function nextFragment() {
1453
1454                 // Vertical slides:
1455                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1456                         var verticalFragments = sortFragments( document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' ) );
1457
1458                         if( verticalFragments.length ) {
1459                                 verticalFragments[0].classList.add( 'visible' );
1460
1461                                 // Notify subscribers of the change
1462                                 dispatchEvent( 'fragmentshown', { fragment: verticalFragments[0] } );
1463                                 return true;
1464                         }
1465                 }
1466                 // Horizontal slides:
1467                 else {
1468                         var horizontalFragments = sortFragments( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' ) );
1469
1470                         if( horizontalFragments.length ) {
1471                                 horizontalFragments[0].classList.add( 'visible' );
1472
1473                                 // Notify subscribers of the change
1474                                 dispatchEvent( 'fragmentshown', { fragment: horizontalFragments[0] } );
1475                                 return true;
1476                         }
1477                 }
1478
1479                 return false;
1480
1481         }
1482
1483         /**
1484          * Navigate to the previous slide fragment.
1485          *
1486          * @return {Boolean} true if there was a previous fragment,
1487          * false otherwise
1488          */
1489         function previousFragment() {
1490
1491                 // Vertical slides:
1492                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1493                         var verticalFragments = sortFragments( document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment.visible' ) );
1494
1495                         if( verticalFragments.length ) {
1496                                 verticalFragments[ verticalFragments.length - 1 ].classList.remove( 'visible' );
1497
1498                                 // Notify subscribers of the change
1499                                 dispatchEvent( 'fragmenthidden', { fragment: verticalFragments[ verticalFragments.length - 1 ] } );
1500                                 return true;
1501                         }
1502                 }
1503                 // Horizontal slides:
1504                 else {
1505                         var horizontalFragments = sortFragments( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment.visible' ) );
1506
1507                         if( horizontalFragments.length ) {
1508                                 horizontalFragments[ horizontalFragments.length - 1 ].classList.remove( 'visible' );
1509
1510                                 // Notify subscribers of the change
1511                                 dispatchEvent( 'fragmenthidden', { fragment: horizontalFragments[ horizontalFragments.length - 1 ] } );
1512                                 return true;
1513                         }
1514                 }
1515
1516                 return false;
1517
1518         }
1519
1520         /**
1521          * Cues a new automated slide if enabled in the config.
1522          */
1523         function cueAutoSlide() {
1524
1525                 clearTimeout( autoSlideTimeout );
1526
1527                 // Cue the next auto-slide if enabled
1528                 if( autoSlide && !isPaused() && !isOverview() ) {
1529                         autoSlideTimeout = setTimeout( navigateNext, autoSlide );
1530                 }
1531
1532         }
1533
1534         /**
1535          * Cancels any ongoing request to auto-slide.
1536          */
1537         function cancelAutoSlide() {
1538
1539                 clearTimeout( autoSlideTimeout );
1540
1541         }
1542
1543         function navigateLeft() {
1544
1545                 // Prioritize hiding fragments
1546                 if( availableRoutes().left && isOverview() || previousFragment() === false ) {
1547                         slide( indexh - 1 );
1548                 }
1549
1550         }
1551
1552         function navigateRight() {
1553
1554                 // Prioritize revealing fragments
1555                 if( availableRoutes().right && isOverview() || nextFragment() === false ) {
1556                         slide( indexh + 1 );
1557                 }
1558
1559         }
1560
1561         function navigateUp() {
1562
1563                 // Prioritize hiding fragments
1564                 if( availableRoutes().up && isOverview() || previousFragment() === false ) {
1565                         slide( indexh, indexv - 1 );
1566                 }
1567
1568         }
1569
1570         function navigateDown() {
1571
1572                 // Prioritize revealing fragments
1573                 if( availableRoutes().down && isOverview() || nextFragment() === false ) {
1574                         slide( indexh, indexv + 1 );
1575                 }
1576
1577         }
1578
1579         /**
1580          * Navigates backwards, prioritized in the following order:
1581          * 1) Previous fragment
1582          * 2) Previous vertical slide
1583          * 3) Previous horizontal slide
1584          */
1585         function navigatePrev() {
1586
1587                 // Prioritize revealing fragments
1588                 if( previousFragment() === false ) {
1589                         if( availableRoutes().up ) {
1590                                 navigateUp();
1591                         }
1592                         else {
1593                                 // Fetch the previous horizontal slide, if there is one
1594                                 var previousSlide = document.querySelector( HORIZONTAL_SLIDES_SELECTOR + '.past:nth-child(' + indexh + ')' );
1595
1596                                 if( previousSlide ) {
1597                                         indexv = ( previousSlide.querySelectorAll( 'section' ).length + 1 ) || undefined;
1598                                         indexh --;
1599                                         slide();
1600                                 }
1601                         }
1602                 }
1603
1604         }
1605
1606         /**
1607          * Same as #navigatePrev() but navigates forwards.
1608          */
1609         function navigateNext() {
1610
1611                 // Prioritize revealing fragments
1612                 if( nextFragment() === false ) {
1613                         availableRoutes().down ? navigateDown() : navigateRight();
1614                 }
1615
1616                 // If auto-sliding is enabled we need to cue up
1617                 // another timeout
1618                 cueAutoSlide();
1619
1620         }
1621
1622
1623         // --------------------------------------------------------------------//
1624         // ----------------------------- EVENTS -------------------------------//
1625         // --------------------------------------------------------------------//
1626
1627
1628         /**
1629          * Handler for the document level 'keydown' event.
1630          *
1631          * @param {Object} event
1632          */
1633         function onDocumentKeyDown( event ) {
1634
1635                 // Check if there's a focused element that could be using
1636                 // the keyboard
1637                 var activeElement = document.activeElement;
1638                 var hasFocus = !!( document.activeElement && ( document.activeElement.type || document.activeElement.href || document.activeElement.contentEditable !== 'inherit' ) );
1639
1640                 // Disregard the event if there's a focused element or a
1641                 // keyboard modifier key is present
1642                 if( hasFocus || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;
1643
1644                 var triggered = true;
1645
1646                 // while paused only allow "unpausing" keyboard events (b and .)
1647                 if( isPaused() && [66,190,191].indexOf( event.keyCode ) === -1 ) {
1648                         return false;
1649                 }
1650
1651                 switch( event.keyCode ) {
1652                         // p, page up
1653                         case 80: case 33: navigatePrev(); break;
1654                         // n, page down
1655                         case 78: case 34: navigateNext(); break;
1656                         // h, left
1657                         case 72: case 37: navigateLeft(); break;
1658                         // l, right
1659                         case 76: case 39: navigateRight(); break;
1660                         // k, up
1661                         case 75: case 38: navigateUp(); break;
1662                         // j, down
1663                         case 74: case 40: navigateDown(); break;
1664                         // home
1665                         case 36: slide( 0 ); break;
1666                         // end
1667                         case 35: slide( Number.MAX_VALUE ); break;
1668                         // space
1669                         case 32: isOverview() ? deactivateOverview() : navigateNext(); break;
1670                         // return
1671                         case 13: isOverview() ? deactivateOverview() : triggered = false; break;
1672                         // b, period, Logitech presenter tools "black screen" button
1673                         case 66: case 190: case 191: togglePause(); break;
1674                         // f
1675                         case 70: enterFullscreen(); break;
1676                         default:
1677                                 triggered = false;
1678                 }
1679
1680                 // If the input resulted in a triggered action we should prevent
1681                 // the browsers default behavior
1682                 if( triggered ) {
1683                         event.preventDefault();
1684                 }
1685                 else if ( event.keyCode === 27 && supports3DTransforms ) {
1686                         toggleOverview();
1687
1688                         event.preventDefault();
1689                 }
1690
1691                 // If auto-sliding is enabled we need to cue up
1692                 // another timeout
1693                 cueAutoSlide();
1694
1695         }
1696
1697         /**
1698          * Handler for the document level 'touchstart' event,
1699          * enables support for swipe and pinch gestures.
1700          */
1701         function onDocumentTouchStart( event ) {
1702
1703                 touch.startX = event.touches[0].clientX;
1704                 touch.startY = event.touches[0].clientY;
1705                 touch.startCount = event.touches.length;
1706
1707                 // If there's two touches we need to memorize the distance
1708                 // between those two points to detect pinching
1709                 if( event.touches.length === 2 && config.overview ) {
1710                         touch.startSpan = distanceBetween( {
1711                                 x: event.touches[1].clientX,
1712                                 y: event.touches[1].clientY
1713                         }, {
1714                                 x: touch.startX,
1715                                 y: touch.startY
1716                         } );
1717                 }
1718
1719         }
1720
1721         /**
1722          * Handler for the document level 'touchmove' event.
1723          */
1724         function onDocumentTouchMove( event ) {
1725
1726                 // Each touch should only trigger one action
1727                 if( !touch.handled ) {
1728                         var currentX = event.touches[0].clientX;
1729                         var currentY = event.touches[0].clientY;
1730
1731                         // If the touch started off with two points and still has
1732                         // two active touches; test for the pinch gesture
1733                         if( event.touches.length === 2 && touch.startCount === 2 && config.overview ) {
1734
1735                                 // The current distance in pixels between the two touch points
1736                                 var currentSpan = distanceBetween( {
1737                                         x: event.touches[1].clientX,
1738                                         y: event.touches[1].clientY
1739                                 }, {
1740                                         x: touch.startX,
1741                                         y: touch.startY
1742                                 } );
1743
1744                                 // If the span is larger than the desire amount we've got
1745                                 // ourselves a pinch
1746                                 if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
1747                                         touch.handled = true;
1748
1749                                         if( currentSpan < touch.startSpan ) {
1750                                                 activateOverview();
1751                                         }
1752                                         else {
1753                                                 deactivateOverview();
1754                                         }
1755                                 }
1756
1757                                 event.preventDefault();
1758
1759                         }
1760                         // There was only one touch point, look for a swipe
1761                         else if( event.touches.length === 1 && touch.startCount !== 2 ) {
1762
1763                                 var deltaX = currentX - touch.startX,
1764                                         deltaY = currentY - touch.startY;
1765
1766                                 if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1767                                         touch.handled = true;
1768                                         navigateLeft();
1769                                 }
1770                                 else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
1771                                         touch.handled = true;
1772                                         navigateRight();
1773                                 }
1774                                 else if( deltaY > touch.threshold ) {
1775                                         touch.handled = true;
1776                                         navigateUp();
1777                                 }
1778                                 else if( deltaY < -touch.threshold ) {
1779                                         touch.handled = true;
1780                                         navigateDown();
1781                                 }
1782
1783                                 event.preventDefault();
1784
1785                         }
1786                 }
1787                 // There's a bug with swiping on some Android devices unless
1788                 // the default action is always prevented
1789                 else if( navigator.userAgent.match( /android/gi ) ) {
1790                         event.preventDefault();
1791                 }
1792
1793         }
1794
1795         /**
1796          * Handler for the document level 'touchend' event.
1797          */
1798         function onDocumentTouchEnd( event ) {
1799
1800                 touch.handled = false;
1801
1802         }
1803
1804         /**
1805          * Handles mouse wheel scrolling, throttled to avoid skipping
1806          * multiple slides.
1807          */
1808         function onDocumentMouseScroll( event ) {
1809
1810                 clearTimeout( mouseWheelTimeout );
1811
1812                 mouseWheelTimeout = setTimeout( function() {
1813                         var delta = event.detail || -event.wheelDelta;
1814                         if( delta > 0 ) {
1815                                 navigateNext();
1816                         }
1817                         else {
1818                                 navigatePrev();
1819                         }
1820                 }, 100 );
1821
1822         }
1823
1824         /**
1825          * Clicking on the progress bar results in a navigation to the
1826          * closest approximate horizontal slide using this equation:
1827          *
1828          * ( clickX / presentationWidth ) * numberOfSlides
1829          */
1830         function onProgressClicked( event ) {
1831
1832                 event.preventDefault();
1833
1834                 var slidesTotal = toArray( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) ).length;
1835                 var slideIndex = Math.floor( ( event.clientX / dom.wrapper.offsetWidth ) * slidesTotal );
1836
1837                 slide( slideIndex );
1838
1839         }
1840
1841         /**
1842          * Event handler for navigation control buttons.
1843          */
1844         function onNavigateLeftClicked( event ) { event.preventDefault(); navigateLeft(); }
1845         function onNavigateRightClicked( event ) { event.preventDefault(); navigateRight(); }
1846         function onNavigateUpClicked( event ) { event.preventDefault(); navigateUp(); }
1847         function onNavigateDownClicked( event ) { event.preventDefault(); navigateDown(); }
1848         function onNavigatePrevClicked( event ) { event.preventDefault(); navigatePrev(); }
1849         function onNavigateNextClicked( event ) { event.preventDefault(); navigateNext(); }
1850
1851         /**
1852          * Handler for the window level 'hashchange' event.
1853          */
1854         function onWindowHashChange( event ) {
1855
1856                 readURL();
1857
1858         }
1859
1860         /**
1861          * Handler for the window level 'resize' event.
1862          */
1863         function onWindowResize( event ) {
1864
1865                 layout();
1866
1867         }
1868
1869         /**
1870          * Invoked when a slide is and we're in the overview.
1871          */
1872         function onOverviewSlideClicked( event ) {
1873
1874                 // TODO There's a bug here where the event listeners are not
1875                 // removed after deactivating the overview.
1876                 if( eventsAreBound && isOverview() ) {
1877                         event.preventDefault();
1878
1879                         var element = event.target;
1880
1881                         while( element && !element.nodeName.match( /section/gi ) ) {
1882                                 element = element.parentNode;
1883                         }
1884
1885                         if( element && !element.classList.contains( 'disabled' ) ) {
1886
1887                                 deactivateOverview();
1888
1889                                 if( element.nodeName.match( /section/gi ) ) {
1890                                         var h = parseInt( element.getAttribute( 'data-index-h' ), 10 ),
1891                                                 v = parseInt( element.getAttribute( 'data-index-v' ), 10 );
1892
1893                                         slide( h, v );
1894                                 }
1895
1896                         }
1897                 }
1898
1899         }
1900
1901
1902         // --------------------------------------------------------------------//
1903         // ------------------------------- API --------------------------------//
1904         // --------------------------------------------------------------------//
1905
1906
1907         return {
1908                 initialize: initialize,
1909                 configure: configure,
1910
1911                 // Navigation methods
1912                 slide: slide,
1913                 left: navigateLeft,
1914                 right: navigateRight,
1915                 up: navigateUp,
1916                 down: navigateDown,
1917                 prev: navigatePrev,
1918                 next: navigateNext,
1919                 prevFragment: previousFragment,
1920                 nextFragment: nextFragment,
1921
1922                 // Deprecated aliases
1923                 navigateTo: slide,
1924                 navigateLeft: navigateLeft,
1925                 navigateRight: navigateRight,
1926                 navigateUp: navigateUp,
1927                 navigateDown: navigateDown,
1928                 navigatePrev: navigatePrev,
1929                 navigateNext: navigateNext,
1930
1931                 // Forces an update in slide layout
1932                 layout: layout,
1933
1934                 // Toggles the overview mode on/off
1935                 toggleOverview: toggleOverview,
1936
1937                 // Toggles the "black screen" mode on/off
1938                 togglePause: togglePause,
1939
1940                 // State checks
1941                 isOverview: isOverview,
1942                 isPaused: isPaused,
1943
1944                 // Adds or removes all internal event listeners (such as keyboard)
1945                 addEventListeners: addEventListeners,
1946                 removeEventListeners: removeEventListeners,
1947
1948                 // Returns the indices of the current, or specified, slide
1949                 getIndices: getIndices,
1950
1951                 // Returns the slide at the specified index, y is optional
1952                 getSlide: function( x, y ) {
1953                         var horizontalSlide = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR )[ x ];
1954                         var verticalSlides = horizontalSlide && horizontalSlide.querySelectorAll( 'section' );
1955
1956                         if( typeof y !== 'undefined' ) {
1957                                 return verticalSlides ? verticalSlides[ y ] : undefined;
1958                         }
1959
1960                         return horizontalSlide;
1961                 },
1962
1963                 // Returns the previous slide element, may be null
1964                 getPreviousSlide: function() {
1965                         return previousSlide;
1966                 },
1967
1968                 // Returns the current slide element
1969                 getCurrentSlide: function() {
1970                         return currentSlide;
1971                 },
1972
1973                 // Returns the current scale of the presentation content
1974                 getScale: function() {
1975                         return scale;
1976                 },
1977
1978                 // Helper method, retrieves query string as a key/value hash
1979                 getQueryHash: function() {
1980                         var query = {};
1981
1982                         location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
1983                                 query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
1984                         } );
1985
1986                         return query;
1987                 },
1988
1989                 // Returns true if we're currently on the first slide
1990                 isFirstSlide: function() {
1991                         return document.querySelector( SLIDES_SELECTOR + '.past' ) == null ? true : false;
1992                 },
1993
1994                 // Returns true if we're currently on the last slide
1995                 isLastSlide: function() {
1996                         if( currentSlide && currentSlide.classList.contains( '.stack' ) ) {
1997                                 return currentSlide.querySelector( SLIDES_SELECTOR + '.future' ) == null ? true : false;
1998                         }
1999                         else {
2000                                 return document.querySelector( SLIDES_SELECTOR + '.future' ) == null ? true : false;
2001                         }
2002                 },
2003
2004                 // Forward event binding to the reveal DOM element
2005                 addEventListener: function( type, listener, useCapture ) {
2006                         if( 'addEventListener' in window ) {
2007                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
2008                         }
2009                 },
2010                 removeEventListener: function( type, listener, useCapture ) {
2011                         if( 'addEventListener' in window ) {
2012                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
2013                         }
2014                 }
2015         };
2016
2017 })();