<!--Copyright 1999-2002 Center for Computer-Assisted Legal Instruction. All Rights Reserved. -->
//
//#######################################################
//################################## START OF COMMON ####
//#######################################################

// 02/19/98 SJG Common JavaScript functions included for all CALI Author page types, a library of sorts.
// 07/99 Added Scoring
// 08/24/00 fixed typos
// 10/15/00 Added Comment option
// 02/01 copied styles into popupwindow since IE doesn't like to link to it, causes lockup.
// 04/18/01 Embedded image patch. Now reference images whose SRC is changed by name instead of index.
// 05/01/01 Push page name away from right margin for Netscape to avoid covering up by scroll bar.
// 05/10/01 Rename SHARE to share and ensure links to images are all lowercase
// 11/16/01 Include browser info in user comment.
// 12/07/01 Fix problem with MC buttons containing double quote.
// 01/17/02 Branching popups now wait til user clicks Continue before moving to next page.
// 06/03/02 Put popup links in window separate from feedbacks.
// 06/27/02, 7/12/02  CALI Quiz tracking support via TScore object.


var popuppage
var pop
var toolbar //11/29/01 declare it to avoid IE error

var RIGHT  ="R"
var WRONG  ="W"
var MAYBE  ="M"
var INFO   ="I"
var POSSIBLE=MAYBE

var RIGHTCOLOR="#CCFFCC"
var WRONGCOLOR="#FFCCCC"
var MAYBECOLOR="#FFFFDD"
var INFOCOLOR= "#DDDDFF"

var gradecolor=new Array(RIGHTCOLOR,WRONGCOLOR,MAYBECOLOR,INFOCOLOR);
var gradeborder=new Array("#00AA00","#AA0000","#DDDD00","#0000AA");
var gradetitle=new Array("Correct","Wrong","Possibly","Information")
var gradeicon= new Array("good.gif","bad.gif","possible.gif","info.gif")

var Browser = navigator.appName
if (Browser.indexOf("Microsoft")==0) Browser="Microsoft"

var Version = navigator.appVersion;
if ((Browser == 'Microsoft') && (Version.indexOf('MSIE ') != -1))
	Version = Version.substring(Version.indexOf('MSIE ')+5);
Version = Version.substring(0,1);
var NETSCAPE = Browser == "Netscape"
var IE = Browser =="Microsoft"
var LAYERS = (Version>=4)
var helpanchor
var helpmsg







if (top==self && popuppage==null)
{
//If we are being displayed in a standalone window and not a Popup, it's an error
	window.onerror=myerrhandler
	//document.writeln("<blink>Warning!</blink> This page must be viewed within the Frame setting to work properly.")
}else{
	if (parent.debug!=null)
		window.onerror=myerrhandler
	else
	//	window.onerror=null
;
}

function myerrhandler(msg,url,linenum)
{
	var errmsg="JavaScript Error\n" + url + '\nLine# ' +linenum + ': '+ msg
	if (hasdebugbox())
		status(errmsg )
	else
		alert(errmsg)
   return true
}

function ignoreerror(msg,url,linenum)
{
	return true;
}

function FEEDBACK(feedback,grade,dest)
{
	this.feedback=feedback
	this.grade=grade
	this.dest=dest
}

function shownote()
{
	var pagename=getpagename()
	if (parent)
		if (parent.emailcontact=="")
			alert("No email address specified by the author.")
		else
		{ // 11/16/01 include browser detail in user's comment.
			var body
			body= "The following helps us respond to your comment faster:" + " %0D%0A"+
					"  Browser: " + navigator.appName + " Version: "+ navigator.appVersion + ". %0D%0A" +
					"  URL: " + parent.body.document.location + ". %0D%0A" +
					"  Lesson: " + parent.lessonid + " (Version " + (parent.revision) + "). %0D%0A" +
					"  Page: '" + escape(pagename)+ "'. %0D%0A" +
					"Please include your comment here:" + " %0D%0A"
			var url="mailto:" + escape(parent.emailcontact) + "?" +
					(parent.emailtechsupportcontact!=""?("cc=" + escape(parent.emailtechsupportcontact)):(""))  + "&" +
					"subject=CALI Lesson Comment: "+(parent.lessonid) + "/" + escape(pagename)  +
					"&body="  + body;


			//var url="mailto:" + parent.emailcontact + "?subject=CALI Lesson Comment: "+(parent.lessonid)+ "/" + pagename
			//alert(url)

			document.location=url
		}
}

function getpagename()
{
	var saveerror=window.onerror
	window.onerror=ignoreerror
	var pagename=""
	pagename= title
	window.onerror=saveerror
	return pagename
}






//### Shared Book Page functions

