/// SBS Javascript ///

//Straight to topic code

dojo.addOnLoad(function() {
					if(document.getElementById("straightToTopic")) {
						var courseGUID = document.getElementById("courseGUID").className;
						var courseTitle = document.getElementById("courseTitle").className;
						addCourseNode(courseTitle,courseGUID,'R','N','N');
					}
				});

//Detect browser
if (navigator.userAgent.match(/MSIE\s6/)) { browser = "ie6"; }
else if (navigator.userAgent.indexOf('Safari') != -1) { browser = "safari"; }
else if (navigator.userAgent.indexOf('Firefox') != -1) { browser = "firefox"; }
else { browser = "other"; }

//resize iFrame according to content

function resizeIFrame() {
	//assign vars
	var iFrame = document.getElementById("mainIFrame");
	var contentBody = iFrame.contentWindow.document.body;
	var mainPane = document.getElementById("myMainPane");
	//behave according to browser
	switch (browser) {
		case "safari":
			//collapse iFrame to properly detect content scrollHeight
			iFrame.height = '';
			//run intermediate safari specific code to account for resizing lag
			intermediateSafariStep(iFrame,contentBody,mainPane);
			break;
		case "firefox":
			//adjust iFrame to content height +20 to compensate for firefox bug
			iFrame.height = contentBody.offsetHeight + 20;
			//function to resize main frame
			resizeMainFrame();
			break;
		case "other":
			//adjust iFrame to content scrollheight
			iFrame.height = contentBody.scrollHeight;
			//function to resize main frame
			resizeMainFrame();
			break;
		case "ie6":
			//adjust iFrame to content scrollheight
			iFrame.height = contentBody.scrollHeight;
			//function to resize main frame
			resizeMainFrame();
			break;
	}
	//function to properly detect content offsetheight in Safari
	function intermediateSafariStep() {
		//if iFrame hasn't been collapsed, run the function again
		if (iFrame.offsetHeight != 150) {
			setTimeout(intermediateSafariStep,200);
		}
		//properly set scroll height and run function to resize main frame
		else {
			iFrame.height = contentBody.scrollHeight;
			resizeMainFrame();
		}
	}
	//function to resize the main pane in response to iFrame height
	function resizeMainFrame() {
		//if iFrame height is more than 450, mainPane needs adjustment
		if (iFrame.offsetHeight + 50 > 450) {
			if(browser.match(/ie6/)) {
				mainPane.style.height = iFrame.offsetHeight + 50 + "px";
				document.getElementById("opac").style.height = iFrame.offsetHeight + 50 + "px";
			}
			else mainPane.style.minHeight = iFrame.offsetHeight + 50 + "px";
		}
		else {
			if(browser.match(/ie6/)) {
				mainPane.style.height = 450 + "px";
				document.getElementById("opac").style.height = iFrame.offsetHeight + 50 + "px";
			}
			else mainPane.style.minHeight = 450 + "px";
		}
	}
}

//show and hide dropdown

function showHideNav() {
	nav = document.getElementById("myDropDown");
	if (nav.style.display == 'none') nav.style.display = 'block';
	else nav.style.display = 'none';
	var opac = document.getElementById("opac");
	if (opac.style.display == "none") opac.style.display = "block";
	else opac.style.display = "none";
}

//View info for a course

function viewCourseInfo (courseTitle,courseId) {
	//hide myButtons
	document.getElementById("myButtons").style.display = "none";
	//hide learnsplash
	document.getElementById("learnsplash").style.display = "none";
	//show lms
	document.getElementById("mainWindow").style.display = "block";
	//define courseID globally
	myCourseId = courseId;
	//define course home
	var goToCourseHome = "course_detail_min_RHB?GUID=" + courseId + "&status=";
	//goto course home
	popIFrame(goToCourseHome);
	//change pane title to courseTitle
	document.getElementById("lms_title").innerHTML = courseTitle;
	//set global title var
	enrollTitle = courseTitle;
	//set global GUID var
	enrollGUID = courseId;
}

//Add a new course node and show the lms window

