comparison core.js @ 1088:3705f68a38b7

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