function GenerateBookPage()
{
	nhotspots=hotspots.length
	nslides=slides.length
	slide=0
/*
	BASE=1
	if (picture!="") BASE++
	if (video!="") BASE+=2
*/

   if (video=="" && nslides==0 && nhotspots==0 && sound=="")
   {
   	helpanchor="TEXT"
   	writeoptions("When you are finished reading click the Next button to go to the next page.",false,false,true)

   	if (picture=="")
   		document.write(text)
   	else
   	{
   		if (alignRight==orientation)
				document.write("<table border=0><tr valign=top><td align=center>"+
						"<img name='picture' src="+picture+"></td><td>"+text+"</td></tr></table>") //"<img align=left src="+picture+">"+text)
   		else
   		if (alignLeft==orientation)
				document.write("<table border=0><tr valign=top><td>"+text+"</td>"+
					"<td align=center><img name='picture' src="+picture+"></td></tr></table>")
   		else
   		if (alignBottom==orientation) document.write("<center><img name='picture' src="+picture+"></center>"+text)
   		else
   		if (alignTop==orientation) document.write(text+"<center><img name='picture' src="+picture+"></center>")
   		else
			if (text!="")
				document.write("<table border=0><tr valign=top><td>"+text+"</td>"+
					"<td align=center><img name='picture' src="+picture+"></td></tr></table>")
			else
				document.write("<center><img name='picture' src="+picture+"></center>")

   		document.write(BRCLR)
   	}
   	writehelp()
	}

   if (video!="")
   {
   	helpanchor="VIDEO"
   	writeoptions("Click the <img border=0 src=../share/video.gif> button to view the video.",false,false,next!="")
   	document.writeln(text)
   	writehelp()
   	document.writeln("<center><a href=javascript:popvideo('" + video + "')>")
   	document.writeln("<img name='video' src=../share/video.gif></a></center>")
   }


   if (nhotspots>0)
   {
   	helpanchor="IMAGEMAP"
   	writeoptions("Click somewhere on the picture.",false,false,next!="")
   	writehelp()
		document.writeln(text);
		document.writeln("<center>")
   	document.writeln("<img name='picture' src="+picture+" usemap=\"#cop\">")
   	document.writeln("<map name=\"cop\">");
   	for (h=0;h<nhotspots;h++)
   			document.writeln("<area shape=RECT coords=\""+
   			hotspots[h].left+','+hotspots[h].top+','+
   			hotspots[h].right+','+hotspots[h].bottom+
   			"\" href=\"javascript:mapclick("+h+")\">");
   	document.writeln("</map></center>")
   }


   if (nslides>0)
   {
   	helpanchor="SLIDE"
   	writeoptions("View each slide by pressing the <img border=0 src=../share/ss-next.gif> button.",false,false,next!="")

   	document.writeln(text)
   	writehelp()
   	icons=new Array("ss-back.gif","ss-back_.gif","ss-next.gif","ss-next_.gif")
   	document.write("<table width=100%>")
   	document.write("<td align=center><img name='slide' src=" +slides[0]+"></td></tr><tr><td align=center>")
   	document.write("<a href=javascript:goslide(-1)><img name='slideback' border=0 src=../share/ss-back.gif></a>")
   	document.write("<a href=javascript:goslide(1)><img name='slidenext' border=0 src=../share/ss-next.gif></td></tr>")
   	document.write("</table>")

   	goslide(0)
   }


   if (sound!="")
   {
   	helpanchor="SOUND"

		if (transcript=="")
   		writeoptions("Listen to the sound.",false,false,next!="")
		else
	   	writeoptions("Listen to the sound. A transcript is also available.",false,false,next!="")


   	document.writeln(text)
   	writehelp()
   	document.write("<BR>")
   	if (picture!="") document.write("<center><img name='picture' src="+picture+"></center>")

		if (sound.indexOf(".mp3")>=0)
		{
   		document.write("<center>")
			WriteMP3(sound)
   		document.write("</center>")
   		document.write("<center><a href=javascript:soundclick()><img name='transcripticon' src=../share/page.gif></a></center>")
		}
		else
		{
//   		document.write("<center><a onclick=\"javascript:soundclick()\" href="+sound+"><img name='sound' src=../share/sound.gif></a></center>")
			document.write("<center>")
			document.write("<a href="+sound+"><img name='sound' src=../share/sound.gif></a>")
			document.write("<a href=javascript:soundclick()><img name='transcripticon' src=../share/page.gif></a>")
			document.write("</center>")
		}
		document.writeln("<div id=transcript>"+transcript+"</div>")
   }

	writepagename()
}


function soundclick()
{
	showLayer("transcript")
}


function WriteMP3(mp3)
{
// Create OBJECT and EMBED code with a FlashVar parameter to pass MP3 sound to play to the Flash movie.
var txt='<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="290" HEIGHT="50" id="WebolisSoundPlayer" ALIGN=""> <PARAM NAME=movie VALUE="../share/webolissoundplayer.swf"> <PARAM NAME=quality VALUE=high> <PARAM NAME=bgcolor VALUE=#FFFFFF> <PARAM NAME=FlashVars VALUE="mp3=' + mp3 + '">' +
	'<EMBED src="../share/webolissoundplayer.swf" quality=high bgcolor=#FFFFFF  WIDTH="290" HEIGHT="50" NAME="WebolisSoundPlayer" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer" FlashVars="mp3=' + mp3 + '"></EMBED>' +
	'</OBJECT>'
document.write(txt)
}



function hotspot(l,t,r,b,link,popup,scored)
{
	this.left=l
	this.top=t
	this.right=r
	this.bottom=b
	this.link=link
	this.popup=popup
	this.scored=scored
}

function goslide(delta)
{
	slide+=delta
	if (slide<0) slide=0;
	if (slide>nslides-1) slide=nslides-1;
	document.images["slide"].src=slides[slide]
	document.images["slideback"].src="../share/"+icons[0+(slide==0)]
	document.images["slidenext"].src="../share/"+icons[2+(slide==nslides-1)]
}

function mapclick(h)
{
	if (hotspots[h].popup)
		pophtml(hotspots[h].link)//,hotspots[h].scored)
	else
		document.location=hotspots[h].link
}

function popvideo(popup)
{
	var popwin2=window.open(popup,"Video",'resizable=0,scrollbars=0,width=200,height=200');
}

//### End shared book page functions

