
// PARAMETERS

if(!self.quizTitle)	self.quizTitle=self.document.title
if(!self.questionTitle)	self.questionTitle="Question"
if(!self.secPerQuestion)self.secPerQuestion=60
if(!self.choiceStyle)	self.choiceStyle="checkbox"
if(!self.bgrColor)	self.bgrColor="white"
if(!self.txtColor)	self.txtColor="black"
if(!self.hdrColor)	self.hdrColor="darkblue"
if(!self.lnkColor)	self.lnkColor="blue"
if(!self.bgrImage)	self.bgrImage=""

if(!self.mailSubject)	self.mailSubject="JQwiz Results"
if(!self.sendMailTo)	self.sendMailTo=""
if(!self.formMailURL)	self.formMailURL=""
if(!self.additionalInfo)self.additionalInfo=""

if(!self.StartButtonText)	self.StartButtonText="Start Quiz"
if(!self.SubmitButtonText)	self.SubmitButtonText="Submit"
if(!self.ShowAnswersButtonText)	self.ShowAnswersButtonText=""
if(!self.NextAnswerButtonText)	self.NextAnswerButtonText="Next correct answer"
if(!self.ShowScoreButtonText)	self.ShowScoreButtonText="Return to your score"
if(!self.ExitButtonText)	self.ExitButtonText=""
if(null==self.onExitDoThis)	self.onExitDoThis="top.close()"

if(!self.introPageURL)		introPageURL="default"

defaultMsg = '<small>'
 +'Made for the <a target=_blank href="http://www.queencitychmm.org">Queen City ACHMM</a>. '
 +'Copyright &#169; 2004 <a href="mailto:jereece@softhome.net?subject=Java Quiz">Jim Reece</a>'
 +'</small>'

JQwizIntroPage = 'JQ_intro.htm'
JQwizMainPage  = 'JQwiz_f1.htm'


// ROOT URL

function regularize(theURL) {
 for (j=0;j<theURL.length;j++) {
  if (theURL.charAt(j)=="\\") theURL=theURL.substring(0,j)+"/"+theURL.substring(j+1,theURL.length);
 }
 return theURL
}
trueRootURL=regularize(""+self.document.location)
trueRootURL=trueRootURL.substring(0,trueRootURL.lastIndexOf("/")+1)


// VARIABLES

currPhase=0
curr=-1;
buf='';
msg=defaultMsg;
elapsedTime=0;
timerID=null;
userEmail=''
userName=''
userCompany=''


// ARRAYS

questions	=new Array()
choices  	=new Array()
nChoices 	=new Array()
answers  	=new Array()
boxes    	=new Array()
codes    	=new Array()
nCorrectChoices	=new Array()
comments	=new Array()


// INITIALIZING QUESTIONS/CHOICES

nq=-1;
function question (str) {
 nq++;
 questions[nq]=str
 answers[nq]=''
 comments[nq]=''
 nQuestions=nq+1;
}

function comment (str) {
 comments[nq] = ( str.charAt(0)==';' ? TAB(str):str )
}

function choice (code,str) {
 if (!choices[nq]) {
  choices[nq]=new Array();
  codes[nq]=new Array();
  nc=0;
 }
 codes[nq][nc]=code;
 choices[nq][nc]=str;
 nChoices[nq]=nc+1;
 answers[nq]+='0';
 nc++;
}

function initAll() {
 var s=0;
 for (var i=0;i<nQuestions;i++) {
  nCorrectChoices[i]=0;
  for (var k=0;k<nChoices[i];k++) {
   if (isAnswerCorrect(i,k)) {
    nCorrectChoices[i]++;
    s++;
   }
  }
 }
 OneCorrectAnswer=(s==nQuestions)?true:false;
 if (choiceStyle.toLowerCase()!='radio') choiceStyle='checkbox';
}

function toMinSec(sec) {
 if (sec<=60) return " "+sec+"&nbsp;seconds ";
 var rsec=sec%60;
 var min=(sec-rsec)/60;
 if (rsec==0) return " "+min+"&nbsp;minutes ";
 return " "+min+"&nbsp;min&nbsp;"+rsec+"&nbsp;sec ";
}

