/*
 $Source: /web/cvs/classware/webapps/classware/WEB-INF/xslt/shared/common_v3.js,v $
 $Revision: 1.59.12.1 $
 $Author: sujoyb $
 $Date: 2008/07/16 21:57:59 $
*/
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Following are temporary, throwaway scripts for server upgrade alert:
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
*/
var XHTMLNS = 'http://www.w3.org/1999/xhtml';
var CURRENT_BOX;
var CURRENT_SHADOW;
var isInfoCenterHomepage = 0;

/* 	NOTE this function now has a purpose: in addition to displaying the temporary alerts when needed,
	it tests whether the user has disabled cookies in his browser.  showTempAlert() should be called only when needed,
	the cookie test should always be included. (For now on the info center homepage only, since that's the default
	entry point to the system.)
*/

function doTempAlert() {

/* NOTE! this test for isInfoCenterHomepage does not work; the variable is set too late. Need to come up with a
better method if we need to bring the tempAlert back... for now checkCookieAvailability can just be on all pages.
(currently only the info center calls this function onLoad. That could easily be extended to the other product types.)
*/
/*
	if (isInfoCenterHomepage) {
		showTempAlert();
	}
*/
	checkCookieAvailability();
}
function showTempAlert() {
/* Removed temporarily; uncomment this when we want the alert to appear.
if (!document.createElement || !document.getElementsByTagName) return;
	if (!document.createElementNS) {
		document.createElementNS = function(ns, elt) {
			return document.createElement(elt);
		}
	}
  var d = document.createElementNS(XHTMLNS, 'div');
    d.className = 'alertbox';
    d.innerHTML = "<p><a href=\"javascript:void 1;\" onClick=\"hideTempAlert();\"><img src=\"/classware/xslt/shared/images/closeX.gif\" align=\"right\" alt=\"Click here to continue\" border=\"0\" hspace=\"10\"></a></p><p><b>Please note:</b></p><p>Beginning on <b>Thursday, July 8th at 5:00PM EST</b> and ending on <b>Sunday, July 11th at 5PM EST</b>, McGraw-Hill Education will perform a system upgrade.  During this period our Online Learning Centers, Course Web Sites, and MathZone titles will not be accessible.</p>  <p>We apologize, in advance, for this inconvenience.  However, the improvements we will be able to accomplish during this designated weekend will allow us to better serve our technology products to the academic and professional communities.</p>  <p>If you are experiencing a service outage outside our set maintenance, please use our <a href=\"http://www.mhhe.com/catalogs/solutions/support_request.html\">technical support request form</a> to contact Customer Support.</p><p><a href=\"javascript:void 1;\" onClick=\"hideTempAlert();\">Click here</a> to continue.</p>";
    var e = document.createElementNS(XHTMLNS, 'div');
    e.className = 'alertboxshadow';
    e.innerHTML = d.innerHTML;
    document.getElementsByTagName('body')[0].appendChild(e);
    CURRENT_SHADOW = e;
    e.style.zIndex=99;
    document.getElementsByTagName('body')[0].appendChild(d);
    CURRENT_BOX = d;
    d.style.zIndex = 100;
*/
}

function checkCookieAvailability() {
	// check cookies first:
	var testcookie = setCookie('testCookie','Chocolate Chip');
	var testget = getCookie('testCookie');
	if (testget != 'Chocolate Chip') {
		// cookies aren't enabled.
		if (!document.createElement || !document.getElementsByTagName) {
			// fancy display won't work:
			alert("Please enable cookies in your browser preferences before continuing.");
			return;
		}
		// fancy display:
		if (!document.createElementNS) {
			document.createElementNS = function(ns, elt) {
				return document.createElement(elt);
			}
		}

		var d = document.createElementNS(XHTMLNS, 'div');
		d.className = 'alertbox';
		d.innerHTML = "<p><a href=\"javascript:void 1;\" onClick=\"hideTempAlert();\"><img src=\"/classware/xslt/shared/images/closeX.gif\" align=\"right\" alt=\"Click here to continue\" border=\"0\" hspace=\"10\"></a></p><p><b>Please note:</b></p><p>You appear to have cookies disabled in your browser. This website will not function correctly without cookies; please enable them in your browser preferences before continuing.</p>";
		var e = document.createElementNS(XHTMLNS, 'div');
		e.className = 'alertboxshadow';
		e.innerHTML = d.innerHTML;
		document.getElementsByTagName('body')[0].appendChild(e);
		CURRENT_SHADOW = e;
		e.style.zIndex=99;
		document.getElementsByTagName('body')[0].appendChild(d);
		CURRENT_BOX = d;
		d.style.zIndex = 100;
	}
	deleteCookie('test');
	return;
}

