// University of New England JavaScript Document //
// Code written by Iain Mackay (x3157) //
// Teaching and Learning Centre //
//
//  thanks Quirksmode - http://www.quirksmode.org
//
// Set up Variables

var sharedDirpath="/tlc/aso/writing/shared/";// path from the root to the 'shared' directory

// globals, Copyright 2001-2005 Michael Foster (Cross-Browser.com)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL

var xOp7Up,xOp6Dn,xIE4Up,xIE4,xIE5,xNN4,xUA=navigator.userAgent.toLowerCase();

//var debug = 1;

if(window.opera){
  var i=xUA.indexOf('opera');
  if(i!=-1){
    var v=parseInt(xUA.charAt(i+6));
    xOp7Up=v>=7;
    xOp6Dn=v<7;
  }
}else if(navigator.vendor!='KDE' && document.all && xUA.indexOf('msie')!=-1){
  xIE4Up=parseFloat(navigator.appVersion)>=4;
  xIE4=xUA.indexOf('msie 4')!=-1;
  xIE5=xUA.indexOf('msie 5')!=-1;
}else if(document.layers){xNN4=true;}

xMac=xUA.indexOf('mac')!=-1;


//
// Functions
//

function tuneUpSetUp(){
	xGetElementsByClassName("cloze", document, null, initCloze);
	xGetElementsByClassName("scratchpad", document, null, scratchPad);
	xGetElementsByClassName("glossary", document, null, glossary);
	xGetElementsByClassName("selectword", document, null, selectWordActivity);
	xGetElementsByClassName("jumbleparagraph", document, null, initJumbledParagraph);
	
}

function scratchPad(textArea){
	if(textArea.innerHTML == "Scratch pad"){
		textArea.onfocus = function(){this.innerHTML='';}
	}
}

function glossary(term){
	// if(debug) { alert("glossary"); }
	var glossary_Term = term.innerHTML.replace(/\s+/g,'_');
	var glossary_term = glossary_Term.toLowerCase();
	var glossaryPath = "../glossary.html";
	term.onclick = function(){launchPopup(glossaryPath+'#'+glossary_term);}
}

function selectWordActivity(activity){
	// if(debug) { alert("selectWordActivity"); }
	var html = '';
	var thisOne = 0;
	var word = activity.innerHTML.split(/\s+/, 100);
	var selectWordform = getAncestorByTag(activity, 'form');
	var rightWord = selectWordform.answer.value.split(/\s+/, 100);
	for (i=0; i<word.length; i++){
		if (word[i] == rightWord[thisOne]){
			var correctSegment = word[i].replace(/_/g,' ');
			html += '<a href="javascript:void(null);" onClick="checkLink(this, true); return false;">'+correctSegment+'</a> ';
			thisOne++;
		} else {
			html += '<a href="javascript:void(null);" onClick="checkLink(this); return false;">'+word[i]+'</a> ';
		}
	}		
	activity.innerHTML = html;
}

function typeActivity(activity){
	var numberOfAnswers = (activity.length-2)/2;
	var correct = 0;
	for (c=0; c<numberOfAnswers; c++){
		var answers = activity.answer[c].value.split(',');
		for (a=0; a<answers.length; a++){ 
			if(activity.elements[c].value==answers[a]){
				correct++;
				activity.elements[c].disabled=true;
			}
		}
	}
	if (numberOfAnswers == correct){
		right(activity, 2);
	}else{
		wrong(activity, 1);
	}
}

function revealTypeActivity(activity){
	var numberOfAnswers = (activity.length-2)/2;
	for (c=0; c<numberOfAnswers; c++){
		var answers = activity.answer[c].value.split(',');
		activity.elements[c].value = answers[0];
		activity.elements[c].disabled=true;
	}
	right(activity);
}

