comparison core.js @ 871:7aa8862850ef

Bug Fix #1313: Added 404 crash and dump when audioObject cannot obtain URL.
author Nicholas Jillings <nicholas.jillings@eecs.qmul.ac.uk>
date Wed, 01 Jul 2015 11:11:20 +0100
parents
children b7fd0296c6ab
comparison
equal deleted inserted replaced
-1:000000000000 871:7aa8862850ef
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 specification;
12 var interfaceContext;
13 var popup; // Hold the interfacePopup object
14 var testState;
15 var currentTrackOrder = []; // Hold the current XML tracks in their (randomised) order
16 var audioEngineContext; // The custome AudioEngine object
17 var projectReturn; // Hold the URL for the return
18
19
20 // Add a prototype to the bufferSourceNode to reference to the audioObject holding it
21 AudioBufferSourceNode.prototype.owner = undefined;
22
23 window.onload = function() {
24 // Function called once the browser has loaded all files.
25 // This should perform any initial commands such as structure / loading documents
26
27 // Create a web audio API context
28 // Fixed for cross-browser support
29 var AudioContext = window.AudioContext || window.webkitAudioContext;
30 audioContext = new AudioContext;
31
32 // Create test state
33 testState = new stateMachine();
34
35 // Create the audio engine object
36 audioEngineContext = new AudioEngine();
37
38 // Create the popup interface object
39 popup = new interfacePopup();
40
41 // Create the specification object
42 specification = new Specification();
43
44 // Create the interface object
45 interfaceContext = new Interface(specification);
46 };
47
48 function interfacePopup() {
49 // Creates an object to manage the popup
50 this.popup = null;
51 this.popupContent = null;
52 this.buttonProceed = null;
53 this.buttonPrevious = null;
54 this.popupOptions = null;
55 this.currentIndex = null;
56 this.responses = null;
57
58 this.createPopup = function(){
59 // Create popup window interface
60 var insertPoint = document.getElementById("topLevelBody");
61 var blank = document.createElement('div');
62 blank.className = 'testHalt';
63
64 this.popup = document.createElement('div');
65 this.popup.id = 'popupHolder';
66 this.popup.className = 'popupHolder';
67 this.popup.style.position = 'absolute';
68 this.popup.style.left = (window.innerWidth/2)-250 + 'px';
69 this.popup.style.top = (window.innerHeight/2)-125 + 'px';
70
71 this.popupContent = document.createElement('div');
72 this.popupContent.id = 'popupContent';
73 this.popupContent.style.marginTop = '25px';
74 this.popupContent.align = 'center';
75 this.popup.appendChild(this.popupContent);
76
77 this.buttonProceed = document.createElement('button');
78 this.buttonProceed.className = 'popupButton';
79 this.buttonProceed.style.left = '440px';
80 this.buttonProceed.style.top = '215px';
81 this.buttonProceed.innerHTML = 'Next';
82 this.buttonProceed.onclick = function(){popup.proceedClicked();};
83
84 this.buttonPrevious = document.createElement('button');
85 this.buttonPrevious.className = 'popupButton';
86 this.buttonPrevious.style.left = '10px';
87 this.buttonPrevious.style.top = '215px';
88 this.buttonPrevious.innerHTML = 'Back';
89 this.buttonPrevious.onclick = function(){popup.previousClick();};
90
91 this.popup.style.zIndex = -1;
92 this.popup.style.visibility = 'hidden';
93 blank.style.zIndex = -2;
94 blank.style.visibility = 'hidden';
95 insertPoint.appendChild(this.popup);
96 insertPoint.appendChild(blank);
97 };
98
99 this.showPopup = function(){
100 if (this.popup == null) {
101 this.createPopup();
102 }
103 this.popup.style.zIndex = 3;
104 this.popup.style.visibility = 'visible';
105 var blank = document.getElementsByClassName('testHalt')[0];
106 blank.style.zIndex = 2;
107 blank.style.visibility = 'visible';
108 };
109
110 this.hidePopup = function(){
111 this.popup.style.zIndex = -1;
112 this.popup.style.visibility = 'hidden';
113 var blank = document.getElementsByClassName('testHalt')[0];
114 blank.style.zIndex = -2;
115 blank.style.visibility = 'hidden';
116 };
117
118 this.postNode = function() {
119 // This will take the node from the popupOptions and display it
120 var node = this.popupOptions[this.currentIndex];
121 this.popupContent.innerHTML = null;
122 if (node.type == 'statement') {
123 var span = document.createElement('span');
124 span.textContent = node.statement;
125 this.popupContent.appendChild(span);
126 } else if (node.type == 'question') {
127 var span = document.createElement('span');
128 span.textContent = node.question;
129 var textArea = document.createElement('textarea');
130 switch (node.boxsize) {
131 case 'small':
132 textArea.cols = "20";
133 textArea.rows = "1";
134 break;
135 case 'normal':
136 textArea.cols = "30";
137 textArea.rows = "2";
138 break;
139 case 'large':
140 textArea.cols = "40";
141 textArea.rows = "5";
142 break;
143 case 'huge':
144 textArea.cols = "50";
145 textArea.rows = "10";
146 break;
147 }
148 var br = document.createElement('br');
149 this.popupContent.appendChild(span);
150 this.popupContent.appendChild(br);
151 this.popupContent.appendChild(textArea);
152 this.popupContent.childNodes[2].focus();
153 } else if (node.type == 'checkbox') {
154 var span = document.createElement('span');
155 span.textContent = node.statement;
156 this.popupContent.appendChild(span);
157 var optHold = document.createElement('div');
158 optHold.id = 'option-holder';
159 optHold.align = 'left';
160 for (var i=0; i<node.options.length; i++) {
161 var option = node.options[i];
162 var input = document.createElement('input');
163 input.id = option.id;
164 input.type = 'checkbox';
165 var span = document.createElement('span');
166 span.textContent = option.text;
167 var hold = document.createElement('div');
168 hold.setAttribute('name','option');
169 hold.style.float = 'left';
170 hold.style.padding = '4px';
171 hold.appendChild(input);
172 hold.appendChild(span);
173 optHold.appendChild(hold);
174 }
175 this.popupContent.appendChild(optHold);
176 } else if (node.type == 'radio') {
177 var span = document.createElement('span');
178 span.textContent = node.statement;
179 this.popupContent.appendChild(span);
180 var optHold = document.createElement('div');
181 optHold.id = 'option-holder';
182 optHold.align = 'none';
183 optHold.style.float = 'left';
184 optHold.style.width = "100%";
185 for (var i=0; i<node.options.length; i++) {
186 var option = node.options[i];
187 var input = document.createElement('input');
188 input.id = option.name;
189 input.type = 'radio';
190 input.name = node.id;
191 var span = document.createElement('span');
192 span.textContent = option.text;
193 var hold = document.createElement('div');
194 hold.setAttribute('name','option');
195 hold.style.padding = '4px';
196 hold.appendChild(input);
197 hold.appendChild(span);
198 optHold.appendChild(hold);
199 }
200 this.popupContent.appendChild(optHold);
201 } else if (node.type == 'number') {
202 var span = document.createElement('span');
203 span.textContent = node.statement;
204 this.popupContent.appendChild(span);
205 this.popupContent.appendChild(document.createElement('br'));
206 var input = document.createElement('input');
207 input.type = 'textarea';
208 if (node.min != null) {input.min = node.min;}
209 if (node.max != null) {input.max = node.max;}
210 if (node.step != null) {input.step = node.step;}
211 this.popupContent.appendChild(input);
212 }
213 this.popupContent.appendChild(this.buttonProceed);
214 if(this.currentIndex+1 == this.popupOptions.length) {
215 this.buttonProceed.textContent = 'Submit';
216 } else {
217 this.buttonProceed.textContent = 'Next';
218 }
219 if(this.currentIndex > 0)
220 this.popupContent.appendChild(this.buttonPrevious);
221 };
222
223 this.initState = function(node) {
224 //Call this with your preTest and postTest nodes when needed to
225 // initialise the popup procedure.
226 this.popupOptions = node.options;
227 if (this.popupOptions.length > 0) {
228 if (node.type == 'pretest') {
229 this.responses = document.createElement('PreTest');
230 } else if (node.type == 'posttest') {
231 this.responses = document.createElement('PostTest');
232 } else {
233 console.log ('WARNING - popup node neither pre or post!');
234 this.responses = document.createElement('responses');
235 }
236 this.currentIndex = 0;
237 this.showPopup();
238 this.postNode();
239 } else {
240 advanceState();
241 }
242 };
243
244 this.proceedClicked = function() {
245 // Each time the popup button is clicked!
246 var node = this.popupOptions[this.currentIndex];
247 if (node.type == 'question') {
248 // Must extract the question data
249 var textArea = $(popup.popupContent).find('textarea')[0];
250 if (node.mandatory == true && textArea.value.length == 0) {
251 alert('This question is mandatory');
252 return;
253 } else {
254 // Save the text content
255 var hold = document.createElement('comment');
256 hold.id = node.id;
257 hold.innerHTML = textArea.value;
258 console.log("Question: "+ node.question);
259 console.log("Question Response: "+ textArea.value);
260 this.responses.appendChild(hold);
261 }
262 } else if (node.type == 'checkbox') {
263 // Must extract checkbox data
264 var optHold = document.getElementById('option-holder');
265 var hold = document.createElement('checkbox');
266 console.log("Checkbox: "+ node.statement);
267 hold.id = node.id;
268 for (var i=0; i<optHold.childElementCount; i++) {
269 var input = optHold.childNodes[i].getElementsByTagName('input')[0];
270 var statement = optHold.childNodes[i].getElementsByTagName('span')[0];
271 var response = document.createElement('option');
272 response.setAttribute('name',input.id);
273 response.textContent = input.checked;
274 hold.appendChild(response);
275 console.log(input.id +': '+ input.checked);
276 }
277 this.responses.appendChild(hold);
278 } else if (node.type == "radio") {
279 var optHold = document.getElementById('option-holder');
280 var hold = document.createElement('radio');
281 var responseID = null;
282 var i=0;
283 while(responseID == null) {
284 var input = optHold.childNodes[i].getElementsByTagName('input')[0];
285 if (input.checked == true) {
286 responseID = i;
287 }
288 i++;
289 }
290 hold.id = node.id;
291 hold.setAttribute('name',node.options[responseID].name);
292 hold.textContent = node.options[responseID].text;
293 this.responses.appendChild(hold);
294 } else if (node.type == "number") {
295 var input = this.popupContent.getElementsByTagName('input')[0];
296 if (node.mandatory == true && input.value.length == 0) {
297 alert('This question is mandatory. Please enter a number');
298 return;
299 }
300 var enteredNumber = Number(input.value);
301 if (isNaN(enteredNumber)) {
302 alert('Please enter a valid number');
303 return;
304 }
305 if (enteredNumber < node.min && node.min != null) {
306 alert('Number is below the minimum value of '+node.min);
307 return;
308 }
309 if (enteredNumber > node.max && node.max != null) {
310 alert('Number is above the maximum value of '+node.max);
311 return;
312 }
313 var hold = document.createElement('number');
314 hold.id = node.id;
315 hold.textContent = input.value;
316 this.responses.appendChild(hold);
317 }
318 this.currentIndex++;
319 if (this.currentIndex < this.popupOptions.length) {
320 this.postNode();
321 } else {
322 // Reached the end of the popupOptions
323 this.hidePopup();
324 if (this.responses.nodeName == testState.stateResults[testState.stateIndex].nodeName) {
325 testState.stateResults[testState.stateIndex] = this.responses;
326 } else {
327 testState.stateResults[testState.stateIndex].appendChild(this.responses);
328 }
329 advanceState();
330 }
331 };
332
333 this.previousClick = function() {
334 // Triggered when the 'Back' button is clicked in the survey
335 if (this.currentIndex > 0) {
336 this.currentIndex--;
337 var node = this.popupOptions[this.currentIndex];
338 if (node.type != 'statement') {
339 var prevResp = this.responses.childNodes[this.responses.childElementCount-1];
340 this.responses.removeChild(prevResp);
341 }
342 this.postNode();
343 if (node.type == 'question') {
344 this.popupContent.getElementsByTagName('textarea')[0].value = prevResp.textContent;
345 } else if (node.type == 'checkbox') {
346 var options = this.popupContent.getElementsByTagName('input');
347 var savedOptions = prevResp.getElementsByTagName('option');
348 for (var i=0; i<options.length; i++) {
349 var id = options[i].id;
350 for (var j=0; j<savedOptions.length; j++) {
351 if (savedOptions[j].getAttribute('name') == id) {
352 if (savedOptions[j].textContent == 'true') {options[i].checked = true;}
353 else {options[i].checked = false;}
354 break;
355 }
356 }
357 }
358 } else if (node.type == 'number') {
359 this.popupContent.getElementsByTagName('input')[0].value = prevResp.textContent;
360 } else if (node.type == 'radio') {
361 var options = this.popupContent.getElementsByTagName('input');
362 var name = prevResp.getAttribute('name');
363 for (var i=0; i<options.length; i++) {
364 if (options[i].id == name) {
365 options[i].checked = true;
366 break;
367 }
368 }
369 }
370 }
371 };
372 }
373
374 function advanceState()
375 {
376 // Just for complete clarity
377 testState.advanceState();
378 }
379
380 function stateMachine()
381 {
382 // Object prototype for tracking and managing the test state
383 this.stateMap = [];
384 this.stateIndex = null;
385 this.currentStateMap = [];
386 this.currentIndex = null;
387 this.currentTestId = 0;
388 this.stateResults = [];
389 this.timerCallBackHolders = null;
390 this.initialise = function(){
391 if (this.stateMap.length > 0) {
392 if(this.stateIndex != null) {
393 console.log('NOTE - State already initialise');
394 }
395 this.stateIndex = -1;
396 var that = this;
397 var aH_pId = 0;
398 for (var id=0; id<this.stateMap.length; id++){
399 var name = this.stateMap[id].type;
400 var obj = document.createElement(name);
401 if (name == 'audioHolder') {
402 obj.id = this.stateMap[id].id;
403 obj.setAttribute('presentedid',aH_pId);
404 aH_pId+=1;
405 }
406 this.stateResults.push(obj);
407 }
408 } else {
409 conolse.log('FATAL - StateMap not correctly constructed. EMPTY_STATE_MAP');
410 }
411 };
412 this.advanceState = function(){
413 if (this.stateIndex == null) {
414 this.initialise();
415 }
416 if (this.stateIndex == -1) {
417 console.log('Starting test...');
418 }
419 if (this.currentIndex == null){
420 if (this.currentStateMap.type == "audioHolder") {
421 // Save current page
422 this.testPageCompleted(this.stateResults[this.stateIndex],this.currentStateMap,this.currentTestId);
423 this.currentTestId++;
424 }
425 this.stateIndex++;
426 if (this.stateIndex >= this.stateMap.length) {
427 console.log('Test Completed');
428 createProjectSave(specification.projectReturn);
429 } else {
430 this.currentStateMap = this.stateMap[this.stateIndex];
431 if (this.currentStateMap.type == "audioHolder") {
432 console.log('Loading test page');
433 loadTest(this.currentStateMap);
434 this.initialiseInnerState(this.currentStateMap);
435 } else if (this.currentStateMap.type == "pretest" || this.currentStateMap.type == "posttest") {
436 if (this.currentStateMap.options.length >= 1) {
437 popup.initState(this.currentStateMap);
438 } else {
439 this.advanceState();
440 }
441 } else {
442 this.advanceState();
443 }
444 }
445 } else {
446 this.advanceInnerState();
447 }
448 };
449
450 this.testPageCompleted = function(store, testXML, testId) {
451 // Function called each time a test page has been completed
452 // Can be used to over-rule default behaviour
453
454 pageXMLSave(store, testXML);
455 };
456
457 this.initialiseInnerState = function(node) {
458 // Parses the received testXML for pre and post test options
459 this.currentStateMap = [];
460 var preTest = node.preTest;
461 var postTest = node.postTest;
462 if (preTest == undefined) {preTest = document.createElement("preTest");}
463 if (postTest == undefined){postTest= document.createElement("postTest");}
464 this.currentStateMap.push(preTest);
465 this.currentStateMap.push(node);
466 this.currentStateMap.push(postTest);
467 this.currentIndex = -1;
468 this.advanceInnerState();
469 };
470
471 this.advanceInnerState = function() {
472 this.currentIndex++;
473 if (this.currentIndex >= this.currentStateMap.length) {
474 this.currentIndex = null;
475 this.currentStateMap = this.stateMap[this.stateIndex];
476 this.advanceState();
477 } else {
478 if (this.currentStateMap[this.currentIndex].type == "audioHolder") {
479 console.log("Loading test page"+this.currentTestId);
480 } else if (this.currentStateMap[this.currentIndex].type == "pretest") {
481 popup.initState(this.currentStateMap[this.currentIndex]);
482 } else if (this.currentStateMap[this.currentIndex].type == "posttest") {
483 popup.initState(this.currentStateMap[this.currentIndex]);
484 } else {
485 this.advanceInnerState();
486 }
487 }
488 };
489
490 this.previousState = function(){};
491 }
492
493 function testEnded(testId)
494 {
495 pageXMLSave(testId);
496 if (testXMLSetups.length-1 > testId)
497 {
498 // Yes we have another test to perform
499 testId = (Number(testId)+1);
500 currentState = 'testRun-'+testId;
501 loadTest(testId);
502 } else {
503 console.log('Testing Completed!');
504 currentState = 'postTest';
505 // Check for any post tests
506 var xmlSetup = projectXML.find('setup');
507 var postTest = xmlSetup.find('PostTest')[0];
508 popup.initState(postTest);
509 }
510 }
511
512 function loadProjectSpec(url) {
513 // Load the project document from the given URL, decode the XML and instruct audioEngine to get audio data
514 // If url is null, request client to upload project XML document
515 var r = new XMLHttpRequest();
516 r.open('GET',url,true);
517 r.onload = function() {
518 loadProjectSpecCallback(r.response);
519 };
520 r.send();
521 };
522
523 function loadProjectSpecCallback(response) {
524 // Function called after asynchronous download of XML project specification
525 //var decode = $.parseXML(response);
526 //projectXML = $(decode);
527
528 var parse = new DOMParser();
529 projectXML = parse.parseFromString(response,'text/xml');
530
531 // Build the specification
532 specification.decode();
533
534 testState.stateMap.push(specification.preTest);
535
536 // New check if we need to randomise the test order
537 if (specification.randomiseOrder)
538 {
539 specification.audioHolders = randomiseOrder(specification.audioHolders);
540 }
541
542 $(specification.audioHolders).each(function(index,elem){
543 testState.stateMap.push(elem);
544 });
545
546 testState.stateMap.push(specification.postTest);
547
548 // Obtain the metrics enabled
549 $(specification.metrics).each(function(index,node){
550 var enabled = node.textContent;
551 switch(node.enabled)
552 {
553 case 'testTimer':
554 sessionMetrics.prototype.enableTestTimer = true;
555 break;
556 case 'elementTimer':
557 sessionMetrics.prototype.enableElementTimer = true;
558 break;
559 case 'elementTracker':
560 sessionMetrics.prototype.enableElementTracker = true;
561 break;
562 case 'elementListenTracker':
563 sessionMetrics.prototype.enableElementListenTracker = true;
564 break;
565 case 'elementInitialPosition':
566 sessionMetrics.prototype.enableElementInitialPosition = true;
567 break;
568 case 'elementFlagListenedTo':
569 sessionMetrics.prototype.enableFlagListenedTo = true;
570 break;
571 case 'elementFlagMoved':
572 sessionMetrics.prototype.enableFlagMoved = true;
573 break;
574 case 'elementFlagComments':
575 sessionMetrics.prototype.enableFlagComments = true;
576 break;
577 }
578 });
579
580
581
582 // Detect the interface to use and load the relevant javascripts.
583 var interfaceJS = document.createElement('script');
584 interfaceJS.setAttribute("type","text/javascript");
585 if (specification.interfaceType == 'APE') {
586 interfaceJS.setAttribute("src","ape.js");
587
588 // APE comes with a css file
589 var css = document.createElement('link');
590 css.rel = 'stylesheet';
591 css.type = 'text/css';
592 css.href = 'ape.css';
593
594 document.getElementsByTagName("head")[0].appendChild(css);
595 }
596 document.getElementsByTagName("head")[0].appendChild(interfaceJS);
597
598 // Define window callbacks for interface
599 window.onresize = function(event){resizeWindow(event);};
600 }
601
602 function createProjectSave(destURL) {
603 // Save the data from interface into XML and send to destURL
604 // If destURL is null then download XML in client
605 // Now time to render file locally
606 var xmlDoc = interfaceXMLSave();
607 var parent = document.createElement("div");
608 parent.appendChild(xmlDoc);
609 var file = [parent.innerHTML];
610 if (destURL == "null" || destURL == undefined) {
611 var bb = new Blob(file,{type : 'application/xml'});
612 var dnlk = window.URL.createObjectURL(bb);
613 var a = document.createElement("a");
614 a.hidden = '';
615 a.href = dnlk;
616 a.download = "save.xml";
617 a.textContent = "Save File";
618
619 popup.showPopup();
620 popup.popupContent.innerHTML = null;
621 popup.popupContent.appendChild(a);
622 } else {
623 var xmlhttp = new XMLHttpRequest;
624 xmlhttp.open("POST",destURL,true);
625 xmlhttp.setRequestHeader('Content-Type', 'text/xml');
626 xmlhttp.onerror = function(){
627 console.log('Error saving file to server! Presenting download locally');
628 createProjectSave(null);
629 };
630 xmlhttp.onreadystatechange = function() {
631 console.log(xmlhttp.status);
632 if (xmlhttp.status != 200 && xmlhttp.readyState == 4) {
633 createProjectSave(null);
634 }
635 };
636 xmlhttp.send(file);
637 }
638 }
639
640 function errorSessionDump(msg){
641 // Create the partial interface XML save
642 // Include error node with message on why the dump occured
643 var xmlDoc = interfaceXMLSave();
644 var err = document.createElement('error');
645 err.textContent = msg;
646 xmlDoc.appendChild(err);
647 var parent = document.createElement("div");
648 parent.appendChild(xmlDoc);
649 var file = [parent.innerHTML];
650 var bb = new Blob(file,{type : 'application/xml'});
651 var dnlk = window.URL.createObjectURL(bb);
652 var a = document.createElement("a");
653 a.hidden = '';
654 a.href = dnlk;
655 a.download = "save.xml";
656 a.textContent = "Save File";
657
658 popup.showPopup();
659 popup.popupContent.innerHTML = "ERROR : "+msg;
660 popup.popupContent.appendChild(a);
661 }
662
663 // Only other global function which must be defined in the interface class. Determines how to create the XML document.
664 function interfaceXMLSave(){
665 // Create the XML string to be exported with results
666 var xmlDoc = document.createElement("BrowserEvaluationResult");
667 var projectDocument = specification.projectXML;
668 projectDocument.setAttribute('file-name',url);
669 xmlDoc.appendChild(projectDocument);
670 xmlDoc.appendChild(returnDateNode());
671 for (var i=0; i<testState.stateResults.length; i++)
672 {
673 xmlDoc.appendChild(testState.stateResults[i]);
674 }
675
676 return xmlDoc;
677 }
678
679 function AudioEngine() {
680
681 // Create two output paths, the main outputGain and fooGain.
682 // Output gain is default to 1 and any items for playback route here
683 // Foo gain is used for analysis to ensure paths get processed, but are not heard
684 // because web audio will optimise and any route which does not go to the destination gets ignored.
685 this.outputGain = audioContext.createGain();
686 this.fooGain = audioContext.createGain();
687 this.fooGain.gain = 0;
688
689 // Use this to detect playback state: 0 - stopped, 1 - playing
690 this.status = 0;
691 this.audioObjectsReady = false;
692
693 // Connect both gains to output
694 this.outputGain.connect(audioContext.destination);
695 this.fooGain.connect(audioContext.destination);
696
697 // Create the timer Object
698 this.timer = new timer();
699 // Create session metrics
700 this.metric = new sessionMetrics(this);
701
702 this.loopPlayback = false;
703
704 // Create store for new audioObjects
705 this.audioObjects = [];
706
707 this.play = function(id) {
708 // Start the timer and set the audioEngine state to playing (1)
709 if (this.status == 0) {
710 // Check if all audioObjects are ready
711 if (this.audioObjectsReady == false) {
712 this.audioObjectsReady = this.checkAllReady();
713 }
714 if (this.audioObjectsReady == true) {
715 this.timer.startTest();
716 this.status = 1;
717 }
718 }
719 if (this.status== 1) {
720 if (id == undefined) {
721 id = -1;
722 } else {
723 interfaceContext.playhead.setTimePerPixel(this.audioObjects[id]);
724 }
725 if (this.loopPlayback) {
726 for (var i=0; i<this.audioObjects.length; i++)
727 {
728 this.audioObjects[i].play(this.timer.getTestTime()+1);
729 if (id == i) {
730 this.audioObjects[i].loopStart();
731 } else {
732 this.audioObjects[i].loopStop();
733 }
734 }
735 } else {
736 for (var i=0; i<this.audioObjects.length; i++)
737 {
738 if (i != id) {
739 this.audioObjects[i].outputGain.gain.value = 0.0;
740 this.audioObjects[i].stop();
741 } else if (i == id) {
742 this.audioObjects[id].outputGain.gain.value = 1.0;
743 this.audioObjects[id].play(audioContext.currentTime+0.01);
744 }
745 }
746 }
747 interfaceContext.playhead.start();
748 }
749 };
750
751 this.stop = function() {
752 // Send stop and reset command to all playback buffers and set audioEngine state to stopped (1)
753 if (this.status == 1) {
754 for (var i=0; i<this.audioObjects.length; i++)
755 {
756 this.audioObjects[i].stop();
757 }
758 interfaceContext.playhead.stop();
759 this.status = 0;
760 }
761 };
762
763 this.newTrack = function(element) {
764 // Pull data from given URL into new audio buffer
765 // URLs must either be from the same source OR be setup to 'Access-Control-Allow-Origin'
766
767 // Create the audioObject with ID of the new track length;
768 audioObjectId = this.audioObjects.length;
769 this.audioObjects[audioObjectId] = new audioObject(audioObjectId);
770
771 // AudioObject will get track itself.
772 this.audioObjects[audioObjectId].specification = element;
773 this.audioObjects[audioObjectId].constructTrack(element.parent.hostURL + element.url);
774 return this.audioObjects[audioObjectId];
775 };
776
777 this.newTestPage = function() {
778 this.state = 0;
779 this.audioObjectsReady = false;
780 this.metric.reset();
781 this.audioObjects = [];
782 };
783
784 this.checkAllPlayed = function() {
785 arr = [];
786 for (var id=0; id<this.audioObjects.length; id++) {
787 if (this.audioObjects[id].metric.wasListenedTo == false) {
788 arr.push(this.audioObjects[id].id);
789 }
790 }
791 return arr;
792 };
793
794 this.checkAllReady = function() {
795 var ready = true;
796 for (var i=0; i<this.audioObjects.length; i++) {
797 if (this.audioObjects[i].state == 0) {
798 // Track not ready
799 console.log('WAIT -- audioObject '+i+' not ready yet!');
800 ready = false;
801 };
802 }
803 return ready;
804 };
805
806 }
807
808 function audioObject(id) {
809 // The main buffer object with common control nodes to the AudioEngine
810
811 this.specification;
812 this.id = id;
813 this.state = 0; // 0 - no data, 1 - ready
814 this.url = null; // Hold the URL given for the output back to the results.
815 this.metric = new metricTracker(this);
816
817 // Bindings for GUI
818 this.interfaceDOM = null;
819 this.commentDOM = null;
820
821 // Create a buffer and external gain control to allow internal patching of effects and volume leveling.
822 this.bufferNode = undefined;
823 this.outputGain = audioContext.createGain();
824
825 // Default output gain to be zero
826 this.outputGain.gain.value = 0.0;
827
828 // Connect buffer to the audio graph
829 this.outputGain.connect(audioEngineContext.outputGain);
830
831 // the audiobuffer is not designed for multi-start playback
832 // When stopeed, the buffer node is deleted and recreated with the stored buffer.
833 this.buffer;
834
835 this.loopStart = function() {
836 this.outputGain.gain.value = 1.0;
837 this.metric.startListening(audioEngineContext.timer.getTestTime());
838 };
839
840 this.loopStop = function() {
841 if (this.outputGain.gain.value != 0.0) {
842 this.outputGain.gain.value = 0.0;
843 this.metric.stopListening(audioEngineContext.timer.getTestTime());
844 }
845 };
846
847 this.play = function(startTime) {
848 if (this.bufferNode == undefined) {
849 this.bufferNode = audioContext.createBufferSource();
850 this.bufferNode.owner = this;
851 this.bufferNode.connect(this.outputGain);
852 this.bufferNode.buffer = this.buffer;
853 this.bufferNode.loop = audioEngineContext.loopPlayback;
854 this.bufferNode.onended = function() {
855 // Safari does not like using 'this' to reference the calling object!
856 event.srcElement.owner.metric.stopListening(audioEngineContext.timer.getTestTime(),event.srcElement.owner.getCurrentPosition());
857 };
858 if (this.bufferNode.loop == false) {
859 this.metric.startListening(audioEngineContext.timer.getTestTime());
860 }
861 this.bufferNode.start(startTime);
862 }
863 };
864
865 this.stop = function() {
866 if (this.bufferNode != undefined)
867 {
868 this.metric.stopListening(audioEngineContext.timer.getTestTime(),this.getCurrentPosition());
869 this.bufferNode.stop(0);
870 this.bufferNode = undefined;
871 }
872 };
873
874 this.getCurrentPosition = function() {
875 var time = audioEngineContext.timer.getTestTime();
876 if (this.bufferNode != undefined) {
877 if (this.bufferNode.loop == true) {
878 if (audioEngineContext.status == 1) {
879 return time%this.buffer.duration;
880 } else {
881 return 0;
882 }
883 } else {
884 if (this.metric.listenHold) {
885 return time - this.metric.listenStart;
886 } else {
887 return 0;
888 }
889 }
890 } else {
891 return 0;
892 }
893 };
894
895 this.constructTrack = function(url) {
896 var request = new XMLHttpRequest();
897 this.url = url;
898 request.open('GET',url,true);
899 request.responseType = 'arraybuffer';
900
901 var audioObj = this;
902
903 // Create callback to decode the data asynchronously
904 request.onloadend = function() {
905 audioContext.decodeAudioData(request.response, function(decodedData) {
906 audioObj.buffer = decodedData;
907 audioObj.state = 1;
908 }, function(){
909 // Should only be called if there was an error, but sometimes gets called continuously
910 // Check here if the error is genuine
911 if (audioObj.state == 0 || audioObj.buffer == undefined) {
912 // Genuine error
913 console.log('FATAL - Error loading buffer on '+audioObj.id);
914 if (request.status == 404)
915 {
916 console.log('FATAL - Fragment '+audioObj.id+' 404 error');
917 console.log('URL: '+audioObj.url);
918 errorSessionDump('Fragment '+audioObj.id+' 404 error');
919 }
920 }
921 });
922 };
923 request.send();
924 };
925
926 this.exportXMLDOM = function() {
927 var root = document.createElement('audioElement');
928 root.id = this.specification.id;
929 root.setAttribute('url',this.url);
930 var file = document.createElement('file');
931 file.setAttribute('sampleRate',this.buffer.sampleRate);
932 file.setAttribute('channels',this.buffer.numberOfChannels);
933 file.setAttribute('sampleCount',this.buffer.length);
934 file.setAttribute('duration',this.buffer.duration);
935 root.appendChild(file);
936 if (this.specification.type != 'outsidereference') {
937 root.appendChild(this.interfaceDOM.exportXMLDOM(this));
938 root.appendChild(this.commentDOM.exportXMLDOM(this));
939 }
940 root.appendChild(this.metric.exportXMLDOM());
941 return root;
942 };
943 }
944
945 function timer()
946 {
947 /* Timer object used in audioEngine to keep track of session timings
948 * Uses the timer of the web audio API, so sample resolution
949 */
950 this.testStarted = false;
951 this.testStartTime = 0;
952 this.testDuration = 0;
953 this.minimumTestTime = 0; // No minimum test time
954 this.startTest = function()
955 {
956 if (this.testStarted == false)
957 {
958 this.testStartTime = audioContext.currentTime;
959 this.testStarted = true;
960 this.updateTestTime();
961 audioEngineContext.metric.initialiseTest();
962 }
963 };
964 this.stopTest = function()
965 {
966 if (this.testStarted)
967 {
968 this.testDuration = this.getTestTime();
969 this.testStarted = false;
970 } else {
971 console.log('ERR: Test tried to end before beginning');
972 }
973 };
974 this.updateTestTime = function()
975 {
976 if (this.testStarted)
977 {
978 this.testDuration = audioContext.currentTime - this.testStartTime;
979 }
980 };
981 this.getTestTime = function()
982 {
983 this.updateTestTime();
984 return this.testDuration;
985 };
986 }
987
988 function sessionMetrics(engine)
989 {
990 /* Used by audioEngine to link to audioObjects to minimise the timer call timers;
991 */
992 this.engine = engine;
993 this.lastClicked = -1;
994 this.data = -1;
995 this.reset = function() {
996 this.lastClicked = -1;
997 this.data = -1;
998 };
999 this.initialiseTest = function(){};
1000 }
1001
1002 function metricTracker(caller)
1003 {
1004 /* Custom object to track and collect metric data
1005 * Used only inside the audioObjects object.
1006 */
1007
1008 this.listenedTimer = 0;
1009 this.listenStart = 0;
1010 this.listenHold = false;
1011 this.initialPosition = -1;
1012 this.movementTracker = [];
1013 this.listenTracker =[];
1014 this.wasListenedTo = false;
1015 this.wasMoved = false;
1016 this.hasComments = false;
1017 this.parent = caller;
1018
1019 this.initialised = function(position)
1020 {
1021 if (this.initialPosition == -1) {
1022 this.initialPosition = position;
1023 }
1024 };
1025
1026 this.moved = function(time,position)
1027 {
1028 this.wasMoved = true;
1029 this.movementTracker[this.movementTracker.length] = [time, position];
1030 };
1031
1032 this.startListening = function(time)
1033 {
1034 if (this.listenHold == false)
1035 {
1036 this.wasListenedTo = true;
1037 this.listenStart = time;
1038 this.listenHold = true;
1039
1040 var evnt = document.createElement('event');
1041 var testTime = document.createElement('testTime');
1042 testTime.setAttribute('start',time);
1043 var bufferTime = document.createElement('bufferTime');
1044 bufferTime.setAttribute('start',this.parent.getCurrentPosition());
1045 evnt.appendChild(testTime);
1046 evnt.appendChild(bufferTime);
1047 this.listenTracker.push(evnt);
1048
1049 console.log('slider ' + this.parent.id + ' played (' + time + ')'); // DEBUG/SAFETY: show played slider id
1050 }
1051 };
1052
1053 this.stopListening = function(time,bufferStopTime)
1054 {
1055 if (this.listenHold == true)
1056 {
1057 var diff = time - this.listenStart;
1058 this.listenedTimer += (diff);
1059 this.listenStart = 0;
1060 this.listenHold = false;
1061
1062 var evnt = this.listenTracker[this.listenTracker.length-1];
1063 var testTime = evnt.getElementsByTagName('testTime')[0];
1064 var bufferTime = evnt.getElementsByTagName('bufferTime')[0];
1065 testTime.setAttribute('stop',time);
1066 if (bufferStopTime == undefined) {
1067 bufferTime.setAttribute('stop',this.parent.getCurrentPosition());
1068 } else {
1069 bufferTime.setAttribute('stop',bufferStopTime);
1070 }
1071 console.log('slider ' + this.parent.id + ' played for (' + diff + ')'); // DEBUG/SAFETY: show played slider id
1072 }
1073 };
1074
1075 this.exportXMLDOM = function() {
1076 var root = document.createElement('metric');
1077 if (audioEngineContext.metric.enableElementTimer) {
1078 var mElementTimer = document.createElement('metricresult');
1079 mElementTimer.setAttribute('name','enableElementTimer');
1080 mElementTimer.textContent = this.listenedTimer;
1081 root.appendChild(mElementTimer);
1082 }
1083 if (audioEngineContext.metric.enableElementTracker) {
1084 var elementTrackerFull = document.createElement('metricResult');
1085 elementTrackerFull.setAttribute('name','elementTrackerFull');
1086 for (var k=0; k<this.movementTracker.length; k++)
1087 {
1088 var timePos = document.createElement('timePos');
1089 timePos.id = k;
1090 var time = document.createElement('time');
1091 time.textContent = this.movementTracker[k][0];
1092 var position = document.createElement('position');
1093 position.textContent = this.movementTracker[k][1];
1094 timePos.appendChild(time);
1095 timePos.appendChild(position);
1096 elementTrackerFull.appendChild(timePos);
1097 }
1098 root.appendChild(elementTrackerFull);
1099 }
1100 if (audioEngineContext.metric.enableElementListenTracker) {
1101 var elementListenTracker = document.createElement('metricResult');
1102 elementListenTracker.setAttribute('name','elementListenTracker');
1103 for (var k=0; k<this.listenTracker.length; k++) {
1104 elementListenTracker.appendChild(this.listenTracker[k]);
1105 }
1106 root.appendChild(elementListenTracker);
1107 }
1108 if (audioEngineContext.metric.enableElementInitialPosition) {
1109 var elementInitial = document.createElement('metricResult');
1110 elementInitial.setAttribute('name','elementInitialPosition');
1111 elementInitial.textContent = this.initialPosition;
1112 root.appendChild(elementInitial);
1113 }
1114 if (audioEngineContext.metric.enableFlagListenedTo) {
1115 var flagListenedTo = document.createElement('metricResult');
1116 flagListenedTo.setAttribute('name','elementFlagListenedTo');
1117 flagListenedTo.textContent = this.wasListenedTo;
1118 root.appendChild(flagListenedTo);
1119 }
1120 if (audioEngineContext.metric.enableFlagMoved) {
1121 var flagMoved = document.createElement('metricResult');
1122 flagMoved.setAttribute('name','elementFlagMoved');
1123 flagMoved.textContent = this.wasMoved;
1124 root.appendChild(flagMoved);
1125 }
1126 if (audioEngineContext.metric.enableFlagComments) {
1127 var flagComments = document.createElement('metricResult');
1128 flagComments.setAttribute('name','elementFlagComments');
1129 if (this.parent.commentDOM == null)
1130 {flag.textContent = 'false';}
1131 else if (this.parent.commentDOM.textContent.length == 0)
1132 {flag.textContent = 'false';}
1133 else
1134 {flag.textContet = 'true';}
1135 root.appendChild(flagComments);
1136 }
1137
1138 return root;
1139 };
1140 }
1141
1142 function randomiseOrder(input)
1143 {
1144 // This takes an array of information and randomises the order
1145 var N = input.length;
1146
1147 var inputSequence = []; // For safety purposes: keep track of randomisation
1148 for (var counter = 0; counter < N; ++counter)
1149 inputSequence.push(counter) // Fill array
1150 var inputSequenceClone = inputSequence.slice(0);
1151
1152 var holdArr = [];
1153 var outputSequence = [];
1154 for (var n=0; n<N; n++)
1155 {
1156 // First pick a random number
1157 var r = Math.random();
1158 // Multiply and floor by the number of elements left
1159 r = Math.floor(r*input.length);
1160 // Pick out that element and delete from the array
1161 holdArr.push(input.splice(r,1)[0]);
1162 // Do the same with sequence
1163 outputSequence.push(inputSequence.splice(r,1)[0]);
1164 }
1165 console.log(inputSequenceClone.toString()); // print original array to console
1166 console.log(outputSequence.toString()); // print randomised array to console
1167 return holdArr;
1168 }
1169
1170 function returnDateNode()
1171 {
1172 // Create an XML Node for the Date and Time a test was conducted
1173 // Structure is
1174 // <datetime>
1175 // <date year="##" month="##" day="##">DD/MM/YY</date>
1176 // <time hour="##" minute="##" sec="##">HH:MM:SS</time>
1177 // </datetime>
1178 var dateTime = new Date();
1179 var year = document.createAttribute('year');
1180 var month = document.createAttribute('month');
1181 var day = document.createAttribute('day');
1182 var hour = document.createAttribute('hour');
1183 var minute = document.createAttribute('minute');
1184 var secs = document.createAttribute('secs');
1185
1186 year.nodeValue = dateTime.getFullYear();
1187 month.nodeValue = dateTime.getMonth()+1;
1188 day.nodeValue = dateTime.getDate();
1189 hour.nodeValue = dateTime.getHours();
1190 minute.nodeValue = dateTime.getMinutes();
1191 secs.nodeValue = dateTime.getSeconds();
1192
1193 var hold = document.createElement("datetime");
1194 var date = document.createElement("date");
1195 date.textContent = year.nodeValue+'/'+month.nodeValue+'/'+day.nodeValue;
1196 var time = document.createElement("time");
1197 time.textContent = hour.nodeValue+':'+minute.nodeValue+':'+secs.nodeValue;
1198
1199 date.setAttributeNode(year);
1200 date.setAttributeNode(month);
1201 date.setAttributeNode(day);
1202 time.setAttributeNode(hour);
1203 time.setAttributeNode(minute);
1204 time.setAttributeNode(secs);
1205
1206 hold.appendChild(date);
1207 hold.appendChild(time);
1208 return hold
1209
1210 }
1211
1212 function testWaitIndicator() {
1213 if (audioEngineContext.checkAllReady() == false) {
1214 var hold = document.createElement("div");
1215 hold.id = "testWaitIndicator";
1216 hold.className = "indicator-box";
1217 hold.style.zIndex = 3;
1218 var span = document.createElement("span");
1219 span.textContent = "Please wait! Elements still loading";
1220 hold.appendChild(span);
1221 var blank = document.createElement('div');
1222 blank.className = 'testHalt';
1223 blank.id = "testHaltBlank";
1224 var body = document.getElementsByTagName('body')[0];
1225 body.appendChild(hold);
1226 body.appendChild(blank);
1227 testWaitTimerIntervalHolder = setInterval(function(){
1228 var ready = audioEngineContext.checkAllReady();
1229 if (ready) {
1230 var elem = document.getElementById('testWaitIndicator');
1231 var blank = document.getElementById('testHaltBlank');
1232 var body = document.getElementsByTagName('body')[0];
1233 body.removeChild(elem);
1234 body.removeChild(blank);
1235 clearInterval(testWaitTimerIntervalHolder);
1236 }
1237 },500,false);
1238 }
1239 }
1240
1241 var testWaitTimerIntervalHolder = null;
1242
1243 function Specification() {
1244 // Handles the decoding of the project specification XML into a simple JavaScript Object.
1245
1246 this.interfaceType;
1247 this.commonInterface;
1248 this.projectReturn;
1249 this.randomiseOrder;
1250 this.collectMetrics;
1251 this.preTest;
1252 this.postTest;
1253 this.metrics =[];
1254
1255 this.audioHolders = [];
1256
1257 this.decode = function() {
1258 // projectXML - DOM Parsed document
1259 this.projectXML = projectXML.childNodes[0];
1260 var setupNode = projectXML.getElementsByTagName('setup')[0];
1261 this.interfaceType = setupNode.getAttribute('interface');
1262 this.projectReturn = setupNode.getAttribute('projectReturn');
1263 if (setupNode.getAttribute('randomiseOrder') == "true") {
1264 this.randomiseOrder = true;
1265 } else {this.randomiseOrder = false;}
1266 if (setupNode.getAttribute('collectMetrics') == "true") {
1267 this.collectMetrics = true;
1268 } else {this.collectMetrics = false;}
1269 var metricCollection = setupNode.getElementsByTagName('Metric');
1270
1271 this.preTest = new this.prepostNode('pretest',setupNode.getElementsByTagName('PreTest'));
1272 this.postTest = new this.prepostNode('posttest',setupNode.getElementsByTagName('PostTest'));
1273
1274 if (metricCollection.length > 0) {
1275 metricCollection = metricCollection[0].getElementsByTagName('metricEnable');
1276 for (var i=0; i<metricCollection.length; i++) {
1277 this.metrics.push(new this.metricNode(metricCollection[i].textContent));
1278 }
1279 }
1280
1281 var commonInterfaceNode = setupNode.getElementsByTagName('interface');
1282 if (commonInterfaceNode.length > 0) {
1283 commonInterfaceNode = commonInterfaceNode[0];
1284 } else {
1285 commonInterfaceNode = undefined;
1286 }
1287
1288 this.commonInterface = new function() {
1289 this.OptionNode = function(child) {
1290 this.type = child.nodeName;
1291 if (this.type == 'check') {
1292 this.check = child.getAttribute('name');
1293 if (this.check == 'scalerange') {
1294 this.min = child.getAttribute('min');
1295 this.max = child.getAttribute('max');
1296 if (this.min == null) {this.min = 1;}
1297 else if (Number(this.min) > 1 && this.min != null) {
1298 this.min = Number(this.min)/100;
1299 } else {
1300 this.min = Number(this.min);
1301 }
1302 if (this.max == null) {this.max = 0;}
1303 else if (Number(this.max) > 1 && this.max != null) {
1304 this.max = Number(this.max)/100;
1305 } else {
1306 this.max = Number(this.max);
1307 }
1308 }
1309 } else if (this.type == 'anchor' || this.type == 'reference') {
1310 this.value = Number(child.textContent);
1311 }
1312 };
1313 this.options = [];
1314 if (commonInterfaceNode != undefined) {
1315 var child = commonInterfaceNode.firstElementChild;
1316 while (child != undefined) {
1317 this.options.push(new this.OptionNode(child));
1318 child = child.nextElementSibling;
1319 }
1320 }
1321 };
1322
1323 var audioHolders = projectXML.getElementsByTagName('audioHolder');
1324 for (var i=0; i<audioHolders.length; i++) {
1325 this.audioHolders.push(new this.audioHolderNode(this,audioHolders[i]));
1326 }
1327
1328 };
1329
1330 this.prepostNode = function(type,Collection) {
1331 this.type = type;
1332 this.options = [];
1333
1334 this.OptionNode = function(child) {
1335
1336 this.childOption = function(element) {
1337 this.type = 'option';
1338 this.id = element.id;
1339 this.name = element.getAttribute('name');
1340 this.text = element.textContent;
1341 };
1342
1343 this.type = child.nodeName;
1344 if (child.nodeName == "question") {
1345 this.id = child.id;
1346 this.mandatory;
1347 if (child.getAttribute('mandatory') == "true") {this.mandatory = true;}
1348 else {this.mandatory = false;}
1349 this.question = child.textContent;
1350 if (child.getAttribute('boxsize') == null) {
1351 this.boxsize = 'normal';
1352 } else {
1353 this.boxsize = child.getAttribute('boxsize');
1354 }
1355 } else if (child.nodeName == "statement") {
1356 this.statement = child.textContent;
1357 } else if (child.nodeName == "checkbox" || child.nodeName == "radio") {
1358 var element = child.firstElementChild;
1359 this.id = child.id;
1360 if (element == null) {
1361 console.log('Malformed' +child.nodeName+ 'entry');
1362 this.statement = 'Malformed' +child.nodeName+ 'entry';
1363 this.type = 'statement';
1364 } else {
1365 this.options = [];
1366 while (element != null) {
1367 if (element.nodeName == 'statement' && this.statement == undefined){
1368 this.statement = element.textContent;
1369 } else if (element.nodeName == 'option') {
1370 this.options.push(new this.childOption(element));
1371 }
1372 element = element.nextElementSibling;
1373 }
1374 }
1375 } else if (child.nodeName == "number") {
1376 this.statement = child.textContent;
1377 this.id = child.id;
1378 this.min = child.getAttribute('min');
1379 this.max = child.getAttribute('max');
1380 this.step = child.getAttribute('step');
1381 }
1382 };
1383
1384 // On construction:
1385 if (Collection.length != 0) {
1386 Collection = Collection[0];
1387 if (Collection.childElementCount != 0) {
1388 var child = Collection.firstElementChild;
1389 this.options.push(new this.OptionNode(child));
1390 while (child.nextElementSibling != null) {
1391 child = child.nextElementSibling;
1392 this.options.push(new this.OptionNode(child));
1393 }
1394 }
1395 }
1396 };
1397
1398 this.metricNode = function(name) {
1399 this.enabled = name;
1400 };
1401
1402 this.audioHolderNode = function(parent,xml) {
1403 this.type = 'audioHolder';
1404 this.interfaceNode = function(DOM) {
1405 var title = DOM.getElementsByTagName('title');
1406 if (title.length == 0) {this.title = null;}
1407 else {this.title = title[0].textContent;}
1408 this.options = parent.commonInterface.options;
1409 var scale = DOM.getElementsByTagName('scale');
1410 this.scale = [];
1411 for (var i=0; i<scale.length; i++) {
1412 var arr = [null, null];
1413 arr[0] = scale[i].getAttribute('position');
1414 arr[1] = scale[i].textContent;
1415 this.scale.push(arr);
1416 }
1417 };
1418
1419 this.audioElementNode = function(parent,xml) {
1420 this.url = xml.getAttribute('url');
1421 this.id = xml.id;
1422 this.parent = parent;
1423 this.type = xml.getAttribute('type');
1424 if (this.type == null) {this.type = "normal";}
1425 if (this.type == 'anchor') {this.anchor = true;}
1426 else {this.anchor = false;}
1427 if (this.type == 'reference') {this.reference = true;}
1428 else {this.reference = false;}
1429
1430 this.marker = xml.getAttribute('marker');
1431 if (this.marker == null) {this.marker = undefined;}
1432
1433 if (this.anchor == true && this.marker == undefined) {
1434 this.marker = anchor;
1435 }
1436 else if (this.reference == true && this.marker == undefined) {
1437 this.marker = reference;
1438 }
1439
1440 if (this.marker != undefined) {
1441 this.marker = Number(this.marker);
1442 if (this.marker > 1) {this.marker /= 100;}
1443 }
1444 };
1445
1446 this.commentQuestionNode = function(xml) {
1447 this.childOption = function(element) {
1448 this.type = 'option';
1449 this.name = element.getAttribute('name');
1450 this.text = element.textContent;
1451 };
1452 this.id = xml.id;
1453 if (xml.getAttribute('mandatory') == 'true') {this.mandatory = true;}
1454 else {this.mandatory = false;}
1455 this.type = xml.getAttribute('type');
1456 if (this.type == undefined) {this.type = 'text';}
1457 switch (this.type) {
1458 case 'text':
1459 this.question = xml.textContent;
1460 break;
1461 case 'radio':
1462 var child = xml.firstElementChild;
1463 this.options = [];
1464 while (child != undefined) {
1465 if (child.nodeName == 'statement' && this.statement == undefined) {
1466 this.statement = child.textContent;
1467 } else if (child.nodeName == 'option') {
1468 this.options.push(new this.childOption(child));
1469 }
1470 child = child.nextElementSibling;
1471 }
1472 break;
1473 case 'checkbox':
1474 var child = xml.firstElementChild;
1475 this.options = [];
1476 while (child != undefined) {
1477 if (child.nodeName == 'statement' && this.statement == undefined) {
1478 this.statement = child.textContent;
1479 } else if (child.nodeName == 'option') {
1480 this.options.push(new this.childOption(child));
1481 }
1482 child = child.nextElementSibling;
1483 }
1484 break;
1485 }
1486 };
1487
1488 this.id = xml.id;
1489 this.hostURL = xml.getAttribute('hostURL');
1490 this.sampleRate = xml.getAttribute('sampleRate');
1491 if (xml.getAttribute('randomiseOrder') == "true") {this.randomiseOrder = true;}
1492 else {this.randomiseOrder = false;}
1493 this.repeatCount = xml.getAttribute('repeatCount');
1494 if (xml.getAttribute('loop') == 'true') {this.loop = true;}
1495 else {this.loop == false;}
1496 if (xml.getAttribute('elementComments') == "true") {this.elementComments = true;}
1497 else {this.elementComments = false;}
1498
1499 var anchor = xml.getElementsByTagName('anchor');
1500 if (anchor.length == 0) {
1501 // Find anchor in commonInterface;
1502 for (var i=0; i<parent.commonInterface.options.length; i++) {
1503 if(parent.commonInterface.options[i].type == 'anchor') {
1504 anchor = parent.commonInterface.options[i].value;
1505 break;
1506 }
1507 }
1508 if (typeof(anchor) == "object") {
1509 anchor = null;
1510 }
1511 } else {
1512 anchor = anchor[0].textContent;
1513 }
1514
1515 var reference = xml.getElementsByTagName('anchor');
1516 if (reference.length == 0) {
1517 // Find anchor in commonInterface;
1518 for (var i=0; i<parent.commonInterface.options.length; i++) {
1519 if(parent.commonInterface.options[i].type == 'reference') {
1520 reference = parent.commonInterface.options[i].value;
1521 break;
1522 }
1523 }
1524 if (typeof(reference) == "object") {
1525 reference = null;
1526 }
1527 } else {
1528 reference = reference[0].textContent;
1529 }
1530
1531 if (typeof(anchor) == 'number') {
1532 if (anchor > 1 && anchor < 100) {anchor /= 100.0;}
1533 }
1534
1535 if (typeof(reference) == 'number') {
1536 if (reference > 1 && reference < 100) {reference /= 100.0;}
1537 }
1538
1539 this.preTest = new parent.prepostNode('pretest',xml.getElementsByTagName('PreTest'));
1540 this.postTest = new parent.prepostNode('posttest',xml.getElementsByTagName('PostTest'));
1541
1542 this.interfaces = [];
1543 var interfaceDOM = xml.getElementsByTagName('interface');
1544 for (var i=0; i<interfaceDOM.length; i++) {
1545 this.interfaces.push(new this.interfaceNode(interfaceDOM[i]));
1546 }
1547
1548 this.commentBoxPrefix = xml.getElementsByTagName('commentBoxPrefix');
1549 if (this.commentBoxPrefix.length != 0) {
1550 this.commentBoxPrefix = this.commentBoxPrefix[0].textContent;
1551 } else {
1552 this.commentBoxPrefix = "Comment on track";
1553 }
1554
1555 this.audioElements =[];
1556 var audioElementsDOM = xml.getElementsByTagName('audioElements');
1557 this.outsideReference = null;
1558 for (var i=0; i<audioElementsDOM.length; i++) {
1559 if (audioElementsDOM[i].getAttribute('type') == 'outsidereference') {
1560 if (this.outsideReference == null) {
1561 this.outsideReference = new this.audioElementNode(this,audioElementsDOM[i]);
1562 } else {
1563 console.log('Error only one audioelement can be of type outsidereference per audioholder');
1564 this.audioElements.push(new this.audioElementNode(this,audioElementsDOM[i]));
1565 console.log('Element id '+audioElementsDOM[i].id+' made into normal node');
1566 }
1567 } else {
1568 this.audioElements.push(new this.audioElementNode(this,audioElementsDOM[i]));
1569 }
1570 }
1571
1572 if (this.randomiseOrder) {
1573 this.audioElements = randomiseOrder(this.audioElements);
1574 }
1575
1576 // Check only one anchor and one reference per audioNode
1577 var anchor = [];
1578 var reference = [];
1579 this.anchorId = null;
1580 this.referenceId = null;
1581 for (var i=0; i<this.audioElements.length; i++)
1582 {
1583 if (this.audioElements[i].anchor == true) {anchor.push(i);}
1584 if (this.audioElements[i].reference == true) {reference.push(i);}
1585 }
1586
1587 if (anchor.length > 1) {
1588 console.log('Error - cannot have more than one anchor!');
1589 console.log('Each anchor node will be a normal mode to continue the test');
1590 for (var i=0; i<anchor.length; i++)
1591 {
1592 this.audioElements[anchor[i]].anchor = false;
1593 this.audioElements[anchor[i]].value = undefined;
1594 }
1595 } else {this.anchorId = anchor[0];}
1596 if (reference.length > 1) {
1597 console.log('Error - cannot have more than one anchor!');
1598 console.log('Each anchor node will be a normal mode to continue the test');
1599 for (var i=0; i<reference.length; i++)
1600 {
1601 this.audioElements[reference[i]].reference = false;
1602 this.audioElements[reference[i]].value = undefined;
1603 }
1604 } else {this.referenceId = reference[0];}
1605
1606 this.commentQuestions = [];
1607 var commentQuestionsDOM = xml.getElementsByTagName('CommentQuestion');
1608 for (var i=0; i<commentQuestionsDOM.length; i++) {
1609 this.commentQuestions.push(new this.commentQuestionNode(commentQuestionsDOM[i]));
1610 }
1611 };
1612 }
1613
1614 function Interface(specificationObject) {
1615 // This handles the bindings between the interface and the audioEngineContext;
1616 this.specification = specificationObject;
1617 this.insertPoint = document.getElementById("topLevelBody");
1618
1619 // Bounded by interface!!
1620 // Interface object MUST have an exportXMLDOM method which returns the various DOM levels
1621 // For example, APE returns the slider position normalised in a <value> tag.
1622 this.interfaceObjects = [];
1623 this.interfaceObject = function(){};
1624
1625 this.commentBoxes = [];
1626 this.elementCommentBox = function(audioObject) {
1627 var element = audioObject.specification;
1628 this.audioObject = audioObject;
1629 this.id = audioObject.id;
1630 var audioHolderObject = audioObject.specification.parent;
1631 // Create document objects to hold the comment boxes
1632 this.trackComment = document.createElement('div');
1633 this.trackComment.className = 'comment-div';
1634 this.trackComment.id = 'comment-div-'+audioObject.id;
1635 // Create a string next to each comment asking for a comment
1636 this.trackString = document.createElement('span');
1637 this.trackString.innerHTML = audioHolderObject.commentBoxPrefix+' '+audioObject.id;
1638 // Create the HTML5 comment box 'textarea'
1639 this.trackCommentBox = document.createElement('textarea');
1640 this.trackCommentBox.rows = '4';
1641 this.trackCommentBox.cols = '100';
1642 this.trackCommentBox.name = 'trackComment'+audioObject.id;
1643 this.trackCommentBox.className = 'trackComment';
1644 var br = document.createElement('br');
1645 // Add to the holder.
1646 this.trackComment.appendChild(this.trackString);
1647 this.trackComment.appendChild(br);
1648 this.trackComment.appendChild(this.trackCommentBox);
1649
1650 this.exportXMLDOM = function() {
1651 var root = document.createElement('comment');
1652 if (this.audioObject.specification.parent.elementComments) {
1653 var question = document.createElement('question');
1654 question.textContent = this.trackString.textContent;
1655 var response = document.createElement('response');
1656 response.textContent = this.trackCommentBox.value;
1657 console.log("Comment frag-"+this.id+": "+response.textContent);
1658 root.appendChild(question);
1659 root.appendChild(response);
1660 }
1661 return root;
1662 };
1663 };
1664
1665 this.commentQuestions = [];
1666
1667 this.commentBox = function(commentQuestion) {
1668 this.specification = commentQuestion;
1669 // Create document objects to hold the comment boxes
1670 this.holder = document.createElement('div');
1671 this.holder.className = 'comment-div';
1672 // Create a string next to each comment asking for a comment
1673 this.string = document.createElement('span');
1674 this.string.innerHTML = commentQuestion.question;
1675 // Create the HTML5 comment box 'textarea'
1676 this.textArea = document.createElement('textarea');
1677 this.textArea.rows = '4';
1678 this.textArea.cols = '100';
1679 this.textArea.className = 'trackComment';
1680 var br = document.createElement('br');
1681 // Add to the holder.
1682 this.holder.appendChild(this.string);
1683 this.holder.appendChild(br);
1684 this.holder.appendChild(this.textArea);
1685
1686 this.exportXMLDOM = function() {
1687 var root = document.createElement('comment');
1688 root.id = this.specification.id;
1689 root.setAttribute('type',this.specification.type);
1690 root.textContent = this.textArea.value;
1691 console.log("Question :"+this.string.textContent);
1692 console.log("Response :"+root.textContent);
1693 return root;
1694 };
1695 };
1696
1697 this.radioBox = function(commentQuestion) {
1698 this.specification = commentQuestion;
1699 // Create document objects to hold the comment boxes
1700 this.holder = document.createElement('div');
1701 this.holder.className = 'comment-div';
1702 // Create a string next to each comment asking for a comment
1703 this.string = document.createElement('span');
1704 this.string.innerHTML = commentQuestion.statement;
1705 var br = document.createElement('br');
1706 // Add to the holder.
1707 this.holder.appendChild(this.string);
1708 this.holder.appendChild(br);
1709 this.options = [];
1710 this.inputs = document.createElement('div');
1711 this.span = document.createElement('div');
1712 this.inputs.align = 'center';
1713 this.inputs.style.marginLeft = '12px';
1714 this.span.style.marginLeft = '12px';
1715 this.span.align = 'center';
1716 this.span.style.marginTop = '15px';
1717
1718 var optCount = commentQuestion.options.length;
1719 var spanMargin = Math.floor(((600-(optCount*100))/(optCount))/2)+'px';
1720 console.log(spanMargin);
1721 for (var i=0; i<optCount; i++)
1722 {
1723 var div = document.createElement('div');
1724 div.style.width = '100px';
1725 div.style.float = 'left';
1726 div.style.marginRight = spanMargin;
1727 div.style.marginLeft = spanMargin;
1728 var input = document.createElement('input');
1729 input.type = 'radio';
1730 input.name = commentQuestion.id;
1731 input.setAttribute('setvalue',commentQuestion.options[i].name);
1732 input.className = 'comment-radio';
1733 div.appendChild(input);
1734 this.inputs.appendChild(div);
1735
1736
1737 div = document.createElement('div');
1738 div.style.width = '100px';
1739 div.style.float = 'left';
1740 div.style.marginRight = spanMargin;
1741 div.style.marginLeft = spanMargin;
1742 div.align = 'center';
1743 var span = document.createElement('span');
1744 span.textContent = commentQuestion.options[i].text;
1745 span.className = 'comment-radio-span';
1746 div.appendChild(span);
1747 this.span.appendChild(div);
1748 this.options.push(input);
1749 }
1750 this.holder.appendChild(this.span);
1751 this.holder.appendChild(this.inputs);
1752
1753 this.exportXMLDOM = function() {
1754 var root = document.createElement('comment');
1755 root.id = this.specification.id;
1756 root.setAttribute('type',this.specification.type);
1757 var question = document.createElement('question');
1758 question.textContent = this.string.textContent;
1759 var response = document.createElement('response');
1760 var i=0;
1761 while(this.options[i].checked == false) {
1762 i++;
1763 if (i >= this.options.length) {
1764 break;
1765 }
1766 }
1767 if (i >= this.options.length) {
1768 response.textContent = 'null';
1769 } else {
1770 response.textContent = this.options[i].getAttribute('setvalue');
1771 response.setAttribute('number',i);
1772 }
1773 console.log('Comment: '+question.textContent);
1774 console.log('Response: '+response.textContent);
1775 root.appendChild(question);
1776 root.appendChild(response);
1777 return root;
1778 };
1779 };
1780
1781 this.checkboxBox = function(commentQuestion) {
1782 this.specification = commentQuestion;
1783 // Create document objects to hold the comment boxes
1784 this.holder = document.createElement('div');
1785 this.holder.className = 'comment-div';
1786 // Create a string next to each comment asking for a comment
1787 this.string = document.createElement('span');
1788 this.string.innerHTML = commentQuestion.statement;
1789 var br = document.createElement('br');
1790 // Add to the holder.
1791 this.holder.appendChild(this.string);
1792 this.holder.appendChild(br);
1793 this.options = [];
1794 this.inputs = document.createElement('div');
1795 this.span = document.createElement('div');
1796 this.inputs.align = 'center';
1797 this.inputs.style.marginLeft = '12px';
1798 this.span.style.marginLeft = '12px';
1799 this.span.align = 'center';
1800 this.span.style.marginTop = '15px';
1801
1802 var optCount = commentQuestion.options.length;
1803 var spanMargin = Math.floor(((600-(optCount*100))/(optCount))/2)+'px';
1804 console.log(spanMargin);
1805 for (var i=0; i<optCount; i++)
1806 {
1807 var div = document.createElement('div');
1808 div.style.width = '100px';
1809 div.style.float = 'left';
1810 div.style.marginRight = spanMargin;
1811 div.style.marginLeft = spanMargin;
1812 var input = document.createElement('input');
1813 input.type = 'checkbox';
1814 input.name = commentQuestion.id;
1815 input.setAttribute('setvalue',commentQuestion.options[i].name);
1816 input.className = 'comment-radio';
1817 div.appendChild(input);
1818 this.inputs.appendChild(div);
1819
1820
1821 div = document.createElement('div');
1822 div.style.width = '100px';
1823 div.style.float = 'left';
1824 div.style.marginRight = spanMargin;
1825 div.style.marginLeft = spanMargin;
1826 div.align = 'center';
1827 var span = document.createElement('span');
1828 span.textContent = commentQuestion.options[i].text;
1829 span.className = 'comment-radio-span';
1830 div.appendChild(span);
1831 this.span.appendChild(div);
1832 this.options.push(input);
1833 }
1834 this.holder.appendChild(this.span);
1835 this.holder.appendChild(this.inputs);
1836
1837 this.exportXMLDOM = function() {
1838 var root = document.createElement('comment');
1839 root.id = this.specification.id;
1840 root.setAttribute('type',this.specification.type);
1841 var question = document.createElement('question');
1842 question.textContent = this.string.textContent;
1843 root.appendChild(question);
1844 console.log('Comment: '+question.textContent);
1845 for (var i=0; i<this.options.length; i++) {
1846 var response = document.createElement('response');
1847 response.textContent = this.options[i].checked;
1848 response.setAttribute('name',this.options[i].getAttribute('setvalue'));
1849 root.appendChild(response);
1850 console.log('Response '+response.getAttribute('name') +': '+response.textContent);
1851 }
1852 return root;
1853 };
1854 };
1855
1856 this.createCommentBox = function(audioObject) {
1857 var node = new this.elementCommentBox(audioObject);
1858 this.commentBoxes.push(node);
1859 audioObject.commentDOM = node;
1860 return node;
1861 };
1862
1863 this.sortCommentBoxes = function() {
1864 var holder = [];
1865 while (this.commentBoxes.length > 0) {
1866 var node = this.commentBoxes.pop(0);
1867 holder[node.id] = node;
1868 }
1869 this.commentBoxes = holder;
1870 };
1871
1872 this.showCommentBoxes = function(inject, sort) {
1873 if (sort) {interfaceContext.sortCommentBoxes();}
1874 for (var i=0; i<interfaceContext.commentBoxes.length; i++) {
1875 inject.appendChild(this.commentBoxes[i].trackComment);
1876 }
1877 };
1878
1879 this.deleteCommentBoxes = function() {
1880 this.commentBoxes = [];
1881 };
1882
1883 this.createCommentQuestion = function(element) {
1884 var node;
1885 if (element.type == 'text') {
1886 node = new this.commentBox(element);
1887 } else if (element.type == 'radio') {
1888 node = new this.radioBox(element);
1889 } else if (element.type == 'checkbox') {
1890 node = new this.checkboxBox(element);
1891 }
1892 this.commentQuestions.push(node);
1893 return node;
1894 };
1895
1896 this.deleteCommentQuestions = function()
1897 {
1898 this.commentQuestions = [];
1899 };
1900
1901 this.playhead = new function()
1902 {
1903 this.object = document.createElement('div');
1904 this.object.className = 'playhead';
1905 this.object.align = 'left';
1906 var curTime = document.createElement('div');
1907 curTime.style.width = '50px';
1908 this.curTimeSpan = document.createElement('span');
1909 this.curTimeSpan.textContent = '00:00';
1910 curTime.appendChild(this.curTimeSpan);
1911 this.object.appendChild(curTime);
1912 this.scrubberTrack = document.createElement('div');
1913 this.scrubberTrack.className = 'playhead-scrub-track';
1914
1915 this.scrubberHead = document.createElement('div');
1916 this.scrubberHead.id = 'playhead-scrubber';
1917 this.scrubberTrack.appendChild(this.scrubberHead);
1918 this.object.appendChild(this.scrubberTrack);
1919
1920 this.timePerPixel = 0;
1921 this.maxTime = 0;
1922
1923 this.playbackObject;
1924
1925 this.setTimePerPixel = function(audioObject) {
1926 //maxTime must be in seconds
1927 this.playbackObject = audioObject;
1928 this.maxTime = audioObject.buffer.duration;
1929 var width = 490; //500 - 10, 5 each side of the tracker head
1930 this.timePerPixel = this.maxTime/490;
1931 if (this.maxTime < 60) {
1932 this.curTimeSpan.textContent = '0.00';
1933 } else {
1934 this.curTimeSpan.textContent = '00:00';
1935 }
1936 };
1937
1938 this.update = function() {
1939 // Update the playhead position, startPlay must be called
1940 if (this.timePerPixel > 0) {
1941 var time = this.playbackObject.getCurrentPosition();
1942 var width = 490;
1943 var pix = Math.floor(time/this.timePerPixel);
1944 this.scrubberHead.style.left = pix+'px';
1945 if (this.maxTime > 60.0) {
1946 var secs = time%60;
1947 var mins = Math.floor((time-secs)/60);
1948 secs = secs.toString();
1949 secs = secs.substr(0,2);
1950 mins = mins.toString();
1951 this.curTimeSpan.textContent = mins+':'+secs;
1952 } else {
1953 time = time.toString();
1954 this.curTimeSpan.textContent = time.substr(0,4);
1955 }
1956 }
1957 };
1958
1959 this.interval = undefined;
1960
1961 this.start = function() {
1962 if (this.playbackObject != undefined && this.interval == undefined) {
1963 this.interval = setInterval(function(){interfaceContext.playhead.update();},100);
1964 }
1965 };
1966 this.stop = function() {
1967 clearInterval(this.interval);
1968 this.interval = undefined;
1969 };
1970 };
1971
1972 // Global Checkers
1973 // These functions will help enforce the checkers
1974 this.checkHiddenAnchor = function()
1975 {
1976 var audioHolder = testState.currentStateMap[testState.currentIndex];
1977 if (audioHolder.anchorId != null)
1978 {
1979 var audioObject = audioEngineContext.audioObjects[audioHolder.anchorId];
1980 if (audioObject.interfaceDOM.getValue() > audioObject.specification.marker)
1981 {
1982 // Anchor is not set below
1983 console.log('Anchor node not below marker value');
1984 alert('Please keep listening');
1985 return false;
1986 }
1987 }
1988 return true;
1989 };
1990
1991 this.checkHiddenReference = function()
1992 {
1993 var audioHolder = testState.currentStateMap[testState.currentIndex];
1994 if (audioHolder.referenceId != null)
1995 {
1996 var audioObject = audioEngineContext.audioObjects[audioHolder.referenceId];
1997 if (audioObject.interfaceDOM.getValue() < audioObject.specification.marker)
1998 {
1999 // Anchor is not set below
2000 console.log('Reference node not above marker value');
2001 alert('Please keep listening');
2002 return false;
2003 }
2004 }
2005 return true;
2006 };
2007 }