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