/* 
		Duke Energy CBT Template package 2006v1
 
Modified: November 28 2005. Bob Wiker. 2006v1
--- Added the autoMenuPath variable and the doAutoMenu function.
--- Added the activateNext function.
--- Moved the variable declaration for the trimList array into the getCurrentSection() function
    for better JavaScript standards compliance.

Modified: June 22 2004. Bob Wiker. 2004v2
--- Added statement to swapImage() function to strip pathname from filename before searching for rollover image.

Modified: May 4 2004. Bob Wiker.
--- GetCurrentSection() function to work properly when run from CD.

Modified: April 26 2004. Bob Wiker.
---	Modified the "showDebugger" function to update the bookmark-checking routine.
	The Debugger now properly recognizes an autoconfigured bookmark. (bookmarkpage="autobook")

Modified: April 2004. Bob Wiker.
--- Re-scripted the gotoPage function to allow automated next/back/bookmark navigation.
--- Included in this modification is the addition of 3 new functions:
    doAutoNext, doAutoBack, doAutoBook
--- Moved the declaration of the "bookmarkprefix" variable from within the "showDebugger" function
    up to the global declaration section of this file. It was previously used only by the Debugger;
    now it is shared with the doAutoBook function.

Created: December 2003.  Adapted from CBTpage.js.

*/
//---------------------------------------------------------------------------------------------------------------------------------
// Initialize variables

// For debugging; 1=debugger on, 0=debugger off
var debugEnable = 0

/* For Javascript access to global images.
These variables' values are set for pages that are at the site's root level.
If you have pages that are below root level (ie, in subfolders within the site)
then each such page must assign the appropriate values to the variables so that
the header can be drawn.
Example: If a page is 1 level down in a folder, then include this in the <HEAD> of the page:
	globalImagePath = "../_global_images/"
	globalNavImagePath = "../_global_images/navigation_images/"
Example: If a page is 2 levels down in a folder, then include this in the <HEAD> of the page:
	globalImagePath = "../../_global_images/"
	globalNavImagePath = "../../_global_images/navigation_images/"
*/
var globalImagePath = "_global_images/"
var globalNavImagePath = "_global_images/navigation_images/"

// For the bookmark button.
var bookmarkprefix = "_global_asp/BookmarkPage.htm?NextURL="

// For the Main Menu button.
// This is the page you'll go to when menupage="automenu"
var autoMenuPath = "mainmenu.htm"

// For Javascript access to navigation button images for the various states
var imageDownStateSuffix = "_over"
var imagedimSuffix = "_dim"

// These determine which navigation controls to display. 1=show 0=hide
var showpagenumber = 0
var showbookmark = 0
var showmenu = 1
var shownextprev = 1
// These determine whether the items are active or inactive/dimmed. active=anyvalue, inactive/dimmed=""
var bookmarkpage = ""
var menupage = ""
var backpage = ""
var nextpage = ""

var maxPage = 0 // Maximize page automatically? values --> 0 or 1

//End initialization of variables

//---------------------------------------------------------------------------------------------------------------------------------

/* This supresses the Internet Explorer 6.0 Image Toolbar that pops up
when the user rolls over images larger than 200 x 200. */
document.write ('<meta http-equiv="ImageToolBar" content="no">');


/*
initPage()
------------------------------------------------
Called in the BODY tag when the page loads.
Updates page buttons and creates page numbering and
also maximizes the window if maxPage is set to 1.
*/

function initPage() {
	updateButtons()
	if (showpagenumber == 1) {updatePagenumber()}
	if (debugEnable == 1) {showDebugger()}
	if(maxPage == 1) {
		top.window.moveTo(0,0)
		top.window.resizeTo(screen.availWidth,screen.availHeight)
		if (top.window.outerHeight<screen.availHeight||top.window.outerWidth<screen.availWidth) {
			top.window.outerHeight = screen.availHeight
			top.window.outerWidth = screen.availWidth
		}
	}
}

/*
updateButtons()
------------------------------------------------
called from initPage()
updates the navigation buttons: dims if no page is set for the button
*/