function showDirections() {
 if (self.introPageURL && (''+self.introPageURL).toLowerCase().indexOf('.htm')!=-1) {
  self.frames[0].location.replace(trueRootURL+self.introPageURL);
 }
 else self.frames[0].location.replace(trueRootURL+self.JQwizIntroPage);
}

function showStartButton() {
 buf='\n<p><form name=f1 action="" onSubmit="parent.askQuestion();return false">'
 if (self.formMailURL && self.sendMailTo) {
  buf+='<table border=0 cellpadding=2 cellspacing=2>'
  buf+='<tr><td>Your name:</td><td><input name=userName type=text value="" size=20></td></tr>'
  buf+='<tr><td>Your email:</td><td><input name=userEmail type=text value="" size=20></td></tr>'
  if (additionalInfo) buf+='<tr><td>'+additionalInfo+':</td><td><input name=userCompany type=text value="" size=20></td></tr>'
  buf+='</table>'
 }
 buf+='<br><input type=button value="'+self.StartButtonText+'" onClick=parent.askQuestion()>'
 +'</form>\n'
 self.frames[0].document.write(buf);
 buf='';
}

function stripSpaces(str) {
 var out=str;
 while (out.charAt(out.length-1)==" ") out=out.substring(0,out.length-1);
 while (out.charAt(0)==" ") out=out.substring(1,out.length);
 return out;
}

function isValidEmail(str) {
 var strLC=(''+str).toLowerCase();
 if (strLC.indexOf('@')<1) return 0;
 if (strLC.indexOf('@')!=strLC.lastIndexOf('@')) return 0;
 if (strLC.indexOf('@')+1==strLC.length) return 0;
 if (strLC.indexOf('.')<1) return 0;
 if (strLC.indexOf('.')+1==strLC.length) return 0;
 for (var k=strLC.indexOf('@');k<strLC.length;k++) {
  if ('abcdefghijklmnopqrstuvwxyz1234567890@-._'.indexOf(strLC.charAt(k))==-1) return 0;
 }
 return 1;
}

function askQuestion() {
 if (curr==-1) {
  if (self.formMailURL && self.sendMailTo
   && self.f1JQwiz.document
   && self.f1JQwiz.document.f1
   && self.f1JQwiz.document.f1.userEmail
  )
  {
   userName=""
   userCompany=""
   userEmail=stripSpaces(''+self.f1JQwiz.document.f1.userEmail.value)
   if (!isValidEmail(userEmail)) {
    alert ('Invalid email! Please enter your email again...')
    return;
   }
   if (self.f1JQwiz.document.f1.userName) {
    userName=stripSpaces(''+self.f1JQwiz.document.f1.userName.value)
    if (userName=="") { alert('Please enter your name!'); return}
   }
   if (self.f1JQwiz.document.f1.userCompany) {
    userCompany=stripSpaces(''+self.f1JQwiz.document.f1.userCompany.value)
    if (additionalInfo && userCompany=="") { alert('Please enter your '+additionalInfo.toLowerCase()+'!'); return}
   }
  }
  curr=0;
 }
 if (!self.isUsingWizard) clearMessage();
 showQuestion();
 buf+='<p><input type=button value="'+self.SubmitButtonText+'" onClick=parent.submitAnswer()></form>'
 self.f1JQwiz.location=self.trueRootURL+JQwizMainPage;
 secondsLeft=secPerQuestion;
 if (!self.isUsingWizard) setTimeout("self.status='"+secondsLeft+" sec left';timer()",300);
}

function clearMessage() {
 msg=defaultMsg;
 self.f2JQwiz.location=''+self.f2JQwiz.location;
}

function showQuestion() {
 buf='<H3><font color="'+self.hdrColor+'">'+self.questionTitle+' '+(curr+1)+'</font></H3>';
 buf+=questions[curr];
 buf+='\n<form name=f1><table border=0 cellspacing=2 cellpadding=0>\n';

 for (var k=0;k<nChoices[curr];k++) {
  buf+='<tr><td valign=baseline><input name=c'+k+' type='+choiceStyle+' onClick=parent.clkbox('+k+')></td>'
  buf+='<td>'+choices[curr][k]+'</td></tr>\n'

  boxes[k]=0;
 }
 buf+='</table>'
}

