comparison core.js @ 813:f452455b5977

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