function updateButtons() {
	if(bookmarkpage < " ") {
		if(document.getElementById("top_bookmark")) document.getElementById("top_bookmark").setAttribute("src",globalNavImagePath+"bookmark_dim.gif")
	}
	if(menupage < " ") {
		if(document.getElementById("top_menu")) document.getElementById("top_menu").setAttribute("src",globalNavImagePath+"menu_dim.gif")
	}	
	if(backpage < " ") {
		if(document.getElementById("top_back")) document.getElementById("top_back").setAttribute("src",globalNavImagePath+"back_dim.gif")
	}	
	if(nextpage < " ") {
		if(document.getElementById("top_next")) document.getElementById("top_next").setAttribute("src",globalNavImagePath+"next_dim.gif")
	}	
	
}

/*
updatePagenumber()
------------------------------------------------
called from initPage()
updates the page number
*/

function updatePagenumber() {
	var pagetext = "Page "+getCurrentPageNumber()+" of "+getMaxPages()
	document.getElementById("pagenumber").innerHTML = pagetext
}

//---------------------------------------------------------------------------------------------------------------------------------
//NAV BAR

/*
Preload the navigation images
*/

var preLoadImgs = new Array()

preLoadImgs = [
			"bookmark.gif","bookmark_over.gif",
			"menu.gif","menu_over.gif",
			"back.gif","back_over.gif",
			"next.gif","next_over.gif"
			]

for (var i=0; i<preLoadImgs.length; i++) {
	eval("var pnavimage"+i+"=new Image()")
	eval("pnavimage"+i+".setAttribute('src','"+globalNavImagePath+preLoadImgs[i]+"')")
}

/*
swapImage()
swaps out navigation images by a toggle method.
uses the preLoadImgs() array for names
*/

function swapImage(whatimage) {
	var currentImage = whatimage.getAttribute("src") //Get the pathname of the image.
	currentImage = currentImage.substring(currentImage.lastIndexOf("/")+1); // Strip off all but the filename.
	if(currentImage.indexOf(imagedimSuffix) > 0) return // If the button is dimmed, leave it that way.
	// Cycle through array of image filenames until we find a match.
	for (var i=0; i<preLoadImgs.length; i++) if (currentImage.indexOf(preLoadImgs[i]) != -1) { var imageIndex = i; break }
	// Get appropriate image in array.
	var imageIndexState = (currentImage.indexOf(imageDownStateSuffix) > 0) ? -1 : 1
	whatimage.setAttribute("src",globalNavImagePath+preLoadImgs[imageIndex + imageIndexState])
}


// Navigates to a page.
function gotoPage(whatpage) {
// check that variable has a value.
	if(whatpage > " ") { 
		switch (whatpage) {
			case "automenu": {doAutoMenu();break;}
			case "autoback": {doAutoBack();break;}
			case "autonext": {doAutoNext();break;}
			case "autobook": {doAutoBook();break;}
			default: {top.document.location.href=whatpage;}
		}
	}
}

function doAutoMenu() {
// Go to menupage.
		top.document.location.href = autoMenuPath
}

function doAutoBack() {
// If first page, go to menupage.
	if (getCurrentPageNumber() == 1) {
		top.document.location.href=autoMenuPath
	}
// Go to previous page. Note that 2 is subtracted for index array; one for going back a page 
// and one because getCurrentPageNumber counts from 1 while Javascript arrays count from zero.
	else {
		top.document.location.href = eval(getCurrentSection() + "[" + (getCurrentPageNumber()-2) + "]");
	}
}

function doAutoNext() {
// If last page, go to menupage.
	if (getCurrentPageNumber() == getMaxPages()) {
		top.document.location.href=autoMenuPath
	}
// Go to next page. Note that nothing is added to getCurrentPageNumber for index array 
// because getCurrentPageNumber counts from 1 while Javascript arrays count from zero.
// That numeric difference gives us the one-digit increment we're seeking.
	else {
		top.document.location.href = eval(getCurrentSection() + "[" + getCurrentPageNumber() + "]");
	}
}

function doAutoBook() {
	top.document.location.href=(bookmarkprefix + getCurrentPageName())
}

// This function sets the Next button to the proper image and then makes it active 
// by setting the 'nextpage' variable to the value of correctpage.
// Use it with interactions, call it from Flash, or whenever you want to keep the learner from
// advancing until you're ready.
// To use it on your page, set nextpage="" and set correctpage="yourpagehere.htm" or correctpage="autonext"
function activateNext() {
	document.getElementById("top_next").setAttribute("src",globalNavImagePath + "next.gif");
	nextpage = correctpage; 
}

// Puts a message into the browser's Status Bar.
function say(what) { window.status=what }