function addCourseNode(courseTitle,courseId,courseStatus,progress,getTopic) {
	//show myButtons
	document.getElementById("myButtons").style.display = "block";
	//hide learnsplash
	document.getElementById("learnsplash").style.display = "none";
	//show lms
	document.getElementById("mainWindow").style.display = "block";
	//define courseID globally
	myCourseId = courseId;
	var courseTree = dojo.widget.byId("courseTree");
	//kill any existing children
	courseTree.destroyChildren();
	//define course home
	goToCourseHome = "course_detail_min_RHB?GUID=" + courseId + "&status=" + courseStatus;
	//create a new tree node
	var node = dojo.widget.createWidget("TreeNode",{
		title:courseTitle,
		isFolder:true,
		widgetId:courseId,
		object:goToCourseHome
	});
	//add the node to the tree
	courseTree.addChild(node);
	//and register it
	courseTree.registerChild(node);
	var treeSelector = dojo.widget.byId("treeSelector");
	//select the course node
	treeSelector.doSelect(node);
	//if progress is requested, load progress screen
	if (progress == "Y") {
		document.getElementById("loading").style.display = "block";
		var goToProgress = "teacherLevelDetailProgressByGUID?GUIDs=" + courseId;
		popIFrame(goToProgress);
		var treeController = dojo.widget.byId("treeController");
		treeController.expand(node);
	}
	//otherwise, register node as selected to autoload course home
	else {
		document.getElementById("loading").style.display = "block";
		if (getTopic != 'Y') popIFrame(goToCourseHome);
		else popIFrame("blankForCenterPanel");
		var treeController = dojo.widget.byId("treeController");
		treeController.expand(node);
	}
	//change pane title to courseTitle
	document.getElementById("lms_title").innerHTML = courseTitle;
	//globally define the currentCourse node
	currentCourse = dojo.widget.byId(courseId);
	//fix safari bug with myButtons displaying incorrectly
    if (browser == "safari") document.getElementById("courselisting").style.backgroundPosition = '0 0';
    if (getTopic == 'Y') {
		var timestamp = new Date().getTime();
    	dojo.io.bind({
			url: "getLastTopic?courseGUID=" + courseId + "&timestamp=" + timestamp,
			handle: getLastTopicCallback,
			mimetype: "text/plain",
			method: "get"
 		});
    }
    if(document.getElementById("straightToTopic")) loadTopic();
}

function loadTopic() {
	if (!currentCourse.isExpanded || typeof myType == 'undefined') setTimeout(loadTopic, 200);
	else {
		var topicGUID = document.getElementById("topicGUID").className;
		var subSectionGUID = document.getElementById("subSectionGUID").className;
		var sectionGUID = document.getElementById("sectionGUID").className;
		selectTreeItem(topicGUID,subSectionGUID,sectionGUID);
	}
}

//callback function for getLastTopic script from learnsplash

function getLastTopicCallback(type,data,evt) {
	if (!currentCourse.isExpanded || typeof myType == 'undefined') setTimeout(function() { getLastTopicCallback(type,data,evt); }, 200);
	else {
		if (data == "false") popIFrame(goToCourseHome);
		else eval(data);
	}
}

//function to populate iframe without history, checks to make sure window exists first for safari

function popIFrame(targ) {
	if (frames['mainIFrame']) frames['mainIFrame'].location.replace(targ);
	else setTimeout(function() { popIFrame(targ); }, 200);
}

//check progress

function checkProgress() {
	document.getElementById("loading").style.display = "block";
	popIFrame("teacherLevelDetailProgressByGUID?GUIDs=" + myCourseId);
}

//return to learnsplash

function courseListing() {
	//hide lms
	document.getElementById("mainWindow").style.display = "none";
	//show learnsplash
	document.getElementById("learnsplash").style.display = "block";
	//blank course variables
	myCourseId = '';
	courseTitle = '';
	currentCourse = '';
	var courseTree = dojo.widget.byId("courseTree");
	//kill the existing children
	courseTree.destroyChildren();
	//blank iFrame
	popIFrame('blankForCenterPanel');
}

//safari specific function to fix hover state bug