function clkbox(k) {
 if (nCorrectChoices[curr]==1) {
  for (var n=0;n<nChoices[curr];n++) {
   eval('self.f1JQwiz.document.f1.c'+n+'.checked=false');
   boxes[n]=0;
  }
  eval('self.f1JQwiz.document.f1.c'+k+'.checked=true');
  boxes[k]=1;
 }
 else {
  if (boxes[k]==0) {
   eval('self.f1JQwiz.document.f1.c'+k+'.checked=true');
   boxes[k]=1;
  }
  else {
   eval('self.f1JQwiz.document.f1.c'+k+'.checked=false');
   boxes[k]=0;
  }
 }
}

function timer() {
 if (secondsLeft>0) {
  if (secondsLeft==10) {
   msg='<center><H3><font color=red>'+secondsLeft+' seconds left!</font></H3></center>';
   self.f2JQwiz.location=''+self.f2JQwiz.location;
   setTimeout("parent.status='"+secondsLeft+" sec left'",300);
  }
  self.status=secondsLeft+' sec left'
  elapsedTime++;
  secondsLeft--;
  timerID=setTimeout('timer()',1000);
 }
 else getAnswer();
}

function submitAnswer() {
 clearTimeout(timerID);
 getAnswer();
}

function getAnswer() {
 answers[curr]='';
 for (k=0;k<nChoices[curr];k++) {
  answers[curr]+=boxes[k];
 }
 curr++;
 if (curr<nQuestions) setTimeout("askQuestion()",100);
 else {curr=-1; currPhase=1; setTimeout("finalizeResults()",100);}
}

function finalizeResults() {
 nCorr=correctAnswersCount()
 msg=defaultMsg
 if (self.isUsingWizard==null && self.formMailURL && self.sendMailTo && self.userEmail) 
 {
  msg+=''
  +'\n<form name=f2 target=_self ACTION="'+formMailURL+'" METHOD="POST">'
  +'\n<input type=hidden name="subject" value="'+mailSubject+'">'
  +'\n<input type=hidden name="redirect" value="'+self.f2JQwiz.location+'">'
  +'\n<input type=hidden name="recipient" value="'+sendMailTo+'">'
  +'\n<input type=hidden name="email" value="'+userEmail+'">'
  +'\n<input type=hidden name="Name....................." value="'+userName+'">'
  +'\n<input type=hidden name="Additional info (company)" value="'+userCompany+'">'
  +'\n<input type=hidden name="Email...................." value="'+userEmail+'">'
  +'\n<input type=hidden name="Number of correct answers" value="'+nCorr+' of '+nQuestions+'">'
  +'\n<input type=hidden name="Percentage correct......." value="'+(Math.round(100*nCorr/nQuestions))+'\%">'
  +'\n<input type=hidden name="Elapsed time............." value="'+elapsedTime+' sec">'
  +'\n<input type=hidden name="Average time per question" value="'+(Math.round(elapsedTime/nQuestions))+' sec">'
  +'\n<input type=hidden name="Wrong answer(s).........." value="'+(inCorrList==''?'None':inCorrList)+'">'
  +'\n</form>'
 }

 self.f2JQwiz.location=''+self.f2JQwiz.location;
 setTimeout("sendResults()",100);
}

resultsAlreadySent=0
nAttemptsToSend=0

function sendResults() {
 if (!resultsAlreadySent && self.isUsingWizard==null && self.formMailURL && self.sendMailTo && self.userEmail)
 {
  nAttemptsToSend++
  if (self.f2JQwiz.document && self.f2JQwiz.document.f2) {
   self.f2JQwiz.document.f2.submit()
   resultsAlreadySent=1
  }
  else if (nAttemptsToSend<10) {setTimeout("sendResults()",1000); return}
 }
 setTimeout("displayResults()",100);
}