//---------------------------------------------------------------------------------------------------------------------------------
//PAGE COUNTING

// If you're getting errors with numbering and everything else is correct,
// try adjusting these numbers.
var trimH = 22
var trimL = 19

// Extracts the section name from the URL.
function getCurrentSection() {
	var trimList = ["0","1","2","3","4","5","6","7","8","9","_"] // Remove these chars from the end of a file name
	var lastSlashIndex
	var myURLlastChar
	var myURLfragment
	myURLfragment = document.location.href.toLowerCase()
	myURLfragment = myURLfragment.substring(2, myURLfragment.length-5) // Shorten down URL. Important to remove last 5 chars, too.
	// Remove directory prefix
	lastSlashIndex = myURLfragment.lastIndexOf("/")
	if(lastSlashIndex == -1) lastSlashIndex = myURLfragment.lastIndexOf("\\")
	if(lastSlashIndex == -1) return "error! getCurrentSection: file parse: no directory"
	myURLfragment = myURLfragment.substring(lastSlashIndex+1, myURLfragment.length)
	myURLlastChar = myURLfragment.charAt(myURLfragment.length-1)
	// loop and remove number suffix, checks against trimList array
	// 2 tries
	for(var ctries=0; ctries<2; ctries++) {
		// loop through trim list
		for(var trimListIndex =0; trimListIndex < trimList.length; trimListIndex++) {
			// check current against list of page sets. allows for numbers at the end of a set name
			for(var setListIndex = 0; setListIndex < setList.length; setListIndex++) {
				if(myURLfragment == setList[setListIndex]) {
					// MATCH! return page set name in lower case
					for (var i=0; i < setList.length; i++) {
						if(setList[i].indexOf(myURLfragment) >= 0) {return setList[i].toLowerCase()}
					}
				}
			}
			// if end of filename is a char in the trimList, shorten name by 1 char
			if(trimList[trimListIndex] == myURLlastChar) { 
				myURLfragment = myURLfragment.substring(0, myURLfragment.length-1)
				myURLlastChar = myURLfragment.charAt(myURLfragment.length-1)
			}
		}
	}
	// didn't find resulting page set name in page set list
	return "error! getCurrentSection: file parse: no such section"
}


// takes apart the url of the current page and returns the page name
function getCurrentPageName() {
	var temp
	var cpage = document.location.href.toLowerCase()
	if(cpage.length > trimH) cpage = cpage.substring(cpage.length-(trimH-1), cpage.length)
	temp = cpage.lastIndexOf("/")
	if(temp == -1) temp = cpage.lastIndexOf("\\")
	if(temp == -1) return "error! getCurrentPageName: file parse: no directory"
	cpage = cpage.substring(temp+1, cpage.length)
	return cpage.toLowerCase()
}

// gets the total number of pages in the current page's section array
function getMaxPages() {
	var whatsection = getCurrentSection()
	if (whatsection.indexOf("error") != -1) return whatsection
	return eval(whatsection+".length")
}

// returns the position of the current page in the section array
function getCurrentPageNumber() {
	var whatsection = getCurrentSection().toLowerCase()
	if (whatsection.indexOf("error") != -1) return whatsection
	thissection = eval(whatsection)
	var cpage = getCurrentPageName().toLowerCase()
	for (var i=0; i < thissection.length; i++) {
		if(cpage.indexOf(thissection[i].toLowerCase()) != -1) return i+1
	}
	return "error! getCurrentPageNumber: page not found"
}

//---------------------------------------------------------------------------------------------------------------------------------
//VOCABULARY POP-UPS

function cursorOut() {
	document.getElementById("popdesc").style.visibility = "hidden"
	theDescLayer.style.left = 0
	theDescLayer.style.top = -1000
	document.onmousemove = null
}

function cursorOver(vlidx) {
	document.onmousemove = doMouseMove
	theDescLayer = document.getElementById("popdesc")
	theDescLayer.innerHTML = vocabList[vlidx]
	theDescLayer.style.visibility = "visible"
}

function doMouseMove(e) {
	theDescLayer = document.getElementById("popdesc")
	var newLeft = isIE ? window.event.clientX : e.clientX
	var newTop = isIE ? window.event.clientY + document.body.scrollTop : e.clientY
	theDescLayer.style.left = newLeft + 15
	theDescLayer.style.top = newTop - 10
}