function fixHover(state) {
	if (browser == "safari") {
		var x = document.getElementById("courselisting");
		if (state == "on") x.style.backgroundPosition = "-125px 0";
		else x.style.backgroundPosition = "0 0";
	}
}

//select course home node

function courseHome() {
	var treeSelector = dojo.widget.byId("treeSelector");
	treeSelector.deselect();
	treeSelector.doSelect(currentCourse);
	dojo.event.topic.publish(treeSelector.eventNames.select, {node: currentCourse} );
}

//Move course node in learnsplash and update attributes

function moveThis(nodeId) {
	//define node to be moved
	var nodeToMove = document.getElementById(nodeId);
	//define registered courses node
	var rc = document.getElementById("registeredCourses");
	//define available courses node
	var ac = document.getElementById("availableCourses");
	//define course home span id value
	var s1val = nodeId + "s1";
	//define view progress span id value
	var s2val = nodeId + "s2";
	//define take course span id value
	var s3val = nodeId + "s3";
	//define image span id value
	var i1val = nodeId + "i1";
	//define course home span node
	var s1 = document.getElementById(s1val);
	//define view progress span node
	var s2 = document.getElementById(s2val);
	//define take course span node
	var s3 = document.getElementById(s3val);
	//define image node
	var i1 = document.getElementById(i1val);
	//make s2 visible
	s2.style.display = "inline";
	//make s3 invisible
	s3.style.display = "none";
	//get the alternate onclick value for course home node
	var altval = s1.getAttribute("altclick");
	//assign the alternate onclick value for course home node
	s1.setAttribute("onclick", altval);
	//assign the alternate onclick value for image node
	i1.setAttribute("onclick", altval);
	//move the node
	rc.appendChild(nodeToMove);
	//if there are no nodes left in ac, say so
	if (ac.getElementsByTagName("div").length == 0) {
		ac.innerHTML = "<div style='text-align:center\;font-weight:bold'>No courses available.</div>";
	}
	document.getElementById("mycoursestr").style.display = 'block';
}

//initialize variables on mainFrame load

function initializeVars() {
  var treeSelector = dojo.widget.byId("treeSelector");
  myType = "";
  if (null != treeSelector) {
    currentNode = treeSelector.selectedNode;
    if (null != currentNode) {
      myType = currentNode.elementType;
    }
  }
	//determine where the user is in the navigation tree
	switch (myType) {
		case "sections":
			currentTopic = "none";
			currentSubsection = "none";
			currentSection = currentNode;
			break;
		case "subsection":
			currentTopic = "none";
			currentSubsection = currentNode;
			currentSection = currentNode.parent;
			break;
		case "topic":
			currentTopic = currentNode;
			currentSubsection = currentNode.parent;
			if (currentSubsection.elementType == "sections") {
                          currentSection = currentSubsection;
                          currentSubsection = "none";
                        }
                        else
                          currentSection = currentSubsection.parent;
			break;
		case "sectionquiz":
			currentTopic = currentNode;
			currentSubsection = "none";
			currentSection = currentNode.parent;
			break;
		default:
			myType = "course";
			currentTopic = "none";
			currentSubsection = "none";
			currentSection = "none";
			break;
	}
}

//function to select tree items from anywhere