function hideTempAlert() {
	if (!document.getElementsByTagName) return;
	if (CURRENT_BOX) {
		document.getElementsByTagName('body')[0].removeChild(CURRENT_BOX);
		CURRENT_BOX = null;
		document.getElementsByTagName('body')[0].removeChild(CURRENT_SHADOW);
		CURRENT_SHADOW = null;
	}
}
function addEvent(obj, evType, fn) {
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, true);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent('on'+evType, fn);
		return r;
	} else {
		return false;
	}
}
/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
End of temp stuff
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
*/

/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
countdown timer for classware quizzes
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// Manickraj, Tricon: using a new global parameter isExcelProject for bug fix 323
   This variable isExcelProject is available only in ala_autograder/default.xsl

*/
function quizCountdownTimer(secondsLeft,isActivityTimer) {
	var h = Math.floor(secondsLeft / 3600);
	var r = secondsLeft - (h*3600);
	var m = Math.floor(r / 60);
	var s = r - (m*60);
	var res = "You have ";
	if (h > 0) {res += h + " hours, "}
	if (m > 0) {res += m + " minute"}
	if (m == 1) {res += " "}
	if (m > 1) {res += "s "}
	if (s > 0) {
		if (m > 0 && h < 1) {res += "and "}
		if (h < 1) {res +=  s + " seconds "};
	}
	if (isActivityTimer == 0) {
		if(typeof(isExcelProject)!="undefined" && isExcelProject==true){
			res += "to submit the project file for this assignment.";
			if (secondsLeft == 0) {
				res = "This assignment has past due. You cannot submit project file anymore.";
			}
		}else{
			res += "to complete this assignment.";
			if (secondsLeft == 0) {
				res = "Assignment due. Autosubmitting quiz.";
			}
		}
	} else {
		if(typeof(isExcelProject)!="undefined" && isExcelProject==true){
			res += "to submit the project file for this activity.";
			if (secondsLeft == 0) {
				res = "This activity has past due. You cannot submit project file anymore.";
			}
		}else{
			res += "to complete this activity.";
			if (secondsLeft == 0) {
				res = "Activity due. Autosubmitting quiz.";
			}
		}		
	}
	var bObj = new getObj("quizBorder");
	var cObj= new getObj("countdownTimer");
	if (cObj.obj) {cObj.obj.innerHTML = res};
	/* show color border if time is low */
	if (secondsLeft <= 10) {
		if ((secondsLeft % 2) == 0) {
			if (bObj.style) {bObj.style.borderColor="#F00"};
			if (cObj.style) {cObj.style.backgroundColor="#F00"};
		} else {
			if (bObj.style) {bObj.style.borderColor="#FF0"};
			if (cObj.style) {cObj.style.backgroundColor="#FF0"};
		}
	} else if (secondsLeft <= 30) {
		if (bObj.style) {bObj.style.borderColor="#F00"};
		if (cObj.style) {cObj.style.backgroundColor="#F00"};
	} else if (secondsLeft <= 60) {
		if (bObj.style) {bObj.style.borderColor="#FF0"};
		if (cObj.style) {cObj.style.backgroundColor="#FF0"};
	}
	/*
		if there are hours left, only update once per minute. (round to even minute first.)
		If minutes>10, update every 15 seconds
		minutes > 1, update every 5 seconds
		otherwise every second.
	*/
	if (secondsLeft > 0) {
		if (h > 0) {
			setTimeout("quizCountdownTimer("+(secondsLeft-60-s)+");",60000 + (s*1000));
		} else if (m > 9) {
			setTimeout("quizCountdownTimer("+(secondsLeft-15-(s % 15))+");",15000 + (s % 15)*1000);
		} else if (m > 0) {
			setTimeout("quizCountdownTimer("+(secondsLeft-5-(s % 5))+");",5000 + (s % 5)*1000);
		} else {
			setTimeout("quizCountdownTimer("+(secondsLeft-1)+");",1000);
		}
	} else {
		saveAndSubmitQuiz();
	}
}

/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
Quick hack for win/IE downloadable files
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
*/
function downloadWarning() {
	var is = new BrowserIs();
	if (is.win && is.ie) {
		document.write("<div class='instructions'>Right-click and select 'Save As...' to download this file.</div>");
	}
}

function launchHelp(whichPage) {
	if (document.forms.helpPageIDForm) {
		if (whichPage) {
			document.forms.helpPageIDForm.helpPageID.value = whichPage;
		}
		var myNewHelpWin = window.open('','helpWin','width=750,height=450,resizable,scrollbars');
		myNewHelpWin.focus();
		document.forms.helpPageIDForm.submit();
	}
}

