f42811d77540180d441fbeff9a4083ece988502c
[hacks/simpleWebSlides.git] / simpleWebSlides.js
1 /*
2   Namespace object.
3 */
4
5 var SWS = SWS || {};
6
7
8
9 SWS.Utils = new function () {
10     var self = this;
11
12     self.isUndefined = function (o) { return typeof o == "undefined"; };
13     self.push2 = function (t, i, v) {
14         if ((typeof t[i]) == 'undefined') {
15             t[i] = new Array();
16         };
17         var l = t[i].length;
18         t[i][l] = v;
19     };
20
21     self.isEmpty = function (o) {
22         for(var _ in o) return false;
23         return true;
24     };
25
26     self.parseFrameSpec = function (s) {
27         var elems = s.split("_");
28         var result = {};
29         var min_last = 10000;
30         var max_value = -1;
31         for(var i = 0; i < elems.length; i++){
32             var bounds = elems[i].split("-");
33             if (bounds.length > 2 || bounds.length == 0) return {};
34             if (bounds.length == 1) bounds[1] = bounds[0];
35             var a = parseInt(bounds[0]);
36             var b = parseInt(bounds[1])
37             if (!isFinite(a) || !isFinite(b)) return {};
38             a = Math.min(a, 1000); // don't allow more than 1000 frames/slide
39             b = Math.min(b, 1000);
40             if (b > max_value) max_value = b;
41             for (var j = a; j <= b; j++)
42                 result[j] = true;
43         };
44         return result;
45     };
46
47     self.getParameterByName = function (name) {
48         name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
49         var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
50         results = regex.exec(location.search);
51         return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
52     }
53 };
54
55
56
57
58 SWS.Templates = new function () {
59     var self = this;
60     self.controlPanel = "<div id='sws-control-panel-canvas'><div id='sws-control-panel'>\
61 <div id='sws-control-panel-title-bar'>\
62 <a title='Toggle fullscreen' id='sws-control-panel-fullscreen' class='sws-symbol' onclick='SWS.Presentation.toggleFullScreen();'></a>\
63 <a title='Close panel' id='sws-control-panel-close' onclick='$(\"#sws-control-panel-canvas\").toggle();'>&#x2716;</a>\
64 </div>\
65 <div id='sws-control-panel-options'>\
66 <span title='Change the aspect ratio' class='sws-symbol' >&#x1f4bb;</span><select id='sws-aspect-select' onchange='SWS.Presentation.changeAspect();'>\
67 <option value='sws-aspect-4-3'>4:3</option>\
68 <option value='sws-aspect-16-9'>16:9</option>\
69 <option value='sws-aspect-16-10'>16:10</option>\
70 </select>\
71 <span title='Change the theme' class='sws-symbol'>&#x1f3a8;</span><select id='sws-theme-select' onchange='SWS.Presentation.changeTheme();'></select>\
72 <a onclick='SWS.Presentation.openPrint()' ><span title='Open Print-Out' class='sws-symbol'>&#59158;</span></a>\
73 </div>\
74 <div id='sws-control-panel-navigation'>\
75 <a title='First slide' class='sws-symbol' onclick='SWS.Presentation.goToSlide(SWS.Presentation.firstSlide());' >&#x23ee;</a>\
76 <a title='Previous slide' class='sws-symbol' onclick='SWS.Presentation.previousSlide();SWS.Presentation.refresh();'>&#x23ea;</a>\
77 <a title='Previous step' class='sws-symbol' style='-webkit-transform: scaleX(-1);' onclick='SWS.Presentation.previous();SWS.Presentation.refresh();'>&#x25b6;</a>\
78 <a title='Next step' class='sws-symbol' onclick='SWS.Presentation.next();SWS.Presentation.refresh();'>&#x25b6;</a>\
79 <a title='Next slide' class='sws-symbol' onclick='SWS.Presentation.nextSlide();SWS.Presentation.refresh();'>&#x23e9;</a>\
80 <a title='Last slide' class='sws-symbol' onclick='SWS.Presentation.goToSlide(SWS.Presentation.lastSlide());'>&#x23ed;</a>\
81 <br/>\
82 <span class='sws-symbol'>&#xe4ae;</span><input type='text' id='sws-control-panel-slide-input' oninput='SWS.Presentation.goToSlide($(\"#sws-control-panel-slide-input\").val()-1);'></input><span id='sws-control-panel-total-slides'></span>\
83 <input type='range' title='Navigate the presentation' id='sws-control-panel-navigation-bar' onchange='SWS.Presentation.navigate();' step='1'></input>\
84 </div>\
85 </div>\
86 </div>";
87     self.slideActivate = function (o) {
88         if (!(o.hasClass("sws-active-slide"))){
89             o.removeClass("sws-inactive-slide").addClass("sws-active-slide");
90         };
91     };
92
93     self.slideDeactivate = function (o) {
94         if (!(o.hasClass("sws-inactive-slide"))){
95             o.removeClass("sws-active-slide").addClass("sws-inactive-slide");
96         };
97     };
98
99     self.slideChange = function (from, to) {
100         var canvas = $(".sws-canvas");
101         self.slideDeactivate($(canvas[from]));
102         self.slideActivate($(canvas[to]));
103     };
104
105     self.objectActivate = function (o) {
106         if (!(o.hasClass("sws-active-object"))){
107             o.removeClass("sws-inactive-object").addClass("sws-active-object");
108             return true;
109         };
110         return false;
111     };
112
113     self.objectDeactivate = function (o) {
114         if (!(o.hasClass("sws-inactive-object"))){
115             o.addClass("sws-inactive-object").removeClass("sws-active-object");
116             return true;
117         };
118         return false;
119     };
120
121     self.updateFooter = function (o) {
122         var footer = o.find(".sws-footer");
123         if (footer.length && (footer.children("*").length == 0)) {
124             var i = SWS.Presentation.getCurrentSlide();
125             var cur = $( "<span class='sws-current-slide-number'>"
126                          + (i + 1)
127                          +"</span>");
128             var sep = $( "<span class='sws-slide-num-sep' />");
129             var tot = $( "<span class='sws-last-slide-number'>"
130                          + (SWS.Presentation.getNumSlides())
131                          +"</span>");
132             footer.append(cur).append(sep).append(tot);
133         };
134     };
135     self.updateHeader = function (o) {};
136 };
137 SWS.ConfigBuilder = function () {
138     var self = this;
139     self['sws-object-activate'] = SWS.Templates.objectActivate;
140     self['sws-object-deactivate'] = SWS.Templates.objectDeactivate;
141     self['sws-slide-change'] = SWS.Templates.slideChange;
142     self['sws-update-footer'] = SWS.Templates.updateFooter;
143     self['sws-update-header'] = SWS.Templates.updateHeader;
144 };
145
146 SWS.Defaults = new SWS.ConfigBuilder ();
147
148 SWS.Config = new SWS.ConfigBuilder ();
149
150
151 SWS.Effects = new function () {
152     var self = this;
153
154     self.objectDeactivateFadeOut = function (o) {
155         o.animate({'opacity': '0'}, 200,
156                   function () {
157
158                       SWS.Templates.objectDeactivate(o);
159                   });
160     };
161
162     self.objectActivateFadeIn = function (o) {
163
164         if (SWS.Templates.objectActivate(o)){
165             o.animate({'opacity': '1' }, 200);
166         };
167
168     };
169
170     self.slideChangeHorizontalFlip = function (from, to){
171         var f = SWS.Presentation.getSlide(from);
172         var t = SWS.Presentation.getSlide(to);
173         f.animate({ 'left': '50%', 'width': '0pt', 'opacity':'0' }, 150,
174                   function  () {
175                       SWS.Templates.slideDeactivate(f);
176                       f.css({'left':'0%', 'width': '100%'});
177                       t.css({ 'left': '50%', 'width': '0pt','opacity':'0' });
178                       SWS.Templates.slideActivate(t);
179                       t.animate({'left':'0%', 'width': '100%','opacity':'1'});
180                   });
181     };
182     self.slideChangeFadeOutIn = function (from, to) {
183         var f = SWS.Presentation.getSlide(from);
184         var t = SWS.Presentation.getSlide(to);
185         f.animate({ 'opacity': '0'}, 150,
186                   function () { SWS.Templates.slideDeactivate(f);
187                                 SWS.Templates.slideActivate(t);
188                                 t.css('opacity', '0');
189                                 t.animate({ 'opacity': '1'}, 150);
190                               });
191     };
192     self.slideChangeHorizontalSlide = function (from, to) {
193         var f = SWS.Presentation.getSlide(from);
194         var t = SWS.Presentation.getSlide(to);
195         if (from < to) {
196             t.css('left', '100%');
197             t.css('opacity', '1');
198             SWS.Templates.slideActivate(t);
199             f.animate({ 'left': '-100%' }, 250, function () { SWS.Templates.slideDeactivate(f);
200                                                               f.css('opacity', '0');
201                                                               t.animate({ 'left': '0%' }, 250);
202                                                             });
203         } else {
204             t.css('left', '-100%');
205             SWS.Templates.slideActivate(t);
206             f.animate({ 'left': '100%' }, 250, function () { SWS.Templates.slideDeactivate(f);
207                                                              f.css('opacity', '0');
208                                                            });
209             t.css('opacity', '1');
210             t.animate({ 'left': '0%' }, 250);
211         };
212     };
213
214
215     self.slideChangeVerticalSlide = function (from, to) {
216         var f = SWS.Presentation.getSlide(from);
217         var t = SWS.Presentation.getSlide(to);
218         if (from < to) {
219             t.css('top', '100%');
220             SWS.Templates.slideActivate(t);
221             f.animate({ 'top': '-100%' }, 250, function () { SWS.Templates.slideDeactivate(f); });
222             t.animate({ 'top': '0%' }, 250);
223         } else {
224             t.css('top', '-100%');
225             SWS.Templates.slideActivate(t);
226             f.animate({ 'top': '100%' }, 250, function () { SWS.Templates.slideDeactivate(f); });
227             t.animate({ 'top': '0%' }, 250);
228         };
229     };
230
231 };
232
233 SWS.Fullscreen = new function () {
234     var self = this;
235
236     if (SWS.Utils.isUndefined(document.fullScreen)) {
237         if (SWS.Utils.isUndefined(document.mozfullScreen)) {
238             self.status = function () { return document.webkitIsFullScreen; };
239             self.enter = function(e) {
240                 e.webkitRequestFullScreen();
241             };
242             self.exit = function () {
243                 document.webkitCancelFullScreen();
244             };
245
246         } else {
247             self.status = function () { return document.mozfullScreen; };
248             self.enter = function(e) {
249                 e.mozRequestFullScreen();
250             };
251             self.exit = function () {
252                 document.mozCancelFullScreen();
253             };
254
255         };
256     } else {
257             self.status = function () { return document.fullScreen; };
258             self.enter = function(e) {
259                 e.requestFullScreen();
260             };
261             self.exit = function () {
262                 document.cancelFullScreen();
263             };
264
265     };
266
267
268 };
269
270 SWS.Presentation = new function () {
271
272
273     var self = this;
274
275     //TODO move outside of the Presentation object
276
277
278     var _total_slides;
279     var _initialized = false;
280     var _disable_input_events = false;
281     var _print_mode = false;
282     var _slide_callbacks = new Array ();
283     var _total_steps = -1;
284     var _current_theme = "";
285
286     self.getNumSlides = function () { return _total_slides; };
287
288     self.getSlide = function(i) {
289         return $($(".sws-canvas")[i]);
290     };
291
292     self.registerCallback = function (i, f) {
293         if (_initialized) return;
294         //jQuery does not seem to work well
295         //on a partial DOM
296         var slides = $(".sws-slide");
297         var h1s = $("body").children("h1");
298         var slide_num = slides.add(h1s).length - 1;
299
300         SWS.Utils.push2(_slide_callbacks, slide_num,{ 'fn': f, 'frame': i });
301
302     };
303
304     if (typeof(Storage)!=="undefined"){
305         self.getCurrentSlide = function () {
306             //unary + casts to integer
307             var i = +(sessionStorage.getItem("current_slide"));
308             if (!(i >= 0 && i < self.getNumSlides())){
309                 return 0;
310             } else {
311                 return i;
312             };
313         };
314
315         self.setCurrentSlide = function (i) {
316             sessionStorage.setItem("current_slide", i);
317         };
318
319     } else {
320         var _current_slide = 0;
321         self.getCurrentSlide = function () { return _current_slide; };
322         self.setCurrentSlide = function (i) { _current_slide = i; };
323
324     };
325     self.firstSlide = function () { return 0; };
326     self.lastSlide = function () { return self.getNumSlides() - 1; };
327     self.refresh = function () {
328         /* block upcoming input event until all animations are finished */
329         _disable_input_events = true;
330
331         var canvas = $(".sws-canvas");
332         var from_slide_num = canvas.index($(".sws-active-slide"));
333         var to_slide_num = self.getCurrentSlide();
334         var watch_slide_anim = false;
335         var to_slide = $(canvas[to_slide_num]);
336         var from_slide = $(canvas[from_slide_num]);
337         var slide_change = (from_slide_num != to_slide_num);
338
339
340         var info = to_slide.data("sws-frame-info");
341         SWS.Config['sws-update-header'](to_slide);
342         SWS.Config['sws-update-footer'](to_slide);
343
344         if (slide_change) {
345             //Launch a slide transition:
346             SWS.Config['sws-slide-change'](from_slide_num, to_slide_num);
347             watch_slide_anim = true;
348             for (var i = 0; i < info.callbacks.at_slide.length;i++){
349                 info.callbacks.at_slide[i](to_slide);
350             };
351         };
352
353
354         var cur = info.current;
355         var custom = info.custom;
356         var real_slide = to_slide.find(".sws-slide");
357
358         real_slide.find("*").andSelf().each(function (i){
359             var frameset = $(this).data("sws-frame-set") || {};
360             if (frameset[cur])
361                 SWS.Config['sws-object-activate']($(this));
362             else
363                 SWS.Config['sws-object-deactivate']($(this));
364         });
365         var callbacks;
366         if (callbacks = info.callbacks.at_frame[self.getCurrentFrame()]){
367             for (var k = 0; k < callbacks.length; k++)
368                 callbacks[k]($(to_slide));
369         };
370
371         var all = $(from_slide).add(to_slide);
372         all.find("*").addBack().promise().done(function() {
373             _disable_input_events = false;
374         });
375     };
376
377     self.nextSlide = function () {
378         self.setCurrentSlide(Math.min(self.getCurrentSlide()+1,
379                                       self.lastSlide()));
380         self.setCurrentFrame(self.firstFrame());
381     };
382
383     self.previousSlide = function () {
384         self.setCurrentSlide(Math.max(self.getCurrentSlide()-1,
385                                       self.firstSlide()));
386         self.setCurrentFrame(self.firstFrame());
387     };
388
389     self.getFrameInfo = function () {
390
391         var i = self.getCurrentSlide();
392         var canvas = $($(".sws-canvas")[i]);
393         var infos = canvas.data("sws-frame-info");
394         return infos;
395     };
396
397     self.getTotalSteps = function () {
398         if (_total_steps >= 0) return _total_steps;
399         _total_steps = 0;
400         $(".sws-canvas").each(function(i) {
401             var canvas = $($(".sws-canvas")[i]);
402             var infos = canvas.data("sws-frame-info");
403             _total_steps += infos.last + 1;
404         });
405         return _total_steps;
406     };
407
408     self.getCurrentFrame = function () { return self.getFrameInfo().current; };
409     self.setCurrentFrame = function (i) { self.getFrameInfo().current = i; };
410     self.firstFrame = function () { return 0; };
411     self.lastFrame = function () { return self.getFrameInfo().last; };
412
413     self.nextFrame = function () {
414         self.setCurrentFrame(Math.min(self.getCurrentFrame()+1,
415                                       self.lastFrame()));
416
417     };
418     self.previousFrame = function () {
419         self.setCurrentFrame(Math.max(self.getCurrentFrame()-1,
420                                        self.firstFrame()));
421     };
422
423     self.next = function () {
424         var i = self.getCurrentFrame();
425         if (i == self.lastFrame()) {
426             self.nextSlide();
427             self.setCurrentFrame(self.firstFrame());
428         } else
429             self.nextFrame();
430     };
431
432     self.previous = function () {
433         var i = self.getCurrentFrame();
434         if (i == self.firstFrame()){
435             self.previousSlide();
436             self.setCurrentFrame(self.lastFrame());
437         }
438         else
439             self.previousFrame();
440     };
441
442     self.goToSlide = function (s, f) {
443         if (SWS.Utils.isUndefined(f))
444             f = 0;
445         if (!(s >= self.firstSlide() && s <= self.lastSlide())) return;
446         self.setCurrentSlide(s);
447         if (!(f >= self.firstFrame() && f <= self.lastFrame())) f = 0;
448         self.setCurrentFrame(f);
449         self.refresh();
450     };
451
452     self.cycleStyle = function() {
453         var styles = $("head").children('link[rel$="stylesheet"][title]');
454         var j = styles.index(styles.filter(':not(:disabled)'));
455         styles[j].disabled = true;
456         if (++j == styles.length) j = 0;
457         styles[j].disabled = false;
458     };
459
460
461     self.printMode = function () {
462         _print_mode = true;
463         var progress = $("<div style='position:fixed;top:0pt;left:0pt;background:white;color:black;width:100%;height:100vh;z-index:200;' id='sws-print-progress'>Rendering presentation: <span id='sws-percent-progress'></span>%</div>");
464         $("body").append(progress);
465
466         $("html").removeClass("sws-display").addClass("sws-print");
467         self.goToSlide(0,0);
468         var steps = self.getTotalSteps();
469         var total_steps = steps;
470         var loop;
471         loop = function () {
472             if (steps >= 0) {
473                 //Crazy workaround for chromium
474                 ($("link.sws-theme[rel='stylesheet']")[0]).disabled = false;
475                 $(".sws-canvas").find("*").addBack().promise().done(function() {
476                     var percent = ((total_steps - steps) / total_steps) * 100;
477                     $("#sws-percent-progress").text(Math.round(percent));
478                     SWS.Config['sws-slide-change'] = SWS.Templates.slideChange;
479                     self.refresh();
480                     $($(".sws-canvas")[self.getCurrentSlide()]).css('opacity', 1 );
481                     self.next();
482                     steps--;
483                     loop();
484                     })
485             } else {
486                 $("#sws-percent-progress").text(100);
487                 progress.remove();
488             }
489         };
490         loop();
491
492     }
493
494     self.buildFullTOC = function () {
495
496         var build_sections = function (doc) {
497             var res = [];
498             var h1s = doc.find("body").first().children("h1");
499             var slides = doc.find("body").first().children(".sws-slide");
500             var slide_num = 1;
501             var collection = h1s.add(slides);
502             collection.each (function () {
503                 if ($(this).is("h1")) {
504                     res.push({ 'title' : $(this).text(),
505                                'slide' : slide_num });
506                 } else {
507                     slide_num++;
508                 }
509             });
510             return res;
511         };
512
513         var toc = [];
514
515         var append = function (a,e) {
516             return a.push(e);
517         };
518         var prepend = function (a,e) {
519             return a.unshift(e);
520         };
521
522         var loop = function (doc, dir, add, ignoreFirst) {
523             if (ignoreFirst !== true) {
524                 var this_toc = { 'title' : doc.find("title").first().text(),
525                                  'sections' : build_sections(doc) };
526                 add(toc, this_toc);
527             };
528             var url = doc.find(dir).first().attr("href");
529             if (!SWS.Utils.isUndefined(url) && url != "") {
530                 $.ajax({ 'url' : url, 'async' : false ,'success' : function (page) {
531                     loop ($(page), dir, add, false);
532                 }});
533             };
534         };
535         loop ($(document), ".sws-previous", prepend, false);
536         return toc;
537
538     };
539
540
541
542     var _xstart = 0;
543     self.inputHandler = function (event) {
544         if (_disable_input_events || _print_mode) return;
545         var code = 0;
546         switch (event.type) {
547         case 'touchstart':
548             _xstart = event.changedTouches[0].clientX;
549             return;
550         case 'touchend':
551
552             var dist = event.changedTouches[0].clientX - _xstart;
553             if (dist > 20) code = 37
554             else if (dist < -20) code = 39
555             else if (!$("#sws-control-panel-canvas").is(":visible")) code = 67;
556             break;
557         case 'keydown':
558             code = event.which;
559             break;
560         default:
561             return;
562         };
563         switch (code) {
564         case 36:/* Home */
565             self.setCurrentSlide(self.firstSlide());
566             break;
567
568         case 35:/* End */
569             self.setCurrentSlide(self.lastSlide());
570             break;
571         case 32: /* space */
572         case 34: /* PgDown */
573         case 39: /* -> */
574             if (self.getCurrentSlide() == self.lastSlide()
575                 && self.getCurrentFrame() == self.lastFrame()) return;
576             self.next();
577             break;
578         case 78: /* n */
579             self.nextSlide();
580             break;
581         case 8: /* backspace */
582         case 33: /* PgUp */
583         case 37: /* <-   */
584             self.previous();
585             break;
586         case 80: /* p */
587             self.previousSlide();
588             break;
589         case 83: /* s */
590                 self.cycleStyle();
591             return;
592         case 67: /* c */
593             $("#sws-control-panel-canvas").toggle();
594
595         default:
596             return;
597         };
598         self.refresh();
599 };
600
601
602
603     function init_canvas(canvas, custom) {
604         var cur_frame = 0;
605         var last_frame = canvas.find(".sws-pause").length;
606         //Add all regular elements to the frame list
607         var slide = $(canvas.find(".sws-slide")[0]);
608
609         var callbacks = { at_slide : new Array(),
610                           at_frame : new Array() }
611
612         if (SWS.Utils.isUndefined(custom)) {
613             custom = new Array ();
614         };
615
616         for (var i = 0; i < custom.length; i++) {
617             if (isFinite(custom[i].frame)){
618                 var num = +(custom[i].frame);
619                 if (num > last_frame) last_frame = num;
620                 SWS.Utils.push2(callbacks.at_frame, num, custom[i].fn);
621             } else if (custom[i].frame == "slide")
622                 callbacks.at_slide.push(custom[i].fn);
623             else {
624                 var frame_set = SWS.Utils.parseFrameSpec(custom[i].frame);
625                 for(var f in frame_set){
626                     if (f > last_frame) last_frame = f;
627                     SWS.Utils.push2(callbacks.at_frame, +(f), custom[i].fn);
628                 };
629             }
630         };
631
632         var specials = $([]);
633
634         slide.find('*[class*="sws-onframe-"]').each(function(_){
635             var cls = $(this).attr('class');
636             var idx = cls.indexOf("sws-onframe-");
637             if (idx >= 0) {
638                 var end = cls.indexOf(" ", idx);
639                 end = (end == -1) ? cls.length : end;
640                 var spec = cls.substring(idx+12, end);
641                 var o = SWS.Utils.parseFrameSpec(spec);
642                 for(var f in o)
643                     if (f > last_frame) last_frame = f;
644                 $(this).find("*").andSelf().each(function(_){
645                     if (!SWS.Utils.isEmpty(o)){
646                         $(this).data("sws-frame-set", o);
647                     }
648                     specials = specials.add($(this));
649                 });
650             };
651         });
652
653         slide.find("*").andSelf().not(specials).each(function(i) {
654             if ($(this).hasClass("sws-pause"))  cur_frame++;
655             var o = {};
656             for (var j = cur_frame; j <= last_frame; j++)
657                 o[ j ] = true;
658             if (!SWS.Utils.isEmpty(o))
659                 $(this).data("sws-frame-set", o);
660         });
661
662         canvas.data("sws-frame-info", { current: 0,
663                                         last: (last_frame - 0), // force cast to integer
664                                         callbacks: callbacks
665                                       });
666
667     };
668
669     /* Forces redrawing the page without reloading */
670     self.redraw = function (f) {
671         if (SWS.Utils.isUndefined(f))
672             $("body").hide().show(400, function () {
673                 $("body").css("display","block");
674                 if (!SWS.Utils.isUndefined(f))
675                     f();
676             });
677     };
678     self.changeAspect = function() {
679         $("html").removeClass("sws-aspect-4-3")
680             .removeClass("sws-aspect-16-9")
681             .removeClass("sws-aspect-16-10")
682             .addClass($("#sws-aspect-select").val());
683         self.redraw();
684     };
685
686     self.getCurrentTheme = function () {
687         var l = $("link.sws-theme[rel='stylesheet']")[0];
688
689         if (l) {
690             return  l.title;
691         } else
692             return ""
693     };
694
695     self.changeTheme = function (name) {
696         var theme_name;
697         if (typeof name === 'undefined')
698             theme_name = $("#sws-theme-select").val()
699         else
700             theme_name = name;
701
702         _current_theme = theme_name;
703         $("link.sws-theme").each (function (i) {
704             var e = this;
705             var title =  e.title;
706             if (title == theme_name) {
707                 e.rel = "stylesheet";
708                 e.disabled = false;
709                 e.media="all";
710             } else {
711                 e.rel = "alternate stylesheet";
712                 e.disabled = true;
713                 e.media="all";
714             };
715         });
716         self.redraw();
717
718     };
719
720     self.openPrint = function () {
721         window.open ("?mode=print&theme=" + self.getCurrentTheme());
722     }
723     var _fullscreen_icon_on = "&#xe746;";
724     var _fullscreen_icon_off = "&#xe744;";
725
726     self.toggleFullScreen = function () {
727         if (SWS.Fullscreen.status()) {
728             SWS.Fullscreen.exit();
729             $("a#sws-control-panel-fullscreen")
730                 .html(_fullscreen_icon_off);
731
732
733
734         } else {
735             SWS.Fullscreen.enter($("body")[0]);
736             $("a#sws-control-panel-fullscreen")
737                 .html(_fullscreen_icon_on);
738         };
739     };
740     function _update_ui() {
741         var nav = $('#sws-control-panel-navigation-bar');
742         nav.val(SWS.Presentation.getCurrentSlide() + 1);
743         $('#sws-control-panel-slide-input').val(nav.val());
744     }
745     self.navigate = function () {
746         self.goToSlide($("#sws-control-panel-navigation-bar").val()-1);
747         _update_ui();
748     };
749
750
751     self.init = function () {
752
753
754         $("html").addClass("sws-display");
755         //$(window).resize(self.redraw);
756
757         var slides = $(".sws-slide");
758         var h1s = $("body").children("h1");
759         var slide_num = slides.add(h1s).length - 1;
760
761         _total_slides = $(".sws-slide").add($("body").children("h1")).length;
762
763         var cur = self.getCurrentSlide();
764         var toc = self.buildFullTOC();
765         var common_html = "<div class='sws-slide sws-toc'><h1>Plan</h1><ul style='list-style-type:none'>";
766         var i;
767         for (i= 0; i < toc.length - 1; i++)
768             common_html += "<li class='done'>" + (i+1) +
769             ' ' + toc[i].title + "</li>";
770
771         common_html += "<li>" + toc.length + ' ' + toc[toc.length - 1].title;
772         common_html += "<ul style='list-style-type:none' >";
773         var sections = toc[toc.length - 1].sections;
774         $("body").children("h1").each(function (i) {
775             var this_html = common_html;
776             var j;
777             var secnum = toc.length + '.';
778             for (j = 0; j < i; ++j)
779                 this_html += "<li class='done'>" + secnum + (j+1) + ' ' + 
780                 sections[j].title + "</li>";
781             this_html += "<li class='hl'>" + secnum + (i+1) + ' ' +
782                 sections[i].title + "</li>";
783             for (j = i+1; j < sections.length; j++)
784                 this_html += "<li>" + secnum + (j+1) + ' ' 
785                 +sections[j].title + "</li>";
786             this_html += "</ul></li></ul></div>";
787             $(this).after(this_html);
788         });
789
790         $(".sws-slide").each(function (i) {
791
792             var par = $(this).parent();
793
794
795             $(this).remove();
796             var canvas = $('<div class="sws-canvas"/>');
797
798             if (!($(this).hasClass("sws-option-noheader"))) {
799                 canvas.append($('<div class="sws-header"/>'));
800             };
801             if (!$(this).hasClass("sws-cover")) {
802                 var title = $($(this).find("h1")[0]);
803                 var title_div = $('<div class="sws-title" />');
804                 title_div.append(title);
805                 canvas.append(title_div);
806             }
807             var inner = $('<div class="sws-inner-canvas"/>');
808             var content = $('<div class="sws-content"/>');
809             $(this).find('script[type="text/javascript"]').remove();
810             content.append($(this));
811             inner.append(content);
812             canvas.append(inner);
813
814             if (!($(this).hasClass("sws-option-nofooter"))) {
815                 canvas.append($('<div class="sws-footer"/>'));
816             };
817
818             par.append(canvas);
819
820             if (i == cur) {
821                 canvas
822                     .addClass("sws-active-slide")
823                     .removeClass("sws-inactive-slide");
824             } else {
825                 canvas
826                     .addClass("sws-inactive-slide")
827                     .removeClass("sws-active-slide");
828             };
829             init_canvas(canvas,_slide_callbacks[i]);
830
831         });
832
833         // Initialize the control panel
834         $("body").append($(SWS.Templates.controlPanel));
835         // Fill the theme switcher
836         $("link.sws-theme").each (function (i) {
837             var e = $(this);
838             var opt = "<option value='";
839             opt += e.attr("title");
840             opt += "' ";
841             if (e.attr("rel") == "stylesheet") {
842                 opt+= "selected='selected'";
843             };
844             opt += ">" + e.attr("title") + "</option>";
845             $("#sws-theme-select").append($(opt));
846         });
847         // Set the fullscreen icon
848         if (SWS.Fullscreen.status()) {
849             $("a#sws-control-panel-fullscreen")
850                 .html(_fullscreen_icon_on);
851         } else {
852             $("a#sws-control-panel-fullscreen")
853                 .html(_fullscreen_icon_off);
854         };
855         // Put the navigation range at the correct position
856         var nav = $('#sws-control-panel-navigation-bar');
857         nav.attr("min", SWS.Presentation.firstSlide() + 1);
858         nav.attr("max", SWS.Presentation.lastSlide() + 1);
859         $('#sws-control-panel-total-slides').text('/' + SWS.Presentation.getNumSlides());
860         _update_ui();
861
862         _slide_callbacks = null; /* avoid a leak */
863         var passed_theme = SWS.Utils.getParameterByName("theme");
864
865
866         //workaround weird chrome CSS loading bug
867         var f =
868             function () {
869                 if (passed_theme == "")
870                     self.changeTheme();
871                 else
872                     self.changeTheme(passed_theme);
873                 if (SWS.Utils.getParameterByName("mode") == "print") {
874                     self.printMode();
875                 }
876                 else
877                     self.refresh();
878                 $(document).keydown(self.inputHandler);
879                 document.body.addEventListener('touchstart',self.inputHandler, false);
880                 document.body.addEventListener('touchend',self.inputHandler, false);
881
882                 _initialized = true;
883             };
884         setTimeout(f, 100);
885     };
886
887 };