This repository has been archived by the owner on Jul 29, 2021. It is now read-only.
forked from timesheets/timesheets.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtimesheets.js
2140 lines (1974 loc) · 83 KB
/
timesheets.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Copyright (c) 2010-2013 Fabien Cazenave, INRIA <http://wam.inrialpes.fr/>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* author : Fabien Cazenave (:kaze)
* contact : [email protected]
* license : MIT
* version : 0.6.0
* last change : 2013-01-29
*
* TODO:
* - factorize the onbegin/onend code
* in smilTimeItem and smilTimeContainer_generic
* - support complex event-values (event + time offset)
* - add a decent onDOMReady() for IE<9
* - fix the repeatCount/repeatDur stuff
* - fix the 'begin' behaviour in 'seq' containers
* - redesign EVENTS to make it compatible with bean.js
* - propose timesheets.js as a jQuery module
*/
/*****************************************************************************\
| |
| Browser Abstraction Layer: |
| required to cope with Internet Explorer 6/7/8 (see the 'OLDIE' tag) |
| |
\*****************************************************************************/
// ===========================================================================
// EVENTS.[*]: event handler
// ===========================================================================
(function() {
/***************************************************************************\
| |
| Basic Event Management Abstraction Layer |
| completely useless... except to support Internet Explorer 6/7/8 :-/ |
| * fixes the 'this' reference issue in callbacks on IE<9 |
| * handles custom (= non W3C-standard) events on IE<9 |
| exposed as window.EVENTS |
| |
|---------------------------------------------------------------------------|
| |
| Generic events: |
| EVENTS.bind(node, type, callback) |
| equivalent to 'node.addEventListener(type, callback, false)' |
| EVENTS.unbind(node, type, callback) |
| equivalent to 'node.removeEventListener(type, callback, false)' |
| EVENTS.trigger(node, type) |
| equivalent to 'node.dispatchEvent()' |
| EVENTS.preventDefault(event) |
| equivalent to 'event.preventDefault()' |
| |
| Specific events: |
| EVENTS.onHashChange(callback) |
| triggers 'callback()' when the URL hash is changed |
| EVENTS.onDOMReady(callback) |
| triggers 'callback()' when the DOM content is loaded |
| EVENTS.onSMILReady(callback) |
| triggers 'callback()' when the SMIL content is parsed |
| |
\***************************************************************************/
var EVENTS = {
bind: function(node, type, callback) {},
unbind: function(node, type, callback) {},
trigger: function(node, type) {}
};
// ==========================================================================
// Generic Events
// ==========================================================================
// addEventListener should work fine everywhere except with IE<9
if (window.addEventListener) { // modern browsers
EVENTS.bind = function(node, type, callback) {
if (!node) return;
node.addEventListener(type, callback, false);
};
EVENTS.unbind = function(node, type, callback) {
if (!node) return;
node.removeEventListener(type, callback, false);
};
EVENTS.trigger = function(node, type) {
if (!node) return;
if (!EVENTS.eventList)
EVENTS.eventList = [];
var evtObject = EVENTS.eventList[type];
if (!evtObject) {
evtObject = document.createEvent('Event');
evtObject.initEvent(type, false, false);
EVENTS.eventList[type] = evtObject;
}
node.dispatchEvent(evtObject);
};
EVENTS.preventDefault = function(e) {
e.preventDefault();
};
}
else if (window.attachEvent) { // Internet Explorer 6/7/8
/**
* This also fixes the 'this' reference issue in all callbacks
* -- both for standard and custom events.
* http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
* However, this solution isn't perfect. We probably should think of a
* jQuery dependency for OLDIE.
*/
EVENTS.bind = function(node, type, callback) {
if (!node) return;
var ref = type + callback;
type = 'on' + type;
if (type in node) { // standard DOM event
if (!node['e' + ref]) {
node['e' + ref] = callback;
node[ref] = function() { // try {
node['e' + ref](window.event);
};
node.attachEvent(type, node[ref]);
}
}
else { // custom event
if (!node.eventList)
node.eventList = [];
if (!node.eventList[type])
node.eventList[type] = [];
node.eventList[type].push(callback);
}
};
EVENTS.unbind = function(node, type, callback) {
if (!node) return;
var ref = type + callback;
type = 'on' + type;
if (type in node) { // standard DOM event
if (node['e' + ref]) {
node.detachEvent(type, node[ref]);
try {
delete(node[ref]);
delete(node['e' + ref]);
} catch (e) { // IE6 doesn't support 'delete()' above
node[ref] = null;
node['e' + ref] = null;
}
}
}
else { // custom event
if (!node || !node.eventList || !node.eventList[type])
return;
var callbacks = node.eventList[type];
var cbLength = callbacks.length;
for (var i = 0; i < cbLength; i++) {
if (callbacks[i] == callback) {
callbacks.slice(i, 1);
return;
}
}
}
};
EVENTS.trigger = function(node, type) {
if (!node) return;
type = 'on' + type;
if (type in node) try { // standard DOM event?
node.fireEvent(type);
return;
} catch (e) {}
// custom event: pass an event-like structure to the callback
// + use call() to set the 'this' reference within the callback
var evtObject = {};
evtObject.target = node;
evtObject.srcElement = node;
if (!node || !node.eventList || !node.eventList[type])
return;
var callbacks = node.eventList[type];
var cbLength = callbacks.length;
for (var i = 0; i < cbLength; i++)
callbacks[i].call(node, evtObject);
};
EVENTS.preventDefault = function(e) {
e.returnValue = false;
};
}
// ==========================================================================
// Specific Events
// ==========================================================================
// 'hashchange' works on most recent browsers
EVENTS.onHashChange = function(callback) {
if ('onhashchange' in window) // IE8 and modern browsers
EVENTS.bind(window, 'hashchange', callback);
else { // use a setInterval loop for older browsers
var hash = '';
window.setInterval(function() {
if (hash != window.location.hash) {
hash = window.location.hash;
callback();
}
}, 250); // 250ms timerate by default
}
};
// 'DOMContentLoaded' should work fine everywhere except with IE<9
EVENTS.onDOMReady = function(callback) { // TODO: test readyState
if (window.addEventListener) // modern browsers
/**
* http://perfectionlabstips.wordpress.com/2008/12/01/which-browsers-support-native-domcontentloaded-event/
* A few browsers support addEventListener without DOMContentLoaded:
* namely, Firefox 1.0, Opera <8 and Safari <2 (according to this link).
* As these browsers aren't supported any more, we can safely ignore them.
*/
window.addEventListener('DOMContentLoaded', callback, false);
else { // Internet Explorer 6/7/8
/**
* There are plenty other ways to do this without delaying the execution
* but we haven't taken the time to test the properly yet (FIXME).
* http://javascript.nwbox.com/IEContentLoaded/
* http://tanny.ica.com/ICA/TKO/tkoblog.nsf/dx/domcontentloaded-for-browsers-part-v
* http://www.javascriptfr.com/codes/DOMCONTENTLOADED-DOCUMENT-READY_49923.aspx
* https://github.com/ded/domready
* http://www.dustindiaz.com/smallest-domready-ever/
*/
EVENTS.bind(window, 'load', callback);
}
};
// 'MediaContentLoaded' is fired when all media elements have been parsed
EVENTS.onMediaReady = function(callback) {
EVENTS.bind(window, 'MediaContentLoaded', callback);
};
// 'SMILContentLoaded' is fired when all time containers have been parsed
EVENTS.onSMILReady = function(callback) {
EVENTS.bind(window, 'SMILContentLoaded', callback);
};
// ==========================================================================
// Expose as window.EVENTS
// ==========================================================================
window.EVENTS = EVENTS;
})();
// ============================================================================
// QWERY.[*]: CSS selector (requires qwery|sizzle|jQuery|YUI)
// ============================================================================
(function() {
/***************************************************************************\
| |
| CSS Query Selector Abstraction Layer |
| completely useless... except to support Internet Explorer 6/7 :-/ |
| exposed as window.qwerySelector[All] |
| |
| No specific code is included, one of these libraries is required: |
| qwery.js http://dustindiaz.com/qwery |
| sizzle.js http://sizzlejs.com/ |
| jQuery http://jquery.com/ |
| YUI http://developer.yahoo.com/yui/ |
| |
|---------------------------------------------------------------------------|
| |
| Generic methods: |
| QWERY.select(cssQuery [, context]) |
| equivalent to 'document.querySelector(cssQuery)' |
| or 'context.querySelector(cssQuery)' |
| QWERY.selectAll(cssQuery [, context]) |
| equivalent to 'document.querySelectorAll(cssQuery)' |
| or 'context.querySelectorAll(cssQuery)' |
| |
| Specific methods: |
| QWERY.selectTimeContainers() |
| returns all inline time containers |
| QWERY.selectExtTimesheets() |
| returns all <link> nodes pointing to external timesheets |
| |
| Properties: (read-only) |
| QWERY.supported |
| true if a CSS selector engine is usable, false if not |
| QWERY.native |
| true if no supported CSS selector library is used |
| |
\***************************************************************************/
var gSupported = true; // 'false' when no CSS selector can be used
var gNative = false; // 'true' when using native *.querySelector[All]
function qwerySelector(cssQuery, context) {}
function qwerySelectorAll(cssQuery, context) {}
// ==========================================================================
// querySelectorAll() is required by 'select' attributes in timesheets
// ==========================================================================
if (window.qwery) { // http://www.dustindiaz.com/qwery
qwerySelectorAll = qwery;
}
else if (window.Sizzle) { // http://sizzlejs.com/
qwerySelectorAll = Sizzle;
}
/**
* These two libs do not return elements in the right DOM order. Blocker!
* That's surprising for Dojo, since Sizzle.js is a Dojo Foundation project.
*
* else if (window.cssQuery) { // http://dean.edwards.name/my/cssQuery/
* qwerySelectorAll = cssQuery;
* }
* else if (window.dojo) { // http://dojotoolkit.org/
* qwerySelectorAll = dojo.query;
* }
*/
else if (window.jQuery) { // http://jquery.com/
qwerySelectorAll = function(cssQuery, context) {
return $(cssQuery, context);
};
}
else if (window.YAHOO && // http://developer.yahoo.com/yui/
window.YAHOO.util &&
window.YAHOO.util.Selector) {
qwerySelectorAll = YAHOO.util.Selector.query;
}
/**
* These frameworks are untested:
*
* else if (window.Ext) { // http://www.sencha.com/products/js/
* qwerySelectorAll = Ext.select;
* }
* else if (window.$$) { // http://prototypejs.org/ http://mootools.net/
* qwerySelectorAll = function(cssQuery, context) {
* return $$(cssQuery, context);
* };
* }
*/
else if (document.querySelectorAll) { // IE8 and modern browsers
gNative = true;
qwerySelectorAll = function(cssQuery, context) {
context = context || document;
return context.querySelectorAll(cssQuery);
};
}
else { // OLDIE (IE6, IE7) and no CSS Selector library
gSupported = false;
// Crap. We'll just test anchors and tag names then.
// XXX this will never work for 'select' attributes (timesheets)
qwerySelectorAll = function(cssQuery, context) {
context = context || document;
var results = [];
if (/^#[^\s]+$/.test(cssQuery)) { // anchor?
var target = document.getElementById(cssQuery.substring(1));
if (target)
results.push(target);
}
else if (/^[a-z]+$/i.test(cssQuery)) { // tag name?
results = context.getElementsByTagName(cssQuery);
}
return results;
}
}
// ==========================================================================
// querySelector() is required to support the 'mediaSync' attribute
// ==========================================================================
if (document.querySelector) { // IE8 and modern browsers
qwerySelector = function(cssQuery, context) {
context = context || document;
return context.querySelector(cssQuery);
};
}
else { // OLDIE (IE6, IE7) and no CSS Selector library
// fallback to qwerySelectorAll()
qwerySelector = function(cssQuery, context) {
var results = qwerySelectorAll(cssQuery, context);
if (results && results.length) {
return results[0];
} else {
return null;
}
};
}
// ==========================================================================
// Timesheets-specific parsing helpers
// ==========================================================================
function qweryTimeContainers() { // inline time containers
if (gSupported) return qwerySelectorAll(
'*[data-timecontainer], *[smil-timecontainer], *[timeContainer]');
// OLDIE (IE6, IE7) and no CSS Selector library
var results = [];
var tmp = document.getElementsByTagName('*');
var re = /^(par|seq|excl)$/i;
for (var i = 0; i < tmp.length; i++) {
if (re.test(tmp[i].nodeName) ||
tmp[i].getAttribute('data-timecontainer') ||
tmp[i].getAttribute('smil-timecontainer') ||
tmp[i].getAttribute('timeContainer')) {
results.push(tmp[i]);
}
}
return results;
}
function qweryExtTimesheets() { // external timesheets
if (gSupported) return qwerySelectorAll('link[rel=timesheet]');
// OLDIE (IE6, IE7) and no CSS Selector library
var results = [];
var links = document.getElementsByTagName('link');
for (var i = 0; i < links.length; i++) {
if (links[i].rel.toLowerCase() == 'timesheet') {
results.push(links[i]);
}
}
return results;
}
// ==========================================================================
// Expose
// ==========================================================================
window.QWERY = {
select: qwerySelector,
selectAll: qwerySelectorAll,
selectTimeContainers: qweryTimeContainers,
selectExtTimesheets: qweryExtTimesheets,
supported: gSupported,
nativeSelector: gNative
};
})();
// ============================================================================
// Array.indexOf(), Date.now()
// ============================================================================
if (!Array.indexOf) Array.prototype.indexOf = function(obj) {
for (var i = 0; i < this.length; i++) {
if (this[i] == obj) {
return i;
}
}
return -1;
};
if (!Date.now) Date.now = function() {
var timestamp = new Date();
return timestamp.getTime();
};
/*****************************************************************************\
| |
| SMIL/Timing and SMIL/Timesheet implementation |
| |
|*****************************************************************************|
| |
| (function(){ |
|-----------------------------------------------------------------------------|
| Utilities: |
| |
| checkHash(), parseAllTimeContainers() |
| startup sequence |
| smil[In|Ex]ternalTimer |
| timers |
|-----------------------------------------------------------------------------|
| SMIL Objects: |
| |
| smilTimeItem |
| base class for SMIL items |
| smilTimeContainer_generic |
| abstract class for SMIL containers |
| inherits smilTimeItem |
| smilTimeContainer_[par|seq|excl] |
| base class for SMIL containers |
| inherits smilTimeContainer_generic |
| smilTimeElement |
| constructor for all SMIL elements |
| always inherits smilTimeItem |
| inherits smilTimeContainer_* when necessary |
|-----------------------------------------------------------------------------|
| |
| Public API: |
| |
| document.createTimeContainer(domNode, parentNode, targetNode, timerate) |
| document.getTimeNodesByTarget(node) |
| document.getTimeContainersByTarget(node) |
| document.getTimeContainersByTagName(tagName) |
| |
|-----------------------------------------------------------------------------|
| })(); |
| |
\*****************************************************************************/
(function() {
// Note: all lines containing 'consoleLog' will be deleted by the minifier
var DEBUG = true; // consoleLog
function consoleLog(message) { // consoleLog
if (DEBUG && (typeof(console) == 'object')) { // consoleLog
console.log(message); // consoleLog
} // consoleLog
} // consoleLog
function consoleWarn(message) {
if (typeof(console) == 'object') {
console.warn(message);
}
}
// default timeContainer refresh rate = 40ms (25fps)
var TIMERATE = 40;
if (window.mejs) { // http://mediaelementjs.com/
mejs.MediaElementDefaults.timerRate = TIMERATE;
}
// array to store all time containers
var TIMECONTAINERS = [];
// Detect Internet Explorer 6/7/8
// these browsers don't support XHTML, <audio|video>, addEventListener...
var OLDIE = (window.addEventListener) ? false : true;
// var IE6 = (window.XMLHttpRequest) ? false : true;
// ===========================================================================
// Activate a time node if a hash is found in the URL
// ===========================================================================
function checkHash() {
var targetElement = null; // target DOM node
var targetTiming = null; // target time node
var container = null; // ???
var i, tmp;
// get the URI target element
var hash = document.location.hash;
if (hash.length) {
consoleLog('new hash: ' + hash);
var targetID = hash.substr(1).replace(/\&.*$/, '');
// the hash may contain a leading char (e.g. '_') to prevent scrolling
targetElement = document.getElementById(targetID) ||
document.getElementById(targetID.substr(1));
}
if (!targetElement) return;
consoleLog(targetElement);
// get the target time node (if any)
tmp = document.getTimeNodesByTarget(targetElement);
if (tmp.length) {
targetTiming = tmp[0];
container = tmp[0].parentNode;
}
// the hash might contain some temporal MediaFragment information
var time = NaN;
if (targetTiming && targetTiming.timeContainer) {
tmp = hash.split('&');
for (i = 0; i < tmp.length; i++) {
if (/^t=.*/i.test(tmp[i])) { // drop end time (if any)
time = targetTiming.parseTime(tmp[i].substr(2).replace(/,.*$/, ''));
break;
}
}
}
/**
* Activate the time container on the target element:
* http://www.w3.org/TR/SMIL3/smil-timing.html#Timing-HyperlinkImplicationsOnSeqExcl
* We're extending this to all time containers, including <par> -- but we
* still haven't checked wether '.selectIndex()' works properly with <par>.
*/
var containers = [];
var indexes = [];
var timeNodes = [];
var element = targetElement;
while (container) {
for (var index = 0; index < container.timeNodes.length; index++) {
if (container.timeNodes[index].target == element) {
consoleLog('target found: ' + element.nodeName + '#' + element.id);
if (!container.timeNodes[index].isActive()) {
containers.push(container);
indexes.push(index);
timeNodes.push(container.timeNodes[index]);
}
break;
}
}
// loop on the parent container
element = container.getNode();
container = container.parentNode;
}
for (i = containers.length - 1; i >= 0; i--) {
consoleLog(containers[i].nodeName + ' - index=' + indexes[i]);
containers[i].selectIndex(indexes[i]);
}
// set the target time container to a specific time if requested
if (targetTiming && !isNaN(time)) {
targetTiming.setCurrentTime(time);
consoleLog(targetElement.nodeName + ' time: ' + time);
}
// ensure the target element is visible
// targetElement.focus(); // not working if targetElement has no tabIndex
if (targetElement['scrollIntoViewIfNeeded'] != undefined) {
targetElement.scrollIntoViewIfNeeded(); // WebKit browsers only
}
else try {
var tabIndex = targetElement.tabIndex;
targetElement.tabIndex = 0;
targetElement.focus();
targetElement.blur();
if (tabIndex >= 0)
targetElement.tabIndex = tabIndex;
else
targetElement.removeAttribute('tabIndex');
} catch (e) {}
}
EVENTS.onSMILReady(function() {
consoleLog("SMIL data parsed, starting 'hashchange' event listener.");
checkHash(); // force to check once at startup
EVENTS.onHashChange(checkHash);
});
// ===========================================================================
// Find all <audio|video> elements in the current document
// ===========================================================================
function parseMediaElement(node) {
// use MediaElement.js when available: http://mediaelementjs.com/
if (window.MediaElement) {
var m = new MediaElement(node, {
success: function(mediaAPI, element) {
// note: element == node here
consoleLog('MediaElement with ' + mediaAPI.pluginType + ' player');
if ((/^(flash|silverlight)$/i).test(mediaAPI.pluginType)) {
/**
* we're using a Flash/Silverlight <object|embed> fallback
* now find the related <object|embed> element -- by default, it
* should be the previous sibling of the <audio|video> element.
*/
var pluginElement = element.previousSibling;
/**
* XXX this is precisely what I dislike about MediaElement.js:
* . there's no proper way to get the <object> node ref
* . the <object> node can be included in a <div> container
* . the <object> node is not a child of the <audio|video> element
*
* IE: pluginElement =
* <object id="me_[flash|Silverlight]_##" ... </object>
* other: pluginElement =
* <div class="me-plugin"><object ... </object></div>
*/
if (element.firstChild &&
(/^(object|embed)$/i).test(element.firstChild.nodeName)) {
// Good news! We're using mediaelement4oldie.js:
// the <object> fallback is a child of the <audio|video> element
pluginElement = element.firstChild;
consoleLog(' (childNode)');
}
else if (pluginElement && (
(/^me_flash/).test(pluginElement.id) || // IE<9 +Flash
(/^me_silverlight/).test(pluginElement.id) || // IE<9 +Silverlight
(pluginElement.className == 'me-plugin')
)) {
// Bad news: MediaElement.js has inserted the <object|embed>
// fallback outside of the <audio|video> element.
// XXX ugly hack to avoid a "display: none" on the object container
pluginElement.setAttribute('timeAction', 'none');
consoleLog(' (previousSibling)');
}
// store a pointer to the <object|embed> element, just in case
element.pluginElement = pluginElement;
element.mediaAPI = mediaAPI;
}
EVENTS.trigger(document, 'MediaElementLoaded');
},
error: function() {
// throw("MediaElement error");
alert('MediaElement error');
}
});
}
else { // native HTML5 media element
node.setCurrentTime = function(time) {
node.currentTime = time;
};
// TODO: add other MediaElement setters
EVENTS.trigger(document, 'MediaElementLoaded');
}
}
function parseAllMediaElements() {
var allAudioElements = document.getElementsByTagName('audio');
var allVideoElements = document.getElementsByTagName('video');
var meLength = allAudioElements.length + allVideoElements.length;
if (meLength === 0) {
// early way out: no <audio|video> element in the current document
EVENTS.trigger(window, 'MediaContentLoaded');
return;
}
else if (OLDIE && !window.MediaElement) {
// http://mediaelementjs.com/ required
// disabled at the moment
if (0) throw 'MediaElement.js is required on IE<9';
}
// callback to count all parsed media elements
var meParsed = 0;
function CountMediaElements() {
meParsed++;
if (meParsed >= meLength) {
EVENTS.unbind(document, 'MediaElementLoaded', CountMediaElements);
EVENTS.trigger(window, 'MediaContentLoaded');
}
}
EVENTS.bind(document, 'MediaElementLoaded', CountMediaElements);
// initialize all media elements
for (var i = 0; i < allAudioElements.length; i++) {
parseMediaElement(allAudioElements[i]);
}
for (i = 0; i < allVideoElements.length; i++) {
parseMediaElement(allVideoElements[i]);
}
}
// ===========================================================================
// Find all time containers in the current document
// ===========================================================================
function parseTimeContainerNode(node) {
if (!node) return;
// Don't create a new smilTimeElement if this node already has a
// parent time container.
if (!node.timing) {
consoleLog('Main time container found: ' + node.nodeName);
consoleLog(node);
// the "timing" property isn't set: this node hasn't been parsed yet.
var smilPlayer = new smilTimeElement(node);
smilPlayer.show();
} else {
consoleLog('Child time container found: ' + node.nodeName);
}
}
function parseTimesheetNode(timesheetNode) {
var containers = timesheetNode.childNodes;
for (var i = 0; i < containers.length; i++) {
if (containers[i].nodeType == 1) { // Node.ELEMENT_NODE
parseTimeContainerNode(containers[i]);
}
}
}
function parseAllTimeContainers() {
TIMECONTAINERS = [];
// Inline Time Containers (HTML namespace)
var allTimeContainers = QWERY.selectTimeContainers();
for (var i = 0; i < allTimeContainers.length; i++)
parseTimeContainerNode(allTimeContainers[i]);
// External Timesheets: callback to count all parsed timesheets
var timesheets = QWERY.selectExtTimesheets();
var tsLength = timesheets.length;
var tsParsed = 0;
function CountTimesheets() {
tsParsed++;
if (tsParsed > tsLength) {
EVENTS.unbind(document, 'SMILTimesheetLoaded', CountTimesheets);
EVENTS.trigger(window, 'SMILContentLoaded');
}
}
EVENTS.bind(document, 'SMILTimesheetLoaded', CountTimesheets);
// External Timesheets: parsing
var xhr;
for (i = 0; i < tsLength; i++) {
/**
* IE6 doesn't support XMLHttpRequest natively
* IE6/7/8 don't support overrideMimeType with native XMLHttpRequest
* IE6/7/8/9 don't allow loading any local file with native XMLHttpRequest
* so we use ActiveX for XHR on IE, period.
*/
if (window.ActiveXObject) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', timesheets[i].href, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// overrideMimeType("text/xml") doesn't work on IE6
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.loadXML(xhr.responseText);
var tsNodes = xmlDoc.getElementsByTagName('timesheet');
if (tsNodes && tsNodes.length)
parseTimesheetNode(tsNodes[0]);
EVENTS.trigger(document, 'SMILTimesheetLoaded');
}
};
xhr.send(null);
}
else if (window.XMLHttpRequest) {
// note that Chrome won't allow loading any local timesheet with XHR
xhr = new XMLHttpRequest();
xhr.overrideMimeType('text/xml');
xhr.open('GET', timesheets[i].href, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var tsNodes = xhr.responseXML.getElementsByTagName('timesheet');
if (tsNodes && tsNodes.length)
parseTimesheetNode(tsNodes[0]);
EVENTS.trigger(document, 'SMILTimesheetLoaded');
}
};
xhr.send(null);
}
else { // can't load the timesheet but still dispatch the related event
EVENTS.trigger(document, 'SMILTimesheetLoaded');
}
}
/**
* Internet Explorer 6/7/8 don't support XHTML sent as application/xhtml+xml
* => these browsers won't support internal timesheets nor smil:* attributes
* => don't use internal timesheets nor smil:* attributes for web content!
*/
if (!OLDIE) {
var docElt = document.documentElement;
var ns = {
'xhtml' : 'http://www.w3.org/1999/xhtml',
'svg' : 'http://www.w3.org/2000/svg',
'smil' : docElt.getAttribute('xmlns:smil') || 'http://www.w3.org/ns/SMIL'
};
function nsResolver(prefix) { return ns[prefix] || null; }
// Internal Timesheets
var TimesheetNS = nsResolver('smil');
timesheets = document.getElementsByTagNameNS(TimesheetNS, 'timesheet');
if (!timesheets.length) { // polyglot markup (not working with OLDIE)
timesheets = document.getElementsByTagName('timesheet');
}
for (i = 0; i < timesheets.length; i++) {
parseTimesheetNode(timesheets[i]);
}
// Inline Time Containers (SMIL namespace) -- we have to use XPath because
// document.querySelectorAll("[smil|timeContainer]") raises an exception.
if (docElt.getAttribute('xmlns')) {
// the document might have SMIL extensions
var containers = document.evaluate('//*[@smil:timeContainer]', document,
nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
var thisContainer = containers.iterateNext();
try {
while (thisContainer) {
parseTimeContainerNode(thisContainer);
thisContainer = containers.iterateNext();
}
} catch (e) {} // Safari tends to raise exceptions here, dunno why
}
}
// for our counter, all internal timing data is considered as one timesheet
EVENTS.trigger(document, 'SMILTimesheetLoaded');
}
// ===========================================================================
// Startup: get all media elements first, then all time containers
// ===========================================================================
EVENTS.onDOMReady(function() {
consoleLog('SMIL/HTML Timing: startup');
EVENTS.onMediaReady(parseAllTimeContainers);
parseAllMediaElements();
});
/*****************************************************************************\
| |
| smilInternalTimer ( |
| timerate : update time in milliseconds (default = 40ms) |
| ) |
| smilExternalTimer ( |
| mediaPlayerNode : <audio|video> node used as time base |
| ) |
| |
|*****************************************************************************|
| |
| .onTimeUpdate callback function to be triggered on each time update |
| |
| .isPaused() returns 'true' when paused |
| .getTime() returns the current elapsed time, in seconds |
| |
| .Play() starts playing (and triggering the callback function) |
| .Pause() stops playing (and suspend the callback function) |
| .Stop() stops playing (and resets the time to zero) |
| |
\*****************************************************************************/
/**
* These two timers implement the same API. Each time container will choose
* the appropriate timer -- internal by default, external when an <audio|video>
* element is in charge of the timing (see the 'syncMaster' SMIL attribute).
*
* I'm not sure these timers really need Play/Pause/Stop methods: they've been
* implemented mostly for backward compatibility with the LimSee3 project, but
* it's not clear whether this project is still maintained or not.
*/
function smilInternalTimer(timerate) {
if (!timerate)
timerate = TIMERATE; // default = 40 milliseconds timerate (25 fps)
var self = this;
this.onTimeUpdate = null;
// read-only properties: isPaused(), getTime()
var timerID = null;
var timeStart = 0; // milliseconds since 1970/01/01 00:00
var timePause = 0; // milliseconds since last Play()
var paused = true;
this.isPaused = function() { return paused; };
this.getTime = function() {
var ms = timePause;
if (!paused)
ms += Date.now() - timeStart;
return (ms / 1000); // returns elapsed time in seconds (float)
};
this.setTime = function(time) {
timeStart -= (time - self.getTime()) * 1000;
};
// public methods: Play(), Pause(), Stop()
this.Play = function() {
if (!paused) return;
timeStart = Date.now();
timerID = setInterval(function() { self.onTimeUpdate(); }, timerate);
paused = false;
};
this.Pause = function() {
if (paused) return;
clearInterval(timerID);
timerID = null;
timePause = 1000 * self.getTime();
paused = true;
self.onTimeUpdate();
};
this.Stop = function() {
if (!timerID) return;
clearInterval(timerID);
timerID = null;
timePause = 0;
paused = true;
self.onTimeUpdate();
};
}
function smilExternalTimer(mediaPlayerNode) {
var self = this;
var currentTime = NaN;
this.onTimeUpdate = null;
// use MediaElement.js when available: http://mediaelementjs.com/
var mediaPlayerAPI = mediaPlayerNode;
if (mediaPlayerNode.mediaAPI) {
// XXX looks like MediaElement.js makes this useless. Sweet!
// ...but IE6 somehow needs it. Ugh.
mediaPlayerAPI = mediaPlayerNode.mediaAPI;
consoleLog('MediaElement interface found.');
}
// read-only properties: isPaused(), getTime()
this.isPaused = function() { return mediaPlayerAPI.paused; };
this.getTime = function() {
return isNaN(currentTime) ? mediaPlayerAPI.currentTime : currentTime;
};
this.setTime = function(time) {
consoleLog('setting media time to ' + time);
if (mediaPlayerAPI.seeking) {
consoleWarn('seeking');
function setThisTime() {
mediaPlayerAPI.setCurrentTime(time);
mediaPlayerAPI.removeEventListener('seeked', setThisTime, false);
consoleLog(' readyState = ' + mediaPlayerAPI.readyState);
}
mediaPlayerAPI.removeEventListener('seeked', setThisTime, false);
mediaPlayerAPI.addEventListener('seeked', setThisTime, false);
}
else try {
mediaPlayerAPI.setCurrentTime(time);
} catch (e) {