/*
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
	tabs and drawers code, shared by these products:
	olc, cw, information_center
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
*/
var curScript = "";
var nextScript = "";
var intervalID = 0;
var curTool = "";
var toolOrigin = 80;
var toolTop = 80;
var scrolledBy = 0;
var floatNav = 1;
var floaters = new Array();
var glideSpeed="1";
var newFloat;
var newGlide;
var siteISBN="";
function initPage(isbn) {
	// capture the isbn for later:
	siteISBN = isbn;
	initPrefs();
	initNav();
	initFloat();
}
function initHelpPage(isbn) {
	siteISBN = isbn;
	initPrefs();
	initHelpNav();
	initFloat();
}
function initHelpNav() {
      showLayer("divNavContents");
	  hideLayer("divNavClass");
}
function initPrefs() {
	// read prefs cookie, if present; set glideSpeed and floatNav.
	var cookieName = getCookie("OLCGroup") ? "OLCGroup" : "OLC" + siteISBN;
	if (document.forms.frmPrefsDataContainer) {
		newFloat = document.forms.frmPrefsDataContainer.UIFloatNav.value;
		newGlide = document.forms.frmPrefsDataContainer.UIDrawerSpeed.value;
	}
	glideSpeed = newGlide ? newGlide : 1;
	floatNav = newFloat ? newFloat : 1;
	if (document.forms.frmPrefs && document.forms.frmPrefs.float_nav) {
		document.forms.frmPrefs.float_nav.selectedIndex = floatNav;
		document.forms.frmPrefs.drawer_speed.selectedIndex = glideSpeed;
	}
}
function initFloat() {
	if (floatNav == 1) {
		floaters = ["divTools"];
	} else if (floatNav == 2) {
		floaters = ["divTools","divNavClass","divNavContents","divNavContentsExtra"];
	}
	// start the page monitor...
	if (intervalID == 0) {
		intervalID = setInterval("Monitor()",10);
	}
	doFloat();
}
function initNav() {
	if (getCookie("courseWareNav") == 'classroom') {
		swapNav('classroom');
	} else {
		swapNav('contents');
	}
}
// ------------------------------------------------------------
function swapNav(newNav) {
	hideLayer("divNavClass");
	hideLayer("divNavContents");
	if (newNav) {
		setCookie("courseWareNav",newNav);
	} else {
		newNav = getCookie("courseWareNav");
	}
	if (newNav == 'classroom') {
		window.setTimeout("showLayer('divNavClass');",5);
	} else {
		window.setTimeout("showLayer('divNavContents');",5);
	}
}


function showHideTable(imageId, theTableId) {
	var image = document.getElementById(imageId);
	var source = image.src;

	if (source.lastIndexOf('collapse.gif') > 0) {
		image.src = source.replace('collapse', 'expand');
		document.getElementById(theTableId).style.display = 'block';
	} else {
		image.src = source.replace('expand', 'collapse');
		document.getElementById(theTableId).style.display = 'none';
	}
	    var str=navigator.appVersion;
    	var opSys=navigator.platform;

    	if (str.match("Safari")  && opSys.match("Mac")) {
    		initParts();
    	} else if (str.match("MSIE")  && opSys.match("Mac")){
    		initParts();
    	} else{
    	    return(true);
    	}
}


// ------------------------------------------------------------
function popWindow(theUrl) {
	var newWin = window.open(theUrl,"Window","width=500,height=400");
	newWin.focus();
	return false;
}
// ------------------------------------------------------------


