comparison core.js @ 1106:282dfb8076f5

Merge default to dev_main
author Nicholas Jillings <n.g.r.jillings@se14.qmul.ac.uk>
date Wed, 17 Feb 2016 11:29:18 +0000
parents
children f53b1098795f
comparison
equal deleted inserted replaced
-1:000000000000 1106:282dfb8076f5
1 /**
2 * core.js
3 *
4 * Main script to run, calls all other core functions and manages loading/store to backend.
5 * Also contains all global variables.
6 */
7
8 /* create the web audio API context and store in audioContext*/
9 var audioContext; // Hold the browser web audio API
10 var projectXML; // Hold the parsed setup XML
11 var schemaXSD; // Hold the parsed schema XSD
12 var specification;
13 var interfaceContext;
14 var storage;
15 var popup; // Hold the interfacePopup object
16 var testState;
17 var currentTrackOrder = []; // Hold the current XML tracks in their (randomised) order
18 var audioEngineContext; // The custome AudioEngine object
19 var projectReturn; // Hold the URL for the return
20
21
22 // Add a prototype to the bufferSourceNode to reference to the audioObject holding it
23 AudioBufferSourceNode.prototype.owner = undefined;
24 // Add a prototype to the bufferNode to hold the desired LINEAR gain
25 AudioBuffer.prototype.playbackGain = undefined;
26 // Add a prototype to the bufferNode to hold the computed LUFS loudness
27 AudioBuffer.prototype.lufs = undefined;
28
29 // Firefox does not have an XMLDocument.prototype.getElementsByName
30 // and there is no searchAll style command, this custom function will
31 // search all children recusrively for the name. Used for XSD where all
32 // element nodes must have a name and therefore can pull the schema node
33 XMLDocument.prototype.getAllElementsByName = function(name)
34 {
35 name = String(name);
36 var selected = this.documentElement.getAllElementsByName(name);
37 return selected;
38 }
39
40 Element.prototype.getAllElementsByName = function(name)
41 {
42 name = String(name);
43 var selected = [];
44 var node = this.firstElementChild;
45 while(node != null)
46 {
47 if (node.getAttribute('name') == name)
48 {
49 selected.push(node);
50 }
51 if (node.childElementCount > 0)
52 {
53 selected = selected.concat(node.getAllElementsByName(name));
54 }
55 node = node.nextElementSibling;
56 }
57 return selected;
58 }
59
60 XMLDocument.prototype.getAllElementsByTagName = function(name)
61 {
62 name = String(name);
63 var selected = this.documentElement.getAllElementsByTagName(name);
64 return selected;
65 }
66
67 Element.prototype.getAllElementsByTagName = function(name)
68 {
69 name = String(name);
70 var selected = [];
71 var node = this.firstElementChild;
72 while(node != null)
73 {
74 if (node.nodeName == name)
75 {
76 selected.push(node);
77 }
78 if (node.childElementCount > 0)
79 {
80 selected = selected.concat(node.getAllElementsByTagName(name));
81 }
82 node = node.nextElementSibling;
83 }
84 return selected;
85 }
86
87 // Firefox does not have an XMLDocument.prototype.getElementsByName
88 if (typeof XMLDocument.prototype.getElementsByName != "function") {
89 XMLDocument.prototype.getElementsByName = function(name)
90 {
91 name = String(name);
92 var node = this.documentElement.firstElementChild;
93 var selected = [];
94 while(node != null)
95 {
96 if (node.getAttribute('name') == name)
97 {
98 selected.push(node);
99 }
100 node = node.nextElementSibling;
101 }
102 return selected;
103 }
104 }
105
106 window.onload = function() {
107 // Function called once the browser has loaded all files.
108 // This should perform any initial commands such as structure / loading documents
109
110 // Create a web audio API context
111 // Fixed for cross-browser support
112 var AudioContext = window.AudioContext || window.webkitAudioContext;
113 audioContext = new AudioContext;
114
115 // Create test state
116 testState = new stateMachine();
117
118 // Create the popup interface object
119 popup = new interfacePopup();
120
121 // Create the specification object
122 specification = new Specification();
123
124 // Create the interface object
125 interfaceContext = new Interface(specification);
126
127 // Create the storage object
128 storage = new Storage();
129 // Define window callbacks for interface
130 window.onresize = function(event){interfaceContext.resizeWindow(event);};
131 };
132
133 function loadProjectSpec(url) {
134 // Load the project document from the given URL, decode the XML and instruct audioEngine to get audio data
135 // If url is null, request client to upload project XML document
136 var xmlhttp = new XMLHttpRequest();
137 xmlhttp.open("GET",'test-schema.xsd',true);
138 xmlhttp.onload = function()
139 {
140 schemaXSD = xmlhttp.response;
141 var parse = new DOMParser();
142 specification.schema = parse.parseFromString(xmlhttp.response,'text/xml');
143 var r = new XMLHttpRequest();
144 r.open('GET',url,true);
145 r.onload = function() {
146 loadProjectSpecCallback(r.response);
147 };
148 r.send();
149 };
150 xmlhttp.send();
151 };
152
153 function loadProjectSpecCallback(response) {
154 // Function called after asynchronous download of XML project specification
155 //var decode = $.parseXML(response);
156 //projectXML = $(decode);
157
158 // First perform XML schema validation
159 var Module = {
160 xml: response,
161 schema: schemaXSD,
162 arguments:["--noout", "--schema", 'test-schema.xsd','document.xml']
163 };
164
165 var xmllint = validateXML(Module);
166 console.log(xmllint);
167 if(xmllint != 'document.xml validates\n')
168 {
169 document.getElementsByTagName('body')[0].innerHTML = null;
170 var msg = document.createElement("h3");
171 msg.textContent = "FATAL ERROR";
172 var span = document.createElement("h4");
173 span.textContent = "The XML validator returned the following errors when decoding your XML file";
174 document.getElementsByTagName('body')[0].appendChild(msg);
175 document.getElementsByTagName('body')[0].appendChild(span);
176 xmllint = xmllint.split('\n');
177 for (var i in xmllint)
178 {
179 document.getElementsByTagName('body')[0].appendChild(document.createElement('br'));
180 var span = document.createElement("span");
181 span.textContent = xmllint[i];
182 document.getElementsByTagName('body')[0].appendChild(span);
183 }
184 return;
185 }
186
187 var parse = new DOMParser();
188 projectXML = parse.parseFromString(response,'text/xml');
189 var errorNode = projectXML.getElementsByTagName('parsererror');
190 if (errorNode.length >= 1)
191 {
192 var msg = document.createElement("h3");
193 msg.textContent = "FATAL ERROR";
194 var span = document.createElement("span");
195 span.textContent = "The XML parser returned the following errors when decoding your XML file";
196 document.getElementsByTagName('body')[0].innerHTML = null;
197 document.getElementsByTagName('body')[0].appendChild(msg);
198 document.getElementsByTagName('body')[0].appendChild(span);
199 document.getElementsByTagName('body')[0].appendChild(errorNode[0]);
200 return;
201 }
202
203 // Build the specification
204 specification.decode(projectXML);
205 storage.initialise();
206 /// CHECK FOR SAMPLE RATE COMPATIBILITY
207 if (specification.sampleRate != undefined) {
208 if (Number(specification.sampleRate) != audioContext.sampleRate) {
209 var errStr = 'Sample rates do not match! Requested '+Number(specification.sampleRate)+', got '+audioContext.sampleRate+'. Please set the sample rate to match before completing this test.';
210 alert(errStr);
211 return;
212 }
213 }
214
215 // Detect the interface to use and load the relevant javascripts.
216 var interfaceJS = document.createElement('script');
217 interfaceJS.setAttribute("type","text/javascript");
218 switch(specification.interface)
219 {
220 case "APE":
221 interfaceJS.setAttribute("src","interfaces/ape.js");
222
223 // APE comes with a css file
224 var css = document.createElement('link');
225 css.rel = 'stylesheet';
226 css.type = 'text/css';
227 css.href = 'interfaces/ape.css';
228
229 document.getElementsByTagName("head")[0].appendChild(css);
230 break;
231
232 case "MUSHRA":
233 interfaceJS.setAttribute("src","interfaces/mushra.js");
234
235 // MUSHRA comes with a css file
236 var css = document.createElement('link');
237 css.rel = 'stylesheet';
238 css.type = 'text/css';
239 css.href = 'interfaces/mushra.css';
240
241 document.getElementsByTagName("head")[0].appendChild(css);
242 break;
243
244 case "AB":
245 interfaceJS.setAttribute("src","interfaces/AB.js");
246
247 // AB comes with a css file
248 var css = document.createElement('link');
249 css.rel = 'stylesheet';
250 css.type = 'text/css';
251 css.href = 'interfaces/AB.css';
252
253 document.getElementsByTagName("head")[0].appendChild(css);
254 break;
255 case "Bipolar":
256 case "ACR":
257 case "DCR":
258 case "CCR":
259 case "ABC":
260 // Above enumerate to horizontal sliders
261 interfaceJS.setAttribute("src","interfaces/horizontal-sliders.js");
262
263 // horizontal-sliders comes with a css file
264 var css = document.createElement('link');
265 css.rel = 'stylesheet';
266 css.type = 'text/css';
267 css.href = 'interfaces/horizontal-sliders.css';
268
269 document.getElementsByTagName("head")[0].appendChild(css);
270 break;
271 case "discrete":
272 case "likert":
273 // Above enumerate to horizontal discrete radios
274 interfaceJS.setAttribute("src","interfaces/discrete.js");
275
276 // horizontal-sliders comes with a css file
277 var css = document.createElement('link');
278 css.rel = 'stylesheet';
279 css.type = 'text/css';
280 css.href = 'interfaces/discrete.css';
281
282 document.getElementsByTagName("head")[0].appendChild(css);
283 break;
284 }
285 document.getElementsByTagName("head")[0].appendChild(interfaceJS);
286
287 // Create the audio engine object
288 audioEngineContext = new AudioEngine(specification);
289
290 $(specification.pages).each(function(index,elem){
291 $(elem.audioElements).each(function(i,audioElem){
292 var URL = elem.hostURL + audioElem.url;
293 var buffer = null;
294 for (var i=0; i<audioEngineContext.buffers.length; i++)
295 {
296 if (URL == audioEngineContext.buffers[i].url)
297 {
298 buffer = audioEngineContext.buffers[i];
299 break;
300 }
301 }
302 if (buffer == null)
303 {
304 buffer = new audioEngineContext.bufferObj();
305 buffer.getMedia(URL);
306 audioEngineContext.buffers.push(buffer);
307 }
308 });
309 });
310 }
311
312 function createProjectSave(destURL) {
313 // Save the data from interface into XML and send to destURL
314 // If destURL is null then download XML in client
315 // Now time to render file locally
316 var xmlDoc = interfaceXMLSave();
317 var parent = document.createElement("div");
318 parent.appendChild(xmlDoc);
319 var file = [parent.innerHTML];
320 if (destURL == "null" || destURL == undefined) {
321 var bb = new Blob(file,{type : 'application/xml'});
322 var dnlk = window.URL.createObjectURL(bb);
323 var a = document.createElement("a");
324 a.hidden = '';
325 a.href = dnlk;
326 a.download = "save.xml";
327 a.textContent = "Save File";
328
329 popup.showPopup();
330 popup.popupContent.innerHTML = "</span>Please save the file below to give to your test supervisor</span><br>";
331 popup.popupContent.appendChild(a);
332 } else {
333 var xmlhttp = new XMLHttpRequest;
334 xmlhttp.open("POST",destURL,true);
335 xmlhttp.setRequestHeader('Content-Type', 'text/xml');
336 xmlhttp.onerror = function(){
337 console.log('Error saving file to server! Presenting download locally');
338 createProjectSave(null);
339 };
340 xmlhttp.onreadystatechange = function() {
341 console.log(xmlhttp.status);
342 if (xmlhttp.status != 200 && xmlhttp.readyState == 4) {
343 createProjectSave(null);
344 } else {
345 if (xmlhttp.responseXML == null)
346 {
347 createProjectSave('null');
348 }
349 var response = xmlhttp.responseXML.childNodes[0];
350 if (response.getAttribute('state') == "OK")
351 {
352 var file = response.getElementsByTagName('file')[0];
353 console.log('Save OK: Filename '+file.textContent+','+file.getAttribute('bytes')+'B');
354 popup.showPopup();
355 popup.popupContent.innerHTML = null;
356 popup.popupContent.textContent = "Thank you!";
357 } else {
358 var message = response.getElementsByTagName('message')[0];
359 errorSessionDump(message.textContent);
360 }
361 }
362 };
363 xmlhttp.send(file);
364 popup.showPopup();
365 popup.popupContent.innerHTML = null;
366 popup.popupContent.textContent = "Submitting. Please Wait";
367 }
368 }
369
370 function errorSessionDump(msg){
371 // Create the partial interface XML save
372 // Include error node with message on why the dump occured
373 popup.showPopup();
374 popup.popupContent.innerHTML = null;
375 var err = document.createElement('error');
376 var parent = document.createElement("div");
377 if (typeof msg === "object")
378 {
379 err.appendChild(msg);
380 popup.popupContent.appendChild(msg);
381
382 } else {
383 err.textContent = msg;
384 popup.popupContent.innerHTML = "ERROR : "+msg;
385 }
386 var xmlDoc = interfaceXMLSave();
387 xmlDoc.appendChild(err);
388 parent.appendChild(xmlDoc);
389 var file = [parent.innerHTML];
390 var bb = new Blob(file,{type : 'application/xml'});
391 var dnlk = window.URL.createObjectURL(bb);
392 var a = document.createElement("a");
393 a.hidden = '';
394 a.href = dnlk;
395 a.download = "save.xml";
396 a.textContent = "Save File";
397
398
399
400 popup.popupContent.appendChild(a);
401 }
402
403 // Only other global function which must be defined in the interface class. Determines how to create the XML document.
404 function interfaceXMLSave(){
405 // Create the XML string to be exported with results
406 return storage.finish();
407 }
408
409 function linearToDecibel(gain)
410 {
411 return 20.0*Math.log10(gain);
412 }
413
414 function decibelToLinear(gain)
415 {
416 return Math.pow(10,gain/20.0);
417 }
418
419 function interfacePopup() {
420 // Creates an object to manage the popup
421 this.popup = null;
422 this.popupContent = null;
423 this.popupTitle = null;
424 this.popupResponse = null;
425 this.buttonProceed = null;
426 this.buttonPrevious = null;
427 this.popupOptions = null;
428 this.currentIndex = null;
429 this.node = null;
430 this.store = null;
431 $(window).keypress(function(e){
432 if (e.keyCode == 13 && popup.popup.style.visibility == 'visible')
433 {
434 console.log(e);
435 popup.buttonProceed.onclick();
436 e.preventDefault();
437 }
438 });
439
440 this.createPopup = function(){
441 // Create popup window interface
442 var insertPoint = document.getElementById("topLevelBody");
443
444 this.popup = document.getElementById('popupHolder');
445 this.popup.style.left = (window.innerWidth/2)-250 + 'px';
446 this.popup.style.top = (window.innerHeight/2)-125 + 'px';
447
448 this.popupContent = document.getElementById('popupContent');
449
450 this.popupTitle = document.getElementById('popupTitle');
451
452 this.popupResponse = document.getElementById('popupResponse');
453
454 this.buttonProceed = document.getElementById('popup-proceed');
455 this.buttonProceed.onclick = function(){popup.proceedClicked();};
456
457 this.buttonPrevious = document.getElementById('popup-previous');
458 this.buttonPrevious.onclick = function(){popup.previousClick();};
459
460 this.hidePopup();
461
462 this.popup.style.zIndex = -1;
463 this.popup.style.visibility = 'hidden';
464 };
465
466 this.showPopup = function(){
467 if (this.popup == null) {
468 this.createPopup();
469 }
470 this.popup.style.zIndex = 3;
471 this.popup.style.visibility = 'visible';
472 var blank = document.getElementsByClassName('testHalt')[0];
473 blank.style.zIndex = 2;
474 blank.style.visibility = 'visible';
475 };
476
477 this.hidePopup = function(){
478 this.popup.style.zIndex = -1;
479 this.popup.style.visibility = 'hidden';
480 var blank = document.getElementsByClassName('testHalt')[0];
481 blank.style.zIndex = -2;
482 blank.style.visibility = 'hidden';
483 this.buttonPrevious.style.visibility = 'inherit';
484 };
485
486 this.postNode = function() {
487 // This will take the node from the popupOptions and display it
488 var node = this.popupOptions[this.currentIndex];
489 this.popupResponse.innerHTML = null;
490 this.popupTitle.textContent = node.specification.statement;
491 if (node.specification.type == 'question') {
492 var textArea = document.createElement('textarea');
493 switch (node.specification.boxsize) {
494 case 'small':
495 textArea.cols = "20";
496 textArea.rows = "1";
497 break;
498 case 'normal':
499 textArea.cols = "30";
500 textArea.rows = "2";
501 break;
502 case 'large':
503 textArea.cols = "40";
504 textArea.rows = "5";
505 break;
506 case 'huge':
507 textArea.cols = "50";
508 textArea.rows = "10";
509 break;
510 }
511 if (node.response == undefined) {
512 node.response = "";
513 } else {
514 textArea.value = node.response;
515 }
516 this.popupResponse.appendChild(textArea);
517 textArea.focus();
518 this.popupResponse.style.textAlign="center";
519 this.popupResponse.style.left="0%";
520 } else if (node.specification.type == 'checkbox') {
521 if (node.response == undefined) {
522 node.response = Array(node.specification.options.length);
523 }
524 var index = 0;
525 var max_w = 0;
526 for (var option of node.specification.options) {
527 var input = document.createElement('input');
528 input.id = option.name;
529 input.type = 'checkbox';
530 var span = document.createElement('span');
531 span.textContent = option.text;
532 var hold = document.createElement('div');
533 hold.setAttribute('name','option');
534 hold.style.padding = '4px';
535 hold.appendChild(input);
536 hold.appendChild(span);
537 this.popupResponse.appendChild(hold);
538 if (node.response[index] != undefined){
539 if (node.response[index].checked == true) {
540 input.checked = "true";
541 }
542 }
543 var w = $(span).width();
544 if (w > max_w)
545 max_w = w;
546 index++;
547 }
548 max_w += 12;
549 this.popupResponse.style.textAlign="";
550 var leftP = ((max_w/500)/2)*100;
551 this.popupResponse.style.left=leftP+"%";
552 } else if (node.specification.type == 'radio') {
553 if (node.response == undefined) {
554 node.response = {name: "", text: ""};
555 }
556 var index = 0;
557 var max_w = 0;
558 for (var option of node.specification.options) {
559 var input = document.createElement('input');
560 input.id = option.name;
561 input.type = 'radio';
562 input.name = node.specification.id;
563 var span = document.createElement('span');
564 span.textContent = option.text;
565 var hold = document.createElement('div');
566 hold.setAttribute('name','option');
567 hold.style.padding = '4px';
568 hold.appendChild(input);
569 hold.appendChild(span);
570 this.popupResponse.appendChild(hold);
571 if (input.id == node.response.name) {
572 input.checked = "true";
573 }
574 var w = $(span).width();
575 if (w > max_w)
576 max_w = w;
577 }
578 max_w += 12;
579 this.popupResponse.style.textAlign="";
580 var leftP = ((max_w/500)/2)*100;
581 this.popupResponse.style.left=leftP+"%";
582 } else if (node.specification.type == 'number') {
583 var input = document.createElement('input');
584 input.type = 'textarea';
585 if (node.min != null) {input.min = node.specification.min;}
586 if (node.max != null) {input.max = node.specification.max;}
587 if (node.step != null) {input.step = node.specification.step;}
588 if (node.response != undefined) {
589 input.value = node.response;
590 }
591 this.popupResponse.appendChild(input);
592 this.popupResponse.style.textAlign="center";
593 this.popupResponse.style.left="0%";
594 }
595 if(this.currentIndex+1 == this.popupOptions.length) {
596 if (this.node.location == "pre") {
597 this.buttonProceed.textContent = 'Start';
598 } else {
599 this.buttonProceed.textContent = 'Submit';
600 }
601 } else {
602 this.buttonProceed.textContent = 'Next';
603 }
604 if(this.currentIndex > 0)
605 this.buttonPrevious.style.visibility = 'visible';
606 else
607 this.buttonPrevious.style.visibility = 'hidden';
608 };
609
610 this.initState = function(node,store) {
611 //Call this with your preTest and postTest nodes when needed to
612 // initialise the popup procedure.
613 if (node.options.length > 0) {
614 this.popupOptions = [];
615 this.node = node;
616 this.store = store;
617 for (var opt of node.options)
618 {
619 this.popupOptions.push({
620 specification: opt,
621 response: null
622 });
623 }
624 this.currentIndex = 0;
625 this.showPopup();
626 this.postNode();
627 } else {
628 advanceState();
629 }
630 };
631
632 this.proceedClicked = function() {
633 // Each time the popup button is clicked!
634 var node = this.popupOptions[this.currentIndex];
635 if (node.specification.type == 'question') {
636 // Must extract the question data
637 var textArea = $(popup.popupContent).find('textarea')[0];
638 if (node.specification.mandatory == true && textArea.value.length == 0) {
639 alert('This question is mandatory');
640 return;
641 } else {
642 // Save the text content
643 console.log("Question: "+ node.specification.statement);
644 console.log("Question Response: "+ textArea.value);
645 node.response = textArea.value;
646 }
647 } else if (node.specification.type == 'checkbox') {
648 // Must extract checkbox data
649 console.log("Checkbox: "+ node.specification.statement);
650 var inputs = this.popupResponse.getElementsByTagName('input');
651 node.response = [];
652 for (var i=0; i<node.specification.options.length; i++) {
653 node.response.push({
654 name: node.specification.options[i].name,
655 text: node.specification.options[i].text,
656 checked: inputs[i].checked
657 });
658 console.log(node.specification.options[i].name+": "+ inputs[i].checked);
659 }
660 } else if (node.specification.type == "radio") {
661 var optHold = this.popupResponse;
662 console.log("Radio: "+ node.specification.statement);
663 node.response = null;
664 var i=0;
665 var inputs = optHold.getElementsByTagName('input');
666 while(node.response == null) {
667 if (i == inputs.length)
668 {
669 if (node.specification.mandatory == true)
670 {
671 alert("This radio is mandatory");
672 } else {
673 node.response = -1;
674 }
675 return;
676 }
677 if (inputs[i].checked == true) {
678 node.response = node.specification.options[i];
679 console.log("Selected: "+ node.specification.options[i].name);
680 }
681 i++;
682 }
683 } else if (node.specification.type == "number") {
684 var input = this.popupContent.getElementsByTagName('input')[0];
685 if (node.mandatory == true && input.value.length == 0) {
686 alert('This question is mandatory. Please enter a number');
687 return;
688 }
689 var enteredNumber = Number(input.value);
690 if (isNaN(enteredNumber)) {
691 alert('Please enter a valid number');
692 return;
693 }
694 if (enteredNumber < node.min && node.min != null) {
695 alert('Number is below the minimum value of '+node.min);
696 return;
697 }
698 if (enteredNumber > node.max && node.max != null) {
699 alert('Number is above the maximum value of '+node.max);
700 return;
701 }
702 node.response = input.value;
703 }
704 this.currentIndex++;
705 if (this.currentIndex < this.popupOptions.length) {
706 this.postNode();
707 } else {
708 // Reached the end of the popupOptions
709 this.hidePopup();
710 for (var node of this.popupOptions)
711 {
712 this.store.postResult(node);
713 }
714 advanceState();
715 }
716 };
717
718 this.previousClick = function() {
719 // Triggered when the 'Back' button is clicked in the survey
720 if (this.currentIndex > 0) {
721 this.currentIndex--;
722 this.postNode();
723 }
724 };
725
726 this.resize = function(event)
727 {
728 // Called on window resize;
729 if (this.popup != null) {
730 this.popup.style.left = (window.innerWidth/2)-250 + 'px';
731 this.popup.style.top = (window.innerHeight/2)-125 + 'px';
732 var blank = document.getElementsByClassName('testHalt')[0];
733 blank.style.width = window.innerWidth;
734 blank.style.height = window.innerHeight;
735 }
736 };
737 }
738
739 function advanceState()
740 {
741 // Just for complete clarity
742 testState.advanceState();
743 }
744
745 function stateMachine()
746 {
747 // Object prototype for tracking and managing the test state
748 this.stateMap = [];
749 this.preTestSurvey = null;
750 this.postTestSurvey = null;
751 this.stateIndex = null;
752 this.currentStateMap = null;
753 this.currentStatePosition = null;
754 this.currentStore = null;
755 this.initialise = function(){
756
757 // Get the data from Specification
758 var pageHolder = [];
759 for (var page of specification.pages)
760 {
761 var repeat = page.repeatCount;
762 while(repeat >= 0)
763 {
764 pageHolder.push(page);
765 repeat--;
766 }
767 }
768 if (specification.randomiseOrder)
769 {
770 pageHolder = randomiseOrder(pageHolder);
771 }
772 for (var i=0; i<pageHolder.length; i++)
773 {
774 pageHolder[i].presentedId = i;
775 }
776 for (var i=0; i<specification.pages.length; i++)
777 {
778 if (specification.testPages < i && specification.testPages != 0) {break;}
779 this.stateMap.push(pageHolder[i]);
780
781 }
782 if (specification.preTest != null) {this.preTestSurvey = specification.preTest;}
783 if (specification.postTest != null) {this.postTestSurvey = specification.postTest;}
784
785 if (this.stateMap.length > 0) {
786 if(this.stateIndex != null) {
787 console.log('NOTE - State already initialise');
788 }
789 this.stateIndex = -1;
790 } else {
791 console.log('FATAL - StateMap not correctly constructed. EMPTY_STATE_MAP');
792 }
793 };
794 this.advanceState = function(){
795 if (this.stateIndex == null) {
796 this.initialise();
797 }
798 if (this.stateIndex == -1) {
799 this.stateIndex++;
800 console.log('Starting test...');
801 if (this.preTestSurvey != null)
802 {
803 popup.initState(this.preTestSurvey,storage.globalPreTest);
804 } else {
805 this.advanceState();
806 }
807 } else if (this.stateIndex == this.stateMap.length)
808 {
809 // All test pages complete, post test
810 console.log('Ending test ...');
811 this.stateIndex++;
812 if (this.postTestSurvey == null) {
813 this.advanceState();
814 } else {
815 popup.initState(this.postTestSurvey,storage.globalPostTest);
816 }
817 } else if (this.stateIndex > this.stateMap.length)
818 {
819 createProjectSave(specification.projectReturn);
820 }
821 else
822 {
823 if (this.currentStateMap == null)
824 {
825 this.currentStateMap = this.stateMap[this.stateIndex];
826 if (this.currentStateMap.randomiseOrder)
827 {
828 this.currentStateMap.audioElements = randomiseOrder(this.currentStateMap.audioElements);
829 }
830 this.currentStore = storage.createTestPageStore(this.currentStateMap);
831 if (this.currentStateMap.preTest != null)
832 {
833 this.currentStatePosition = 'pre';
834 popup.initState(this.currentStateMap.preTest,storage.testPages[this.stateIndex].preTest);
835 } else {
836 this.currentStatePosition = 'test';
837 }
838 interfaceContext.newPage(this.currentStateMap,storage.testPages[this.stateIndex]);
839 return;
840 }
841 switch(this.currentStatePosition)
842 {
843 case 'pre':
844 this.currentStatePosition = 'test';
845 break;
846 case 'test':
847 this.currentStatePosition = 'post';
848 // Save the data
849 this.testPageCompleted();
850 if (this.currentStateMap.postTest == null)
851 {
852 this.advanceState();
853 return;
854 } else {
855 popup.initState(this.currentStateMap.postTest,storage.testPages[this.stateIndex].postTest);
856 }
857 break;
858 case 'post':
859 this.stateIndex++;
860 this.currentStateMap = null;
861 this.advanceState();
862 break;
863 };
864 }
865 };
866
867 this.testPageCompleted = function() {
868 // Function called each time a test page has been completed
869 var storePoint = storage.testPages[this.stateIndex];
870 // First get the test metric
871
872 var metric = storePoint.XMLDOM.getElementsByTagName('metric')[0];
873 if (audioEngineContext.metric.enableTestTimer)
874 {
875 var testTime = storePoint.parent.document.createElement('metricresult');
876 testTime.id = 'testTime';
877 testTime.textContent = audioEngineContext.timer.testDuration;
878 metric.appendChild(testTime);
879 }
880
881 var audioObjects = audioEngineContext.audioObjects;
882 for (var ao of audioEngineContext.audioObjects)
883 {
884 ao.exportXMLDOM();
885 }
886 for (var element of interfaceContext.commentQuestions)
887 {
888 element.exportXMLDOM(storePoint);
889 }
890 pageXMLSave(storePoint.XMLDOM, this.currentStateMap);
891 };
892 }
893
894 function AudioEngine(specification) {
895
896 // Create two output paths, the main outputGain and fooGain.
897 // Output gain is default to 1 and any items for playback route here
898 // Foo gain is used for analysis to ensure paths get processed, but are not heard
899 // because web audio will optimise and any route which does not go to the destination gets ignored.
900 this.outputGain = audioContext.createGain();
901 this.fooGain = audioContext.createGain();
902 this.fooGain.gain = 0;
903
904 // Use this to detect playback state: 0 - stopped, 1 - playing
905 this.status = 0;
906
907 // Connect both gains to output
908 this.outputGain.connect(audioContext.destination);
909 this.fooGain.connect(audioContext.destination);
910
911 // Create the timer Object
912 this.timer = new timer();
913 // Create session metrics
914 this.metric = new sessionMetrics(this,specification);
915
916 this.loopPlayback = false;
917
918 this.pageStore = null;
919
920 // Create store for new audioObjects
921 this.audioObjects = [];
922
923 this.buffers = [];
924 this.bufferObj = function()
925 {
926 this.url = null;
927 this.buffer = null;
928 this.xmlRequest = new XMLHttpRequest();
929 this.xmlRequest.parent = this;
930 this.users = [];
931 this.progress = 0;
932 this.status = 0;
933 this.ready = function()
934 {
935 if (this.status >= 2)
936 {
937 this.status = 3;
938 }
939 for (var i=0; i<this.users.length; i++)
940 {
941 this.users[i].state = 1;
942 if (this.users[i].interfaceDOM != null)
943 {
944 this.users[i].bufferLoaded(this);
945 }
946 }
947 };
948 this.getMedia = function(url) {
949 this.url = url;
950 this.xmlRequest.open('GET',this.url,true);
951 this.xmlRequest.responseType = 'arraybuffer';
952
953 var bufferObj = this;
954
955 // Create callback to decode the data asynchronously
956 this.xmlRequest.onloadend = function() {
957 // Use inbuilt WAVE decoder first
958 var waveObj = new WAVE();
959 if (waveObj.open(bufferObj.xmlRequest.response) == 0)
960 {
961 bufferObj.buffer = audioContext.createBuffer(waveObj.num_channels,waveObj.num_samples,waveObj.sample_rate);
962 for (var c=0; c<waveObj.num_channels; c++)
963 {
964 var buffer_ptr = bufferObj.buffer.getChannelData(c);
965 for (var n=0; n<waveObj.num_samples; n++)
966 {
967 buffer_ptr[n] = waveObj.decoded_data[c][n];
968 }
969 }
970
971 delete waveObj;
972 } else {
973 audioContext.decodeAudioData(bufferObj.xmlRequest.response, function(decodedData) {
974 bufferObj.buffer = decodedData;
975 }, function(e){
976 // Should only be called if there was an error, but sometimes gets called continuously
977 // Check here if the error is genuine
978 if (bufferObj.xmlRequest.response == undefined) {
979 // Genuine error
980 console.log('FATAL - Error loading buffer on '+audioObj.id);
981 if (request.status == 404)
982 {
983 console.log('FATAL - Fragment '+audioObj.id+' 404 error');
984 console.log('URL: '+audioObj.url);
985 errorSessionDump('Fragment '+audioObj.id+' 404 error');
986 }
987 this.status = -1;
988 }
989 });
990 }
991 if (bufferObj.buffer != undefined)
992 {
993 bufferObj.status = 2;
994 calculateLoudness(bufferObj,"I");
995 }
996 };
997 this.progress = 0;
998 this.progressCallback = function(event){
999 if (event.lengthComputable)
1000 {
1001 this.parent.progress = event.loaded / event.total;
1002 for (var i=0; i<this.parent.users.length; i++)
1003 {
1004 if(this.parent.users[i].interfaceDOM != null)
1005 {
1006 if (typeof this.parent.users[i].interfaceDOM.updateLoading === "function")
1007 {
1008 this.parent.users[i].interfaceDOM.updateLoading(this.parent.progress*100);
1009 }
1010 }
1011 }
1012 }
1013 };
1014 this.xmlRequest.addEventListener("progress", this.progressCallback);
1015 this.status = 1;
1016 this.xmlRequest.send();
1017 };
1018
1019 this.registerAudioObject = function(audioObject)
1020 {
1021 // Called by an audioObject to register to the buffer for use
1022 // First check if already in the register pool
1023 for (var objects of this.users)
1024 {
1025 if (audioObject.id == objects.id){return 0;}
1026 }
1027 this.users.push(audioObject);
1028 if (this.status == 3)
1029 {
1030 // The buffer is already ready, trigger bufferLoaded
1031 audioObject.bufferLoaded(this);
1032 }
1033 }
1034 };
1035
1036 this.play = function(id) {
1037 // Start the timer and set the audioEngine state to playing (1)
1038 if (this.status == 0 && this.loopPlayback) {
1039 // Check if all audioObjects are ready
1040 if(this.checkAllReady())
1041 {
1042 this.status = 1;
1043 this.setSynchronousLoop();
1044 }
1045 }
1046 else
1047 {
1048 this.status = 1;
1049 }
1050 if (this.status== 1) {
1051 this.timer.startTest();
1052 if (id == undefined) {
1053 id = -1;
1054 console.log('FATAL - Passed id was undefined - AudioEngineContext.play(id)');
1055 return;
1056 } else {
1057 interfaceContext.playhead.setTimePerPixel(this.audioObjects[id]);
1058 }
1059 if (this.loopPlayback) {
1060 var setTime = audioContext.currentTime+2;
1061 for (var i=0; i<this.audioObjects.length; i++)
1062 {
1063 this.audioObjects[i].play(setTime-2);
1064 if (id == i) {
1065 this.audioObjects[i].loopStart(setTime);
1066 } else {
1067 this.audioObjects[i].loopStop(setTime);
1068 }
1069 }
1070 } else {
1071 var setTime = audioContext.currentTime+0.1;
1072 for (var i=0; i<this.audioObjects.length; i++)
1073 {
1074 if (i != id) {
1075 this.audioObjects[i].stop(setTime);
1076 } else if (i == id) {
1077 this.audioObjects[id].play(setTime);
1078 }
1079 }
1080 }
1081 interfaceContext.playhead.start();
1082 }
1083 };
1084
1085 this.stop = function() {
1086 // Send stop and reset command to all playback buffers
1087 if (this.status == 1) {
1088 var setTime = audioContext.currentTime+0.1;
1089 for (var i=0; i<this.audioObjects.length; i++)
1090 {
1091 this.audioObjects[i].stop(setTime);
1092 }
1093 interfaceContext.playhead.stop();
1094 }
1095 };
1096
1097 this.newTrack = function(element) {
1098 // Pull data from given URL into new audio buffer
1099 // URLs must either be from the same source OR be setup to 'Access-Control-Allow-Origin'
1100
1101 // Create the audioObject with ID of the new track length;
1102 audioObjectId = this.audioObjects.length;
1103 this.audioObjects[audioObjectId] = new audioObject(audioObjectId);
1104
1105 // Check if audioObject buffer is currently stored by full URL
1106 var URL = testState.currentStateMap.hostURL + element.url;
1107 var buffer = null;
1108 for (var i=0; i<this.buffers.length; i++)
1109 {
1110 if (URL == this.buffers[i].url)
1111 {
1112 buffer = this.buffers[i];
1113 break;
1114 }
1115 }
1116 if (buffer == null)
1117 {
1118 console.log("[WARN]: Buffer was not loaded in pre-test! "+URL);
1119 buffer = new this.bufferObj();
1120 this.buffers.push(buffer);
1121 buffer.getMedia(URL);
1122 }
1123 this.audioObjects[audioObjectId].specification = element;
1124 this.audioObjects[audioObjectId].url = URL;
1125 // Obtain store node
1126 var aeNodes = this.pageStore.XMLDOM.getElementsByTagName('audioelement');
1127 for (var i=0; i<aeNodes.length; i++)
1128 {
1129 if(aeNodes[i].id == element.id)
1130 {
1131 this.audioObjects[audioObjectId].storeDOM = aeNodes[i];
1132 break;
1133 }
1134 }
1135 buffer.registerAudioObject(this.audioObjects[audioObjectId]);
1136 return this.audioObjects[audioObjectId];
1137 };
1138
1139 this.newTestPage = function(audioHolderObject,store) {
1140 this.pageStore = store;
1141 this.state = 0;
1142 this.audioObjectsReady = false;
1143 this.metric.reset();
1144 for (var i=0; i < this.buffers.length; i++)
1145 {
1146 this.buffers[i].users = [];
1147 }
1148 this.audioObjects = [];
1149 this.timer = new timer();
1150 this.loopPlayback = audioHolderObject.loop;
1151 };
1152
1153 this.checkAllPlayed = function() {
1154 arr = [];
1155 for (var id=0; id<this.audioObjects.length; id++) {
1156 if (this.audioObjects[id].metric.wasListenedTo == false) {
1157 arr.push(this.audioObjects[id].id);
1158 }
1159 }
1160 return arr;
1161 };
1162
1163 this.checkAllReady = function() {
1164 var ready = true;
1165 for (var i=0; i<this.audioObjects.length; i++) {
1166 if (this.audioObjects[i].state == 0) {
1167 // Track not ready
1168 console.log('WAIT -- audioObject '+i+' not ready yet!');
1169 ready = false;
1170 };
1171 }
1172 return ready;
1173 };
1174
1175 this.setSynchronousLoop = function() {
1176 // Pads the signals so they are all exactly the same length
1177 var length = 0;
1178 var maxId;
1179 for (var i=0; i<this.audioObjects.length; i++)
1180 {
1181 if (length < this.audioObjects[i].buffer.buffer.length)
1182 {
1183 length = this.audioObjects[i].buffer.buffer.length;
1184 maxId = i;
1185 }
1186 }
1187 // Extract the audio and zero-pad
1188 for (var i=0; i<this.audioObjects.length; i++)
1189 {
1190 var orig = this.audioObjects[i].buffer.buffer;
1191 var hold = audioContext.createBuffer(orig.numberOfChannels,length,orig.sampleRate);
1192 for (var c=0; c<orig.numberOfChannels; c++)
1193 {
1194 var inData = hold.getChannelData(c);
1195 var outData = orig.getChannelData(c);
1196 for (var n=0; n<orig.length; n++)
1197 {inData[n] = outData[n];}
1198 }
1199 hold.playbackGain = orig.playbackGain;
1200 hold.lufs = orig.lufs;
1201 this.audioObjects[i].buffer.buffer = hold;
1202 }
1203 };
1204
1205 this.exportXML = function()
1206 {
1207
1208 };
1209
1210 }
1211
1212 function audioObject(id) {
1213 // The main buffer object with common control nodes to the AudioEngine
1214
1215 this.specification;
1216 this.id = id;
1217 this.state = 0; // 0 - no data, 1 - ready
1218 this.url = null; // Hold the URL given for the output back to the results.
1219 this.metric = new metricTracker(this);
1220 this.storeDOM = null;
1221
1222 // Bindings for GUI
1223 this.interfaceDOM = null;
1224 this.commentDOM = null;
1225
1226 // Create a buffer and external gain control to allow internal patching of effects and volume leveling.
1227 this.bufferNode = undefined;
1228 this.outputGain = audioContext.createGain();
1229
1230 this.onplayGain = 1.0;
1231
1232 // Connect buffer to the audio graph
1233 this.outputGain.connect(audioEngineContext.outputGain);
1234
1235 // the audiobuffer is not designed for multi-start playback
1236 // When stopeed, the buffer node is deleted and recreated with the stored buffer.
1237 this.buffer;
1238
1239 this.bufferLoaded = function(callee)
1240 {
1241 // Called by the associated buffer when it has finished loading, will then 'bind' the buffer to the
1242 // audioObject and trigger the interfaceDOM.enable() function for user feedback
1243 if (audioEngineContext.loopPlayback){
1244 // First copy the buffer into this.buffer
1245 this.buffer = new audioEngineContext.bufferObj();
1246 this.buffer.url = callee.url;
1247 this.buffer.buffer = audioContext.createBuffer(callee.buffer.numberOfChannels, callee.buffer.length, callee.buffer.sampleRate);
1248 for (var c=0; c<callee.buffer.numberOfChannels; c++)
1249 {
1250 var src = callee.buffer.getChannelData(c);
1251 var dst = this.buffer.buffer.getChannelData(c);
1252 for (var n=0; n<src.length; n++)
1253 {
1254 dst[n] = src[n];
1255 }
1256 }
1257 } else {
1258 this.buffer = callee;
1259 }
1260 this.state = 1;
1261 this.buffer.buffer.playbackGain = callee.buffer.playbackGain;
1262 this.buffer.buffer.lufs = callee.buffer.lufs;
1263 var targetLUFS = this.specification.parent.loudness || specification.loudness;
1264 if (typeof targetLUFS === "number")
1265 {
1266 this.buffer.buffer.playbackGain = decibelToLinear(targetLUFS - this.buffer.buffer.lufs);
1267 } else {
1268 this.buffer.buffer.playbackGain = 1.0;
1269 }
1270 if (this.interfaceDOM != null) {
1271 this.interfaceDOM.enable();
1272 }
1273 this.onplayGain = decibelToLinear(this.specification.gain)*this.buffer.buffer.playbackGain;
1274 this.storeDOM.setAttribute('playGain',linearToDecibel(this.onplayGain));
1275 };
1276
1277 this.bindInterface = function(interfaceObject)
1278 {
1279 this.interfaceDOM = interfaceObject;
1280 this.metric.initialise(interfaceObject.getValue());
1281 if (this.state == 1)
1282 {
1283 this.interfaceDOM.enable();
1284 }
1285 this.storeDOM.setAttribute('presentedId',interfaceObject.getPresentedId());
1286 };
1287
1288 this.loopStart = function(setTime) {
1289 this.outputGain.gain.linearRampToValueAtTime(this.onplayGain,setTime);
1290 this.metric.startListening(audioEngineContext.timer.getTestTime());
1291 this.interfaceDOM.startPlayback();
1292 };
1293
1294 this.loopStop = function(setTime) {
1295 if (this.outputGain.gain.value != 0.0) {
1296 this.outputGain.gain.linearRampToValueAtTime(0.0,setTime);
1297 this.metric.stopListening(audioEngineContext.timer.getTestTime());
1298 }
1299 this.interfaceDOM.stopPlayback();
1300 };
1301
1302 this.play = function(startTime) {
1303 if (this.bufferNode == undefined && this.buffer.buffer != undefined) {
1304 this.bufferNode = audioContext.createBufferSource();
1305 this.bufferNode.owner = this;
1306 this.bufferNode.connect(this.outputGain);
1307 this.bufferNode.buffer = this.buffer.buffer;
1308 this.bufferNode.loop = audioEngineContext.loopPlayback;
1309 this.bufferNode.onended = function(event) {
1310 // Safari does not like using 'this' to reference the calling object!
1311 //event.currentTarget.owner.metric.stopListening(audioEngineContext.timer.getTestTime(),event.currentTarget.owner.getCurrentPosition());
1312 event.currentTarget.owner.stop(audioContext.currentTime+1);
1313 };
1314 if (this.bufferNode.loop == false) {
1315 this.metric.startListening(audioEngineContext.timer.getTestTime());
1316 this.outputGain.gain.setValueAtTime(this.onplayGain,startTime);
1317 this.interfaceDOM.startPlayback();
1318 } else {
1319 this.outputGain.gain.setValueAtTime(0.0,startTime);
1320 }
1321 this.bufferNode.start(startTime);
1322 }
1323 };
1324
1325 this.stop = function(stopTime) {
1326 this.outputGain.gain.cancelScheduledValues(audioContext.currentTime);
1327 if (this.bufferNode != undefined)
1328 {
1329 this.metric.stopListening(audioEngineContext.timer.getTestTime(),this.getCurrentPosition());
1330 this.bufferNode.stop(stopTime);
1331 this.bufferNode = undefined;
1332 }
1333 this.outputGain.gain.value = 0.0;
1334 this.interfaceDOM.stopPlayback();
1335 };
1336
1337 this.getCurrentPosition = function() {
1338 var time = audioEngineContext.timer.getTestTime();
1339 if (this.bufferNode != undefined) {
1340 if (this.bufferNode.loop == true) {
1341 if (audioEngineContext.status == 1) {
1342 return (time-this.metric.listenStart)%this.buffer.buffer.duration;
1343 } else {
1344 return 0;
1345 }
1346 } else {
1347 if (this.metric.listenHold) {
1348 return time - this.metric.listenStart;
1349 } else {
1350 return 0;
1351 }
1352 }
1353 } else {
1354 return 0;
1355 }
1356 };
1357
1358 this.exportXMLDOM = function() {
1359 var file = storage.document.createElement('file');
1360 file.setAttribute('sampleRate',this.buffer.buffer.sampleRate);
1361 file.setAttribute('channels',this.buffer.buffer.numberOfChannels);
1362 file.setAttribute('sampleCount',this.buffer.buffer.length);
1363 file.setAttribute('duration',this.buffer.buffer.duration);
1364 this.storeDOM.appendChild(file);
1365 if (this.specification.type != 'outside-reference') {
1366 var interfaceXML = this.interfaceDOM.exportXMLDOM(this);
1367 if (interfaceXML != null)
1368 {
1369 if (interfaceXML.length == undefined) {
1370 this.storeDOM.appendChild(interfaceXML);
1371 } else {
1372 for (var i=0; i<interfaceXML.length; i++)
1373 {
1374 this.storeDOM.appendChild(interfaceXML[i]);
1375 }
1376 }
1377 }
1378 if (this.commentDOM != null) {
1379 this.storeDOM.appendChild(this.commentDOM.exportXMLDOM(this));
1380 }
1381 }
1382 var nodes = this.metric.exportXMLDOM();
1383 var mroot = this.storeDOM.getElementsByTagName('metric')[0];
1384 for (var i=0; i<nodes.length; i++)
1385 {
1386 mroot.appendChild(nodes[i]);
1387 }
1388 };
1389 }
1390
1391 function timer()
1392 {
1393 /* Timer object used in audioEngine to keep track of session timings
1394 * Uses the timer of the web audio API, so sample resolution
1395 */
1396 this.testStarted = false;
1397 this.testStartTime = 0;
1398 this.testDuration = 0;
1399 this.minimumTestTime = 0; // No minimum test time
1400 this.startTest = function()
1401 {
1402 if (this.testStarted == false)
1403 {
1404 this.testStartTime = audioContext.currentTime;
1405 this.testStarted = true;
1406 this.updateTestTime();
1407 audioEngineContext.metric.initialiseTest();
1408 }
1409 };
1410 this.stopTest = function()
1411 {
1412 if (this.testStarted)
1413 {
1414 this.testDuration = this.getTestTime();
1415 this.testStarted = false;
1416 } else {
1417 console.log('ERR: Test tried to end before beginning');
1418 }
1419 };
1420 this.updateTestTime = function()
1421 {
1422 if (this.testStarted)
1423 {
1424 this.testDuration = audioContext.currentTime - this.testStartTime;
1425 }
1426 };
1427 this.getTestTime = function()
1428 {
1429 this.updateTestTime();
1430 return this.testDuration;
1431 };
1432 }
1433
1434 function sessionMetrics(engine,specification)
1435 {
1436 /* Used by audioEngine to link to audioObjects to minimise the timer call timers;
1437 */
1438 this.engine = engine;
1439 this.lastClicked = -1;
1440 this.data = -1;
1441 this.reset = function() {
1442 this.lastClicked = -1;
1443 this.data = -1;
1444 };
1445
1446 this.enableElementInitialPosition = false;
1447 this.enableElementListenTracker = false;
1448 this.enableElementTimer = false;
1449 this.enableElementTracker = false;
1450 this.enableFlagListenedTo = false;
1451 this.enableFlagMoved = false;
1452 this.enableTestTimer = false;
1453 // Obtain the metrics enabled
1454 for (var i=0; i<specification.metrics.enabled.length; i++)
1455 {
1456 var node = specification.metrics.enabled[i];
1457 switch(node)
1458 {
1459 case 'testTimer':
1460 this.enableTestTimer = true;
1461 break;
1462 case 'elementTimer':
1463 this.enableElementTimer = true;
1464 break;
1465 case 'elementTracker':
1466 this.enableElementTracker = true;
1467 break;
1468 case 'elementListenTracker':
1469 this.enableElementListenTracker = true;
1470 break;
1471 case 'elementInitialPosition':
1472 this.enableElementInitialPosition = true;
1473 break;
1474 case 'elementFlagListenedTo':
1475 this.enableFlagListenedTo = true;
1476 break;
1477 case 'elementFlagMoved':
1478 this.enableFlagMoved = true;
1479 break;
1480 case 'elementFlagComments':
1481 this.enableFlagComments = true;
1482 break;
1483 }
1484 }
1485 this.initialiseTest = function(){};
1486 }
1487
1488 function metricTracker(caller)
1489 {
1490 /* Custom object to track and collect metric data
1491 * Used only inside the audioObjects object.
1492 */
1493
1494 this.listenedTimer = 0;
1495 this.listenStart = 0;
1496 this.listenHold = false;
1497 this.initialPosition = -1;
1498 this.movementTracker = [];
1499 this.listenTracker =[];
1500 this.wasListenedTo = false;
1501 this.wasMoved = false;
1502 this.hasComments = false;
1503 this.parent = caller;
1504
1505 this.initialise = function(position)
1506 {
1507 if (this.initialPosition == -1) {
1508 this.initialPosition = position;
1509 this.moved(0,position);
1510 }
1511 };
1512
1513 this.moved = function(time,position)
1514 {
1515 if (time > 0) {this.wasMoved = true;}
1516 this.movementTracker[this.movementTracker.length] = [time, position];
1517 };
1518
1519 this.startListening = function(time)
1520 {
1521 if (this.listenHold == false)
1522 {
1523 this.wasListenedTo = true;
1524 this.listenStart = time;
1525 this.listenHold = true;
1526
1527 var evnt = document.createElement('event');
1528 var testTime = document.createElement('testTime');
1529 testTime.setAttribute('start',time);
1530 var bufferTime = document.createElement('bufferTime');
1531 bufferTime.setAttribute('start',this.parent.getCurrentPosition());
1532 evnt.appendChild(testTime);
1533 evnt.appendChild(bufferTime);
1534 this.listenTracker.push(evnt);
1535
1536 console.log('slider ' + this.parent.id + ' played (' + time + ')'); // DEBUG/SAFETY: show played slider id
1537 }
1538 };
1539
1540 this.stopListening = function(time,bufferStopTime)
1541 {
1542 if (this.listenHold == true)
1543 {
1544 var diff = time - this.listenStart;
1545 this.listenedTimer += (diff);
1546 this.listenStart = 0;
1547 this.listenHold = false;
1548
1549 var evnt = this.listenTracker[this.listenTracker.length-1];
1550 var testTime = evnt.getElementsByTagName('testTime')[0];
1551 var bufferTime = evnt.getElementsByTagName('bufferTime')[0];
1552 testTime.setAttribute('stop',time);
1553 if (bufferStopTime == undefined) {
1554 bufferTime.setAttribute('stop',this.parent.getCurrentPosition());
1555 } else {
1556 bufferTime.setAttribute('stop',bufferStopTime);
1557 }
1558 console.log('slider ' + this.parent.id + ' played for (' + diff + ')'); // DEBUG/SAFETY: show played slider id
1559 }
1560 };
1561
1562 this.exportXMLDOM = function() {
1563 var storeDOM = [];
1564 if (audioEngineContext.metric.enableElementTimer) {
1565 var mElementTimer = storage.document.createElement('metricresult');
1566 mElementTimer.setAttribute('name','enableElementTimer');
1567 mElementTimer.textContent = this.listenedTimer;
1568 storeDOM.push(mElementTimer);
1569 }
1570 if (audioEngineContext.metric.enableElementTracker) {
1571 var elementTrackerFull = storage.document.createElement('metricResult');
1572 elementTrackerFull.setAttribute('name','elementTrackerFull');
1573 for (var k=0; k<this.movementTracker.length; k++)
1574 {
1575 var timePos = storage.document.createElement('timePos');
1576 timePos.id = k;
1577 var time = storage.document.createElement('time');
1578 time.textContent = this.movementTracker[k][0];
1579 var position = document.createElement('position');
1580 position.textContent = this.movementTracker[k][1];
1581 timePos.appendChild(time);
1582 timePos.appendChild(position);
1583 elementTrackerFull.appendChild(timePos);
1584 }
1585 storeDOM.push(elementTrackerFull);
1586 }
1587 if (audioEngineContext.metric.enableElementListenTracker) {
1588 var elementListenTracker = storage.document.createElement('metricResult');
1589 elementListenTracker.setAttribute('name','elementListenTracker');
1590 for (var k=0; k<this.listenTracker.length; k++) {
1591 elementListenTracker.appendChild(this.listenTracker[k]);
1592 }
1593 storeDOM.push(elementListenTracker);
1594 }
1595 if (audioEngineContext.metric.enableElementInitialPosition) {
1596 var elementInitial = storage.document.createElement('metricResult');
1597 elementInitial.setAttribute('name','elementInitialPosition');
1598 elementInitial.textContent = this.initialPosition;
1599 storeDOM.push(elementInitial);
1600 }
1601 if (audioEngineContext.metric.enableFlagListenedTo) {
1602 var flagListenedTo = storage.document.createElement('metricResult');
1603 flagListenedTo.setAttribute('name','elementFlagListenedTo');
1604 flagListenedTo.textContent = this.wasListenedTo;
1605 storeDOM.push(flagListenedTo);
1606 }
1607 if (audioEngineContext.metric.enableFlagMoved) {
1608 var flagMoved = storage.document.createElement('metricResult');
1609 flagMoved.setAttribute('name','elementFlagMoved');
1610 flagMoved.textContent = this.wasMoved;
1611 storeDOM.push(flagMoved);
1612 }
1613 if (audioEngineContext.metric.enableFlagComments) {
1614 var flagComments = storage.document.createElement('metricResult');
1615 flagComments.setAttribute('name','elementFlagComments');
1616 if (this.parent.commentDOM == null)
1617 {flag.textContent = 'false';}
1618 else if (this.parent.commentDOM.textContent.length == 0)
1619 {flag.textContent = 'false';}
1620 else
1621 {flag.textContet = 'true';}
1622 storeDOM.push(flagComments);
1623 }
1624 return storeDOM;
1625 };
1626 }
1627
1628 function randomiseOrder(input)
1629 {
1630 // This takes an array of information and randomises the order
1631 var N = input.length;
1632
1633 var inputSequence = []; // For safety purposes: keep track of randomisation
1634 for (var counter = 0; counter < N; ++counter)
1635 inputSequence.push(counter) // Fill array
1636 var inputSequenceClone = inputSequence.slice(0);
1637
1638 var holdArr = [];
1639 var outputSequence = [];
1640 for (var n=0; n<N; n++)
1641 {
1642 // First pick a random number
1643 var r = Math.random();
1644 // Multiply and floor by the number of elements left
1645 r = Math.floor(r*input.length);
1646 // Pick out that element and delete from the array
1647 holdArr.push(input.splice(r,1)[0]);
1648 // Do the same with sequence
1649 outputSequence.push(inputSequence.splice(r,1)[0]);
1650 }
1651 console.log(inputSequenceClone.toString()); // print original array to console
1652 console.log(outputSequence.toString()); // print randomised array to console
1653 return holdArr;
1654 }
1655
1656 function returnDateNode()
1657 {
1658 // Create an XML Node for the Date and Time a test was conducted
1659 // Structure is
1660 // <datetime>
1661 // <date year="##" month="##" day="##">DD/MM/YY</date>
1662 // <time hour="##" minute="##" sec="##">HH:MM:SS</time>
1663 // </datetime>
1664 var dateTime = new Date();
1665 var year = document.createAttribute('year');
1666 var month = document.createAttribute('month');
1667 var day = document.createAttribute('day');
1668 var hour = document.createAttribute('hour');
1669 var minute = document.createAttribute('minute');
1670 var secs = document.createAttribute('secs');
1671
1672 year.nodeValue = dateTime.getFullYear();
1673 month.nodeValue = dateTime.getMonth()+1;
1674 day.nodeValue = dateTime.getDate();
1675 hour.nodeValue = dateTime.getHours();
1676 minute.nodeValue = dateTime.getMinutes();
1677 secs.nodeValue = dateTime.getSeconds();
1678
1679 var hold = document.createElement("datetime");
1680 var date = document.createElement("date");
1681 date.textContent = year.nodeValue+'/'+month.nodeValue+'/'+day.nodeValue;
1682 var time = document.createElement("time");
1683 time.textContent = hour.nodeValue+':'+minute.nodeValue+':'+secs.nodeValue;
1684
1685 date.setAttributeNode(year);
1686 date.setAttributeNode(month);
1687 date.setAttributeNode(day);
1688 time.setAttributeNode(hour);
1689 time.setAttributeNode(minute);
1690 time.setAttributeNode(secs);
1691
1692 hold.appendChild(date);
1693 hold.appendChild(time);
1694 return hold;
1695
1696 }
1697
1698 function Specification() {
1699 // Handles the decoding of the project specification XML into a simple JavaScript Object.
1700
1701 this.interface = null;
1702 this.projectReturn = "null";
1703 this.randomiseOrder = null;
1704 this.testPages = null;
1705 this.pages = [];
1706 this.metrics = null;
1707 this.interfaces = null;
1708 this.loudness = null;
1709 this.errors = [];
1710 this.schema = null;
1711
1712 this.processAttribute = function(attribute,schema)
1713 {
1714 // attribute is the string returned from getAttribute on the XML
1715 // schema is the <xs:attribute> node
1716 if (schema.getAttribute('name') == undefined && schema.getAttribute('ref') != undefined)
1717 {
1718 schema = this.schema.getAllElementsByName(schema.getAttribute('ref'))[0];
1719 }
1720 var defaultOpt = schema.getAttribute('default');
1721 if (attribute == null) {
1722 attribute = defaultOpt;
1723 }
1724 var dataType = schema.getAttribute('type');
1725 if (typeof dataType == "string") { dataType = dataType.substr(3);}
1726 else {dataType = "string";}
1727 if (attribute == null)
1728 {
1729 return attribute;
1730 }
1731 switch(dataType)
1732 {
1733 case "boolean":
1734 if (attribute == 'true'){attribute = true;}else{attribute=false;}
1735 break;
1736 case "negativeInteger":
1737 case "positiveInteger":
1738 case "nonNegativeInteger":
1739 case "nonPositiveInteger":
1740 case "integer":
1741 case "decimal":
1742 case "short":
1743 attribute = Number(attribute);
1744 break;
1745 case "string":
1746 default:
1747 attribute = String(attribute);
1748 break;
1749 }
1750 return attribute;
1751 };
1752
1753 this.decode = function(projectXML) {
1754 this.errors = [];
1755 // projectXML - DOM Parsed document
1756 this.projectXML = projectXML.childNodes[0];
1757 var setupNode = projectXML.getElementsByTagName('setup')[0];
1758 var schemaSetup = this.schema.getAllElementsByName('setup')[0];
1759 // First decode the attributes
1760 var attributes = schemaSetup.getAllElementsByTagName('xs:attribute');
1761 for (var i in attributes)
1762 {
1763 if (isNaN(Number(i)) == true){break;}
1764 var attributeName = attributes[i].getAttribute('name');
1765 var projectAttr = setupNode.getAttribute(attributeName);
1766 projectAttr = this.processAttribute(projectAttr,attributes[i]);
1767 switch(typeof projectAttr)
1768 {
1769 case "number":
1770 case "boolean":
1771 eval('this.'+attributeName+' = '+projectAttr);
1772 break;
1773 case "string":
1774 eval('this.'+attributeName+' = "'+projectAttr+'"');
1775 break;
1776 }
1777
1778 }
1779
1780 this.metrics = new this.metricNode();
1781
1782 this.metrics.decode(this,setupNode.getElementsByTagName('metric')[0]);
1783
1784 // Now process the survey node options
1785 var survey = setupNode.getElementsByTagName('survey');
1786 for (var i in survey) {
1787 if (isNaN(Number(i)) == true){break;}
1788 var location = survey[i].getAttribute('location');
1789 if (location == 'pre' || location == 'before')
1790 {
1791 if (this.preTest != null){this.errors.push("Already a pre/before test survey defined! Ignoring second!!");}
1792 else {
1793 this.preTest = new this.surveyNode();
1794 this.preTest.decode(this,survey[i]);
1795 }
1796 } else if (location == 'post' || location == 'after') {
1797 if (this.postTest != null){this.errors.push("Already a post/after test survey defined! Ignoring second!!");}
1798 else {
1799 this.postTest = new this.surveyNode();
1800 this.postTest.decode(this,survey[i]);
1801 }
1802 }
1803 }
1804
1805 var interfaceNode = setupNode.getElementsByTagName('interface');
1806 if (interfaceNode.length > 1)
1807 {
1808 this.errors.push("Only one <interface> node in the <setup> node allowed! Others except first ingnored!");
1809 }
1810 this.interfaces = new this.interfaceNode();
1811 if (interfaceNode.length != 0)
1812 {
1813 interfaceNode = interfaceNode[0];
1814 this.interfaces.decode(this,interfaceNode,this.schema.getAllElementsByName('interface')[1]);
1815 }
1816
1817 // Page tags
1818 var pageTags = projectXML.getElementsByTagName('page');
1819 var pageSchema = this.schema.getAllElementsByName('page')[0];
1820 for (var i=0; i<pageTags.length; i++)
1821 {
1822 var node = new this.page();
1823 node.decode(this,pageTags[i],pageSchema);
1824 this.pages.push(node);
1825 }
1826 };
1827
1828 this.encode = function()
1829 {
1830 var RootDocument = document.implementation.createDocument(null,"waet");
1831 var root = RootDocument.children[0];
1832 root.setAttribute("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");
1833 root.setAttribute("xsi:noNamespaceSchemaLocation","test-schema.xsd");
1834 // Build setup node
1835 var setup = RootDocument.createElement("setup");
1836 var schemaSetup = this.schema.getAllElementsByName('setup')[0];
1837 // First decode the attributes
1838 var attributes = schemaSetup.getAllElementsByTagName('xs:attribute');
1839 for (var i=0; i<attributes.length; i++)
1840 {
1841 var name = attributes[i].getAttribute("name");
1842 if (name == undefined) {
1843 name = attributes[i].getAttribute("ref");
1844 }
1845 if(eval("this."+name+" != undefined") || attributes[i].getAttribute("use") == "required")
1846 {
1847 eval("setup.setAttribute('"+name+"',this."+name+")");
1848 }
1849 }
1850 root.appendChild(setup);
1851 // Survey node
1852 setup.appendChild(this.preTest.encode(RootDocument));
1853 setup.appendChild(this.postTest.encode(RootDocument));
1854 setup.appendChild(this.metrics.encode(RootDocument));
1855 setup.appendChild(this.interfaces.encode(RootDocument));
1856 for (var page of this.pages)
1857 {
1858 root.appendChild(page.encode(RootDocument));
1859 }
1860 return RootDocument;
1861 };
1862
1863 this.surveyNode = function() {
1864 this.location = null;
1865 this.options = [];
1866 this.schema = specification.schema.getAllElementsByName('survey')[0];
1867
1868 this.OptionNode = function() {
1869 this.type = undefined;
1870 this.schema = specification.schema.getAllElementsByName('surveyentry')[0];
1871 this.id = undefined;
1872 this.mandatory = undefined;
1873 this.statement = undefined;
1874 this.boxsize = undefined;
1875 this.options = [];
1876 this.min = undefined;
1877 this.max = undefined;
1878 this.step = undefined;
1879
1880 this.decode = function(parent,child)
1881 {
1882 var attributeMap = this.schema.getAllElementsByTagName('xs:attribute');
1883 for (var i in attributeMap){
1884 if(isNaN(Number(i)) == true){break;}
1885 var attributeName = attributeMap[i].getAttribute('name') || attributeMap[i].getAttribute('ref');
1886 var projectAttr = child.getAttribute(attributeName);
1887 projectAttr = parent.processAttribute(projectAttr,attributeMap[i]);
1888 switch(typeof projectAttr)
1889 {
1890 case "number":
1891 case "boolean":
1892 eval('this.'+attributeName+' = '+projectAttr);
1893 break;
1894 case "string":
1895 eval('this.'+attributeName+' = "'+projectAttr+'"');
1896 break;
1897 }
1898 }
1899 this.statement = child.getElementsByTagName('statement')[0].textContent;
1900 if (this.type == "checkbox" || this.type == "radio") {
1901 var children = child.getElementsByTagName('option');
1902 if (children.length == null) {
1903 console.log('Malformed' +child.nodeName+ 'entry');
1904 this.statement = 'Malformed' +child.nodeName+ 'entry';
1905 this.type = 'statement';
1906 } else {
1907 this.options = [];
1908 for (var i in children)
1909 {
1910 if (isNaN(Number(i))==true){break;}
1911 this.options.push({
1912 name: children[i].getAttribute('name'),
1913 text: children[i].textContent
1914 });
1915 }
1916 }
1917 }
1918 };
1919
1920 this.exportXML = function(doc)
1921 {
1922 var node = doc.createElement('surveyelement');
1923 node.setAttribute('type',this.type);
1924 var statement = doc.createElement('statement');
1925 statement.textContent = this.statement;
1926 node.appendChild(statement);
1927 switch(this.type)
1928 {
1929 case "statement":
1930 break;
1931 case "question":
1932 node.id = this.id;
1933 node.setAttribute("mandatory",this.mandatory);
1934 node.setAttribute("boxsize",this.boxsize);
1935 break;
1936 case "number":
1937 node.id = this.id;
1938 node.setAttribute("mandatory",this.mandatory);
1939 node.setAttribute("min", this.min);
1940 node.setAttribute("max", this.max);
1941 node.setAttribute("step", this.step);
1942 break;
1943 case "checkbox":
1944 case "radio":
1945 node.id = this.id;
1946 for (var i=0; i<this.options.length; i++)
1947 {
1948 var option = this.options[i];
1949 var optionNode = doc.createElement("option");
1950 optionNode.setAttribute("name",option.name);
1951 optionNode.textContent = option.text;
1952 node.appendChild(optionNode);
1953 }
1954 break;
1955 }
1956 return node;
1957 };
1958 };
1959 this.decode = function(parent,xml) {
1960 this.location = xml.getAttribute('location');
1961 if (this.location == 'before'){this.location = 'pre';}
1962 else if (this.location == 'after'){this.location = 'post';}
1963 for (var i in xml.children)
1964 {
1965 if(isNaN(Number(i))==true){break;}
1966 var node = new this.OptionNode();
1967 node.decode(parent,xml.children[i]);
1968 this.options.push(node);
1969 }
1970 };
1971 this.encode = function(doc) {
1972 var node = doc.createElement('survey');
1973 node.setAttribute('location',this.location);
1974 for (var i=0; i<this.options.length; i++)
1975 {
1976 node.appendChild(this.options[i].exportXML(doc));
1977 }
1978 return node;
1979 };
1980 };
1981
1982 this.interfaceNode = function()
1983 {
1984 this.title = null;
1985 this.name = null;
1986 this.options = [];
1987 this.scales = [];
1988 this.schema = specification.schema.getAllElementsByName('interface')[1];
1989
1990 this.decode = function(parent,xml) {
1991 this.name = xml.getAttribute('name');
1992 var titleNode = xml.getElementsByTagName('title');
1993 if (titleNode.length == 1)
1994 {
1995 this.title = titleNode[0].textContent;
1996 }
1997 var interfaceOptionNodes = xml.getElementsByTagName('interfaceoption');
1998 // Extract interfaceoption node schema
1999 var interfaceOptionNodeSchema = this.schema.getAllElementsByName('interfaceoption')[0];
2000 var attributeMap = interfaceOptionNodeSchema.getAllElementsByTagName('xs:attribute');
2001 for (var i=0; i<interfaceOptionNodes.length; i++)
2002 {
2003 var ioNode = interfaceOptionNodes[i];
2004 var option = {};
2005 for (var j=0; j<attributeMap.length; j++)
2006 {
2007 var attributeName = attributeMap[j].getAttribute('name') || attributeMap[j].getAttribute('ref');
2008 var projectAttr = ioNode.getAttribute(attributeName);
2009 projectAttr = parent.processAttribute(projectAttr,attributeMap[j]);
2010 switch(typeof projectAttr)
2011 {
2012 case "number":
2013 case "boolean":
2014 eval('option.'+attributeName+' = '+projectAttr);
2015 break;
2016 case "string":
2017 eval('option.'+attributeName+' = "'+projectAttr+'"');
2018 break;
2019 }
2020 }
2021 this.options.push(option);
2022 }
2023
2024 // Now the scales nodes
2025 var scaleParent = xml.getElementsByTagName('scales');
2026 if (scaleParent.length == 1) {
2027 scaleParent = scaleParent[0];
2028 for (var i=0; i<scaleParent.children.length; i++) {
2029 var child = scaleParent.children[i];
2030 this.scales.push({
2031 text: child.textContent,
2032 position: Number(child.getAttribute('position'))
2033 });
2034 }
2035 }
2036 };
2037
2038 this.encode = function(doc) {
2039 var node = doc.createElement("interface");
2040 if (typeof name == "string")
2041 node.setAttribute("name",this.name);
2042 for (var option of this.options)
2043 {
2044 var child = doc.createElement("interfaceoption");
2045 child.setAttribute("type",option.type);
2046 child.setAttribute("name",option.name);
2047 node.appendChild(child);
2048 }
2049 if (this.scales.length != 0) {
2050 var scales = doc.createElement("scales");
2051 for (var scale of this.scales)
2052 {
2053 var child = doc.createElement("scalelabel");
2054 child.setAttribute("position",scale.position);
2055 child.textContent = scale.text;
2056 scales.appendChild(child);
2057 }
2058 node.appendChild(scales);
2059 }
2060 return node;
2061 };
2062 };
2063
2064 this.metricNode = function() {
2065 this.enabled = [];
2066 this.decode = function(parent, xml) {
2067 var children = xml.getElementsByTagName('metricenable');
2068 for (var i in children) {
2069 if (isNaN(Number(i)) == true){break;}
2070 this.enabled.push(children[i].textContent);
2071 }
2072 }
2073 this.encode = function(doc) {
2074 var node = doc.createElement('metric');
2075 for (var i in this.enabled)
2076 {
2077 if (isNaN(Number(i)) == true){break;}
2078 var child = doc.createElement('metricenable');
2079 child.textContent = this.enabled[i];
2080 node.appendChild(child);
2081 }
2082 return node;
2083 }
2084 }
2085
2086 this.page = function() {
2087 this.presentedId = undefined;
2088 this.id = undefined;
2089 this.hostURL = undefined;
2090 this.randomiseOrder = undefined;
2091 this.loop = undefined;
2092 this.showElementComments = undefined;
2093 this.outsideReference = null;
2094 this.loudness = null;
2095 this.preTest = null;
2096 this.postTest = null;
2097 this.interfaces = [];
2098 this.commentBoxPrefix = "Comment on track";
2099 this.audioElements = [];
2100 this.commentQuestions = [];
2101 this.schema = specification.schema.getAllElementsByName("page")[0];
2102
2103 this.decode = function(parent,xml)
2104 {
2105 var attributeMap = this.schema.getAllElementsByTagName('xs:attribute');
2106 for (var i=0; i<attributeMap.length; i++)
2107 {
2108 var attributeName = attributeMap[i].getAttribute('name') || attributeMap[i].getAttribute('ref');
2109 var projectAttr = xml.getAttribute(attributeName);
2110 projectAttr = parent.processAttribute(projectAttr,attributeMap[i]);
2111 switch(typeof projectAttr)
2112 {
2113 case "number":
2114 case "boolean":
2115 eval('this.'+attributeName+' = '+projectAttr);
2116 break;
2117 case "string":
2118 eval('this.'+attributeName+' = "'+projectAttr+'"');
2119 break;
2120 }
2121 }
2122
2123 // Get the Comment Box Prefix
2124 var CBP = xml.getElementsByTagName('commentboxprefix');
2125 if (CBP.length != 0) {
2126 this.commentBoxPrefix = CBP[0].textContent;
2127 }
2128
2129 // Now decode the interfaces
2130 var interfaceNode = xml.getElementsByTagName('interface');
2131 for (var i=0; i<interfaceNode.length; i++)
2132 {
2133 var node = new parent.interfaceNode();
2134 node.decode(this,interfaceNode[i],parent.schema.getAllElementsByName('interface')[1]);
2135 this.interfaces.push(node);
2136 }
2137
2138 // Now process the survey node options
2139 var survey = xml.getElementsByTagName('survey');
2140 var surveySchema = parent.schema.getAllElementsByName('survey')[0];
2141 for (var i in survey) {
2142 if (isNaN(Number(i)) == true){break;}
2143 var location = survey[i].getAttribute('location');
2144 if (location == 'pre' || location == 'before')
2145 {
2146 if (this.preTest != null){this.errors.push("Already a pre/before test survey defined! Ignoring second!!");}
2147 else {
2148 this.preTest = new parent.surveyNode();
2149 this.preTest.decode(parent,survey[i],surveySchema);
2150 }
2151 } else if (location == 'post' || location == 'after') {
2152 if (this.postTest != null){this.errors.push("Already a post/after test survey defined! Ignoring second!!");}
2153 else {
2154 this.postTest = new parent.surveyNode();
2155 this.postTest.decode(parent,survey[i],surveySchema);
2156 }
2157 }
2158 }
2159
2160 // Now process the audioelement tags
2161 var audioElements = xml.getElementsByTagName('audioelement');
2162 for (var i=0; i<audioElements.length; i++)
2163 {
2164 var node = new this.audioElementNode();
2165 node.decode(this,audioElements[i]);
2166 this.audioElements.push(node);
2167 }
2168
2169 // Now decode the commentquestions
2170 var commentQuestions = xml.getElementsByTagName('commentquestion');
2171 for (var i=0; i<commentQuestions.length; i++)
2172 {
2173 var node = new this.commentQuestionNode();
2174 node.decode(parent,commentQuestions[i]);
2175 this.commentQuestions.push(node);
2176 }
2177 };
2178
2179 this.encode = function(root)
2180 {
2181 var AHNode = root.createElement("page");
2182 // First decode the attributes
2183 var attributes = this.schema.getAllElementsByTagName('xs:attribute');
2184 for (var i=0; i<attributes.length; i++)
2185 {
2186 var name = attributes[i].getAttribute("name");
2187 if (name == undefined) {
2188 name = attributes[i].getAttribute("ref");
2189 }
2190 if(eval("this."+name+" != undefined") || attributes[i].getAttribute("use") == "required")
2191 {
2192 eval("AHNode.setAttribute('"+name+"',this."+name+")");
2193 }
2194 }
2195 if(this.loudness != null) {AHNode.setAttribute("loudness",this.loudness);}
2196 // <commentboxprefix>
2197 var commentboxprefix = root.createElement("commentboxprefix");
2198 commentboxprefix.textContent = this.commentBoxPrefix;
2199 AHNode.appendChild(commentboxprefix);
2200
2201 for (var i=0; i<this.interfaces.length; i++)
2202 {
2203 AHNode.appendChild(this.interfaces[i].encode(root));
2204 }
2205
2206 for (var i=0; i<this.audioElements.length; i++) {
2207 AHNode.appendChild(this.audioElements[i].encode(root));
2208 }
2209 // Create <CommentQuestion>
2210 for (var i=0; i<this.commentQuestions.length; i++)
2211 {
2212 AHNode.appendChild(this.commentQuestions[i].encode(root));
2213 }
2214
2215 AHNode.appendChild(this.preTest.encode(root));
2216 AHNode.appendChild(this.postTest.encode(root));
2217 return AHNode;
2218 };
2219
2220 this.commentQuestionNode = function() {
2221 this.id = null;
2222 this.type = undefined;
2223 this.options = [];
2224 this.statement = undefined;
2225 this.schema = specification.schema.getAllElementsByName('commentquestion')[0];
2226 this.decode = function(parent,xml)
2227 {
2228 this.id = xml.id;
2229 this.type = xml.getAttribute('type');
2230 this.statement = xml.getElementsByTagName('statement')[0].textContent;
2231 var optNodes = xml.getElementsByTagName('option');
2232 for (var i=0; i<optNodes.length; i++)
2233 {
2234 var optNode = optNodes[i];
2235 this.options.push({
2236 name: optNode.getAttribute('name'),
2237 text: optNode.textContent
2238 });
2239 }
2240 };
2241
2242 this.encode = function(root)
2243 {
2244 var node = root.createElement("commentquestion");
2245 node.id = this.id;
2246 node.setAttribute("type",this.type);
2247 var statement = root.createElement("statement");
2248 statement.textContent = this.statement;
2249 node.appendChild(statement);
2250 for (var option of this.options)
2251 {
2252 var child = root.createElement("option");
2253 child.setAttribute("name",option.name);
2254 child.textContent = option.text;
2255 node.appendChild(child);
2256 }
2257 return node;
2258 };
2259 };
2260
2261 this.audioElementNode = function() {
2262 this.url = null;
2263 this.id = null;
2264 this.parent = null;
2265 this.type = null;
2266 this.marker = false;
2267 this.enforce = false;
2268 this.gain = 1.0;
2269 this.schema = specification.schema.getAllElementsByName('audioelement')[0];;
2270 this.parent = null;
2271 this.decode = function(parent,xml)
2272 {
2273 this.parent = parent;
2274 var attributeMap = this.schema.getAllElementsByTagName('xs:attribute');
2275 for (var i=0; i<attributeMap.length; i++)
2276 {
2277 var attributeName = attributeMap[i].getAttribute('name') || attributeMap[i].getAttribute('ref');
2278 var projectAttr = xml.getAttribute(attributeName);
2279 projectAttr = specification.processAttribute(projectAttr,attributeMap[i]);
2280 switch(typeof projectAttr)
2281 {
2282 case "number":
2283 case "boolean":
2284 eval('this.'+attributeName+' = '+projectAttr);
2285 break;
2286 case "string":
2287 eval('this.'+attributeName+' = "'+projectAttr+'"');
2288 break;
2289 }
2290 }
2291
2292 };
2293 this.encode = function(root)
2294 {
2295 var AENode = root.createElement("audioelement");
2296 var attributes = this.schema.getAllElementsByTagName('xs:attribute');
2297 for (var i=0; i<attributes.length; i++)
2298 {
2299 var name = attributes[i].getAttribute("name");
2300 if (name == undefined) {
2301 name = attributes[i].getAttribute("ref");
2302 }
2303 if(eval("this."+name+" != undefined") || attributes[i].getAttribute("use") == "required")
2304 {
2305 eval("AENode.setAttribute('"+name+"',this."+name+")");
2306 }
2307 }
2308 return AENode;
2309 };
2310 };
2311 };
2312 }
2313
2314 function Interface(specificationObject) {
2315 // This handles the bindings between the interface and the audioEngineContext;
2316 this.specification = specificationObject;
2317 this.insertPoint = document.getElementById("topLevelBody");
2318
2319 this.newPage = function(audioHolderObject,store)
2320 {
2321 audioEngineContext.newTestPage(audioHolderObject,store);
2322 interfaceContext.deleteCommentBoxes();
2323 interfaceContext.deleteCommentQuestions();
2324 loadTest(audioHolderObject,store);
2325 };
2326
2327 // Bounded by interface!!
2328 // Interface object MUST have an exportXMLDOM method which returns the various DOM levels
2329 // For example, APE returns the slider position normalised in a <value> tag.
2330 this.interfaceObjects = [];
2331 this.interfaceObject = function(){};
2332
2333 this.resizeWindow = function(event)
2334 {
2335 popup.resize(event);
2336 for(var i=0; i<this.commentBoxes.length; i++)
2337 {this.commentBoxes[i].resize();}
2338 for(var i=0; i<this.commentQuestions.length; i++)
2339 {this.commentQuestions[i].resize();}
2340 try
2341 {
2342 resizeWindow(event);
2343 }
2344 catch(err)
2345 {
2346 console.log("Warning - Interface does not have Resize option");
2347 console.log(err);
2348 }
2349 };
2350
2351 this.returnNavigator = function()
2352 {
2353 var node = storage.document.createElement("navigator");
2354 var platform = storage.document.createElement("platform");
2355 platform.textContent = navigator.platform;
2356 var vendor = storage.document.createElement("vendor");
2357 vendor.textContent = navigator.vendor;
2358 var userAgent = storage.document.createElement("uagent");
2359 userAgent.textContent = navigator.userAgent;
2360 var screen = storage.document.createElement("window");
2361 screen.setAttribute('innerWidth',window.innerWidth);
2362 screen.setAttribute('innerHeight',window.innerHeight);
2363 node.appendChild(platform);
2364 node.appendChild(vendor);
2365 node.appendChild(userAgent);
2366 node.appendChild(screen);
2367 return node;
2368 };
2369
2370 this.commentBoxes = [];
2371 this.elementCommentBox = function(audioObject) {
2372 var element = audioObject.specification;
2373 this.audioObject = audioObject;
2374 this.id = audioObject.id;
2375 var audioHolderObject = audioObject.specification.parent;
2376 // Create document objects to hold the comment boxes
2377 this.trackComment = document.createElement('div');
2378 this.trackComment.className = 'comment-div';
2379 this.trackComment.id = 'comment-div-'+audioObject.id;
2380 // Create a string next to each comment asking for a comment
2381 this.trackString = document.createElement('span');
2382 this.trackString.innerHTML = audioHolderObject.commentBoxPrefix+' '+audioObject.interfaceDOM.getPresentedId();
2383 // Create the HTML5 comment box 'textarea'
2384 this.trackCommentBox = document.createElement('textarea');
2385 this.trackCommentBox.rows = '4';
2386 this.trackCommentBox.cols = '100';
2387 this.trackCommentBox.name = 'trackComment'+audioObject.id;
2388 this.trackCommentBox.className = 'trackComment';
2389 var br = document.createElement('br');
2390 // Add to the holder.
2391 this.trackComment.appendChild(this.trackString);
2392 this.trackComment.appendChild(br);
2393 this.trackComment.appendChild(this.trackCommentBox);
2394
2395 this.exportXMLDOM = function() {
2396 var root = document.createElement('comment');
2397 if (this.audioObject.specification.parent.elementComments) {
2398 var question = document.createElement('question');
2399 question.textContent = this.trackString.textContent;
2400 var response = document.createElement('response');
2401 response.textContent = this.trackCommentBox.value;
2402 console.log("Comment frag-"+this.id+": "+response.textContent);
2403 root.appendChild(question);
2404 root.appendChild(response);
2405 }
2406 return root;
2407 };
2408 this.resize = function()
2409 {
2410 var boxwidth = (window.innerWidth-100)/2;
2411 if (boxwidth >= 600)
2412 {
2413 boxwidth = 600;
2414 }
2415 else if (boxwidth < 400)
2416 {
2417 boxwidth = 400;
2418 }
2419 this.trackComment.style.width = boxwidth+"px";
2420 this.trackCommentBox.style.width = boxwidth-6+"px";
2421 };
2422 this.resize();
2423 };
2424
2425 this.commentQuestions = [];
2426
2427 this.commentBox = function(commentQuestion) {
2428 this.specification = commentQuestion;
2429 // Create document objects to hold the comment boxes
2430 this.holder = document.createElement('div');
2431 this.holder.className = 'comment-div';
2432 // Create a string next to each comment asking for a comment
2433 this.string = document.createElement('span');
2434 this.string.innerHTML = commentQuestion.statement;
2435 // Create the HTML5 comment box 'textarea'
2436 this.textArea = document.createElement('textarea');
2437 this.textArea.rows = '4';
2438 this.textArea.cols = '100';
2439 this.textArea.className = 'trackComment';
2440 var br = document.createElement('br');
2441 // Add to the holder.
2442 this.holder.appendChild(this.string);
2443 this.holder.appendChild(br);
2444 this.holder.appendChild(this.textArea);
2445
2446 this.exportXMLDOM = function() {
2447 var root = document.createElement('comment');
2448 root.id = this.specification.id;
2449 root.setAttribute('type',this.specification.type);
2450 root.textContent = this.textArea.value;
2451 console.log("Question: "+this.string.textContent);
2452 console.log("Response: "+root.textContent);
2453 return root;
2454 };
2455 this.resize = function()
2456 {
2457 var boxwidth = (window.innerWidth-100)/2;
2458 if (boxwidth >= 600)
2459 {
2460 boxwidth = 600;
2461 }
2462 else if (boxwidth < 400)
2463 {
2464 boxwidth = 400;
2465 }
2466 this.holder.style.width = boxwidth+"px";
2467 this.textArea.style.width = boxwidth-6+"px";
2468 };
2469 this.resize();
2470 };
2471
2472 this.radioBox = function(commentQuestion) {
2473 this.specification = commentQuestion;
2474 // Create document objects to hold the comment boxes
2475 this.holder = document.createElement('div');
2476 this.holder.className = 'comment-div';
2477 // Create a string next to each comment asking for a comment
2478 this.string = document.createElement('span');
2479 this.string.innerHTML = commentQuestion.statement;
2480 var br = document.createElement('br');
2481 // Add to the holder.
2482 this.holder.appendChild(this.string);
2483 this.holder.appendChild(br);
2484 this.options = [];
2485 this.inputs = document.createElement('div');
2486 this.span = document.createElement('div');
2487 this.inputs.align = 'center';
2488 this.inputs.style.marginLeft = '12px';
2489 this.span.style.marginLeft = '12px';
2490 this.span.align = 'center';
2491 this.span.style.marginTop = '15px';
2492
2493 var optCount = commentQuestion.options.length;
2494 for (var optNode of commentQuestion.options)
2495 {
2496 var div = document.createElement('div');
2497 div.style.width = '80px';
2498 div.style.float = 'left';
2499 var input = document.createElement('input');
2500 input.type = 'radio';
2501 input.name = commentQuestion.id;
2502 input.setAttribute('setvalue',optNode.name);
2503 input.className = 'comment-radio';
2504 div.appendChild(input);
2505 this.inputs.appendChild(div);
2506
2507
2508 div = document.createElement('div');
2509 div.style.width = '80px';
2510 div.style.float = 'left';
2511 div.align = 'center';
2512 var span = document.createElement('span');
2513 span.textContent = optNode.text;
2514 span.className = 'comment-radio-span';
2515 div.appendChild(span);
2516 this.span.appendChild(div);
2517 this.options.push(input);
2518 }
2519 this.holder.appendChild(this.span);
2520 this.holder.appendChild(this.inputs);
2521
2522 this.exportXMLDOM = function() {
2523 var root = document.createElement('comment');
2524 root.id = this.specification.id;
2525 root.setAttribute('type',this.specification.type);
2526 var question = document.createElement('question');
2527 question.textContent = this.string.textContent;
2528 var response = document.createElement('response');
2529 var i=0;
2530 while(this.options[i].checked == false) {
2531 i++;
2532 if (i >= this.options.length) {
2533 break;
2534 }
2535 }
2536 if (i >= this.options.length) {
2537 response.textContent = 'null';
2538 } else {
2539 response.textContent = this.options[i].getAttribute('setvalue');
2540 response.setAttribute('number',i);
2541 }
2542 console.log('Comment: '+question.textContent);
2543 console.log('Response: '+response.textContent);
2544 root.appendChild(question);
2545 root.appendChild(response);
2546 return root;
2547 };
2548 this.resize = function()
2549 {
2550 var boxwidth = (window.innerWidth-100)/2;
2551 if (boxwidth >= 600)
2552 {
2553 boxwidth = 600;
2554 }
2555 else if (boxwidth < 400)
2556 {
2557 boxwidth = 400;
2558 }
2559 this.holder.style.width = boxwidth+"px";
2560 var text = this.holder.children[2];
2561 var options = this.holder.children[3];
2562 var optCount = options.children.length;
2563 var spanMargin = Math.floor(((boxwidth-20-(optCount*80))/(optCount))/2)+'px';
2564 var options = options.firstChild;
2565 var text = text.firstChild;
2566 options.style.marginRight = spanMargin;
2567 options.style.marginLeft = spanMargin;
2568 text.style.marginRight = spanMargin;
2569 text.style.marginLeft = spanMargin;
2570 while(options.nextSibling != undefined)
2571 {
2572 options = options.nextSibling;
2573 text = text.nextSibling;
2574 options.style.marginRight = spanMargin;
2575 options.style.marginLeft = spanMargin;
2576 text.style.marginRight = spanMargin;
2577 text.style.marginLeft = spanMargin;
2578 }
2579 };
2580 this.resize();
2581 };
2582
2583 this.checkboxBox = function(commentQuestion) {
2584 this.specification = commentQuestion;
2585 // Create document objects to hold the comment boxes
2586 this.holder = document.createElement('div');
2587 this.holder.className = 'comment-div';
2588 // Create a string next to each comment asking for a comment
2589 this.string = document.createElement('span');
2590 this.string.innerHTML = commentQuestion.statement;
2591 var br = document.createElement('br');
2592 // Add to the holder.
2593 this.holder.appendChild(this.string);
2594 this.holder.appendChild(br);
2595 this.options = [];
2596 this.inputs = document.createElement('div');
2597 this.span = document.createElement('div');
2598 this.inputs.align = 'center';
2599 this.inputs.style.marginLeft = '12px';
2600 this.span.style.marginLeft = '12px';
2601 this.span.align = 'center';
2602 this.span.style.marginTop = '15px';
2603
2604 var optCount = commentQuestion.options.length;
2605 for (var i=0; i<optCount; i++)
2606 {
2607 var div = document.createElement('div');
2608 div.style.width = '80px';
2609 div.style.float = 'left';
2610 var input = document.createElement('input');
2611 input.type = 'checkbox';
2612 input.name = commentQuestion.id;
2613 input.setAttribute('setvalue',commentQuestion.options[i].name);
2614 input.className = 'comment-radio';
2615 div.appendChild(input);
2616 this.inputs.appendChild(div);
2617
2618
2619 div = document.createElement('div');
2620 div.style.width = '80px';
2621 div.style.float = 'left';
2622 div.align = 'center';
2623 var span = document.createElement('span');
2624 span.textContent = commentQuestion.options[i].text;
2625 span.className = 'comment-radio-span';
2626 div.appendChild(span);
2627 this.span.appendChild(div);
2628 this.options.push(input);
2629 }
2630 this.holder.appendChild(this.span);
2631 this.holder.appendChild(this.inputs);
2632
2633 this.exportXMLDOM = function() {
2634 var root = document.createElement('comment');
2635 root.id = this.specification.id;
2636 root.setAttribute('type',this.specification.type);
2637 var question = document.createElement('question');
2638 question.textContent = this.string.textContent;
2639 root.appendChild(question);
2640 console.log('Comment: '+question.textContent);
2641 for (var i=0; i<this.options.length; i++) {
2642 var response = document.createElement('response');
2643 response.textContent = this.options[i].checked;
2644 response.setAttribute('name',this.options[i].getAttribute('setvalue'));
2645 root.appendChild(response);
2646 console.log('Response '+response.getAttribute('name') +': '+response.textContent);
2647 }
2648 return root;
2649 };
2650 this.resize = function()
2651 {
2652 var boxwidth = (window.innerWidth-100)/2;
2653 if (boxwidth >= 600)
2654 {
2655 boxwidth = 600;
2656 }
2657 else if (boxwidth < 400)
2658 {
2659 boxwidth = 400;
2660 }
2661 this.holder.style.width = boxwidth+"px";
2662 var text = this.holder.children[2];
2663 var options = this.holder.children[3];
2664 var optCount = options.children.length;
2665 var spanMargin = Math.floor(((boxwidth-20-(optCount*80))/(optCount))/2)+'px';
2666 var options = options.firstChild;
2667 var text = text.firstChild;
2668 options.style.marginRight = spanMargin;
2669 options.style.marginLeft = spanMargin;
2670 text.style.marginRight = spanMargin;
2671 text.style.marginLeft = spanMargin;
2672 while(options.nextSibling != undefined)
2673 {
2674 options = options.nextSibling;
2675 text = text.nextSibling;
2676 options.style.marginRight = spanMargin;
2677 options.style.marginLeft = spanMargin;
2678 text.style.marginRight = spanMargin;
2679 text.style.marginLeft = spanMargin;
2680 }
2681 };
2682 this.resize();
2683 };
2684
2685 this.createCommentBox = function(audioObject) {
2686 var node = new this.elementCommentBox(audioObject);
2687 this.commentBoxes.push(node);
2688 audioObject.commentDOM = node;
2689 return node;
2690 };
2691
2692 this.sortCommentBoxes = function() {
2693 this.commentBoxes.sort(function(a,b){return a.id - b.id;});
2694 };
2695
2696 this.showCommentBoxes = function(inject, sort) {
2697 if (sort) {interfaceContext.sortCommentBoxes();}
2698 for (var box of interfaceContext.commentBoxes) {
2699 inject.appendChild(box.trackComment);
2700 }
2701 };
2702
2703 this.deleteCommentBoxes = function() {
2704 this.commentBoxes = [];
2705 };
2706
2707 this.createCommentQuestion = function(element) {
2708 var node;
2709 if (element.type == 'question') {
2710 node = new this.commentBox(element);
2711 } else if (element.type == 'radio') {
2712 node = new this.radioBox(element);
2713 } else if (element.type == 'checkbox') {
2714 node = new this.checkboxBox(element);
2715 }
2716 this.commentQuestions.push(node);
2717 return node;
2718 };
2719
2720 this.deleteCommentQuestions = function()
2721 {
2722 this.commentQuestions = [];
2723 };
2724
2725 this.playhead = new function()
2726 {
2727 this.object = document.createElement('div');
2728 this.object.className = 'playhead';
2729 this.object.align = 'left';
2730 var curTime = document.createElement('div');
2731 curTime.style.width = '50px';
2732 this.curTimeSpan = document.createElement('span');
2733 this.curTimeSpan.textContent = '00:00';
2734 curTime.appendChild(this.curTimeSpan);
2735 this.object.appendChild(curTime);
2736 this.scrubberTrack = document.createElement('div');
2737 this.scrubberTrack.className = 'playhead-scrub-track';
2738
2739 this.scrubberHead = document.createElement('div');
2740 this.scrubberHead.id = 'playhead-scrubber';
2741 this.scrubberTrack.appendChild(this.scrubberHead);
2742 this.object.appendChild(this.scrubberTrack);
2743
2744 this.timePerPixel = 0;
2745 this.maxTime = 0;
2746
2747 this.playbackObject;
2748
2749 this.setTimePerPixel = function(audioObject) {
2750 //maxTime must be in seconds
2751 this.playbackObject = audioObject;
2752 this.maxTime = audioObject.buffer.buffer.duration;
2753 var width = 490; //500 - 10, 5 each side of the tracker head
2754 this.timePerPixel = this.maxTime/490;
2755 if (this.maxTime < 60) {
2756 this.curTimeSpan.textContent = '0.00';
2757 } else {
2758 this.curTimeSpan.textContent = '00:00';
2759 }
2760 };
2761
2762 this.update = function() {
2763 // Update the playhead position, startPlay must be called
2764 if (this.timePerPixel > 0) {
2765 var time = this.playbackObject.getCurrentPosition();
2766 if (time > 0 && time < this.maxTime) {
2767 var width = 490;
2768 var pix = Math.floor(time/this.timePerPixel);
2769 this.scrubberHead.style.left = pix+'px';
2770 if (this.maxTime > 60.0) {
2771 var secs = time%60;
2772 var mins = Math.floor((time-secs)/60);
2773 secs = secs.toString();
2774 secs = secs.substr(0,2);
2775 mins = mins.toString();
2776 this.curTimeSpan.textContent = mins+':'+secs;
2777 } else {
2778 time = time.toString();
2779 this.curTimeSpan.textContent = time.substr(0,4);
2780 }
2781 } else {
2782 this.scrubberHead.style.left = '0px';
2783 if (this.maxTime < 60) {
2784 this.curTimeSpan.textContent = '0.00';
2785 } else {
2786 this.curTimeSpan.textContent = '00:00';
2787 }
2788 }
2789 }
2790 };
2791
2792 this.interval = undefined;
2793
2794 this.start = function() {
2795 if (this.playbackObject != undefined && this.interval == undefined) {
2796 if (this.maxTime < 60) {
2797 this.interval = setInterval(function(){interfaceContext.playhead.update();},10);
2798 } else {
2799 this.interval = setInterval(function(){interfaceContext.playhead.update();},100);
2800 }
2801 }
2802 };
2803 this.stop = function() {
2804 clearInterval(this.interval);
2805 this.interval = undefined;
2806 if (this.maxTime < 60) {
2807 this.curTimeSpan.textContent = '0.00';
2808 } else {
2809 this.curTimeSpan.textContent = '00:00';
2810 }
2811 };
2812 };
2813
2814 this.volume = new function()
2815 {
2816 // An in-built volume module which can be viewed on page
2817 // Includes trackers on page-by-page data
2818 // Volume does NOT reset to 0dB on each page load
2819 this.valueLin = 1.0;
2820 this.valueDB = 0.0;
2821 this.object = document.createElement('div');
2822 this.object.id = 'master-volume-holder';
2823 this.slider = document.createElement('input');
2824 this.slider.id = 'master-volume-control';
2825 this.slider.type = 'range';
2826 this.valueText = document.createElement('span');
2827 this.valueText.id = 'master-volume-feedback';
2828 this.valueText.textContent = '0dB';
2829
2830 this.slider.min = -60;
2831 this.slider.max = 12;
2832 this.slider.value = 0;
2833 this.slider.step = 1;
2834 this.slider.onmousemove = function(event)
2835 {
2836 interfaceContext.volume.valueDB = event.currentTarget.value;
2837 interfaceContext.volume.valueLin = decibelToLinear(interfaceContext.volume.valueDB);
2838 interfaceContext.volume.valueText.textContent = interfaceContext.volume.valueDB+'dB';
2839 audioEngineContext.outputGain.gain.value = interfaceContext.volume.valueLin;
2840 }
2841 this.slider.onmouseup = function(event)
2842 {
2843 var storePoint = testState.currentStore.XMLDOM.children[0].getAllElementsByName('volumeTracker');
2844 if (storePoint.length == 0)
2845 {
2846 storePoint = storage.document.createElement('metricresult');
2847 storePoint.setAttribute('name','volumeTracker');
2848 testState.currentStore.XMLDOM.children[0].appendChild(storePoint);
2849 }
2850 else {
2851 storePoint = storePoint[0];
2852 }
2853 var node = storage.document.createElement('movement');
2854 node.setAttribute('test-time',audioEngineContext.timer.getTestTime());
2855 node.setAttribute('volume',interfaceContext.volume.valueDB);
2856 node.setAttribute('format','dBFS');
2857 storePoint.appendChild(node);
2858 }
2859
2860 var title = document.createElement('div');
2861 title.innerHTML = '<span>Master Volume Control</span>';
2862 title.style.fontSize = '0.75em';
2863 title.style.width = "100%";
2864 title.align = 'center';
2865 this.object.appendChild(title);
2866
2867 this.object.appendChild(this.slider);
2868 this.object.appendChild(this.valueText);
2869 }
2870 // Global Checkers
2871 // These functions will help enforce the checkers
2872 this.checkHiddenAnchor = function()
2873 {
2874 for (var ao of audioEngineContext.audioObjects)
2875 {
2876 if (ao.specification.type == "anchor")
2877 {
2878 if (ao.interfaceDOM.getValue() > (ao.specification.marker/100) && ao.specification.marker > 0) {
2879 // Anchor is not set below
2880 console.log('Anchor node not below marker value');
2881 alert('Please keep listening');
2882 this.storeErrorNode('Anchor node not below marker value');
2883 return false;
2884 }
2885 }
2886 }
2887 return true;
2888 };
2889
2890 this.checkHiddenReference = function()
2891 {
2892 for (var ao of audioEngineContext.audioObjects)
2893 {
2894 if (ao.specification.type == "reference")
2895 {
2896 if (ao.interfaceDOM.getValue() < (ao.specification.marker/100) && ao.specification.marker > 0) {
2897 // Anchor is not set below
2898 console.log('Reference node not above marker value');
2899 this.storeErrorNode('Reference node not above marker value');
2900 alert('Please keep listening');
2901 return false;
2902 }
2903 }
2904 }
2905 return true;
2906 };
2907
2908 this.checkFragmentsFullyPlayed = function ()
2909 {
2910 // Checks the entire file has been played back
2911 // NOTE ! This will return true IF playback is Looped!!!
2912 if (audioEngineContext.loopPlayback)
2913 {
2914 console.log("WARNING - Looped source: Cannot check fragments are fully played");
2915 return true;
2916 }
2917 var check_pass = true;
2918 var error_obj = [];
2919 for (var i = 0; i<audioEngineContext.audioObjects.length; i++)
2920 {
2921 var object = audioEngineContext.audioObjects[i];
2922 var time = object.buffer.buffer.duration;
2923 var metric = object.metric;
2924 var passed = false;
2925 for (var j=0; j<metric.listenTracker.length; j++)
2926 {
2927 var bt = metric.listenTracker[j].getElementsByTagName('buffertime');
2928 var start_time = Number(bt[0].getAttribute('start'));
2929 var stop_time = Number(bt[0].getAttribute('stop'));
2930 var delta = stop_time - start_time;
2931 if (delta >= time)
2932 {
2933 passed = true;
2934 break;
2935 }
2936 }
2937 if (passed == false)
2938 {
2939 check_pass = false;
2940 console.log("Continue listening to track-"+audioEngineContext.audioObjects.interfaceDOM.getPresentedId());
2941 error_obj.push(audioEngineContext.audioObjects.interfaceDOM.getPresentedId());
2942 }
2943 }
2944 if (check_pass == false)
2945 {
2946 var str_start = "You have not completely listened to fragments ";
2947 for (var i=0; i<error_obj.length; i++)
2948 {
2949 str_start += error_obj[i];
2950 if (i != error_obj.length-1)
2951 {
2952 str_start += ', ';
2953 }
2954 }
2955 str_start += ". Please keep listening";
2956 console.log("[ALERT]: "+str_start);
2957 this.storeErrorNode("[ALERT]: "+str_start);
2958 alert(str_start);
2959 }
2960 };
2961 this.checkAllMoved = function()
2962 {
2963 var str = "You have not moved ";
2964 var failed = [];
2965 for (var ao of audioEngineContext.audioObjects)
2966 {
2967 if(ao.metric.wasMoved == false && ao.interfaceDOM.canMove() == true)
2968 {
2969 failed.push(ao.interfaceDOM.getPresentedId());
2970 }
2971 }
2972 if (failed.length == 0)
2973 {
2974 return true;
2975 } else if (failed.length == 1)
2976 {
2977 str += 'track '+failed[0];
2978 } else {
2979 str += 'tracks ';
2980 for (var i=0; i<failed.length-1; i++)
2981 {
2982 str += failed[i]+', ';
2983 }
2984 str += 'and '+failed[i];
2985 }
2986 str +='.';
2987 alert(str);
2988 console.log(str);
2989 this.storeErrorNode(str);
2990 return false;
2991 };
2992 this.checkAllPlayed = function()
2993 {
2994 var str = "You have not played ";
2995 var failed = [];
2996 for (var ao of audioEngineContext.audioObjects)
2997 {
2998 if(ao.metric.wasListenedTo == false)
2999 {
3000 failed.push(ao.interfaceDOM.getPresentedId());
3001 }
3002 }
3003 if (failed.length == 0)
3004 {
3005 return true;
3006 } else if (failed.length == 1)
3007 {
3008 str += 'track '+failed[0];
3009 } else {
3010 str += 'tracks ';
3011 for (var i=0; i<failed.length-1; i++)
3012 {
3013 str += failed[i]+', ';
3014 }
3015 str += 'and '+failed[i];
3016 }
3017 str +='.';
3018 alert(str);
3019 console.log(str);
3020 this.storeErrorNode(str);
3021 return false;
3022 };
3023
3024 this.storeErrorNode = function(errorMessage)
3025 {
3026 var time = audioEngineContext.timer.getTestTime();
3027 var node = storage.document.createElement('error');
3028 node.setAttribute('time',time);
3029 node.textContent = errorMessage;
3030 testState.currentStore.XMLDOM.appendChild(node);
3031 };
3032 }
3033
3034 function Storage()
3035 {
3036 // Holds results in XML format until ready for collection
3037 this.globalPreTest = null;
3038 this.globalPostTest = null;
3039 this.testPages = [];
3040 this.document = document.implementation.createDocument(null,"waetresult");
3041 this.root = this.document.children[0];
3042 this.state = 0;
3043
3044 this.initialise = function()
3045 {
3046 if (specification.preTest != undefined){this.globalPreTest = new this.surveyNode(this,this.root,specification.preTest);}
3047 if (specification.postTest != undefined){this.globalPostTest = new this.surveyNode(this,this.root,specification.postTest);}
3048 };
3049
3050 this.createTestPageStore = function(specification)
3051 {
3052 var store = new this.pageNode(this,specification);
3053 this.testPages.push(store);
3054 return this.testPages[this.testPages.length-1];
3055 };
3056
3057 this.surveyNode = function(parent,root,specification)
3058 {
3059 this.specification = specification;
3060 this.parent = parent;
3061 this.XMLDOM = this.parent.document.createElement('survey');
3062 this.XMLDOM.setAttribute('location',this.specification.location);
3063 for (var optNode of this.specification.options)
3064 {
3065 if (optNode.type != 'statement')
3066 {
3067 var node = this.parent.document.createElement('surveyresult');
3068 node.id = optNode.id;
3069 node.setAttribute('type',optNode.type);
3070 this.XMLDOM.appendChild(node);
3071 }
3072 }
3073 root.appendChild(this.XMLDOM);
3074
3075 this.postResult = function(node)
3076 {
3077 // From popup: node is the popupOption node containing both spec. and results
3078 // ID is the position
3079 if (node.specification.type == 'statement'){return;}
3080 var surveyresult = this.parent.document.getElementById(node.specification.id);
3081 switch(node.specification.type)
3082 {
3083 case "number":
3084 case "question":
3085 var child = this.parent.document.createElement('response');
3086 child.textContent = node.response;
3087 surveyresult.appendChild(child);
3088 break;
3089 case "radio":
3090 var child = this.parent.document.createElement('response');
3091 child.setAttribute('name',node.response.name);
3092 child.textContent = node.response.text;
3093 surveyresult.appendChild(child);
3094 break;
3095 case "checkbox":
3096 for (var i=0; i<node.response.length; i++)
3097 {
3098 var checkNode = this.parent.document.createElement('response');
3099 checkNode.setAttribute('name',node.response[i].name);
3100 checkNode.setAttribute('checked',node.response[i].checked);
3101 surveyresult.appendChild(checkNode);
3102 }
3103 break;
3104 }
3105 };
3106 };
3107
3108 this.pageNode = function(parent,specification)
3109 {
3110 // Create one store per test page
3111 this.specification = specification;
3112 this.parent = parent;
3113 this.XMLDOM = this.parent.document.createElement('page');
3114 this.XMLDOM.setAttribute('id',specification.id);
3115 this.XMLDOM.setAttribute('presentedId',specification.presentedId);
3116 if (specification.preTest != undefined){this.preTest = new this.parent.surveyNode(this.parent,this.XMLDOM,this.specification.preTest);}
3117 if (specification.postTest != undefined){this.postTest = new this.parent.surveyNode(this.parent,this.XMLDOM,this.specification.postTest);}
3118
3119 // Add any page metrics
3120 var page_metric = this.parent.document.createElement('metric');
3121 this.XMLDOM.appendChild(page_metric);
3122
3123 // Add the audioelement
3124 for (var element of this.specification.audioElements)
3125 {
3126 var aeNode = this.parent.document.createElement('audioelement');
3127 aeNode.id = element.id;
3128 aeNode.setAttribute('type',element.type);
3129 aeNode.setAttribute('url', element.url);
3130 aeNode.setAttribute('gain', element.gain);
3131 if (element.type == 'anchor' || element.type == 'reference')
3132 {
3133 if (element.marker > 0)
3134 {
3135 aeNode.setAttribute('marker',element.marker);
3136 }
3137 }
3138 var ae_metric = this.parent.document.createElement('metric');
3139 aeNode.appendChild(ae_metric);
3140 this.XMLDOM.appendChild(aeNode);
3141 }
3142
3143 // Add any commentQuestions
3144 for (var element of this.specification.commentQuestions)
3145 {
3146 var cqNode = this.parent.document.createElement('commentquestion');
3147 cqNode.id = element.id;
3148 cqNode.setAttribute('type',element.type);
3149 var statement = this.parent.document.createElement('statement');
3150 statement.textContent = cqNode.statement;
3151 cqNode.appendChild(statement);
3152 var response = this.parent.document.createElement('response');
3153 cqNode.appendChild(response);
3154 this.XMLDOM.appendChild(cqNode);
3155 }
3156
3157 this.parent.root.appendChild(this.XMLDOM);
3158 };
3159 this.finish = function()
3160 {
3161 if (this.state == 0)
3162 {
3163 var projectDocument = specification.projectXML;
3164 projectDocument.setAttribute('file-name',url);
3165 this.root.appendChild(projectDocument);
3166 this.root.appendChild(returnDateNode());
3167 this.root.appendChild(interfaceContext.returnNavigator());
3168 }
3169 this.state = 1;
3170 return this.root;
3171 };
3172 }