function selectTreeItem(topicId,subsectionId,sectionId) {
	//define vars
	var newTopicValue = topicId;
	var newSubsectionValue = subsectionId;
	var newSectionValue = sectionId;
	var treeController = dojo.widget.byId("treeController");
	var treeSelector = dojo.widget.byId("treeSelector");
	//pull window scope vars for clarity
	var currentSubsection = window.currentSubsection;
	var currentSection = window.currentSection;
	var currentCourse = window.currentCourse;
	var myType = window.myType;
	//expand currentCourse if collapsed
	if (!currentCourse.isExpanded) treeController.expand(currentCourse);
	//determine next step after expanding course
	afterExpandCourse();
	//function to determine next step after expanding course
	function afterExpandCourse() {
		//determine where user is
		switch (myType) {
			//if user is on the course screen
			case "course":
				//if the new topic value is null, user must be going to a section
				if (newTopicValue == '') {
					treeSelector.doSelect(currentCourse);
					treeSelector.deselect();
					var mySection = dojo.widget.byId(newSectionValue);
					selectAndPublish(mySection);
				}
				//otherwise, navigate to the first topic
				else checkForSwitchedNodes();
				break;
			//if user is not on course screen, currentSection is defined
			default:
				if (!currentSection.isExpanded) treeController.expand(currentSection);
				afterExpandSection();
				break;
		}
	}
	//determines next step after expanding section
	function afterExpandSection() {
		//determine where user is
		switch (myType) {
			//if user is on section screen
			case "sections":
				treeSelector.doSelect(currentSection);
				treeSelector.deselect();
				//if newSubsectionValue is not null, target is a subsection
				if (newSubsectionValue != '') {
					var mySubsection = dojo.widget.byId(newSubsectionValue);
                                        selectAndPublish(mySubsection);
				}
				//if newSectionValue is null, target is a quiz
				else {
					var myQuiz = dojo.widget.byId(newTopicValue);
					selectAndPublish(myQuiz);
				}
				break;
			default:
				//if there is no current subsection, user is on a quiz, no need to expand subsection
				if (currentSubsection != "none") {
					if (!currentSubsection.isExpanded) treeController.expand(currentSubsection);
				}
				afterExpandSubsection();
				break;
		}
	}
	//expands subsection and moves to next step
	function afterExpandSubsection() {
		//determine where user is
		switch (myType) {
			//if user is on subsection screen
			case "subsection":
				treeSelector.doSelect(currentSubsection);
				treeSelector.deselect();
				var myTopic = dojo.widget.byId(newTopicValue);
				selectAndPublish(myTopic);
				break;
			default:
				checkForSwitchedNodes();
				break;
		}
	}
	//checks if new nodes have to be expanded
	function checkForSwitchedNodes() {
		//if currentTopic is not defined, user is navigating from course home
		var correctNode = (currentTopic != "none") ? currentTopic : currentCourse;
		treeSelector.doSelect(correctNode);
		treeSelector.deselect();
		//if new section value is defined, switch sections
		if (newSectionValue != '') {
			if (currentSubsection != "none") treeController.collapse(currentSubsection);
			if (currentSection != "none") treeController.collapse(currentSection);
			var newSection = dojo.widget.byId(newSectionValue);
			treeController.expand(newSection);
			afterExpandNewSection();
		}
		//if new subsection is defined, switch subsections
		else if (newSubsectionValue != '') {
			if (currentSubsection != "none") treeController.collapse(currentSubsection);
			var newSubsection = dojo.widget.byId(newSubsectionValue);
			if (typeof newSubsection != "undefined") {
                          treeController.expand(newSubsection);
                        }
			afterExpandNewSubsection();
		}
		//if only new topic is defined, select new topic
		else {
			var newTopic = dojo.widget.byId(newTopicValue);
			if (newTopic.elementType == "sectionquiz") treeController.collapse(currentSubsection == "none" ? currentSection : currentSubsection);
			selectAndPublish(newTopic);
		}
	}
	//determines next step after expanding new section
	function afterExpandNewSection() {
		//if newSubsection value is not null, target is a topic
		if (newSubsectionValue != '') {
			var newSubsection = dojo.widget.byId(newSubsectionValue);
			//if newSubsection exists, expand it
			if (typeof newSubsection != "undefined") {
				treeController.expand(newSubsection);
				afterExpandNewSubsection();
			}
			else if (newTopicValue != '') {
                          var newTopic = dojo.widget.byId(newTopicValue);
                          if (typeof newTopic != "undefined") {
                            selectAndPublish(newTopic);
                          }
                          else setTimeout(afterExpandNewSection,100);
                        }
                        //otherwise run the function again
			else setTimeout(afterExpandNewSection,100);
		}
		//if newSubsection value is null, target is a quiz
		else {
			var newTopic = dojo.widget.byId(newTopicValue);
			//if newTopic exists, select it
			if (typeof newTopic != "undefined") selectAndPublish(newTopic);
			//otherwise run the function again
			else setTimeout(afterExpandNewSubsection,100);
		}
	}
	//determines next step after expanding new subsection
	function afterExpandNewSubsection() {
		var newTopic = dojo.widget.byId(newTopicValue);
		//if newTopic exists, select it
		if (typeof newTopic != "undefined") selectAndPublish(newTopic);
		//otherwise run the function again
		else setTimeout(afterExpandNewSubsection,100);
	}
	//selects final node and publishes it as selected
	function selectAndPublish(node) {
		var treeSelector = dojo.widget.byId("treeSelector");
		treeSelector.doSelect(node);
		dojo.event.topic.publish(treeSelector.eventNames.select, {node: node} );
	}
}