function validatePrefs(f) {
	// not really validation; just sets various form elements
	f.isbn.value = siteISBN;
	var gotourl = window.location.href;
    var lastChar = gotourl.substring(gotourl.length-1,gotourl.length);
    //strip the # in the end
    if (lastChar=='#') gotourl = gotourl.substring(0,gotourl.length-1);

	if (document.forms.IDform) {
		var pageid = document.forms.IDform.pageID.value;
		var curid = document.forms.IDform.curID.value;
	}
	// correct oddball urls to avoid doublesubmits.  Should probably trust pageid and curid more for this,
	// but need to check the actual values since they seem to have drifted quite a bit from spec
	if (gotourl.indexOf("passthrough.do") > -1) { gotourl = "/classware/gradebook.do?isbn=" + siteISBN }
	if (gotourl.indexOf("gradePolicyEdit.do") > -1) { gotourl = "/classware/gradebook.do?action=policy&isbn=" + siteISBN }
	if (gotourl.indexOf("assignmentEdit.do") > -1) { gotourl = "/classware/assignments.do"}
	if (gotourl.indexOf("assignmentChangeDates.do") > -1) { gotourl = "/classware/assignments.do"}
	if (gotourl.indexOf("activity.do") > -1) { gotourl = "/classware/assignments.do"}
	if (gotourl.indexOf("gradeQuiz.do") > -1) { gotourl = "/classware/ala.do?isbn=" + siteISBN + "&alaid=ala_" + pageid}
	// A massive proliferation of course edit pages:
	if ((gotourl.indexOf("restoreCourse") > -1) ||
		(gotourl.indexOf("secRegistration.do") > -1) ||
		(gotourl.indexOf("courseinfoEdit.do") > -1) ||
		(gotourl.indexOf("copyCourse.do") > -1) ||
		(gotourl.indexOf("archiveCourse.do") > -1) ||
		(gotourl.indexOf("createNewSection.do") > -1)) { gotourl = "/classware/courseinfo.do?isbn=" + siteISBN }
	if ( (gotourl.indexOf("assignmentInfo.do") > -1 ) ||
	    ( gotourl.indexOf("assignmentContent.do") > -1) ||
	    (gotourl.indexOf("assignmentPref.do") > -1) ) {
        var assignmentId = document.forms.assignmentForm.assignmentID.value;
        var action = "edit";
        if( assignmentId == "" || assignmentId == 'inprogress' ) {
            gotourl = "/classware/assignments.do?action=new&isbn=" + siteISBN
        } else {
            gotourl = "/classware/assignments.do?action=edit&isbn=" + siteISBN +"&assignmentID=" + assignmentId;
        }
	}
	if( gotourl.indexOf("copyandeditcustomala.do") > -1 ) {
		alert( "You cannot change preferences in the middle of editing/copying a Custom Assignment.");
		return false;
	}
	f.goto_url.value = gotourl;
	f.chrome.value = "/sites/" + siteISBN + "/chrome.vm";
	stopTool();
	return true;
}
// ------------------------------------------------------------
function Monitor() {
	// This script runs continuously, checking for changed window state (scroll, size)
	// and handling the drawer animations.
	// Originally had the drawers using their own setIntervals, but Opera on Windows
	// doesn't handle that very well. (memory problems, I think.)
	// check for window scroll:
	if (typeof(window.pageYOffset) != "undefined") {
		// Netscape 4; must check this first or else N7 gets lost
		if (window.pageYOffset != scrolledBy) {
			scrolledBy = window.pageYOffset;
			doFloat();
		}
	} else if (typeof(document.body) != "undefined") {
		if (typeof(document.body.scrollTop) != "undefined") {
			// IE, Mozilla
			if (document.body.scrollTop != scrolledBy) {
				scrolledBy = document.body.scrollTop;
				doFloat();
			}
		} else {
			// Opera:  body.scrollTop should work, but doesn't...?
			// try to fix this... this is the only reason floating doesn't
			// work in opera right now.
			scrolledBy=0;
		}
	} else {
		// unknown, noncompliant browser
		scrolledBy = 0;
	}
	// run any ongoing scripts:
	if (curScript) {
		eval(curScript);
	}
	return true;
}
function glideIn(myName, stopPos, whenDone) {
	var curTop = getTop(myName);
	if (curTop >= stopPos) {
		// stop the animation
		setTop(myName, stopPos);
		// workaround for a browser-specific visual glitch:
		if (navigator.appName.indexOf("Netscape") != -1 && parseInt(navigator.appVersion) == 4) {
			hideLayer(myName);
			window.setTimeout("showLayer('"+myName+"');",5);
		}
		if (whenDone) eval(whenDone);
		curScript = nextScript;
		nextScript = "";
	} else {
		// Netscape 6 is way slow... so we bump its speed up.
		if (browserIs.ns && (browserIs.major == 6)) {
			var newTop = (glideSpeed > 0) ? Math.ceil(curTop + ((stopPos-curTop) / (glideSpeed / 2))) + 1 : stopPos;
		} else {
			var newTop = (glideSpeed > 0) ? Math.ceil(curTop + ((stopPos-curTop) / (glideSpeed * 4))) + 1 : stopPos;
		}
		// move the content:
		//setTop("divContent", (getTop("divContent") + (newTop - curTop)));
		// move the drawer:
		setTop(myName, newTop);
	}
}
function glideOut(myName, startPos, whenDone) {
	var curTop = getTop(myName);
	if (curTop <= scrolledBy-120) {
		// stop the animation
		setTop(myName, -300);
		hideLayer(myName);
		setZindex(myName, 6);
		if (whenDone) eval(whenDone);
		curScript = nextScript;
		nextScript = "";
		setTop("divContent", 120);
	} else {
		// Netscape 6 is way slow... so we bump its speed up.
		if (browserIs.ns && (browserIs.major == 6)) {
			var newTop = (glideSpeed > 0) ? Math.ceil(curTop - ((startPos-curTop) / (glideSpeed / 4))) - 1 : -1000;
		} else {
			var newTop = (glideSpeed > 0) ? Math.ceil(curTop - ((startPos-curTop) / (glideSpeed * 2))) - 1 : -1000;
		}
		// move the drawer:
		setTop(myName, newTop);
		// move the content:
		// setTop("divContent", (getTop("divContent") - (curTop - newTop)));
	}
}

