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