function replace(string,text,by) {
  // Replaces text with by in string. From http://developer.irt.org/script/771.htm
      var strLength = string.length, txtLength = text.length;
      if ((strLength == 0) || (txtLength == 0)) return string;

      var i = string.indexOf(text);
      if ((!i) && (text != string.substring(0,txtLength))) return string;
      if (i == -1) return string;

      var newstr = string.substring(0,i) + by;

      if (i+txtLength < strLength)
          newstr += replace(string.substring(i+txtLength,strLength),text,by);

      return newstr;
  }

//### Shared Multiple choice Page functions

function FixButtonName(name)
{// If name contains a double quote, make it &quot;
	return replace(name,"\"","&quot;")
}
function GenerateMCPage()
{
	nbuttons=buttons.length
	ndetails=details.length
	attempts=0
	writeoptions("Click on the buttons to indicate your choices.",false,true,next!="")

	document.write(ques)

	writehelp()
	document.write("<table>")
	if (justbuttons)
	{
		document.write("<tr align=center>")
		for (var c=0;c<nbuttons;c++)
		{
			document.write("<td><img name='button" + c + "' src=../share/blank.gif></td>")
			document.write("<td><input type=button onclick='mc_choose(" + c + ");' value=\" "+FixButtonName(buttons[c])+" \"></td>")
		}
		document.write("</tr>")
	}
	else if (multiplebuttons)
	{
		for (var d=0;d<ndetails;d++)
		{
			document.writeln("<tr valign=top><td><b>"+(d+1)+".</b></td>")
			for (var b=0;b<nbuttons;b++)
			{
				document.write("<td><img name='button"+mc_checkindex(d,b)+"' src=../share/blank.gif></td>")
				document.writeln("<td><input type=button onclick='mc_choosemulti(" + d + "," + b + ");' value=\""+FixButtonName(buttons[b])+"\"></td>" )
			}
			document.writeln("<td>"+details[d]+"</td></tr>")
		}
	}
	else
	{
		for (var c=0;c<ndetails;c++)
		{
			document.write("<tr valign=top>")
			document.write("<td><img name='button"+c+"' src=../share/blank.gif></td>")
			document.write("<td><a href='' onclick='mc_choose(" + c + ");return false'><img border=0 src=../share/"+letter.substring(c,c+1)+".gif></a></td>" )
			document.write("<td>"+details[c]+"</td></tr>")
		}
	}
	document.write("</table>")
	writepagename()
}

function mc_choose(c)
{
	attempts=attempts+1
	if (attempts==1)
		if (justbuttons)
			answerSave(title,c+1,buttons[c])
		else
			answerSave(title,c+1,letter.substring(c,c+1).toUpperCase())
	if (feedback[c].feedback!="")
	{
		setgradeicon("button"+c,feedback[c].grade)
		showfeedback(feedback[c].feedback,feedback[c].grade,feedback[c].dest)
	}
	else
		showfeedback("",feedback[c].grade,feedback[c].dest) // 1/22/02 If no feedback, see if just a jump.
}


function mc_choosemulti(q,c)
{
	attempts=attempts+1
	if (attempts==1)
		answerSave(title,(q+1)+"-"+(c+1), (q+1)+"-"+buttons[c])
	var idx=mc_checkindex(q,c)
	setgradeicon("button"+ idx,feedback[idx].grade)
	showfeedback(feedback[idx].feedback,feedback[idx].grade)
}

function mc_checkindex(q,c)
{
	return c+q*nbuttons
}

function mc_doreveal()
{
	if (attempts==0) {tryitonce();return;}
	if (multiplebuttons)
		for (q=0;q<ndetails;q++)
			for (c=0;c<nbuttons;c++)
			{
				var idx=mc_checkindex(q,c)
				setgradeicon("button"+idx,feedback[idx].grade)
			}
	else
	if (justbuttons)
		for (c=0;c<nbuttons;c++) setgradeicon("button"+c,feedback[c].grade);
	else
		for (c=0;c<ndetails;c++) setgradeicon("button"+c,feedback[c].grade);
}


//### End of shared Multiple choice Page functions

function hasdebugbox()
{
	return (document.forms["debug"]!=null)
}
function debug(s)
{
	if (hasdebugbox()){
		var e=document.forms["debug"].elements["trace"]
		e.value=s + " [] " + e.value
	}else if (parent.WriteInstructions==null) window.status=s;else parent.WriteInstructions("Status",s);//window.status=s
}


function htmlgradeicon(grade)
{
	return "<img src=../share/"+gradeicon[gradeindex(grade)]+">"
}

function gradeindex(grade){
	var idx="RWMI".indexOf(grade);
	if (idx < 0)
		alert("Grade index underflow with '"+grade+"'!");
	return idx;
}

//### DHTML Options
/* 6/12/01 Should use cookie to remember prefs but needs more work.
function CookieGet(Name)
{
	var cookie=document.cookie
	var p=cookie.indexOf(Name+"=")
	if (p>=0)
	{
		var p2=0
		p2=cookie.substring(p,cookie.length).indexOf(";")
		if (p2>=0)
			p2=p+p2
		else
			p2=cookie.length
		cookie=cookie.substring(p,p2)
		return cookie.split("=")[1]
	}else
		return ""
}
function CookieSet(Name,Val)
{
	if (document.cookie.length>0)
		if (cookie.charAt(document.cookie.length-1)!=';') cookie+=";"
	document.cookie +=  Name + "=" + Val
	alert("New cookie='"+document.cookie +"'")
}
function CookieClear(Name)
{
	var cookie=document.cookie
	var p=cookie.indexOf(Name+"=")
	if (p>=0)
	{
		alert("Clearing cookie");
		var p2=0
		p2=cookie.substring(p,cookie.length).indexOf(";")
		if (p2>=0)
		{
			p2=p+p2
			document.cookie= cookie.substring(0,p-1) + cookie.substring(p2,cookie.length)
		}
		else
			if (p==0) document.cookie=""
			else
{alert(cookie.substring(0,p-1))
				document.cookie= cookie.substring(0,p-1)
}
	alert("Result cookie='" + document.cookie+"'");
	}
}
*/