/// BB Javascript ///

function DisplayTreeContent(){
	this.update = function(message) {
		document.getElementById("loading").style.display = "block";
		var clickedTreeNode = message.node;
		if (typeof currentTreeNode != "undefined" && currentTreeNode.elementType != "sectionquiz") previousTreeNode = currentTreeNode;
		currentTreeNode = clickedTreeNode;
		currentElementType = clickedTreeNode.elementType;
		//alert("displaying: "+clickedTreeNode.elementType);
		var targetPane = dojo.widget.byId("mainPane");  //================================
		var file = clickedTreeNode.object;
		//alert(clickedTreeNode);
		if (currentElementType == "sectionquiz") {
			//alert("sectionQuiz.title: "+clickedTreeNode.title);
			title = clickedTreeNode.title;
			//alert("title: "+title+"\ntitle.indexOf :"+title.indexOf("incomplete16x16.png"));
			parentNode=clickedTreeNode.parent;
			//alert("parentNode: "+parentNode);
			children=parentNode.getDescendants();
			//alert("parent has "+children.length+" children: "+children);
			for (i=0;i<children.length;i++) {
				child=children[i];
				//alert("checking child "+i+": "+child+"\ntype: "+child.elementType);
				if (child.elementType == "subsection") {
					subsectionTitle=child.title;
					//alert("found a subsection with title: "+subsectionTitle+"\index: "+subsectionTitle.indexOf("incomplete16x16.png"));
					//alert("found a subsection with title: "+subsectionTitle+"\index: "+subsectionTitle.indexOf("notvisited16x16red.gif"));
					if (subsectionTitle.indexOf("incomplete16x16.png")>0) {
					dojo.widget.byId("treeSelector").deselect();
					if (typeof previousTreeNode != "undefined") dojo.widget.byId("treeSelector").doSelect(previousTreeNode);
					alert("Sorry, you must complete all subsections before taking the quiz");
					document.getElementById("loading").style.display = "none";
					return;
					}
					if (subsectionTitle.indexOf("notvisited16x16red.gif")>0) {
						dojo.widget.byId("treeSelector").deselect();
						if (typeof previousTreeNode != "undefined") dojo.widget.byId("treeSelector").doSelect(previousTreeNode);
						alert("Sorry, you must complete all subsections before taking the quiz");
						document.getElementById("loading").style.display = "none";
						return;
					}
				}
        	}
        	sectionQuizState = "loading";
        	sectionQuizNode = currentTreeNode;
      	}
		if (typeof file != "unknown") {
			popIFrame(file);
		}
		else {
			popIFrame(blank);
		}
		dojo.widget.byId("treeController").expand(clickedTreeNode);
	}
}

var currentTreeNode;
var currentElementType;
var subsectionTreeNode;
var sectionTreeNode;
var courseTreeNode;
var sectionQuizState = "unloaded";
var sectionQuizNode;
var dumpFrameHolding = "";
var lastAvailableCourseNodeSelected;

function takeCourse(guid,title) {
	dumpFrameHolding = 'courseRegistrationResults';
	enrollGUID = guid;
	enrollTitle = title;
	frames['dumpFrame'].location.href = 'zp_insertCourseTracking?GUID=' + guid + '&objPath=';
}