function initCloze(activity){
	var chosenArray = '';
	var responseArray = '';
	var responseArray = activity.response.value.split(',');
	if(responseArray[0] != 0 ){responseArray.unshift(0);}
	chosenArray = new Array(responseArray.length-1);
   for (c=0; c<chosenArray.length; c++){
	   chosenArray[c] = 0;
	   //addEvent(activity.elements[c], 'Change', chooseCloze, false);
	   //activity.elements[c].setAttribute('onchange', 'chooseCloze(this, '+c+');');
      for (j=0; j<responseArray.length; j++){
      	activity.elements[c].options[j]=new Option(activity.selections[responseArray[j]].value, activity.selections[responseArray[j]].value);
	  }
    }
	
	/*var Check = document.createElement('input');
	Check.setAttribute('type','button');
	Check.setAttribute('name','check');
	Check.setAttribute('value','Check answer');
	Check.setAttribute('onClick', 'checkCloze(this.form);');
	activity.appendChild(Check);
	
	var Chosen = document.createElement('input');
	Chosen.setAttribute('type','hidden');
	Chosen.setAttribute('name','chosen');
	activity.appendChild(Chosen);
	activity.chosen = Chosen;*/
	
	activity.chosen.value = chosenArray.join(',');
	activity.response.value = responseArray.join(',');
}

function chooseCloze(selObj, choice){
	//alert("chooseCloze");
	var activity = selObj.form;
   var responseArray = activity.response.value.split(',');
   var chosenArray = activity.chosen.value.split(',');
   var selection = selObj.options[selObj.selectedIndex].value;
   for (c=0; c<responseArray.length; c++){
	   if(selection == activity.selections[c].value){
		   chosenArray[choice] = c;
		   break;
	   }
   }
	activity.chosen.value = chosenArray.join(',');
	
	refreshCloze(activity);
}

function refreshCloze(activity){
	//alert("refreshCloze");
  var restArray = new Array();
  var responseArray = activity.response.value.split(',');
  var chosenArray = activity.chosen.value.split(',');
  var n = 0;
  var taken = 0;
   for (j=0; j<responseArray.length; j++){
	    
	   for (c=0; c<chosenArray.length; c++){
		
		   if(responseArray[j] == chosenArray[c]){
			   taken = 1;
			   break;
		   }
	   }
	   if (taken == 0){
		   restArray[n] = activity.selections[responseArray[j]].value;
		   n++;
	   }
	   taken = 0;
	   
   }

	for (c=0; c<chosenArray.length; c++)
		for (j=0; j<responseArray.length; j++)
			activity.elements[c].options[0]=null;
		
	for (c=0; c<chosenArray.length; c++){
		activity.elements[c].options[0]=new Option(activity.selections[chosenArray[c]].value, activity.selections[chosenArray[c]].value, true);
		for (j=0; j<restArray.length; j++){
			 activity.elements[c].options[j+1]=new Option(restArray[j], restArray[j]);
	  	}
	}   
}

function checkCloze(activity){
	//alert("checkCloze");
	var chosenArray = activity.chosen.value.split(',');
	var correct = 0;
	for (c=0; c<chosenArray.length; c++){
		if(chosenArray[c] == c+1){
			correct++;
			activity.elements[c].disabled=true;
		}else{
			chosenArray[c] = 0;
		}
   }
   if(correct==chosenArray.length){
	   right(activity,2);
   }else{
	   wrong(activity,1);
   		activity.chosen.value = chosenArray.join(',');
		setTimeout(function(){refreshCloze(activity);},3000);
   }
}

function checkLink(node, correct){
	// if(debug) { alert("checkLink"); }
  var activity = getAncestorByTag(node, 'form');
  if(correct){right(activity,1);}
  else{wrong(activity);}
}

function initJumbledParagraph(activity){
	// if(debug) { alert("initJumbledParagraph"); }
	/*var jumbledParagraph = document.createElement('p');
	jumbledParagraph.setAttribute('class','jumbledParagraph');
	activity.appendChild(jumbledParagraph);
	
	var Up = document.createElement('input');
	Up.setAttribute('type','button');
	Up.setAttribute('name','up');
	Up.setAttribute('value',' Up ');
	Up.setAttribute('onClick', 'upJumbledParagraph(this.form);');
	activity.appendChild(Up);
	
	var Down = document.createElement('input');
	Down.setAttribute('type','button');
	Down.setAttribute('name','down');
	Down.setAttribute('value','Down');
	Down.setAttribute('onClick', 'downJumbledParagraph(this.form);');
	activity.appendChild(Down);
	
	var Check = document.createElement('input');
	Check.setAttribute('type','button');
	Check.setAttribute('name','check');
	Check.setAttribute('value','Check answer');
	Check.setAttribute('onClick', 'checkJumbledParagraph(this.form);');
	activity.appendChild(Check);
	
	var Chosen = document.createElement('input');
	Chosen.setAttribute('type','hidden');
	Chosen.setAttribute('name','chosen');
	Chosen.setAttribute('value','1');
	activity.appendChild(Chosen);
	activity.chosen = Chosen;
	
	var No_Correct = document.createElement('input');
	No_Correct.setAttribute('type','hidden');
	No_Correct.setAttribute('name','numberCorrect');
	No_Correct.setAttribute('value','0');
	activity.appendChild(No_Correct);
	activity.numberCorrect = No_Correct;*/

	drawJumbledParagraph(activity);
	// if(debug) { alert("doneInitJumbledParagraph"); }
}