function DHTML_GetPref(pref)
{
	//return CookieGet("DHTML")!=0//Use DHTML unless cookie says DHTML=0.
	if (parent)
		return parent.useDHTML
	else
		return -1
}

function DHTML_WriteLink()
{
	document.write("<P align=center><small><a href=javascript:DHTML_FormatSwitch()>Alternate layout</a></small></p>")
	//document.write("<a href=javascript:alert(document.cookie)>Cookie</a>")
}

function xDHTML_FormatSwitch(pref)
{
	//alert("Current cookie='" + document.cookie + "' -> " + CookieGet("DHTML"))
	//if (CookieGet("DHTML")!="")
	//	CookieClear("DHTML")
	//else
	//	CookieSet("DHTML",0)
	//alert("New cookie=" +  document.cookie + " -> " + CookieGet("DHTML"))

	if (parent) parent.useDHTML=1-parent.useDHTML
	window.location.reload()
}



//################# Write various components to the page


function embedhelp(helpmsg)
{
	var firsttimehelp=0

	if (parent && parent.HelpMessagesSeen)
		if (parent.HelpMessagesSeen.indexOf(helpmsg)<0)
			{	//If question not already answered, and is either RIGHT or WRONG add to list and increment score tally.
				parent.HelpMessagesSeen=parent.HelpMessagesSeen + helpmsg;
				firsttimehelp=1
			}


	if (firsttimehelp)
		helpmsg="<b>Instructions: " + helpmsg + "</b>"
	else
		helpmsg= "<font size=-1>" + helpmsg + "</font>"

	document.write(
		"<table width=100% hspace=10 cellpadding=4 cellspacing=0 border=1><tr><td>"+
		//"<a href='javascript:parent.nav.popupdirections()'>" +
		"<font color=#444488 >" +
		helpmsg +
		"</font>" +
		//"</a>"+
		"</td></tr></table>"+
		"\n")



	/*else
	document.write(
		"<BR><table width=100% border=0><tr><td width=50%></td><td width=50%>"+
		"<i><a href='javascript:parent.nav.popupdirections()'><font size=-1 color=#444488>" + helpmsg +
		"</font></a></i>"+
		"</td></tr></table><BR>"+
		"\n")
*/

//	document.write("<p style='width:50%;align:right'><i><a href='javascript:parent.nav.popupdirections()'><font size=-1 color=#444488>" + helpmsg + "</font></a></i></P><BR>")

}

function writehelp()
{
	embedhelp(helpmsg)
//11/1/99
	if (parent!=null && parent.nav!=null)
	if (toolbar!=null)
		{
			if (toolbar[0]=="CLEAR")
				parent.nav.clearlinks()
			for (var i=1;i<toolbar.length;i+=2)
				parent.nav.addlink(toolbar[i],toolbar[i+1])
		}
}

function writeoptions(instructions,grade,reveal,nextpage)
{
// Output the page title and instructions and activate appropriate navigator buttons

	if (pop!=null) { pop.close();pop=null;}//1/99 Close the feedback window if it's open.


	if (grade==null) grade=true
	if (reveal==null) reveal=true
	if (nextpage==null) nextpage=true

	helpmsg=instructions

	if (parent.WriteInstructions)
	{
		parent.WriteInstructions(title,instructions)
		parent.nav.SetNavBar(nextpage,grade,reveal)
	}
	else if(1)
	{ //This stuff is printed on the page if the page is in its own document and not in a frame set with a Nav Bar
		document.write("<table width=100% border=0 cellpadding=6 cellspacing=0><tr bgcolor=#eeeeee><td>&nbsp;")
		document.write("Frame navigation bar is missing. ");
		if (grade) document.write("<a href=javascript:dograde()>GRADE</a> ")
		if (reveal) document.write("<a href=javascript:doreveal()>REVEAL</a> ")
		if (nextpage) document.write("<a href=" + next + ">NEXT:"+next+"</a> ")
		else document.write("NEXT (available from a popup's Continue button)");
		document.write("</td></tr></table>")
		document.write(instructions+"<hr>")
	}
}


function writeunsupported()
{
	document.writeln("<b>The full functionality of this page requires version 4 or higher of "+Browser+"</B>")
}

//########### Process interactions


function tryitonce()
{
	note("Please try it at least once.");
}
function setgradeicon(iconname,grade)
{
	//alert("Setting grade icon for "+iconname+" to "+grade)
	if (iconname!="") document.images[iconname].src="../share/"+gradeicon[gradeindex(grade)];
}
function donextpage()
{
	if (next)
		if (next!="")
			gotopage(next)
}
function dooutline()
{
	window.location="lesson_outline.htm"
}

function gotopage(page)
{//7/98
	window.location=page;
}

function note(notemsg)
{
//We might want to use a different window for notes in the future so we use note() instead of alert()
	alert(notemsg)
}


function pophtml(popup)//Called when user clicks on a popup link within text
{
	pop=window.open(popup,"Popup",'resizable=1,scrollbars=1,width=400,height=400,');
	//11/24/99 if you leave out "Popup", popup replaces current frame!
	pop.focus()
}
function jumphtml(popup)//Called when user clicks on a jump link within text of either regular or popped up page
{
	window.location=popup
}