function dumpFrameLoaded(){
	//alert("dumpFrameLoaded, sectionQuizState: "+top.sectionQuizState);
	if (dumpFrameHolding == "sectionQuizResults") {
		if (top.sectionQuizState == "completed") {
			//alert("sectionQuizNode.title: "+sectionQuizNode.title+"\nsectionQuizNode.widgetId: "+sectionQuizNode.widgetId);
			dojo.io.bind({
				url: "getQuizCompletionStatus",
				handle: updateQuizStatusCompletionCallback,
				content: {GUID: sectionQuizNode.widgetId },
				mimetype: "text/json",
				method: "post",
				transport: "XMLHTTPTransport"
 			});
		}
	}
	else if (dumpFrameHolding == "courseRegistrationResults") {
		moveThis(enrollGUID);
		addCourseNode(enrollTitle,enrollGUID,'R','N','Y');
	}
}

function updateQuizStatusCompletionCallback(type, obj){
	if (type == 'error') {
		alert('updateQuizStatusCompletionCallback, Error when retrieving quiz status from the server!');
	}
    else {
		adjustCompletionIcons(sectionQuizNode,obj.completionState);
	}
 }

function mainLoaded() {
	if (frames['mainIFrame'].location.href.indexOf('blankForCenterPanel') == -1) document.getElementById("loading").style.display = "none";
	resizeIFrame();
    initializeVars();
    //alert("mainLoaded with node: "+currentTreeNode);
    if (currentTreeNode) {
		//currentTreeNode.collapse();
		if (currentElementType) {
        	//alert("mainLoaded, completing elementType: "+currentElementType);
        	if (currentElementType == "topic") {
				//alert("updating topic tree node: "+currentTreeNode.widgetId);
				//alert("mainLoaded, topic, checking parantage: "+currentTreeNode.parent.parent.parent.parent.widgetId);
				if (currentTreeNode.parent.parent.widgetId == myCourseId || currentTreeNode.parent.parent.parent.widgetId == myCourseId) {
					//alert("mainLoaded, updating topic completion");
					updateTopicCompletion();
				}
				else {
					//alert("mainLoaded, not a registered course");
				}
			}
			else if (currentElementType == "sectionquiz") {
				//alert("updating quiz: "+frames['mainIFrame'].location.href);
			}
		}
	}
	else {
		//alert("mainLoaded, tree node not defined");
    }
}

function updateTopicCompletion() {
    //alert("updateTopicCompletion, completing topic\nupdateGUID: "+currentTreeNode.widgetId);
    dojo.io.bind({
		url: "processTopicCompletion",
		handle: updateTopicCompletionCallback,
		content: {updateGUID: currentTreeNode.widgetId },
		mimetype: "text/json",
		method: "post",
		transport: "XMLHTTPTransport"
	});
    //alert("io.bind complete");
}

function updateTopicCompletionCallback(type, data,evt) {
    //alert(type);
    //alert(data);
    if (type == 'error') {
		alert('updateTopicCompletionCallback, Error when retrieving topic state from the server!\n'+obj);
	}
    else {
		//alert("updateTopicCompletionCallback, GUID: "+obj.updatedGUID+"\nuserId: "+obj.userId+"\nuserName: "+obj.userName+"\ncourseId: "+obj.courseId+"\noldTopicStatus: "+obj.oldTopicStatus+"\nnewTopicStatus: "+obj.newTopicStatus);
		// at this point, we need to walk up the tree.
		//alert("updateTopicCompletionCallback, adjusting completion icons");
		//alert(data.newTopicStatus);
		adjustCompletionIcons(currentTreeNode,data.newTopicStatus);
	}
}

