new paused mode feature (closes #144), controls and progress DOM elements are no...
[reveal.js.git] / js / reveal.js
1 /*!
2  * reveal.js 2.1 r29
3  * http://lab.hakim.se/reveal-js
4  * MIT licensed
5  * 
6  * Copyright (C) 2011-2012 Hakim El Hattab, http://hakim.se
7  */
8 var Reveal = (function(){
9
10         'use strict';
11         
12         var HORIZONTAL_SLIDES_SELECTOR = '.reveal .slides>section',
13                 VERTICAL_SLIDES_SELECTOR = '.reveal .slides>section.present>section',
14
15                 // Configurations defaults, can be overridden at initialization time 
16                 config = {
17                         // Display controls in the bottom right corner
18                         controls: true,
19
20                         // Display a presentation progress bar
21                         progress: true,
22
23                         // Push each slide change to the browser history
24                         history: false,
25
26                         // Enable keyboard shortcuts for navigation
27                         keyboard: true,
28
29                         // Enable the slide overview mode
30                         overview: true,
31
32                         // Loop the presentation
33                         loop: false,
34
35                         // Number of milliseconds between automatically proceeding to the 
36                         // next slide, disabled when set to 0
37                         autoSlide: 0,
38
39                         // Enable slide navigation via mouse wheel
40                         mouseWheel: true,
41
42                         // Apply a 3D roll to links on hover
43                         rollingLinks: true,
44
45                         // Transition style (see /css/theme)
46                         theme: 'default', 
47
48                         // Transition style
49                         transition: 'default', // default/cube/page/concave/linear(2d),
50
51                         // Script dependencies to load
52                         dependencies: []
53                 },
54
55                 // The horizontal and verical index of the currently active slide
56                 indexh = 0,
57                 indexv = 0,
58
59                 // The previous and current slide HTML elements
60                 previousSlide,
61                 currentSlide,
62
63                 // Slides may hold a data-state attribute which we pick up and apply 
64                 // as a class to the body. This list contains the combined state of 
65                 // all current slides.
66                 state = [],
67
68                 // Cached references to DOM elements
69                 dom = {},
70
71                 // Detect support for CSS 3D transforms
72                 supports3DTransforms =  'WebkitPerspective' in document.body.style ||
73                                                                 'MozPerspective' in document.body.style ||
74                                                                 'msPerspective' in document.body.style ||
75                                                                 'OPerspective' in document.body.style ||
76                                                                 'perspective' in document.body.style,
77                 
78                 supports2DTransforms =  'WebkitTransform' in document.body.style ||
79                                                                 'MozTransform' in document.body.style ||
80                                                                 'msTransform' in document.body.style ||
81                                                                 'OTransform' in document.body.style ||
82                                                                 'transform' in document.body.style,
83                 
84                 // Throttles mouse wheel navigation
85                 mouseWheelTimeout = 0,
86
87                 // An interval used to automatically move on to the next slide
88                 autoSlideTimeout = 0,
89
90                 // Delays updates to the URL due to a Chrome thumbnailer bug
91                 writeURLTimeout = 0,
92
93                 // Holds information about the currently ongoing touch input
94                 touch = {
95                         startX: 0,
96                         startY: 0,
97                         startSpan: 0,
98                         startCount: 0,
99                         handled: false,
100                         threshold: 40
101                 };
102         
103         
104         /**
105          * Starts up the presentation if the client is capable.
106          */
107         function initialize( options ) {
108                 if( ( !supports2DTransforms && !supports3DTransforms ) ) {
109                         document.body.setAttribute( 'class', 'no-transforms' );
110
111                         // If the browser doesn't support core features we won't be 
112                         // using JavaScript to control the presentation
113                         return;
114                 }
115
116                 // Copy options over to our config object
117                 extend( config, options );
118
119                 // Make sure we've got all the DOM elements we need
120                 setupDOM();
121
122                 // Hide the address bar in mobile browsers
123                 hideAddressBar();
124
125                 // Loads the dependencies and continues to #start() once done
126                 load();
127                 
128         }
129
130         /**
131          * Finds and stores references to DOM elements which are 
132          * required by the presentation. If a required element is 
133          * not found, it is created.
134          */
135         function setupDOM() {
136                 // Cache references to key DOM elements
137                 dom.theme = document.querySelector( '#theme' );
138                 dom.wrapper = document.querySelector( '.reveal' );
139
140                 // Progress bar
141                 if( !dom.wrapper.querySelector( '.progress' ) && config.progress ) {
142                         var progressElement = document.createElement( 'div' );
143                         progressElement.classList.add( 'progress' );
144                         progressElement.innerHTML = '<span></span>';
145                         dom.wrapper.appendChild( progressElement );
146                 }
147
148                 // Arrow controls
149                 if( !dom.wrapper.querySelector( '.controls' ) && config.controls ) {
150                         var controlsElement = document.createElement( 'aside' );
151                         controlsElement.classList.add( 'controls' );
152                         controlsElement.innerHTML = '<a class="left" href="#">&#x25C4;</a>' +
153                                                                                 '<a class="right" href="#">&#x25BA;</a>' +
154                                                                                 '<a class="up" href="#">&#x25B2;</a>' +
155                                                                                 '<a class="down" href="#">&#x25BC;</a>';
156                         dom.wrapper.appendChild( controlsElement );
157                 }
158
159                 // Presentation background element
160                 if( !dom.wrapper.querySelector( '.state-background' ) ) {
161                         var backgroundElement = document.createElement( 'div' );
162                         backgroundElement.classList.add( 'state-background' );
163                         dom.wrapper.appendChild( backgroundElement );
164                 }
165
166                 // Overlay graphic which is displayed during the paused mode
167                 if( !dom.wrapper.querySelector( '.pause-overlay' ) ) {
168                         var pausedElement = document.createElement( 'div' );
169                         pausedElement.classList.add( 'pause-overlay' );
170                         dom.wrapper.appendChild( pausedElement );
171                 }
172
173                 // Cache references to elements
174                 dom.progress = document.querySelector( '.reveal .progress' );
175                 dom.progressbar = document.querySelector( '.reveal .progress span' );
176
177                 if ( config.controls ) {
178                         dom.controls = document.querySelector( '.reveal .controls' );
179                         dom.controlsLeft = document.querySelector( '.reveal .controls .left' );
180                         dom.controlsRight = document.querySelector( '.reveal .controls .right' );
181                         dom.controlsUp = document.querySelector( '.reveal .controls .up' );
182                         dom.controlsDown = document.querySelector( '.reveal .controls .down' );
183                 }
184         }
185
186         /**
187          * Hides the address bar if we're on a mobile device.
188          */
189         function hideAddressBar() {
190                 if( navigator.userAgent.match( /(iphone|ipod|android)/i ) ) {
191                         // Give the page some scrollable overflow
192                         document.documentElement.style.overflow = 'scroll';
193                         document.body.style.height = '120%';
194
195                         // Events that should trigger the address bar to hide
196                         window.addEventListener( 'load', removeAddressBar, false );
197                         window.addEventListener( 'orientationchange', removeAddressBar, false );
198                 }
199         }
200
201         /**
202          * Loads the dependencies of reveal.js. Dependencies are 
203          * defined via the configuration option 'dependencies' 
204          * and will be loaded prior to starting/binding reveal.js. 
205          * Some dependencies may have an 'async' flag, if so they 
206          * will load after reveal.js has been started up.
207          */
208         function load() {
209                 var scripts = [],
210                         scriptsAsync = [];
211
212                 for( var i = 0, len = config.dependencies.length; i < len; i++ ) {
213                         var s = config.dependencies[i];
214
215                         // Load if there's no condition or the condition is truthy
216                         if( !s.condition || s.condition() ) {
217                                 if( s.async ) {
218                                         scriptsAsync.push( s.src );
219                                 }
220                                 else {
221                                         scripts.push( s.src );
222                                 }
223
224                                 // Extension may contain callback functions
225                                 if( typeof s.callback === 'function' ) {
226                                         head.ready( s.src.match( /([\w\d_\-]*)\.?[^\\\/]*$/i )[0], s.callback );
227                                 }
228                         }
229                 }
230
231                 // Called once synchronous scritps finish loading
232                 function proceed() {
233                         // Load asynchronous scripts
234                         head.js.apply( null, scriptsAsync );
235                         
236                         start();
237                 }
238
239                 if( scripts.length ) {
240                         head.ready( proceed );
241
242                         // Load synchronous scripts
243                         head.js.apply( null, scripts );
244                 }
245                 else {
246                         proceed();
247                 }
248         }
249
250         /**
251          * Starts up reveal.js by binding input events and navigating 
252          * to the current URL deeplink if there is one.
253          */
254         function start() {
255                 // Subscribe to input
256                 addEventListeners();
257
258                 // Updates the presentation to match the current configuration values
259                 configure();
260
261                 // Read the initial hash
262                 readURL();
263
264                 // Start auto-sliding if it's enabled
265                 cueAutoSlide();
266         }
267
268         /**
269          * Applies the configuration settings from the config object.
270          */
271         function configure() {
272                 if( supports3DTransforms === false ) {
273                         config.transition = 'linear';
274                 }
275
276                 if( config.controls && dom.controls ) {
277                         dom.controls.style.display = 'block';
278                 }
279
280                 if( config.progress && dom.progress ) {
281                         dom.progress.style.display = 'block';
282                 }
283
284                 // Load the theme in the config, if it's not already loaded
285                 if( config.theme && dom.theme ) {
286                         var themeURL = dom.theme.getAttribute( 'href' );
287                         var themeFinder = /[^\/]*?(?=\.css)/;
288                         var themeName = themeURL.match(themeFinder)[0];
289
290                         if(  config.theme !== themeName ) {
291                                 themeURL = themeURL.replace(themeFinder, config.theme);
292                                 dom.theme.setAttribute( 'href', themeURL );
293                         }
294                 }
295
296                 if( config.transition !== 'default' ) {
297                         dom.wrapper.classList.add( config.transition );
298                 }
299
300                 if( config.mouseWheel ) {
301                         document.addEventListener( 'DOMMouseScroll', onDocumentMouseScroll, false ); // FF
302                         document.addEventListener( 'mousewheel', onDocumentMouseScroll, false );
303                 }
304
305                 if( config.rollingLinks ) {
306                         // Add some 3D magic to our anchors
307                         linkify();
308                 }
309         }
310
311         function addEventListeners() {
312                 document.addEventListener( 'touchstart', onDocumentTouchStart, false );
313                 document.addEventListener( 'touchmove', onDocumentTouchMove, false );
314                 document.addEventListener( 'touchend', onDocumentTouchEnd, false );
315                 window.addEventListener( 'hashchange', onWindowHashChange, false );
316
317                 if( config.keyboard ) {
318                         document.addEventListener( 'keydown', onDocumentKeyDown, false );
319                 }
320
321                 if ( config.controls && dom.controls ) {
322                         dom.controlsLeft.addEventListener( 'click', preventAndForward( navigateLeft ), false );
323                         dom.controlsRight.addEventListener( 'click', preventAndForward( navigateRight ), false );
324                         dom.controlsUp.addEventListener( 'click', preventAndForward( navigateUp ), false );
325                         dom.controlsDown.addEventListener( 'click', preventAndForward( navigateDown ), false ); 
326                 }
327         }
328
329         function removeEventListeners() {
330                 document.removeEventListener( 'keydown', onDocumentKeyDown, false );
331                 document.removeEventListener( 'touchstart', onDocumentTouchStart, false );
332                 document.removeEventListener( 'touchmove', onDocumentTouchMove, false );
333                 document.removeEventListener( 'touchend', onDocumentTouchEnd, false );
334                 window.removeEventListener( 'hashchange', onWindowHashChange, false );
335                 
336                 if ( config.controls && dom.controls ) {
337                         dom.controlsLeft.removeEventListener( 'click', preventAndForward( navigateLeft ), false );
338                         dom.controlsRight.removeEventListener( 'click', preventAndForward( navigateRight ), false );
339                         dom.controlsUp.removeEventListener( 'click', preventAndForward( navigateUp ), false );
340                         dom.controlsDown.removeEventListener( 'click', preventAndForward( navigateDown ), false );
341                 }
342         }
343
344         /**
345          * Extend object a with the properties of object b. 
346          * If there's a conflict, object b takes precedence.
347          */
348         function extend( a, b ) {
349                 for( var i in b ) {
350                         a[ i ] = b[ i ];
351                 }
352         }
353
354         /**
355          * Measures the distance in pixels between point a
356          * and point b. 
357          * 
358          * @param {Object} a point with x/y properties
359          * @param {Object} b point with x/y properties
360          */
361         function distanceBetween( a, b ) {
362                 var dx = a.x - b.x,
363                         dy = a.y - b.y;
364
365                 return Math.sqrt( dx*dx + dy*dy );
366         }
367
368         /**
369          * Prevents an events defaults behavior calls the 
370          * specified delegate.
371          * 
372          * @param {Function} delegate The method to call 
373          * after the wrapper has been executed
374          */
375         function preventAndForward( delegate ) {
376                 return function( event ) {
377                         event.preventDefault();
378                         delegate.call();
379                 };
380         }
381
382         /**
383          * Causes the address bar to hide on mobile devices, 
384          * more vertical space ftw.
385          */
386         function removeAddressBar() {
387                 setTimeout( function() {
388                         window.scrollTo( 0, 1 );
389                 }, 0 );
390         }
391
392         /**
393          * Dispatches an event of the specified type from the 
394          * reveal DOM element.
395          */
396         function dispatchEvent( type, properties ) {
397                 var event = document.createEvent( "HTMLEvents", 1, 2 );
398                 event.initEvent( type, true, true );
399                 extend( event, properties );
400                 dom.wrapper.dispatchEvent( event );
401         }
402         
403         /**
404          * Handler for the document level 'keydown' event.
405          * 
406          * @param {Object} event
407          */
408         function onDocumentKeyDown( event ) {
409                 // Disregard the event if the target is editable or a 
410                 // modifier is present
411                 if ( document.querySelector( ':focus' ) !== null || event.shiftKey || event.altKey || event.ctrlKey || event.metaKey ) return;
412
413                 var triggered = true;
414
415                 switch( event.keyCode ) {
416                         // p, page up
417                         case 80: case 33: navigatePrev(); break; 
418                         // n, page down
419                         case 78: case 34: navigateNext(); break;
420                         // h, left
421                         case 72: case 37: navigateLeft(); break;
422                         // l, right
423                         case 76: case 39: navigateRight(); break;
424                         // k, up
425                         case 75: case 38: navigateUp(); break;
426                         // j, down
427                         case 74: case 40: navigateDown(); break;
428                         // home
429                         case 36: navigateTo( 0 ); break;
430                         // end
431                         case 35: navigateTo( Number.MAX_VALUE ); break;
432                         // space
433                         case 32: isOverviewActive() ? deactivateOverview() : navigateNext(); break;
434                         // return
435                         case 13: isOverviewActive() ? deactivateOverview() : triggered = false; break;
436                         // b, period
437                         case 66: case 190: togglePause(); break;
438                         default:
439                                 triggered = false;
440                 }
441
442                 // If the input resulted in a triggered action we should prevent 
443                 // the browsers default behavior
444                 if( triggered ) {
445                         event.preventDefault();
446                 }
447                 else if ( event.keyCode === 27 && supports3DTransforms ) {
448                         toggleOverview();
449         
450                         event.preventDefault();
451                 }
452
453                 // If auto-sliding is enabled we need to cue up 
454                 // another timeout
455                 cueAutoSlide();
456
457         }
458
459         /**
460          * Handler for the document level 'touchstart' event,
461          * enables support for swipe and pinch gestures.
462          */
463         function onDocumentTouchStart( event ) {
464                 touch.startX = event.touches[0].clientX;
465                 touch.startY = event.touches[0].clientY;
466                 touch.startCount = event.touches.length;
467
468                 // If there's two touches we need to memorize the distance 
469                 // between those two points to detect pinching
470                 if( event.touches.length === 2 ) {
471                         touch.startSpan = distanceBetween( {
472                                 x: event.touches[1].clientX,
473                                 y: event.touches[1].clientY
474                         }, {
475                                 x: touch.startX,
476                                 y: touch.startY
477                         } );
478                 }
479         }
480         
481         /**
482          * Handler for the document level 'touchmove' event.
483          */
484         function onDocumentTouchMove( event ) {
485                 // Each touch should only trigger one action
486                 if( !touch.handled ) {
487                         var currentX = event.touches[0].clientX;
488                         var currentY = event.touches[0].clientY;
489
490                         // If the touch started off with two points and still has 
491                         // two active touches; test for the pinch gesture
492                         if( event.touches.length === 2 && touch.startCount === 2 ) {
493
494                                 // The current distance in pixels between the two touch points
495                                 var currentSpan = distanceBetween( {
496                                         x: event.touches[1].clientX,
497                                         y: event.touches[1].clientY
498                                 }, {
499                                         x: touch.startX,
500                                         y: touch.startY
501                                 } );
502
503                                 // If the span is larger than the desire amount we've got 
504                                 // ourselves a pinch
505                                 if( Math.abs( touch.startSpan - currentSpan ) > touch.threshold ) {
506                                         touch.handled = true;
507
508                                         if( currentSpan < touch.startSpan ) {
509                                                 activateOverview();
510                                         }
511                                         else {
512                                                 deactivateOverview();
513                                         }
514                                 }
515
516                         }
517                         // There was only one touch point, look for a swipe
518                         else if( event.touches.length === 1 ) {
519                                 var deltaX = currentX - touch.startX,
520                                         deltaY = currentY - touch.startY;
521
522                                 if( deltaX > touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
523                                         touch.handled = true;
524                                         navigateLeft();
525                                 } 
526                                 else if( deltaX < -touch.threshold && Math.abs( deltaX ) > Math.abs( deltaY ) ) {
527                                         touch.handled = true;
528                                         navigateRight();
529                                 } 
530                                 else if( deltaY > touch.threshold ) {
531                                         touch.handled = true;
532                                         navigateUp();
533                                 } 
534                                 else if( deltaY < -touch.threshold ) {
535                                         touch.handled = true;
536                                         navigateDown();
537                                 }
538                         }
539
540                         event.preventDefault();
541                 }
542                 // There's a bug with swiping on some Android devices unless 
543                 // the default action is always prevented
544                 else if( navigator.userAgent.match( /android/gi ) ) {
545                         event.preventDefault();
546                 }
547         }
548
549         /**
550          * Handler for the document level 'touchend' event.
551          */
552         function onDocumentTouchEnd( event ) {
553                 touch.handled = false;
554         }
555
556         /**
557          * Handles mouse wheel scrolling, throttled to avoid 
558          * skipping multiple slides.
559          */
560         function onDocumentMouseScroll( event ){
561                 clearTimeout( mouseWheelTimeout );
562
563                 mouseWheelTimeout = setTimeout( function() {
564                         var delta = event.detail || -event.wheelDelta;
565                         if( delta > 0 ) {
566                                 navigateNext();
567                         }
568                         else {
569                                 navigatePrev();
570                         }
571                 }, 100 );
572         }
573         
574         /**
575          * Handler for the window level 'hashchange' event.
576          * 
577          * @param {Object} event
578          */
579         function onWindowHashChange( event ) {
580                 readURL();
581         }
582
583         /**
584          * Invoked when a slide is and we're in the overview.
585          */
586         function onOverviewSlideClicked( event ) {
587                 // TODO There's a bug here where the event listeners are not 
588                 // removed after deactivating the overview.
589                 if( isOverviewActive() ) {
590                         event.preventDefault();
591
592                         deactivateOverview();
593
594                         indexh = this.getAttribute( 'data-index-h' );
595                         indexv = this.getAttribute( 'data-index-v' );
596
597                         slide();
598                 }
599         }
600
601         /**
602          * Wrap all links in 3D goodness.
603          */
604         function linkify() {
605                 if( supports3DTransforms && !( 'msPerspective' in document.body.style ) ) {
606                         var nodes = document.querySelectorAll( '.reveal .slides section a:not(.image)' );
607
608                         for( var i = 0, len = nodes.length; i < len; i++ ) {
609                                 var node = nodes[i];
610                                 
611                                 if( node.textContent && !node.querySelector( 'img' ) && ( !node.className || !node.classList.contains( node, 'roll' ) ) ) {
612                                         node.classList.add( 'roll' );
613                                         node.innerHTML = '<span data-title="'+ node.text +'">' + node.innerHTML + '</span>';
614                                 }
615                         }
616                 }
617         }
618
619         /**
620          * Displays the overview of slides (quick nav) by 
621          * scaling down and arranging all slide elements.
622          * 
623          * Experimental feature, might be dropped if perf 
624          * can't be improved.
625          */
626         function activateOverview() {
627
628                 // Only proceed if enabled in config
629                 if( config.overview ) {
630                 
631                         dom.wrapper.classList.add( 'overview' );
632
633                         var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
634
635                         for( var i = 0, len1 = horizontalSlides.length; i < len1; i++ ) {
636                                 var hslide = horizontalSlides[i],
637                                         htransform = 'translateZ(-2500px) translate(' + ( ( i - indexh ) * 105 ) + '%, 0%)';
638                                 
639                                 hslide.setAttribute( 'data-index-h', i );
640                                 hslide.style.display = 'block';
641                                 hslide.style.WebkitTransform = htransform;
642                                 hslide.style.MozTransform = htransform;
643                                 hslide.style.msTransform = htransform;
644                                 hslide.style.OTransform = htransform;
645                                 hslide.style.transform = htransform;
646                         
647                                 if( !hslide.classList.contains( 'stack' ) ) {
648                                         // Navigate to this slide on click
649                                         hslide.addEventListener( 'click', onOverviewSlideClicked, true );
650                                 }
651                 
652                                 var verticalSlides = hslide.querySelectorAll( 'section' );
653
654                                 for( var j = 0, len2 = verticalSlides.length; j < len2; j++ ) {
655                                         var vslide = verticalSlides[j],
656                                                 vtransform = 'translate(0%, ' + ( ( j - ( i === indexh ? indexv : 0 ) ) * 105 ) + '%)';
657
658                                         vslide.setAttribute( 'data-index-h', i );
659                                         vslide.setAttribute( 'data-index-v', j );
660                                         vslide.style.display = 'block';
661                                         vslide.style.WebkitTransform = vtransform;
662                                         vslide.style.MozTransform = vtransform;
663                                         vslide.style.msTransform = vtransform;
664                                         vslide.style.OTransform = vtransform;
665                                         vslide.style.transform = vtransform;
666
667                                         // Navigate to this slide on click
668                                         vslide.addEventListener( 'click', onOverviewSlideClicked, true );
669                                 }
670                                 
671                         }
672
673                 }
674
675         }
676         
677         /**
678          * Exits the slide overview and enters the currently
679          * active slide.
680          */
681         function deactivateOverview() {
682                 
683                 // Only proceed if enabled in config
684                 if( config.overview ) {
685
686                         dom.wrapper.classList.remove( 'overview' );
687
688                         // Select all slides
689                         var slides = Array.prototype.slice.call( document.querySelectorAll( '.reveal .slides section' ) );
690
691                         for( var i = 0, len = slides.length; i < len; i++ ) {
692                                 var element = slides[i];
693
694                                 // Resets all transforms to use the external styles
695                                 element.style.WebkitTransform = '';
696                                 element.style.MozTransform = '';
697                                 element.style.msTransform = '';
698                                 element.style.OTransform = '';
699                                 element.style.transform = '';
700
701                                 element.removeEventListener( 'click', onOverviewSlideClicked );
702                         }
703
704                         slide();
705                         
706                 }
707         }
708
709         /**
710          * Toggles the slide overview mode on and off.
711          *
712          * @param {Boolean} override Optional flag which overrides the 
713          * toggle logic and forcibly sets the desired state. True means 
714          * overview is open, false means it's closed.
715          */
716         function toggleOverview( override ) {
717                 if( typeof override === 'boolean' ) {
718                         override ? activateOverview() : deactivateOverview();
719                 }
720                 else {
721                         isOverviewActive() ? deactivateOverview() : activateOverview();
722                 }
723         }
724
725         /**
726          * Checks if the overview is currently active.
727          * 
728          * @return {Boolean} true if the overview is active,
729          * false otherwise
730          */
731         function isOverviewActive() {
732                 return dom.wrapper.classList.contains( 'overview' );
733         }
734
735         /**
736          * Enters the paused mode which fades everything on screen to 
737          * black.
738          */
739         function pause() {
740                 dom.wrapper.classList.add( 'paused' );
741         }
742
743         /**
744          * Exits from the paused mode.
745          */
746         function resume() {
747                 dom.wrapper.classList.remove( 'paused' );
748         }
749
750         /**
751          * Toggles the paused mode on and off.
752          */
753         function togglePause() {
754                 if( isPaused() ) {
755                         resume();
756                 }
757                 else {
758                         pause();
759                 }
760         }
761
762         /**
763          * Checks if we are currently in the paused mode.
764          */
765         function isPaused() {
766                 return dom.wrapper.classList.contains( 'paused' );
767         }
768
769         /**
770          * Updates one dimension of slides by showing the slide
771          * with the specified index.
772          * 
773          * @param {String} selector A CSS selector that will fetch
774          * the group of slides we are working with
775          * @param {Number} index The index of the slide that should be
776          * shown
777          * 
778          * @return {Number} The index of the slide that is now shown,
779          * might differ from the passed in index if it was out of 
780          * bounds.
781          */
782         function updateSlides( selector, index ) {
783                 
784                 // Select all slides and convert the NodeList result to
785                 // an array
786                 var slides = Array.prototype.slice.call( document.querySelectorAll( selector ) ),
787                         slidesLength = slides.length;
788                 
789                 if( slidesLength ) {
790
791                         // Should the index loop?
792                         if( config.loop ) {
793                                 index %= slidesLength;
794
795                                 if( index < 0 ) {
796                                         index = slidesLength + index;
797                                 }
798                         }
799                         
800                         // Enforce max and minimum index bounds
801                         index = Math.max( Math.min( index, slidesLength - 1 ), 0 );
802                         
803                         for( var i = 0; i < slidesLength; i++ ) {
804                                 var slide = slides[i];
805
806                                 // Optimization; hide all slides that are three or more steps 
807                                 // away from the present slide
808                                 if( isOverviewActive() === false ) {
809                                         // The distance loops so that it measures 1 between the first
810                                         // and last slides
811                                         var distance = Math.abs( ( index - i ) % ( slidesLength - 3 ) ) || 0;
812
813                                         slide.style.display = distance > 3 ? 'none' : 'block';
814                                 }
815
816                                 slides[i].classList.remove( 'past' );
817                                 slides[i].classList.remove( 'present' );
818                                 slides[i].classList.remove( 'future' );
819
820                                 if( i < index ) {
821                                         // Any element previous to index is given the 'past' class
822                                         slides[i].classList.add( 'past' );
823                                 }
824                                 else if( i > index ) {
825                                         // Any element subsequent to index is given the 'future' class
826                                         slides[i].classList.add( 'future' );
827                                 }
828
829                                 // If this element contains vertical slides
830                                 if( slide.querySelector( 'section' ) ) {
831                                         slides[i].classList.add( 'stack' );
832                                 }
833                         }
834
835                         // Mark the current slide as present
836                         slides[index].classList.add( 'present' );
837
838                         // If this slide has a state associated with it, add it
839                         // onto the current state of the deck
840                         var slideState = slides[index].getAttribute( 'data-state' );
841                         if( slideState ) {
842                                 state = state.concat( slideState.split( ' ' ) );
843                         }
844                 }
845                 else {
846                         // Since there are no slides we can't be anywhere beyond the 
847                         // zeroth index
848                         index = 0;
849                 }
850                 
851                 return index;
852                 
853         }
854         
855         /**
856          * Steps from the current point in the presentation to the 
857          * slide which matches the specified horizontal and vertical 
858          * indices. 
859          *
860          * @param {int} h Horizontal index of the target slide
861          * @param {int} v Vertical index of the target slide
862          */
863         function slide( h, v ) {
864                 // Remember where we were at before
865                 previousSlide = currentSlide;
866
867                 // Remember the state before this slide
868                 var stateBefore = state.concat();
869
870                 // Reset the state array
871                 state.length = 0;
872
873                 var indexhBefore = indexh,
874                         indexvBefore = indexv;
875
876                 // Activate and transition to the new slide
877                 indexh = updateSlides( HORIZONTAL_SLIDES_SELECTOR, h === undefined ? indexh : h );
878                 indexv = updateSlides( VERTICAL_SLIDES_SELECTOR, v === undefined ? indexv : v );
879
880                 // Apply the new state
881                 stateLoop: for( var i = 0, len = state.length; i < len; i++ ) {
882                         // Check if this state existed on the previous slide. If it 
883                         // did, we will avoid adding it repeatedly.
884                         for( var j = 0; j < stateBefore.length; j++ ) {
885                                 if( stateBefore[j] === state[i] ) {
886                                         stateBefore.splice( j, 1 );
887                                         continue stateLoop;
888                                 }
889                         }
890
891                         document.documentElement.classList.add( state[i] );
892
893                         // Dispatch custom event matching the state's name
894                         dispatchEvent( state[i] );
895                 }
896
897                 // Clean up the remaints of the previous state
898                 while( stateBefore.length ) {
899                         document.documentElement.classList.remove( stateBefore.pop() );
900                 }
901
902                 // Update progress if enabled
903                 if( config.progress && dom.progress ) {
904                         dom.progressbar.style.width = ( indexh / ( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ).length - 1 ) ) * window.innerWidth + 'px';
905                 }
906
907                 // If the overview is active, re-activate it to update positions
908                 if( isOverviewActive() ) {
909                         activateOverview();
910                 }
911
912                 updateControls();
913                 
914                 clearTimeout( writeURLTimeout );
915                 writeURLTimeout = setTimeout( writeURL, 1500 );
916
917                 // Query all horizontal slides in the deck
918                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR );
919
920                 // Find the current horizontal slide and any possible vertical slides
921                 // within it
922                 var currentHorizontalSlide = horizontalSlides[ indexh ],
923                         currentVerticalSlides = currentHorizontalSlide.querySelectorAll( 'section' );
924
925                 // Store references to the previous and current slides
926                 currentSlide = currentVerticalSlides[ indexv ] || currentHorizontalSlide;
927
928                 // Dispatch an event if the slide changed
929                 if( indexh !== indexhBefore || indexv !== indexvBefore ) {
930                         dispatchEvent( 'slidechanged', {
931                                 'indexh': indexh, 
932                                 'indexv': indexv,
933                                 'previousSlide': previousSlide,
934                                 'currentSlide': currentSlide
935                         } );
936                 }
937                 else {
938                         // Ensure that the previous slide is never the same as the current
939                         previousSlide = null;
940                 }
941
942                 // Solves an edge case where the previous slide maintains the 
943                 // 'present' class when navigating between adjacent vertical 
944                 // stacks
945                 if( previousSlide ) {
946                         previousSlide.classList.remove( 'present' );
947                 }
948         }
949
950         /**
951          * Updates the state and link pointers of the controls.
952          */
953         function updateControls() {
954                 if ( !config.controls || !dom.controls ) {
955                         return;
956                 }
957                 
958                 var routes = availableRoutes();
959
960                 // Remove the 'enabled' class from all directions
961                 [ dom.controlsLeft, dom.controlsRight, dom.controlsUp, dom.controlsDown ].forEach( function( node ) {
962                         node.classList.remove( 'enabled' );
963                 } );
964
965                 // Add the 'enabled' class to the available routes
966                 if( routes.left ) dom.controlsLeft.classList.add( 'enabled' );
967                 if( routes.right ) dom.controlsRight.classList.add( 'enabled' );
968                 if( routes.up ) dom.controlsUp.classList.add( 'enabled' );
969                 if( routes.down ) dom.controlsDown.classList.add( 'enabled' );
970         }
971
972         /**
973          * Determine what available routes there are for navigation.
974          * 
975          * @return {Object} containing four booleans: left/right/up/down
976          */
977         function availableRoutes() {
978                 var horizontalSlides = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ),
979                         verticalSlides = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR );
980
981                 return {
982                         left: indexh > 0,
983                         right: indexh < horizontalSlides.length - 1,
984                         up: indexv > 0,
985                         down: indexv < verticalSlides.length - 1
986                 };
987         }
988         
989         /**
990          * Reads the current URL (hash) and navigates accordingly.
991          */
992         function readURL() {
993                 var hash = window.location.hash;
994
995                 // Attempt to parse the hash as either an index or name
996                 var bits = hash.slice( 2 ).split( '/' ),
997                         name = hash.replace( /#|\//gi, '' );
998
999                 // If the first bit is invalid and there is a name we can 
1000                 // assume that this is a named link
1001                 if( isNaN( parseInt( bits[0], 10 ) ) && name.length ) {
1002                         // Find the slide with the specified name
1003                         var slide = document.querySelector( '#' + name );
1004
1005                         if( slide ) {
1006                                 // Find the position of the named slide and navigate to it
1007                                 var indices = Reveal.getIndices( slide );
1008                                 navigateTo( indices.h, indices.v );
1009                         }
1010                         // If the slide doesn't exist, navigate to the current slide
1011                         else {
1012                                 navigateTo( indexh, indexv );
1013                         }
1014                 }
1015                 else {
1016                         // Read the index components of the hash
1017                         var h = parseInt( bits[0], 10 ) || 0,
1018                                 v = parseInt( bits[1], 10 ) || 0;
1019
1020                         navigateTo( h, v );
1021                 }
1022         }
1023         
1024         /**
1025          * Updates the page URL (hash) to reflect the current
1026          * state. 
1027          */
1028         function writeURL() {
1029                 if( config.history ) {
1030                         var url = '/';
1031                         
1032                         // Only include the minimum possible number of components in
1033                         // the URL
1034                         if( indexh > 0 || indexv > 0 ) url += indexh;
1035                         if( indexv > 0 ) url += '/' + indexv;
1036                         
1037                         window.location.hash = url;
1038                 }
1039         }
1040
1041         /**
1042          * Navigate to the next slide fragment.
1043          * 
1044          * @return {Boolean} true if there was a next fragment,
1045          * false otherwise
1046          */
1047         function nextFragment() {
1048                 // Vertical slides:
1049                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1050                         var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
1051                         if( verticalFragments.length ) {
1052                                 verticalFragments[0].classList.add( 'visible' );
1053
1054                                 // Notify subscribers of the change
1055                                 dispatchEvent( 'fragmentshown', { fragment: verticalFragments[0] } );
1056                                 return true;
1057                         }
1058                 }
1059                 // Horizontal slides:
1060                 else {
1061                         var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment:not(.visible)' );
1062                         if( horizontalFragments.length ) {
1063                                 horizontalFragments[0].classList.add( 'visible' );
1064
1065                                 // Notify subscribers of the change
1066                                 dispatchEvent( 'fragmentshown', { fragment: horizontalFragments[0] } );
1067                                 return true;
1068                         }
1069                 }
1070
1071                 return false;
1072         }
1073
1074         /**
1075          * Navigate to the previous slide fragment.
1076          * 
1077          * @return {Boolean} true if there was a previous fragment,
1078          * false otherwise
1079          */
1080         function previousFragment() {
1081                 // Vertical slides:
1082                 if( document.querySelector( VERTICAL_SLIDES_SELECTOR + '.present' ) ) {
1083                         var verticalFragments = document.querySelectorAll( VERTICAL_SLIDES_SELECTOR + '.present .fragment.visible' );
1084                         if( verticalFragments.length ) {
1085                                 verticalFragments[ verticalFragments.length - 1 ].classList.remove( 'visible' );
1086
1087                                 // Notify subscribers of the change
1088                                 dispatchEvent( 'fragmenthidden', { fragment: verticalFragments[ verticalFragments.length - 1 ] } );
1089                                 return true;
1090                         }
1091                 }
1092                 // Horizontal slides:
1093                 else {
1094                         var horizontalFragments = document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR + '.present .fragment.visible' );
1095                         if( horizontalFragments.length ) {
1096                                 horizontalFragments[ horizontalFragments.length - 1 ].classList.remove( 'visible' );
1097
1098                                 // Notify subscribers of the change
1099                                 dispatchEvent( 'fragmenthidden', { fragment: horizontalFragments[ horizontalFragments.length - 1 ] } );
1100                                 return true;
1101                         }
1102                 }
1103                 
1104                 return false;
1105         }
1106
1107         /**
1108          * Cues a new automated slide if enabled in the config.
1109          */
1110         function cueAutoSlide() {
1111                 clearTimeout( autoSlideTimeout );
1112
1113                 // Cue the next auto-slide if enabled
1114                 if( config.autoSlide ) {
1115                         autoSlideTimeout = setTimeout( navigateNext, config.autoSlide );
1116                 }
1117         }
1118         
1119         /**
1120          * Triggers a navigation to the specified indices.
1121          * 
1122          * @param {Number} h The horizontal index of the slide to show
1123          * @param {Number} v The vertical index of the slide to show
1124          */
1125         function navigateTo( h, v ) {
1126                 slide( h, v );
1127         }
1128         
1129         function navigateLeft() {
1130                 // Prioritize hiding fragments
1131                 if( isOverviewActive() || previousFragment() === false ) {
1132                         slide( indexh - 1, 0 );
1133                 }
1134         }
1135
1136         function navigateRight() {
1137                 // Prioritize revealing fragments
1138                 if( isOverviewActive() || nextFragment() === false ) {
1139                         slide( indexh + 1, 0 );
1140                 }
1141         }
1142
1143         function navigateUp() {
1144                 // Prioritize hiding fragments
1145                 if( isOverviewActive() || previousFragment() === false ) {
1146                         slide( indexh, indexv - 1 );
1147                 }
1148         }
1149
1150         function navigateDown() {
1151                 // Prioritize revealing fragments
1152                 if( isOverviewActive() || nextFragment() === false ) {
1153                         slide( indexh, indexv + 1 );
1154                 }
1155         }
1156
1157         /**
1158          * Navigates backwards, prioritized in the following order:
1159          * 1) Previous fragment
1160          * 2) Previous vertical slide
1161          * 3) Previous horizontal slide
1162          */
1163         function navigatePrev() {
1164                 // Prioritize revealing fragments
1165                 if( previousFragment() === false ) {
1166                         if( availableRoutes().up ) {
1167                                 navigateUp();
1168                         }
1169                         else {
1170                                 // Fetch the previous horizontal slide, if there is one
1171                                 var previousSlide = document.querySelector( '.reveal .slides>section.past:nth-child(' + indexh + ')' );
1172
1173                                 if( previousSlide ) {
1174                                         indexv = ( previousSlide.querySelectorAll('section').length + 1 ) || 0;
1175                                         indexh --;
1176                                         slide();
1177                                 }
1178                         }
1179                 }
1180         }
1181
1182         /**
1183          * Same as #navigatePrev() but navigates forwards.
1184          */
1185         function navigateNext() {
1186                 // Prioritize revealing fragments
1187                 if( nextFragment() === false ) {
1188                         availableRoutes().down ? navigateDown() : navigateRight();
1189                 }
1190
1191                 // If auto-sliding is enabled we need to cue up 
1192                 // another timeout
1193                 cueAutoSlide();
1194         }
1195         
1196         // Expose some methods publicly
1197         return {
1198                 initialize: initialize,
1199                 navigateTo: navigateTo,
1200                 navigateLeft: navigateLeft,
1201                 navigateRight: navigateRight,
1202                 navigateUp: navigateUp,
1203                 navigateDown: navigateDown,
1204                 navigatePrev: navigatePrev,
1205                 navigateNext: navigateNext,
1206                 toggleOverview: toggleOverview,
1207
1208                 // Adds or removes all internal event listeners (such as keyboard)
1209                 addEventListeners: addEventListeners,
1210                 removeEventListeners: removeEventListeners,
1211
1212                 // Returns the indices of the current, or specified, slide
1213                 getIndices: function( slide ) {
1214                         // By default, return the current indices
1215                         var h = indexh,
1216                                 v = indexv;
1217
1218                         // If a slide is specified, return the indices of that slide
1219                         if( slide ) {
1220                                 var isVertical = !!slide.parentNode.nodeName.match( /section/gi );
1221                                 var slideh = isVertical ? slide.parentNode : slide;
1222
1223                                 // Select all horizontal slides
1224                                 var horizontalSlides = Array.prototype.slice.call( document.querySelectorAll( HORIZONTAL_SLIDES_SELECTOR ) );
1225
1226                                 // Now that we know which the horizontal slide is, get its index
1227                                 h = Math.max( horizontalSlides.indexOf( slideh ), 0 );
1228
1229                                 // If this is a vertical slide, grab the vertical index
1230                                 if( isVertical ) {
1231                                         v = Math.max( Array.prototype.slice.call( slide.parentNode.children ).indexOf( slide ), 0 );
1232                                 }
1233                         }
1234
1235                         return { h: h, v: v };
1236                 },
1237
1238                 // Returns the previous slide element, may be null
1239                 getPreviousSlide: function() {
1240                         return previousSlide;
1241                 },
1242
1243                 // Returns the current slide element
1244                 getCurrentSlide: function() {
1245                         return currentSlide;
1246                 },
1247
1248                 // Helper method, retrieves query string as a key/value hash
1249                 getQueryHash: function() {
1250                         var query = {};
1251
1252                         location.search.replace( /[A-Z0-9]+?=(\w*)/gi, function(a) {
1253                                 query[ a.split( '=' ).shift() ] = a.split( '=' ).pop();
1254                         } );
1255
1256                         return query;
1257                 },
1258
1259                 // Forward event binding to the reveal DOM element
1260                 addEventListener: function( type, listener, useCapture ) {
1261                         if( 'addEventListener' in window ) {
1262                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).addEventListener( type, listener, useCapture );
1263                         }
1264                 },
1265                 removeEventListener: function( type, listener, useCapture ) {
1266                         if( 'addEventListener' in window ) {
1267                                 ( dom.wrapper || document.querySelector( '.reveal' ) ).removeEventListener( type, listener, useCapture );
1268                         }
1269                 }
1270         };
1271         
1272 })();