function drawJumbledParagraph(activity){
	// if(debug) { alert("drawJumbledParagraph"); }
	var html = '';
	var responseArray = '';
	var responseArray = activity.response.value.split(',');
	
   for (c=0; c<responseArray.length; c++){
      if (c < activity.numberCorrect.value){
          html += '<span class="unavailable">'+activity.sentence[responseArray[c]-1].value;
		  html += '</span> \n';
      }
      else{
          html += '<a href="javascript:void(null);" onClick="chooseJumbledParagraph(this, '+c+');">';
          if (activity.chosen.value==c) html += '<strong>' ;
          html += activity.sentence[responseArray[c]-1].value;
          if (activity.chosen.value==c) html += '</strong>' ;
          html += '</a> \n';
	     }
    }
	var paragraph = getChildrenByClass(activity, "jumbledParagraph")[0]
	paragraph.innerHTML = html
	// if(debug) { alert("doneDrawJumbledParagraph"); }
}

function chooseJumbledParagraph(node, choice){
	// if(debug) { alert("chooseJumbledParagraph"); }
   var activity = getAncestorByTag(node, 'form');
   activity.chosen.value = choice;
   drawJumbledParagraph(activity);
	// if(debug) { alert("doneChooseJumbledParagraph"); }
}

function checkJumbledParagraph(activity){
	// if(debug) { alert("checkJumbledParagraph"); }
	var No_Correct = Number(activity.numberCorrect.value);
	var responseArray = activity.response.value.split(',');
	for (c=0; c<responseArray.length; c++){
      if (responseArray[c]!= c+1){
          break;
      }
      No_Correct=c+1;
   }
   if(No_Correct==responseArray.length){right(activity,2);}
   else{wrong(activity,1);}
   activity.numberCorrect.value = No_Correct;
   drawJumbledParagraph(activity);
}

function upJumbledParagraph(activity){
   var responseArray = activity.response.value.split(',');
   var Chosen = Number(activity.chosen.value);
   if (Chosen > Number(activity.numberCorrect.value)){
      temp = responseArray[Chosen];
      responseArray[Chosen] = responseArray[Chosen-1];
      responseArray[Chosen-1] = temp;
      Chosen = Chosen-1;
	  activity.response.value = responseArray.join(',')
	  activity.chosen.value = Chosen;
   }
   drawJumbledParagraph(activity);
}

function downJumbledParagraph(activity){
   var responseArray = activity.response.value.split(',');
   var Chosen = Number(activity.chosen.value);
   if (Chosen < Number(responseArray.length-1)){
      temp = responseArray[Chosen];
      responseArray[Chosen] = responseArray[Chosen+1];
      responseArray[Chosen+1] = temp;
      Chosen = Chosen+1;
	  activity.response.value = responseArray.join(',')
	  activity.chosen.value = Chosen;
   }
   drawJumbledParagraph(activity);
}

function chooseJumbled(selObj){
	var activity = selObj.form;
	if(activity.optionCount){
		activity.optionCount++;
	} else {
		activity.optionCount = 1;
		activity.clear.disabled = false;
	}
	selObj.options[selObj.selectedIndex].disabled = true;
	getChildrenByClass(activity, "answer")[0].innerHTML += selObj.options[selObj.selectedIndex].value+' ';
	activity.response.value += selObj.options[selObj.selectedIndex].value;
	if (activity.optionCount < activity.optionList.size){
		activity.response.value += ' ';
	} else {
		checkJumbled(activity);
		activity.optionCount = false;
	}
}