function writepagename()//6/7/99 used to attach the name of the CALIAuthor page to the end of the HTML page
{
	var score=""
	if (parent.scoretotal>0)
	{
		score="<a href=javascript:showscore()>Score: " +
			parent.scorecount + "/" + parent.scoretotal + " (" + Math.floor(parent.scorecount*100/parent.scoretotal) + "%)" +
			"</a>"
	}
	document.write("<P><P><Table width=80% height=150><tr><td>Page \""+title+"\"</td><td align=right>" + score + "</td></tr></table>")


	//document.write("<BR><table border=0 width=100%><tr><td align=right>" + score + " <font color=#aaaaaa><small>"+title+"</small></font>")
	//if (NETSCAPE) document.write("<img src=spacer.gif width=16 height=1>")// NS4.5 ignores vert scrollbar in width calcs
	//document.write( "</td></tr></table>")
}
function showscore()
{
	if (parent) parent.showscore()
}

function showfeedbackjump(feedback,grade,dest)
{
	showfeedback(feedback,grade,dest)
	// 1/17/02 popup handles jump now. Old Code: if (dest!="") gotopage(dest)
}





function TScore(question)
{	// 06/26/02 An constructor for a question's score.
	// Stores the question name, user's answer, correct answer and grade for user's first attempt.
	this.question=question
	//this.correctanswerid=0 // feedback ID number (1,2,3,etc.)
	//this.correctanswertext="" // text for report (Yes, No, etc.)
	this.useranswerid=0 // user's answer ID number (0 if user didn't match)
	this.useranswertext="" // text for report (Yes, 'hearsay', etc.)
	this.grade=""
}



function FindQuestion(question,createIfNotFound)
{	// 06/26/02 Find question in list of scores. Return it's TScore record or null if not found.
	// But if createIfNotFound is true, we create a record for it, if it wasn't found.
	// If no parent or parent.scoreinfo, we still return null so caller must always check for null.
	if (parent==null) return;
	if (parent.scoreinfo==null) return;


	for (var s=0;s<parent.scoreinfo.length;s++)
		if (parent.scoreinfo[s].question==question)
				return parent.scoreinfo[s];

	if (createIfNotFound == true)
	{
		var newscore=new TScore(title)
		parent.scoreinfo[parent.scoreinfo.length]=newscore
		return newscore
	}
}


function answerSave(Q,AnswerID,AnswerText)
{ // 06/26/02 Save user's answer to question Q in for later retrieval. Such as Essay response.

	// DEBUG alert("answerSave("+Q+","+AnswerID+","+AnswerText+")")

	var newscore=FindQuestion(Q,true)
	if (newscore!=null)
	{
		newscore.useranswerid=AnswerID;
		newscore.useranswertext=AnswerText;
	}

/* OLD
	var list=parent.answers
	if (list==null) return
	for (var i=0;i<list.length;i+=2)
		if (list[i]==Q)
		{
			list[i+1]=Answer;
			parent.answers=list
			return;
		}
	i=list.length;
	list[i]=Q;
	list[i+1]=Answer;
	parent.answers=list
*/

}

function answerLoad(Q)
{// 06/26/02 Retreive user's previous answer to question Q, such as essay response.
	var newscore=FindQuestion(Q,true)

	if (newscore!=null)
		return newscore.useranswertext
	else
		return ""
/*	OLD
	if (!parent) return;
	var list=parent.answers
	if (list==null) return
	for (var i=0;i<list.length;i+=2)
		if (list[i]==Q)
		{
			return list[i+1];
		}
	return "";
*/
}