function startAnimation(newAnim) {
	if (curScript == "") {
		curScript = newAnim;
	} else {
		nextScript = newAnim;
	}
}

function doFloat() {
	if (floatNav > 0) {
		toolTop = (scrolledBy > toolOrigin) ? scrolledBy : toolOrigin;
	} else {
		toolTop = toolOrigin;
	}
	for (i in floaters) {
		setTop(floaters[i], toolTop);
	}
	setTop(curTool, toolTop);
	setTop("navExtra", (scrolledBy + getWindowHeight() - 30));
	//set divNavContentsExtra top equal to divNavContents height so that help and site map always display
	if (getObj("divNavContentsExtra")) {
		var myObj = new getObj("divNavContentsExtra");
		myObj.style.top = document.getElementById('divNavContents').offsetHeight;
	}
}

function startTool(myName) {
	if (curTool != myName) {
		if (curTool != "") stopTool();
		setTop(myName,scrolledBy - 175);
		setZindex(myName, 7);
		showLayer(myName);
		curTool=myName;
		startAnimation("glideIn('"+myName+"', toolTop,'');");
	}
}

function stopTool(whichTool) {
	if (curTool != "") startAnimation("glideOut('"+curTool+"',toolTop,'');");
	curTool = "";
}

function swapTool(whichTool) {
	setTop(whichTool, getTop(curTool));
	showLayer(whichTool);
	hideLayer(curTool);
	setZindex(curTool, 6);
	setTop(curTool, -1000);
	curTool = whichTool;
}

function checkFloat(){
	if (document.getElementById('divNavContentsHTML').offsetHeight > getWindowHeight()) {
		//turn float off if navBar height > window height
		floatNav = 0;
	} else if (document.getElementById('divNavContents').offsetHeight > getWindowHeight()) {
		//turn float off if navBar height > window height
		floatNav = 0;
	} else {
		//change float back to default
		floatNav = newFloat;
	}
	doFloat()
}

function getCurrentURL(){
    var url = window.location.href;
    if (url.indexOf("?") == -1) {
      url += "?";
    }
//    alert("first URL:"+url);
    url = escape(url);
//    alert("current URL:"+url);
    return url;
}


function redirectToALEKSURL(action,activityid,assignmentId,pageID)
{
    //var url = "/classware/aleksALA.do?action=" + action +"&activityid=" +activityid + "&title=" + title+"&assignmentId=" + assignmentId+ "&assignmentTitle=" + assignmentTitle+ "&pageID="+ pageID +"&lastURL="+ getCurrentURL();
    //var URL = "/classware/aleksALA.do?action=" + action +"&amp;activityid=" +activityid + "&amp;title=" + title+"&amp;assignmentId=" + assignmentId+ "&amp;assignmentTitle=" + assignmentTitle+ "&amp;pageID="+ pageID;
    //alert("final URL:"+url);
    //return url;
    //location.href= unescape(URL);
    var thisform=document.ALEKSForm;
    thisform.aleksaction.value=action;
    thisform.activityid.value=activityid;
    //thisform.title.value=title;
    thisform.assignmentId.value=assignmentId;
    //thisform.assignmentTitle.value=assignmentTitle;
    thisform.lastURL.value=getCurrentURL();
    setTimeout("document.ALEKSForm.submit();", 100);
    //return URL;
}

function overdueALEKS(action,activityid,assignmentId,pageID)
{
  var thisform=document.ALEKSForm;
  thisform.isoverdue.value="true";
  redirectToALEKSURL(action,activityid,assignmentId,pageID);
}

function displayGradeAfterdueDate(action,activityid,assignmentId,pageID,duedate)
{
  var thisform=document.ALEKSForm;
  thisform.duedate.value=duedate;
  redirectToALEKSURL(action,activityid,assignmentId,pageID);
}