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