function showfeedback(feedback,grade,jumpdest)
{	//Display text of feedback in popup window. Grade is of type 'R,W,M,I' which determines which icon and background to use.
	if (grade==null) grade=INFO //if no grade given, assume Informational.

	if ((parent) && (parent.scoreinfo!=null))
	{
		// Find/create question.
		var score=FindQuestion(title,true);
		// If no grade assigned yet, do so.
		if ((score!=null) && (score.grade==""))
		{
			score.grade=grade
    		if (grade==RIGHT)
    		{
    			parent.scorecount+=1;//increment score and total
    			parent.scoretotal+=1;
    		}
    		if (grade==WRONG)
    		{
    			parent.scorecount+=0;//no score but increment total
    			parent.scoretotal+=1;
    		}
		}

/* OLD
		if (parent.scoreinfo==null) parent.scoreinfo=""//5/1/01 ensure there's a scoreinfo list.
		//we could save the scores in acookie for recording to Server :-)
		// If we don't find the question, add the score. This means we record only first attempt.
		if (parent.scoreinfo.indexOf("<Q>"+title+"</Q>")<0)
			if (grade==RIGHT || grade==WRONG)
      	{	//If question not already answered, and is either RIGHT or WRONG add to list and increment score tally.
      		parent.scoreinfo=parent.scoreinfo + "<Q>" + title + "</Q><G>" + grade + "</G>\n";
      		if (grade==RIGHT)
      		{
      			parent.scorecount+=1;//increment score and total
      			parent.scoretotal+=1;
      		}
      		if (grade==WRONG)
      		{
      			parent.scorecount+=0;//no score but increment total
      			parent.scoretotal+=1;
      		}
      	}
*/

	}

	//1/21/02 To score a branch only, allow scoring to be handled and then do the jump.
	if (feedback==null || feedback=="")
	{
		if (jumpdest!="") gotopage(jumpdest)
		return //if no feedback, don't show a popup.
	}

	var backgroundimage="bg-" + grade.substring(0,1).toLowerCase() + ".gif"


	grade=gradeindex(grade)
	if (feedback.length<200)
		h=150;
	else
		h=400;



//Create the popup window. 10/20/99 These windows must be closed before proceeding.
//6/3/02 Feedback popup has different name from regular popup.
	pop=window.open("","Feedback","resizable=1,scrollbars=1,width=400,height=" + h);
	if (pop==null) return;
	if (pop.focus!=null) pop.focus();
	if (!pop.opener) pop.opener=self

	//remove leading P so we can insert Grade icon at start of paragraph.
	if (feedback.indexOf("<P>")==0 || feedback.indexOf("<p>")==0) feedback=feedback.substring(3,feedback.length)

	pop.document.writeln("<html><head><title>" + gradetitle[grade] + "</title>")

	// pop.document.writeln("<link rel=\"stylesheet\" href=\"../share/styles.css\">") //  Including this link causes IE to lock up.

	pop.document.writeln("<style type=\"text/css\"> <!--B {font-weight:bold;color:#000000} body,P,UL,LI,OL,TD,DIV 	{ font-family: Verdana, Arial, Geneva; font-size: 10pt; font-weight: normal; margin-left: 4pt; margin-right: 4pt; margin-top: 4pt; margin-bottom: 4pt; font-weight: normal; color: #000000; } H1 { font-size: 14pt; font-weight: bold; } DIV 	{ font-family: Verdana, Arial, Geneva; font-size: 8pt; font-weight: normal; margin-left: 4pt; margin-right: 4pt; margin-top: 4pt; margin-bottom: 4pt; font-weight: normal; color: #300030; } a	{ text-decoration: underline; color: #0000FF } a:hover { text-decoration: underline } a:active { text-decoration: underline; color: #0000ff } --> </style>")


	pop.document.writeln("</head>")
	pop.document.writeln("<body leftmargin=2 topmargin=2 marginwidth=2 marginheight=2 background=../share/"+backgroundimage+">")

	// + " onBlur=self.focus()" - 8/26/98 Don't do auto focus since IE4 scrolls to the bottom. Find afix?
	//" onload=\"document.forms[0].elements[0].focus();self.scroll(0,0);\">");
	//pop.document.writeln("<script language=\"javascript\" src=\"common.js\"></script>")
	// Using this Include script causes IE4 to CRASH AND BURN! Instead include script directly into page.
	//1/29/99 Added JumpHTML to handle jump links in feedback pops.
	//10/19/00 Put feedback in box with a border color indicate grade.

	pop.document.writeln("<script language='javascript'>")

//06/03/02 Ensure popup gets its own window.
	pop.document.writeln("function pophtml(popup) {popwin=window.open(popup,\"Popup\",'resizable=1,scrollbars=1,width=400,height=400');popwin.focus();}")//Popup

	pop.document.writeln("function jumphtml(gourl){if (opener) opener.location=gourl;else if (parent) parent.location=gourl;self.close();}")
	pop.document.writeln("</script>")
	pop.document.writeln("<P><img src=../share/" + gradeicon[grade].toLowerCase() + ">")
	pop.document.writeln(feedback);
	pop.document.writeln("<center>");

	if (jumpdest=="" || jumpdest==null)
	{	// For a popup with no branching.
		pop.document.writeln("<form onsubmit=\"self.close();return false;\">");
		pop.document.writeln("<input type=submit value=\"   OK   \">");
	}
	else
	{ //For a popup that branches.
		pop.document.writeln("<form onsubmit=\"opener.location='" + jumpdest + "';self.close();return false;\">"); //1/17/02
		pop.document.writeln("<input type=submit value=\"Continue\">");
	}
	pop.document.writeln( "</form></center></body></html>");
	pop.document.close();
}


//################################## END OF COMMON




//################################## TOP OF LAYERS
// Netscape or IE layer functions
//GENERAL FUNCTIONS


	if (NETSCAPE){
		layerRef="document.layers";//layerRef is the general reference to all layers
		styleSwitch="";//not used yet (but necessary to access layers in Microsoft
		visibleVar="show";
		windowWidth=window.innerWidth;//this is the way Netscape gets the width and height of the viewing window
		windowHeight=window.innerHeight;
		pxSwitch="";
		widthClipSwitch=".clip.right";
		heightClipSwitch=".clip.bottom";
		eventX="e.pageX";
		eventY="e.pageY";
	}else{
		layerRef="document.all";
		styleSwitch=".style";
		visibleVar="visible";
		windowWidth=window.screen.availWidth;
		windowHeight=window.screen.availHeight;
		pxSwitch="px";
		widthClipSwitch=".posWidth";
		heightClipSwitch=".posHeight";
		eventX="event.clientX";
		eventY="event.clientY";
	}

// ####################
// Must declare functions MOUSEDOWN(), MOUSEUP(),MOUSEDRAG(nx,ny,dx,dy),GETELEMENT(x,y)
	var objSelected=null;
	var objSelectedIndex=null;
// ####################


function startCapture()
{
	if (LAYERS)
		if (NETSCAPE)
		{
			document.captureEvents(Event.MOUSEUP|Event.MOUSEDOWN|Event.MOUSEDRAG|Event.MOUSEMOVE);
			document.onmousedown=doMouseDownN;
			document.onmouseup=doMouseUpN;
			document.onmousemove=doMouseMove;
		}else{
			//document.ondragstart = doMouseDownIE//doDragStartIE;
			document.onmousedown = doMouseDownIE;
			document.onmousemove = doMouseMoveIE;
			document.onmouseup = doMouseUpIE;
		}
}