function checkJumbled(activity){
	var response = activity.response.value;
	var answer = activity.answer.value;
	if(response == answer){
		right(activity, 2);
	} else { 
		wrong(activity, 1);
		setTimeout(function(){clearJumbled(activity);}, 3000);
	}
}

function clearJumbled(activity){
	activity.optionCount = false;
	activity.response.value = '';
	getChildrenByClass(activity, "answer")[0].innerHTML ='';
	activity.clear.disabled = true;
	for(i=0; i < activity.optionList.size; i++){
		activity.optionList.options[i].disabled=false;
		activity.optionList.options[i].selected=false;
	}  
}

function selectOption(selObj){
	var activity = selObj.form;
	var answer = selObj.options[selObj.selectedIndex].value;
 	 if (answer=='right') {right(activity, 1);} 
 	 else {wrong(activity);}
}

function selectWordsActivity(activityId, sentence, selectWords){
	var html = '';
	var thisOne = 0;
	var question = activityId + 'Question';
	var word = sentence.split(/\s+/, 100);
	var selectWord = selectWords.split(/\s+/, 100);
	html += '<p id="'+question+'" style="display:block";>'
	for (i=0; i<word.length; i++){
		if (word[i] == selectWord[thisOne]){
			html += '<a onClick="correct(\''+activityId+'\'); return false;">'+word[i]+'</a> ';
			thisOne = thisOne+1;
		} else {
			html += '<a onClick="incorrect(); return false;">'+word[i]+'</a> ';
		}
	}		
	html += '</p>';
	document.write(html);
}

var sequence = 0;

function right(activity, speed){
  var time = 0;
  if(speed==1) {time = 2000; feedbackWindow(sharedDirpath+'correct_quick.html');}
  if(speed==2) {time = 3000; feedbackWindow(sharedDirpath+'correct.html');}
  var question = getChildrenByClass(activity, "question")[sequence];
  var buttons = getElementsByTagNames('input', activity);
  var answer = getChildrenByClass(activity, "answer")[sequence];
  var correct = getChildrenByClass(activity, "correct")[sequence];
  var feedback = getChildrenByClass(activity, "feedback")[sequence];
  var nextQuestion = getChildrenByClass(activity, "question")[sequence+1];
  if(question) { setTimeout(function(){question.style.display = 'none';}, time);}
  if(buttons) {
	 setTimeout(function(){
	   var b;
	   for (b in buttons){buttons[b].disabled = true;}
	 }, time);
  }
  if(answer) { setTimeout(function(){answer.style.display = 'none';}, time);}
  if(correct) { setTimeout(function(){correct.style.display = 'block';}, time);}
  if(feedback) { setTimeout(function(){feedback.style.display = 'block';}, time);}
  if(nextQuestion) { setTimeout(function(){nextQuestion.disabled = false; sequence++;}, time);}
  else sequence = 0;
}

function wrong(activity, speed){
	var time = 2000;
  if(isUndefined(speed)){feedbackWindow(sharedDirpath+'incorrect_quick.html');}
  else {time = 3000;  feedbackWindow(sharedDirpath+'incorrect.html');}
  var incorrect = getChildrenByClass(activity, "incorrect")[sequence];
  if(incorrect){
	  setTimeout(function(){incorrect.style.display = 'block';}, time);
	  setTimeout(function(){right(activity);}, time);
  }
}

function selectAnswer(selObj){
activityId = selObj.options[selObj.selectedIndex].value;

  if (activityId=='f') {incorrect();}
  else correct(activityId); 
}

function correct(passedActivityId){
  var question = passedActivityId + 'Question';
  var nextQuestion = passedActivityId + 'NextQuestion';
  var activityId = passedActivityId;
  feedbackWindow(sharedDirpath+'correct_quick.html');
  setTimeout("document.getElementById(question).style.display='none'; document.getElementById(activityId).style.display='';", 2000);
  if (document.getElementById(nextQuestion)) {
  	  setTimeout("document.getElementById(nextQuestion).disabled=false;", 2000);
  }
}

function incorrect(){
	feedbackWindow(sharedDirpath+'incorrect_quick.html');
}