//---------------------------------------------------------------------------------------------------------------------------------
// simple detect
var isIE = (document.all) ? 1 : 0
var isMAC = (navigator.userAgent.indexOf("Mac")>-1) ? 1 : 0
var isDOM = (document.getElementById) ? 1 : 0
var isMOZ = (isDOM && !isIE) ? 1 : 0
var isOPERA5=navigator.userAgent.indexOf("Opera 5") > -1
var isIE5=(navigator.appVersion.indexOf("MSIE 5")>-1 && isDOM && !isOPERA5) ? 1 : 0
var isIE55=(navigator.appVersion.indexOf("MSIE 5.5")>-1 && isDOM && !isOPERA5) ? 1 : 0 
var isIE6=(navigator.appVersion.indexOf("MSIE 6")>-1 && isDOM && !isOPERA5) ? 1 : 0
var isNS6=(isDOM && parseInt(navigator.appVersion) >= 5) ? 1 : 0 


//---------------------------------------------------------------------------------------------------------------------------------
/*
Auto center window script- Eric King (http://redrival.com/eak/index.shtml)
Permission granted to Dynamic Drive to feature script in archive
For full source, usage terms, and 100's more DHTML scripts, visit http://dynamicdrive.com
*/

var win = null;
function NewCenteredWindow(mypage,myname,w,h,scroll){
	LeftPosition = (screen.width) ? (screen.width-w)/2 : 0;
	TopPosition = (screen.height) ? (screen.height-h)/2 : 0;
	settings = 'height='+h+',width='+w+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',resizable'
	win = window.open(mypage,myname,settings)
}



//---------------------------------------------------------------------------------------------------------------------------------
/*
Debugging

The Debugger has some generalized functionality, but can (should!) be customized for each CBT course.

The Debugger is enabled/disabled by a variable named debugEnable, whose value is set at the beginning of this file.

The DIV containing the Debugger is defined/drawn in the global_header.js file
and its location/style is defined in debuggerstyle.css.

Debugger has placeholders to display as many as 8 strings, though to display them all you may have to
change the Debugger's DIV size through debuggerstyle.css. Each placeholder is a <SPAN></SPAN> into which
you can stuff some text. These <SPAN> placeholders have unique IDs: debugitem01 through debugitem08.
To stuff a string into a placeholder, use statements such as these:
	document.getElementById("debugitem01").innerHTML = "Your literal string here.<br>"
	document.getElementById("debugitem02").innerHTML = myJavascriptVariable + "<br>"
Note that each ends with the <br> tag to provide a line break.
Here are the current uses of the placeholders:
	debugitem01 contains feedback regarding menu button.
	debugitem02 contains feedback regarding bookmark button.
	debugitem03 contains feedback regarding the answer (question pages only).
	debugitem04 contains feedback regarding the review page (question pages only).
	debugitem05 is available for use.
	debugitem06 is available for use.
	debugitem07 is available for use.
	debugitem08 is available for use.

There can be many uses of the Debugger during development.
Any Javascript variable can be inspected, used, reported.
Links to other files can be stuffed into placeholders.

*/

