// Library of functions for LII distance-learning activities

// Cookies:
// We use a number of them.
// LIIDLAuthenticated="courselist" where courselist is a comma-delimited list of courses,
//     eg. "socsec,copyright"
// LIIDLContext="blah" where blah is a course context.


// Constants
// URL of signin page
var SIGNINPAGE = '/distlearn/signin.php';

// invisible window for timestamper

// Target link for outbound functions
var OUTBOUNDLINK = '';
var CURRENTPAGE = '';

// Times
var TIMEIN = '';
var TIMEOUT = '';

// Array to hold possible stylesheet values for different contexts.
var STYLEARRAY = new Array();
var CONTEXTARRAY = new Array();

// Load up cookies
var authCookie = new Cookie(document, "LIIDLAuthenticated", "", "/", "law.cornell.edu");
var contextCookie = new Cookie(document, "LIIDLContext", "", "/", "law.cornell.edu");

//---------------------------------------------------------
// RequireEnrollment(courselist)
// Allow entry to anyone carrying a cookie for a course
// in courselist, where courselist is a comma-delimited list of
// courses.  If they aren't authenticated, send them to a
// sign-in page.
//---------------------------------------------------------
function RequireEnrollment(courselist){
	isAuthentic = false;
	if (authCookie.load()){
		autharr = new Array();
		coursearr = new Array();
		autharr = authCookie.courses.split(',');
		coursearr = courselist.split(',');
		for (i = 0 ; i < autharr.length ; i++){
			for (j = 0 ; j < coursearr.length ; j++){
				if (coursearr[j] == autharr[i] || coursearr[j] == 'any'){
					isAuthentic = true;
				}
			} // endfor j
		} // endfor i
	} //endif
	if (! isAuthentic){
		// put some properties into the context cookie
		// so the signin page can send the hapless user
		// right back here once they've signed in
		contextCookie.referrer=document.location.href;
		contextCookie.status='authbounced';
		contextCookie.store();
		// bounce to sign in page
		document.location.href = SIGNINPAGE;
	}
}

//---------------------------------------------------------
// SetDLContext(context)
// Sets a cookie describing the context for a particular LII
// distance learner (eg. what course they're engaged in
// at the moment)
//---------------------------------------------------------
function SetDLContext(context){
	//alert("setting context: " + context);
	contextCookie.remove();
	contextCookie.load();
	contextCookie.context = context;
	contextCookie.store();
}

//---------------------------------------------------------
// Sets an authentication cookie once user
// is authenticated.
//---------------------------------------------------------
function SetAuthCookie(sid,coursestr){
	//alert("cookie mess");
	authCookie.remove();
	authCookie.load();
	authCookie.sid = sid;
	authCookie.courses = coursestr;
	authCookie.store();
}

//---------------------------------------------------------
// SetWBCookies
// Sets cookies used by WebBoard
//---------------------------------------------------------
function SetWBCookies(userid,pwd,board){
	document.cookie = "WB-User=" + userid + "; path=/; domain=law.cornell.edu";
	document.cookie = "WB-Pass=" + pwd + "; path=/; domain=law.cornell.edu";
	document.cookie = "WB-BoardID=" + board + "; path=/; domain=law.cornell.edu";
}

//---------------------------------------------------------
// RevokeDLContext(context)
// Unsets a context when a distance learner exits a tour.
//---------------------------------------------------------
function RevokeDLContext(){
	contextCookie.remove();
}

//---------------------------------------------------------
// SetDefaultStyle(stylesheet)
// Sets the style sheet to use for a particular page when
// the person viewing the page is not in some LII context
//---------------------------------------------------------
function SetDefaultStyle(stylesheet){
	SetStyleForContext('default', stylesheet);
}

//---------------------------------------------------------
// SetStyleForContext(context,stylesheet)
// Associates a particular context with a stylesheet on
// the current page
//---------------------------------------------------------
function SetStyleForContext(context,stylesheet){
	defindex = -1;
	for (i=0; i < CONTEXTARRAY.length; i++){
		if (CONTEXTARRAY[i] == context){
			defindex = i;
		}
	}	
	if (defindex != -1){
		STYLEARRAY[defindex] = stylesheet;
	}else{
	    CONTEXTARRAY[CONTEXTARRAY.length] = context;
	    STYLEARRAY[STYLEARRAY.length] = stylesheet;
	}
	currindex = STYLEARRAY.length - 1;
	//alert("set stylearray element " + currindex + " to " + stylesheet);
}

//---------------------------------------------------------
// WriteMyStyle()
// Writes the appropriate style for this user, based on
// their context.
//---------------------------------------------------------
function WriteMyStyle(){
	defaultidx = -1;
	mystyleidx = -1;
	
	if (contextCookie.load()){
		//alert("my context is " + contextCookie.context);
		// see if we have a style sheet for this context
		for(i=0; i < CONTEXTARRAY.length; i++){
			//alert(CONTEXTARRAY[i]);
			if (CONTEXTARRAY[i] == contextCookie.context){
				mystyleidx = i;
			}
		}
	}
	// get a default if there is one
	for(i=0; i < CONTEXTARRAY.length; i++){
		if (CONTEXTARRAY[i] == 'default'){
			defaultidx = i;
		}
	}
	
	if (mystyleidx == -1){
		mystyleidx = defaultidx;
	}
	//alert("style index is: " + mystyleidx + ", sheet is: " + STYLEARRAY[mystyleidx]);	
	if (mystyleidx != -1){
		document.writeln('<LINK REL="STYLESHEET" TYPE="text/css" HREF="' + STYLEARRAY[mystyleidx] + '">');
	}
	
}