function adjustCompletionIcons(node,completionState) {
    var title=new String(node.title);
    var nType=node.elementType;
    //alert("adustCompletionIcons for node type: "+nType+"\ncompletionState: "+completionState);
    //////// TOPIC ////////////
    if (nType == "topic") {
		//find second "<img src=" (first starts at position 0
		if (completionState == "C") {
			start=title.indexOf("<img",5); //skip first <img tag
			end=title.indexOf("/>",start) // find end of tag
			t1=title.slice(0,start);
			t2=title.slice(end+2);
			tmid="<img src='complete16x16.png'/>"
			//alert("TOPIC: "+start+"  "+end+"\n"+title+"\n"+t1+"\n"+t2);
			node.edit({title:t1+tmid+t2});
		}
		if (completionState == "O") {
			start=title.indexOf("<img",5); //skip first <img tag
			end=title.indexOf("/>", start) // find end of tag
			t1=title.slice(0,start);
			t2=title.slice(end+2);
			tmid="<img src='incomplete16x16.png' />"
			//alert("TOPIC: "+start+"  "+end+"\n"+title+"\n"+t1+"\n"+t2);
			node.edit({title:t1+tmid+t2});
		}
		subsectionTreeNode=node.parent;
                if (subsectionTreeNode.elementType == "sections") {
                  sectionTreeNode = subsectionTreeNode;
                  subsectionTreeNode = "none";
                  dojo.io.bind({
 		  url: "getSectionCompletionStatus",
		  handle: updateSectionStatusCompletionCallback,
		  content: {GUID: sectionTreeNode.widgetId },
		  method: "post",
		  mimetype: "text/json",
		  transport: "XMLHTTPTransport"
                  });  
                }
                else
                  dojo.io.bind({
                  url: "getSubsectionCompletionStatus",
                  handle: updateSubsectionStatusCompletionCallback,
                  content: {GUID: subsectionTreeNode.widgetId },
                  method: "post",
                  mimetype: "text/json",
                  transport: "XMLHTTPTransport"
                  });
	} 
	//////// SUBSECTION ////////////
	else if (nType == "subsection") {
		if (completionState == "C") { // no sense going on up the tree if the subsection is not complete
			//find second "<img src=" (first starts at position 0
			start=title.indexOf("<img",0); //no prior image tag
			end=title.indexOf("/>",start) // find end of tag
			t1=title.slice(0,start);
			t2=title.slice(end+2);
			tmid="<img src='complete16x16.png'/>"
			//alert("SUBSECTION: "+start+"  "+end+"\n"+title+"\n"+t1+"\n"+t2);
		}
		if (completionState == "O") { // no sense going on up the tree if the subsection is not complete
			//find second "<img src=" (first starts at position 0
			start=title.indexOf("<img",0); //no prior image tag
			end=title.indexOf("/>",start) // find end of tag
			t1=title.slice(0,start);
			t2=title.slice(end+2);
			tmid="<img src='incomplete16x16.png'/>"
			 //alert("SUBSECTION: "+start+"  "+end+"\n"+title+"\n"+t1+"\n"+t2);
        }
        node.edit({title:t1+tmid+t2});
        sectionTreeNode=node.parent;
        dojo.io.bind({
 			url: "getSectionCompletionStatus",
			handle: updateSectionStatusCompletionCallback,
			content: {GUID: sectionTreeNode.widgetId },
			mimetype: "text/json",
			method: "post",
			transport: "XMLHTTPTransport"
        });  
    }
    //////// QUIZ ////////////
    else if (nType == "sectionquiz") {
		if (completionState == "C") { // no sense going on up the tree if the quiz is not complete
			//find second "<img src=" (first starts at position 0
			start=title.indexOf("<img",5); //skip first <img tag
			end=title.indexOf("/>",start) // find end of tag
			t1=title.slice(0,start);
			t2=title.slice(end+2);
			tmid="<img src='complete16x16.png'/>"
			//alert("SECTIONQUIZ: "+start+"  "+end+"\n"+title+"\n"+t1+"\n"+t2);
			node.edit({title:t1+tmid+t2});
			sectionTreeNode=node.parent;
			dojo.io.bind({
  				url: "getSectionCompletionStatus",
				handle: updateSectionStatusCompletionCallback,
				content: {GUID: sectionTreeNode.widgetId },
				mimetype: "text/json",
				method: "post",
				transport: "XMLHTTPTransport"
			});
			frames['mainIFrame'].location.reload(true);
			alert("Congratulations, you completed the section.  When you are ready, please click the \"Next\" button to move on to the next section.");
		}
		else if (completionState == "I") {
        	alert("Sorry, you did not pass the test");
			frames['mainIFrame'].location.reload(true);	
		}
    }
    //////// SECTION ////////////
    else if (nType == "sections") {
		if (completionState == "C") { // no sense going on up the tree if the subsection is not complete
			//find second "<img src=" (first starts at position 0
			start=title.indexOf("<img",0); //no prior image tag
			end=title.indexOf("/>",start) // find end of tag
			t1=title.slice(0,start);
			t2=title.slice(end+2);
			tmid="<img src='complete16x16.png'/>"
			//alert("SECTION: "+start+"  "+end+"\n"+title+"\n"+t1+"\n"+t2);
			node.edit({title:t1+tmid+t2});
			courseTreeNode=node.parent;
		}
		if (completionState == "O") { // no sense going on up the tree if the subsection is not complete
			//find second "<img src=" (first starts at position 0
			start=title.indexOf("<img",0); //no prior image tag
			end=title.indexOf("/>",start) // find end of tag
			t1=title.slice(0,start);
			t2=title.slice(end+2);
			tmid="<img src='incomplete16x16.png'/>"
			//alert("SECTION: "+start+"  "+end+"\n"+title+"\n"+t1+"\n"+t2);
			node.edit({title:t1+tmid+t2});
			courseTreeNode=node.parent;
		}
		//alert("checking course completion status");
        dojo.io.bind({
			url: "getCourseCompletionStatus",
			handle: updateCourseStatusCompletionCallback,
			content: {GUID: courseTreeNode.widgetId },
			method: "post",
			mimetype: "text/json",
			transport: "XMLHTTPTransport"
		});
    }
    //////// COURSE ////////////
    else if (nType == "RegisteredCourses") {
		if (completionState == "C") {
			//alert("adjustCompletionIcons for course");
			myTree = dojo.widget.byId("courseTree");
			//alert("myTree: "+myTree);
			registeredCourseNode = dojo.widget.manager.getWidgetById("RegisteredCourses");
			//alert("registeredCourseNode: "+registeredCourseNode);
			completedCourseNode = dojo.widget.manager.getWidgetById("CompletedCourses");
			//alert("completedCourseNode: "+completedCourseNode);
			while (registeredCourseNode.children.length > 0) {
				myTree.removeNode(registeredCourseNode.children[0]);
			}
			//alert("removed registered");
			while (completedCourseNode.children.length > 0) {
				myTree.removeNode(completedCourseNode.children[0]);
			}
			//alert("removed available");
			myTreeController = dojo.widget.byId("treeController");
			//alert("myTreeController: "+myTreeController);
			//alert(1);
			myTreeController.loadRemote(completedCourseNode,true);
			//alert(2);
			myTreeController.loadRemote(registeredCourseNode,true);
		}
	}
}