function showDebugger() {
// populate some local variables
	bookmarkprefix = bookmarkprefix.toLowerCase();
	var bookmarksuffix = bookmarkpage.slice(bookmarkprefix.length);
	bookmarksuffix = bookmarksuffix.toLowerCase();
	var mypage = document.location.href.toLowerCase()

	// If menu button is turned on, check value of main menu variable and report in debugitem01
	if (showmenu != 0) { // Menu button turned on (visible)?
		if (menupage == "mainmenu.htm")
			{document.getElementById("debugitem01").innerHTML = "Menu button OK.<br>"}
		else if (menupage == "")
			{document.getElementById("debugitem01").innerHTML = "Menu button inactive.<br>"}
		else
			{document.getElementById("debugitem01").innerHTML = "Menu button warning: " + menupage + "<br>"}
		}
	else // Menu button turned off (not visible).
		 {document.getElementById("debugitem01").innerHTML = "Menu button turned off.<br>"}
		


	// Check integrity of bookmark variable and report in debugitem02
	if (showbookmark != 0) { // Is bookmark button turned on (visible)?
		if (bookmarkpage == "") // Bookmark button inactive?
			{document.getElementById("debugitem02").innerHTML = "Bookmark button inactive.<br>"}
		// Check bookmark's integrity.
		else {
			// If bookmark was autoconfigured then all is OK.
			if(bookmarkpage == "autobook") {
				document.getElementById("debugitem02").innerHTML = "Bookmark button OK.<br>"}
			else { // Bookmark was manually entered, so check its two components.
				// First, check that bookmark URL is proper.
				if(bookmarkpage.toLowerCase().indexOf(bookmarkprefix) != 0)
					{document.getElementById("debugitem02").innerHTML = "Bookmark URL appears to be malformed.<br>"}
				// Second, check that page-to-be-bookmarked is me.
				else {
					if(mypage.indexOf(bookmarksuffix) != mypage.length - (bookmarksuffix.length))
						{document.getElementById("debugitem02").innerHTML = "Bookmark does not point to this page.<br>"}
					else // Bookmark URL formed properly and points to me, so OK.
						{document.getElementById("debugitem02").innerHTML = "Bookmark button OK.<br>"}
				} // end checking page-to-be-bookmarked is me.
			} // end of manually entered bookmark check.
		} // end checking bookmark integrity.
	}
	else // bookmark button turned off (not visible).
		{document.getElementById("debugitem02").innerHTML = "Bookmark button turned off.<br>"}



	// If this is a question page, report answer in debugitem03 and reviewpage in debugitem04.
	// Also, check and make sure that nextpage variable is empty.
	if((typeof(the_key) != "undefined") && (the_key != "")) { // Checkbox style question page? If the_key exists and is non-empty, then it is.
		document.getElementById("debugitem03").innerHTML = "Correct answer is " + the_key + "<br>";
		document.getElementById("debugitem04").innerHTML = "Review page is " + reviewpage + "<br>"
		}
	if((typeof(the_answer) !="undefined") && (the_answer !="")) { // Radio button style question page? If the_answer exists and is non-empty, then it is.
		document.getElementById("debugitem03").innerHTML = "Correct answer is " + the_answer + "<br>"
		document.getElementById("debugitem04").innerHTML = "Review page is " + reviewpage + "<br>"
		}
	// If this is a question page, is nextpage variable empty?
	if ((typeof(the_key) !="undefined" || typeof(the_answer) !="undefined") && nextpage !="")
	{alert('This appears to be a question page whose "Next Page" button is active (which is improper).')}


	// If this is a review page, check that page numbering is off, backpage=nextpage, and bookmarkpage is empty.
	if(mypage.indexOf("review") > 0) {
		var errortext = "This appears to be a review page. If so, the following issues should be checked:\n\n";
		var errorFound = 0 // initialize variable
		if(showpagenumber != 0) {
			errorFound = 1; // found an error.
			errortext += "--Page number display appears to be enabled; it should be disabled.\n";
		}
		if(backpage != nextpage) {
			errorFound = 1; // found an error.
			errortext += "--Back and Next buttons have different values; they should be the same.\n";
			}
		if(showbookmark != 0) { // Is bookmark button even visible?
			if(bookmarkpage !="") {
				errorFound = 1; // found an error.
				errortext += "--Bookmarking appears to be enabled on this page; it should be disabled.\n";
				document.getElementById("debugitem02").innerHTML = ""; // Remove bookmarking feedback message.
			}
			else { // Bookmark is empty, which is OK on a review page. Set bookmarking feedback message.
				document.getElementById("debugitem02").innerHTML = "Bookmark button OK.<br>"; 
			}
		}
		else { // bookmark button is turned off (not visible).
			document.getElementById("debugitem02").innerHTML = "Bookmark button turned off.<br>";
			}
		
		if (errorFound == 1) {alert(errortext)} // If any review page errors were found, display alert.
	} // end of review page checking.
	
} // end showDebugger function.



//---------------------------------------------------------------------------------------------------------------------------------
//MACROMEDIA DREAMWEAVER FUNCTIONS
//---------------------------------------------------------------------------------------------------------------------------------
/* 
These functions are used by Macromedia Dreamweaver Web page layout
software to implement various functionality
(known as 'behaviors' in Dreamweaver).

Other .js include files in this site such as global_init_questions.js
and all the pages that make calls to it rely on these functions.

Such Macromedia functions can be centralized here rather than
sprinkled and embedded throughout the site's Web pages. If a page
uses a Macromedia function that isn't included here, the function could
be moved here and thereby made available to all pages. Additionally,
as new versions of these routines come out from Macromedia, it is
easy to put the newer versions here.

*/



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_showHideLayers() { //v6.0
  var i,p,v,obj,args=MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}

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_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_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];}
}