function displayResults() {
 buf='<H3><font color="'+self.hdrColor+'">Congratulations!</font></H3>';
 buf+='<H4>You completed the <i>'+self.quizTitle+'</i> with the following results:</H4>';
 buf+='<table border=0 cellpadding=2 cellspacing=2>';
 buf+='<tr><td>Correct answers:</td><td>'+nCorr+' of '+nQuestions+'</td></tr>';
 buf+='<tr><td>Percentage correct:</td><td>'+(Math.round(100*nCorr/nQuestions))+'\%</td></tr>';
 buf+='<tr><td>Elapsed time:</td><td>'+elapsedTime+' sec</td></tr>';
 buf+='<tr><td>Average time per question:</td><td>'+(Math.round(elapsedTime/nQuestions))+' sec</td></tr>';
 buf+='</table>';

 buf+='<form name=f1>' 
 if (self.ShowAnswersButtonText) buf+='<input type=button value="'+self.ShowAnswersButtonText+'" onClick="parent.showCorrectAnswer()">';
 if (self.ExitButtonText && self.onExitDoThis) buf+='<input type=button value="'+self.ExitButtonText+'" onClick="'+self.onExitDoThis+'">'
 buf+='</form>'

 self.f1JQwiz.location=trueRootURL+JQwizMainPage;
}

function getCorrectAnswer(n) {
 var str='';
 for (var k=0;k<nChoices[n];k++) str+=isAnswerCorrect(n,k)?1:0;
 return str;
}

function isAnswerCorrect(n,k) {
 return ( parseInt(codes[n][k],36)%33 == 1 )
}

inCorrList=''
function correctAnswersCount(n) {
 var n=0;
 inCorrList='';
 for (var k=0;k<nQuestions;k++) {
  if ((getCorrectAnswer(k)).indexOf(answers[k])==0) n++;
  else inCorrList += (inCorrList=='' ? '' : ',')+(k+1)
 }
 return n;
}

// preload images
crossImg=new Image(); crossImg.src="cross.gif"
checkImg=new Image(); checkImg.src="check.gif"
bkImg   =new Image(); if (self.bgrImage) bkImg.src=bgrImage;


function showCorrectAnswer() {
 curr++; if (curr>=nQuestions) curr=0;

 buf='<H3><font color="'+self.hdrColor+'">'+self.questionTitle+' '+(curr+1)+'</font></H3>'
 +questions[curr]
 +'\n<table border=0 cellspacing=2 cellpadding=0>\n'

 for (var k=0;k<nChoices[curr];k++) {
  buf+='<tr><td valign=baseline>'
  buf+=isAnswerCorrect(curr,k)?'<img src="check.gif"></td>':((answers[curr].charAt(k)==1)?'<img src="cross.gif"></td>':'</td>')
  buf+='<td>'+choices[curr][k]+'</td></tr>\n'
 }
 buf+='</table>'

 if (comments && comments[curr]) buf+='<p>'+comments[curr]

 if (curr==nQuestions-1) {
  buf+='<form name=f1>' 
  buf+='<input type=button value="'+self.ShowScoreButtonText+'" onClick="parent.displayResults()">'
  if (self.onExitDoThis) msg+='<input type=button value="'+self.ExitButtonText+'" onClick="'+self.onExitDoThis+'">'
  buf+='</form>'
 }
 else {
  buf+='<form name=f1>' 
  buf+='<input type=button value="'+self.NextAnswerButtonText+'" onClick="parent.showCorrectAnswer()">'
  buf+='</form>'
 }
 self.f1JQwiz.location=''+self.f1JQwiz.location;
}

function TAB(str) {
 var ch,ix,outStr='',TBL=' 01234ABCDEFGHIJKLM';
 TBL+='/56789NOPQRSTUVWXYZ'+TBL; TBL+=TBL.toLowerCase()
 for (var k=0;k<str.length;k++) {
  ch=str.charAt(k); ix=TBL.indexOf(ch)
  outStr+=(ix==-1)?ch:TBL.charAt(ix+19)
 }
 if (outStr.charAt(0)==';') outStr=outStr.substring(1)
 else outStr=';'+outStr
 return outStr;
}

function unloadHandler() {
 if(isUsingWizard
   && self.f2JQwiz.saveQuiz 
   && confirm("Save quiz '"+quizTitle+"'?")
 ) 
 {
  self.f2JQwiz.saveQuiz()
 }
}

function silentError() {return true}
window.onerror=silentError