//NETSCAPE CLICK N DRAG FUNCTIONS
function doMouseDownN(event) {
//mouse is down, find out which draggable object may have been clicked.
	objSelected=GETELEMENT(event.pageX,event.pageY);
	if (objSelected != null){
		document.captureEvents(Event.MOUSEMOVE);
		document.onmousemove=doMouseDragN;
  		oldX=event.pageX;
		oldY=event.pageY;
		MOUSEDOWN()
		return false;
	}
}
function doMouseUpN(event) {
	if (objSelected != null){
		document.onmousemove=0;
		document.releaseEvents(Event.MOUSEMOVE);
		MOUSEUP()
		objSelected=null;
		return false;
	}
}
function doMouseDragN(event) {
	if (objSelected != null){
		MOUSEDRAG(event.pageX,event.pageY,event.pageX - oldX, event.pageY - oldY);
		oldX = event.pageX;
		oldY = event.pageY;
	}
}
function doMouseMove(event)
{
	MOUSEMOVE(event.pageX,event.pageY)
}

//---------IE CLICK N DRAG CODE--------------------
function getxy(){
	x=event.clientX;
	if (event.srcElement.tagName=="IMG")
		y=event.y
	else
		y=event.offsetY  +event.srcElement.style.posTop
}
function doMouseDownIE() {
  if (event.button==1){
		getxy()
		objSelected = GETELEMENT(x,y);
//debug(event.srcElement.tagName+":"+x+","+y+"  ; "+event.clientY +","+event.offsetY+","+event.y+","+ event.srcElement.style.pixelTop+","+event.srcElement.style.posTop+"  -> "+objSelected)
  		oldX=x;oldY=y;
		if (objSelected!=null) MOUSEDOWN()
	}
/*  if ((event.button==1) && (event.srcElement.tagName=="IMG")){
		objSelected = event.srcElement
		MOUSEDOWN()
	}*/
}
function doMouseMoveIE() {
	if ((event.button==1) && (objSelected!=null))
	{
		getxy()
		event.returnValue = false
		event.cancelBubble =true
		MOUSEDRAG(x,y,x-oldX,y-oldY)
		oldX=x;oldY=y
	}
	else if (event.button==0)
	{
		getxy()
		MOUSEMOVE(x,y);
	}
}

		//var x=event.clientX-document.all.OuterDiv.offsetLeft-(objSelected.offsetWidth/2)
		//if (newleft<0) newleft=0
		//objSelected.style.pixelLeft= newleft
		//var y=event.clientY -document.all.OuterDiv.offsetTop-(objSelected.offsetHeight/2)
		//if (newtop<0) newtop=0
		//objSelected.style.pixelTop= newtop

function doMouseUpIE(){
	objSelected=null;
	MOUSEUP()
}
function doDragStartIE() {
  // Don't do default drag operation.
  if ("DIV"!=event.srcElement.tagName)
    event.returnValue=false;
}



// LAYER CODES


function LayerInfo(x,y,w,h){
	this.x=x
	this.y=y
	this.w=w
	this.h=h
}

function layerInfo(layerName){
	if (NETSCAPE){
		with (document.layers[layerName])
			return new LayerInfo(pageX,pageY,clip.width,clip.height)
	}else{
		return new LayerInfo(0,0,0,0)
	}
}

// Functions taking a layer NAME
function layerObject(layerName)
	{var obj=eval(layerRef+'["'+layerName+'"]');if (obj==null) alert(layerName+" not defined!");return obj}

function showLayer(layerName)
	{eval(layerRef+'["'+layerName+'"]'+styleSwitch+'.visibility="visible"');}

function hideLayer(layerName)
	{eval(layerRef+'["'+layerName+'"]'+styleSwitch+'.visibility="hidden"');}

function layerResize(layerName,sx,sy)
	{var obj=eval(layerRef+'["'+layerName+'"]');if (NETSCAPE) obj.resizeTo(sx,sy);else {obj.style.pixelWidth=sx;obj.style.pixelHeight=sy;}}

function layerZDepth(layerName,newz)
	{if (NETSCAPE) document.layers[layerName].zIndex=newz; else document.all[layerName].style.zIndex=newz;}

function layerColor(layerName,color)
	{if (NETSCAPE) document.layers[layerName].bgColor=color;else document.all[layerName].style.backgroundColor=color;}

// Functions taking a layer OBJECT
function layerLeft(obj)
	{if (NETSCAPE) return obj.pageX; else return obj.offsetLeft;}

function layerTop(obj)
	{if (NETSCAPE) return obj.pageY; else return obj.offsetTop;}

function layerWidth(obj)
	{if (NETSCAPE) return obj.clip.width; else return obj.style.pixelWidth;}

function layerMove(obj,x,y) //WAS BY NAME!
	{if (NETSCAPE) obj.moveTo(x,y);else {obj.style.pixelLeft=x;obj.style.pixelTop=y;}}

function layerOffset(obj,dx,dy)
	{if (NETSCAPE) obj.offset(dx,dy); else {obj.style.pixelLeft+=dx;obj.style.pixelTop+=dy;}}


function layerContainsPoint(obj,clickX,clickY){
	var l,t,r,b;
	if (obj==null) return false;
	if (NETSCAPE){
		l=obj.left;
		r=obj.left+obj.clip.width;
		t=obj.top;
		b=obj.top+obj.clip.height;
	}else{
//alert(obj.style.posTop +","+obj.style.pixelTop)
		l=obj.style.posLeft;
		r=obj.style.posLeft+obj.style.posWidth;
		t=obj.style.posTop;
		b=obj.style.posTop+obj.style.pixelHeight;
	}
	return (clickX > l) && (clickX < r) && (clickY > t) && (clickY < b);
}

function pagewidth(){
	if (NETSCAPE)
		return window.innerWidth;
	else
		return document.body.clientWidth;
}