function updateSubsectionStatusCompletionCallback(type, obj) {
    //alert("i am in the Subsection Status Completion Call back");
    //alert(type);
    //alert(obj);
    if (type == 'error') {
		alert('Error when retrieving subsection status from the server!');
	}
    else {
		adjustCompletionIcons(subsectionTreeNode,obj.completionState);
	}
}

function updateSectionStatusCompletionCallback(type, obj) {
    //alert("i am in the Section Status Completion Call back");
    //alert(obj.completionState);
    if (type == 'error') {
		alert('Error when retrieving section status from the server!');
	}
    else {
		adjustCompletionIcons(sectionTreeNode,obj.completionState);
		if(typeof quizNext != "undefined" && quizNext != '') {
			eval(quizNext);
			quizNext = '';
		}
	}
}

function updateCourseStatusCompletionCallback(type, obj) {
    //alert('i am in the course status completion call back');
    if (type == 'error') {
		alert('Error when retrieving course status from the server!');
	}
    else {
		//alert("updateCourseStatusCompletionCallback completionState: "+obj.completionState);
		adjustCompletionIcons(courseTreeNode,obj.completionState);
	}
}

var displayer = new DisplayTreeContent();
var nodeSelectionTopic = dojo.event.topic.getTopic("nodeSelected");
nodeSelectionTopic.subscribe(displayer, "update");