function highlightTerm(){
	var term=location.hash.substr(1).replace(/#/g,'');
	if(term){
		document.getElementById(term).style.color ='#009900';
	}
}

function launchPopup(filename){
  var theWindow = null;
  w = 720;
  h = 540;
  LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
  TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
  var settings = 'scrollbars=yes, resizable=yes, target="_blank", location=0, statusbar=0, menubar=0, height= '+h+',width= '+w+',top='+TopPosition+',left='+LeftPosition;
  theWindow = window.open(filename, 'Writing', settings);
  theWindow.focus();
  theWindow.scroll;
  return theWindow;
}

function feedbackWindow(filename){
  var win = null;
  w = 200;
  h = 150;
  LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
  TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
  settings = 'scrollbars=no, resizable=no, height= '+h+',width= '+w+',top='+TopPosition+',left='+LeftPosition+''
  feedback = window.open(filename,'Feedback', settings);

}

function printWithCommentary(number_of_comments){
	var i;
	for(i=1; i<number_of_comments+1; i++){
		document.getElementById('commentary_'+i).style.display='';
	}
	window.print();
}

// Library functions //

function getAncestorByTag(node, tag){
  if (!node.parentNode){return null;}
  if (node.parentNode.nodeName.toUpperCase() == tag.toUpperCase()){return node.parentNode;}
  return getAncestorByTag(node.parentNode, tag);
}

function getChildrenByClass(parent, className){
	var collection = parent.childNodes;
	var returnedCollection = [];
	var exp = getRegExp(className,"");
	for(var i = 0, counter = 0; i < collection.length; i++){
		if(exp.test(collection[i].className)){
			returnedCollection[counter++] = collection[i];
		}
	}
	return returnedCollection;
}

var regExpArr = new Array();

function getRegExp(token, flag){
	var x = regExpArr[token];
	if(!x)  x = regExpArr[token] = new RegExp("(^|\\s)"+token+"($|\\s)", flag);
	return x;
}

function xGetElementsByTagName(t,p)
//Returns an array of elements which are descendants of parentEle and have tagName.
//If parentEle is null or not present, document will be used.
//If tagName is null or not present, "*" will be used.
//t - tagNamestring
//p - parentEleelement reference
{
  var list = null;
  t = t || '*';
  p = p || document;
  if (xIE4 || xIE5) {
    if (t == '*') list = p.all;
    else list = p.all.tags(t);
  }
  else if (p.getElementsByTagName) list = p.getElementsByTagName(t);
  return list || new Array();
}


function xGetElementsByClassName(c,p,t,f)
//Returns an array of elements which are descendants of parentEle and have tagName and clsName.
//If parentEle is null or not present, document will be used.
//If tagName is null or not present, "*" will be used.
//c - sClsName
//p - oParentEle
//t - sTagName
//f - fncallback function, iterates thru the returned list
{
  var found = new Array();
  var re = new RegExp('\\b'+c+'\\b', 'i');

  var list = xGetElementsByTagName(t, p);
  for (var i = 0; i < list.length; ++i) {
    if (list[i].className && list[i].className.search(re) != -1) {
      found[found.length] = list[i];
      if (f) f(list[i]);
    }
  }
  return found;
}

function isUndefined(a) { return typeof a == 'undefined' }

function getMousePos(e) {
	var posx = 0;
	var posy = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	// posx and posy contain the mouse position relative to the document
	// Do something with this information
}

function getObj(name)
{
  if (document.getElementById)
  {
  	this.obj = document.getElementById(name);
	this.style = document.getElementById(name).style;
  }
  else if (document.all)
  {
	this.obj = document.all[name];
	this.style = document.all[name].style;
  }
  else if (document.layers)
  {
   	this.obj = document.layers[name];
   	this.style = document.layers[name];
  }
}

function getElementsByTagNames(list,obj) {
	if (!obj) var obj = document;
	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}

function addEvent(elm, evType, fn, useCapture){
	if (elm.addEventListener){
		elm.addEventListener(evType, fn, useCapture);
		return true;
	} else if (elm.attachEvent) {
			   var r =elm.attachEvent('on' + evType, fn);
			   return r;
			   } else {
				   elm['on' + evType] = fn;
			   }
}


// DW scripts //

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