//---------------------------------------------------------
// Get ISO DateTime
//---------------------------------------------------------
function GetISODateTime(){
	now = new Date();
	h = now.getHours() + 1 ;
	if (h < 10) h = '0' + h;
	m = now.getMinutes();
	if (m < 10) m = '0' + m;
	s = now.getSeconds();
	if (s < 10) s = '0' + m;
	d = now.getDate();
	if (d < 10) d = '0' + d;
	mon = now.getMonth() + 1;
	if (mon < 10 ) mon = '0' + mon;
	yr = now.getYear();
	if (yr < 1000) yr += 1900;
	return (yr + "-" + mon + "-" + d + " " + h + ":" + m + ":" + s );
	
}

//---------------------------------------------------------
// GetSID
// Recovers the student ID from a cookie
//---------------------------------------------------------
function GetSID(){
	authCookie.load();
	//return("1");
	//alert(authCookie.sid);
	return (authCookie.sid);
}

//---------------------------------------------------------
// FixupQuizSubmission
// Adds timestamping and student ID information to submitted quiz
//---------------------------------------------------------
function FixupQuizSubmission(f){
	
	
	// figure out what index we're talking about
	var idx = -1;
	for (var i=0; i < document.forms.length; i++){
		if (document.forms[i].name == f) {
			idx = i
			}
	}
	
	// since we can't predict where the fields we want will be placed, we
	// use an ugly approach:
	
  	for (var j = 0; j < document.forms[idx].elements.length; j++){
  		//alert("in loop");
  		
    	if (document.forms[idx].elements[j].name == "SID"){
    		var tmp = GetSID();
		//alert(tmp);
    		document.forms[idx].elements[j].value = tmp;
    		}
    	if (document.forms[idx].elements[j].name == "timein") document.forms[idx].elements[j].value = TIMEIN;
    	if (document.forms[idx].elements[j].name == "timeout") {
    		var tmp = GetISODateTime();
    		document.forms[idx].elements[j].value = tmp;
    		}
    	//alert(" " + document.forms[idx].elements[j].name);
   }
    return true;
}

//---------------------------------------------------------
// SetTimeIn()
//---------------------------------------------------------
function SetTimeIn(){
	TIMEIN = GetISODateTime();
	//alert("inbound: " + TIMEIN);
}

//---------------------------------------------------------
// RecordTiming()
// should only be placed at the bottom of a page
//---------------------------------------------------------
function RecordTiming(){
	// make a new, invisible window that will hold a timestamping form
	stampwindow = window.open("about:blank","win","width=0,height=0,toolbar=no,location=no,status=no,directories=no,menubar=no,scrollbars=no,resizable=no");
	// write in form at the bottom of the page
	stampwindow.document.writeln('<FORM NAME="timestamper" METHOD="POST" ACTION="http://www.law.cornell.edu/cgi-bin/timestamper.cgi">');
	stampwindow.document.writeln('<INPUT TYPE="HIDDEN" NAME="timein" VALUE="0">');
	stampwindow.document.writeln('<INPUT TYPE="HIDDEN" NAME="timeout" VALUE="0">');
	stampwindow.document.writeln('<INPUT TYPE="HIDDEN" NAME="url" VALUE="0">');
	stampwindow.document.writeln('<INPUT TYPE="HIDDEN" NAME="target" VALUE="0">');
	stampwindow.document.writeln('<INPUT TYPE="HIDDEN" NAME="SID" VALUE="0">');
	stampwindow.document.writeln('<INPUT TYPE="HIDDEN" NAME="amtesting" VALUE="1">');
	stampwindow.document.writeln('</FORM>');
	// insert start time
	stampwindow.document.timestamper.timein.value = TIMEIN;
	// get current time and insert
	stampwindow.document.timestamper.timeout.value = GetISODateTime();
	// get student id and insert
	stampwindow.document.timestamper.SID.value = GetSID();
	// get current href and insert
	stampwindow.document.timestamper.url.value = CURRENTPAGE;
	// submit myself
	stampwindow.document.timestamper.submit();
	stampwindow.close();
}

//---------------------------------------------------------
// TimeThisPage()
// Running this causes a page timestamp to be recorded.
// Place at the end of the page, just before </BODY>
//---------------------------------------------------------
function TimeThisPage(){
	
	// record current page here, because doing it as part of an onUnload
	// event is unreliable (might get target page instead)
	CURRENTPAGE = self.location.href;
	// hook SetTimeIn() to page load
	self.onload=SetTimeIn;
	// hook RecordTiming() to page unload
	self.onunload=RecordTiming;
	return true;
	
}

//---------------------------------------------------------
// TimeThisQuizPage(quizname)
//---------------------------------------------------------
function TimeThisQuizPage(){
	
	CURRPAGE = self.location.href;
	// hook SetTimeIn() to page load
	self.onload = SetTimeIn;
	// we use the form to hook in FixupQuizSubmission to fix up form submissions, eg.
	//<FORM NAME="blah" METHOD=POST ACTION="boof" OnSubmit="FixupQuizSubmission(this);">
}

//---------------------------------------------------------
// ConfirmMailing
// don't jump unless they confirm
//---------------------------------------------------------
function ConfirmMailing(url){
	$msg = "You are about to send mail to a lot of people.  Do you really mean to?";
	if (confirm($msg)) location.replace(url);
	return;
}