function layerInit(layername,newx,newy,w,h,showit,color){
	var obj=layerObject(layername)//eval(layerRef+'["'+layername+'"]')
	if (NETSCAPE){
		obj.pageX=newx;
		obj.pageY=newy
		obj.clip.width=w;
	 	obj.clip.height=h;
	}else{
		obj.style.pixelLeft=newx;
		obj.style.pixelTop=newy
		obj.style.pixelWidth=w
		obj.style.pixelHeight=h
		obj.style.clip="rect(0,auto,"+h+",0)"
//		obj.style.clip="rect(0,"+w+","+h+",0)"
	}
	if (color!=null) layerColor(layername,color)
	if (showit) showLayer(layername); else hideLayer(layername);
}

function layerText(layerName,text){
	if (NETSCAPE) {
		//document.layers[layerName].document.open();//10/6/00
		document.layers[layerName].document.write(text);
		document.layers[layerName].document.close();
	}else{
		document.all[layerName].innerHTML=text;
	}
}
//#######################################################
//################################## END OF LAYERS ######
//#######################################################




function HTMLEncode(str)
{	// Replace &,<,>," with HTML codes.
	str="" + str
	str=replace(str,"&","&amp;")
	str=replace(str,"<","&lt;")
	str=replace(str,">","&gt;")
	str=replace(str,"\"","&quot;")
/*
	var re = /&/gi;
	str=str.replace(re, "&amp;");
	var re = /</gi;
	str=str.replace(re, "&lt;");
	var re = />/gi;
	str=str.replace(re, "&gt;");
	var re = /"/gi;
	str=str.replace(re, "&quot;");
*/
	return str
}

/*
function CompareTScore(a, b)
{	// Compares TScore objects a and b. Returns sort order based on Question name.
	if (a.question<b.question)
      return -1
	else
	if (a.question>b.question)
		return 1
	else
		return 0
}
*/


function submitscore(wnd)
{	// Submit score to CALI Quiz website.
	// Expected to be called at the scope of the parent frame.
	// Note: limitation on size of GET URL, so must use POST.
	// wnd is the score popup window. We need this to access the hidden form for POSTing.

	// NO. Sort our questions into some reasonable order. Leave in order of student use. Possible to track flow.
	// DO NOT DO THIS NOW scoreinfo.sort(CompareTScore)

	var data=""

/*	// Version 1
	for (var q=1;q<=scoreinfo.length;q++)
		with (scoreinfo[q-1])
			data+= 	"&Q"+q+"="+escape(question) +
						"&G"+q+"="+escape(grade) +
						"&UAID"+q+"="+escape(useranswerid)+
						"&UA"+q+"="+escape(useranswertext)+"\n"
*/
/*
	window.open(
		"http://lessons.cali.org/performance-submit/?"+
		"UserName="+escape(username)+
		"&LessonID="+escape(lessonid)+
		"&LessonVersion="+escape(revision)+
		"&PerformanceVersion="+escape("PARAM;06/28/02") +
		"&Questions="+scoreinfo.length+ data,"CALIQuiz")
*/

/*
	//XML  format 1 with attributes
	data="<PERFORMANCE>"
		data+="<QUESTIONS>"
		for (var s=0;s<scoreinfo.length;s++)
			with (scoreinfo[s])
			{
				data+= "<QUESTION NAME=\"" + HTMLEncode(question) + "\" GRADE=\"" + HTMLEncode(grade)+"\">";
				//NOT USED NOW "<CORRECT ID=\"" + correctanswerid+"\">" + HTMLEncode(correctanswertext) + "</CORRECT>" +
				if (useranswerid>0 || useranswertext!="")
					data+="<ANSWER ID=\"" + useranswerid+"\">" +  HTMLEncode(useranswertext) + "</ANSWER>";
				data += "</QUESTION>\n";
			}
		data+="</QUESTIONS>\n"
	data+="</PERFORMANCE>\n"
*/
/*
	data="<PERFORMANCE>"
		data+="<QUESTIONS>"
		for (var s=0;s<scoreinfo.length;s++)
			with (scoreinfo[s])
			{
				data+= "<QUESTION><NAME>" + HTMLEncode(question) + "</NAME><GRADE>" + HTMLEncode(grade)+"</GRADE>";
				//data+= "<CORRECTID>" + correctanswerid+"</CORRECTID><CORRECT>" + HTMLEncode(correctanswertext) + "</CORRECT>";
				if (useranswerid>0 || useranswertext!="")
					data+= "<ANSWERID>" + useranswerid+"</ANSWERID><ANSWER>" +  HTMLEncode(useranswertext) + "</ANSWER>";
				data += "</QUESTION>\n";
			}
		data+="</QUESTIONS>\n"
	data+="</PERFORMANCE>\n"
*/

		for (var s=0;s<scoreinfo.length;s++)
			with (scoreinfo[s])
			{
				data+= "<Q><ID>" + HTMLEncode(question) + "</ID><G>" + HTMLEncode(grade)+"</G>";
				if (useranswerid>0 || useranswertext!="")
					data+= "<AID>" + useranswerid+"</AID><A>" +  HTMLEncode(useranswertext) + "</A>";
				data += "</Q>\n";
			}


	// Stuff data we want to send into the score window's form variables.

	wnd.document.datafrm.username.value=username
	wnd.document.datafrm.lessonid.value=lessonid
	wnd.document.datafrm.lessonversion.value=revision
	wnd.document.datafrm.performanceversion.value="XML;07/15/02"
	wnd.document.datafrm.performance.value=data
	wnd.document.datafrm.submit()

}


