/////////////////////////////////////////////////////////////////////////
// cookie and related functions
/*
	needs to be available in login, registration, and from exit.

	author: dmw  on behalf of c2 technologies
	revision history:
		jly 2003: initial version (cms risk mgmt)
		sep 2003: post-beta
*/		
/////////////////////////////////////////////////////////////////////////

if (DEBUG)	{alert("dev: loading cms_cookie.js");	}



// define some cookie and permanent data storage parameters
var usrIDX = 0; // which is current user?
var userTable = new Array();  // list of all users
var passTable = new Array();  // and their (encrypted) passwords
var bookTable = new Array();  // and their bookmarks
var modstatTable = new Array();	// and module access flags for each
var dlinkTable = new Array();	// and dlink state arrays for each
var cookieState = "none";
var userCount = 0;


var expiry = new Date();
// 1 day = 24 hr * 60 min * 60 sec * 1000 millisec = 86400000
// 5 years = int(365.25 * 5) = 667038

var longtemps = expiry.getTime() + (86400000 * 667038);
expiry.setTime(longtemps);

// rot 13
var coding = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMabcdefghijklmnopqrstuvwxyzabcdefghijklm';
function rot13(input) {
    if (!input) return '';
    for (var output = '',i=0;i<input.length;i++) {
        character = input.charAt(i);
        position = coding.indexOf(character);
        if (position > -1)
            character = coding.charAt(position + 13);
        output += character;
    }
    return output;
}

function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

function Set_Cookie(name,value,expires,path,domain,secure) {
    document.cookie = name + "=" +escape(value) +
        ( (expires) ? ";expires=" + expires.toGMTString() : "") +
        ( (path) ? ";path=" + path : "") + 
        ( (domain) ? ";domain=" + domain : "") +
        ( (secure) ? ";secure" : "");
}

function cookietest(yarg)
// see if cookies with names etc are available; if they are, parse; default e-mail to mru user.
{
	// boolean arg -- copy MRU to the form, or no?
if (DEBUG) 	{alert("checking for cookies...");	}

var noDlinks=false; // will be true first time user runs 2004 version, not thereafter
var userlist = unescape(Get_Cookie("cms_users"));
var passlist = unescape(Get_Cookie("cms_pass"));
// nothing will ever be in booklist or modstatlist that needs to be escaped/unescaped
var booklist = Get_Cookie("cms_book");
var modstatlist = Get_Cookie("cms_modstat");
var dlinklist = Get_Cookie("cms_dlink");
//alert("got dlinklist: " + dlinklist);
var mru = parseInt(Get_Cookie("cms_mru"));

//  alert("mru: " + mru + " mru+1:" + (mru+1));
if ((userlist == "null") || (userlist == null))
  {
	if (DEBUG)		{  alert("no cookie found!");		}


  // as a test, try to write cookies for visitor (user 00)
  // no need to escape/unescape here since we know there are no weird characters
  Set_Cookie("cms_users","visitor",expiry);
  Set_Cookie("cms_pass",rot13("visitor"),expiry);
  Set_Cookie("cms_book",rot13("null"),expiry);
	// initially mod 1 is available but nothing else is
  Set_Cookie("cms_modstat",_avail_ + "," + _notavail_ + "," + _notavail_ + "," + _notavail_,expiry);
  Set_Cookie("cms_mru",("0"),expiry);
  Set_Cookie("cms_dlink",false,expiry);

  // try to read them back
  userlist = Get_Cookie("cms_users");
  passlist = Get_Cookie("cms_pass");
  booklist = Get_Cookie("cms_book");
  //booklist = Get_Cookie("cms_book");
  modstatlist = Get_Cookie("cms_modstat");
  dlinklist = Get_Cookie("cms_dlink");
  mru = parseInt(Get_Cookie("cms_mru"));
  
  //alert("mru: " + mru + " mru+1:" + (mru+1));
  
  if (userlist == null)
    {
    alert("Your browser is not configured to allow cookies.\n\n" +
      "This course requires cookies to store your bookmark information.  To enable cookies:\n\n" +
      "  1. Select \"Internet Options\" from the \"Tools\" menu.\n" +
      "  2. Click on \"Security\" tab.\n" + 
      "  3. Click on \"Custom Level\" button.\n" +
      "  4. Scroll down to the \"Cookies\" section of the \"Settings\" window.\n" +
      "  5. Select the Enable radio button under \"Cookies - Allow cookies that are stored on your computer.\"\n" +
      "  6. Click OK.\n" +
      "  7. Press the F5 key to refresh your browser.\n" +
      "If you cannot enable cookies, login with \"visitor\" as your name and password." +
      "You will not be able to bookmark your location in the course.")
    return;
    }
  else
    {
    cookieState = "ok";
    }
  }
else
  {
   cookieState = "ok";
  }

if ((dlinklist == "null") || (dlinklist == null))
	{
	// no dlinks yet -- first time run since dlinks were addded?
	if (DEBUG)		{  alert("no dlinks!");		}
	noDlinks = true;
	}

//alert("user:" + userlist);
//alert("pass:" + passlist);
//alert("book:" + booklist);
// if the last character is a "&" remove it so split works properly
// zero based, so we need an offset
while ("&" == userlist.charAt((userlist.length)-1))
  {
  //alert("removing!"+userlist);
  userlist = userlist.substring(0,(userlist.length)-1);
  }
while ("&" == passlist.charAt((passlist.length)-1))
  {
  //alert("removing!"+passlist);
  passlist = passlist.substring(0,(passlist.length)-1);
  }
while ("&" == booklist.charAt((booklist.length)-1))
  {
  //alert("removing!"+booklist);
  booklist = booklist.substring(0,(booklist.length)-1);
  }
while ("&" == modstatlist.charAt((modstatlist.length)-1))
  {
  if (DEBUG)  	{alert("removing!"+modstatlist);  	}
  modstatlist = modstatlist.substring(0,(modstatlist.length)-1);
  }
if	(!noDlinks)
	{
	while ("&" == dlinklist.charAt((dlinklist.length)-1))
	  {
	  if (DEBUG)  	{alert("removing!"+dlinklist);  	}
	  dlinklist = dlinklist.substring(0,(dlinklist.length)-1);
	  }
	}


//alert("userlist:" + userlist);
passlist =rot13(passlist);
//alert("passlist:" + passlist);
booklist =rot13(booklist);
//alert("booklist:" + booklist);


// split into global tables
userTable = userlist.split("&");
passTable = passlist.split("&");
bookTable = booklist.split("&");
modstatTable = modstatlist.split("&");
if	(!noDlinks)
	{
	// we read a table that looks like this false&false&true&false&false
	// those are STRINGS
	// what we want to get is a boolean table
	var tmpTable = new Array();	// and dlink state arrays for each
	var ii,jj,zz,	msg="";
	tmpTable = dlinklist.split("&");
	jj = tmpTable.length;
	for (ii=0; ii < jj; ii++ )
		{
		//msg = msg + ii + "," + tmpTable[ii] + ";";
		if (tmpTable[ii]=="true")
			{
			dlinkTable[ii] = true;
			}
		else
			{
			dlinkTable[ii] = false;
			}
		}
	//alert(msg);

	}
else
	{
	for (i=0;i<userTable.length ;i++ )
		{
		dlinkTable[i] = false;
		}
	}
//alert("lengths: " + userTable.length + "," + passTable.length + "," + bookTable.length);

// auto fill-in most recent user
if ((yarg) &&((mru != 0) && (mru < userTable.length)))
  {
      // escape/unescape in case there is an ampersand anywhere in the email (unlikely!) or password
	document.login.email.value = unescape(userTable[mru]);
  }

return;
}

// this function de referenced sep 2003
function regger(yarg)
// nav to a window for the student to login with.
// pass extra parameter TRUE (from "forgot" link) to allow student to override existing account info.
{
  var dest="register.htm";
  if (yarg) dest += "?forgot_password";
  document.location.href=dest;
}

// new function, allows login and new registration from same form
function signin_(name,pass)
{
	//alert("hullo, signin_ in cms_cookie," + name + ", " + pass);

// ensure users doesn't accidentally get dlink version
AutoDLink = false;
// ensure user doesn't accidentally get question table from another user
quesTable = new Array();
quesTable[0] = "debug value";


var i,passfound=0,userfound=0;
var msg="",state="none";
// don't allow whitespace names or passwords
var strPassStrip = pass.replace(/\s/g,"");
var strNameStrip = name.replace(/\s/g,"");


// initial state for prototype/new user
MenuState[1] = _notavail_;
MenuState[2] = _notavail_;
MenuState[3] = _notavail_;
MenuState[4] = _notavail_;

//alert("in submitter");
if ((strPassStrip=="")||(strNameStrip==""))
	{
	alert("You must enter a name and password before starting the course.");
	// bail before any more messages or checks
	return;
	}
else if ((name == "visitor") && (pass == "visitor"))
  {
  //alert("visitor!");
  userfound = passfound = true;
  state = "visitor"
  }
else	// see if this user matches password
	{
	  for (var i=0; i< userTable.length; i++)
		{
		// escape/unescape in case there is an ampersand anywhere in the email (unlikely!) or password
		if (name == unescape(userTable[i]))
		  {
		  //alert("matched user at " + i);
		  userfound = true;
		  // escape/unescape in case there is an ampersand anywhere in the email (unlikely!) or password
		  if  (pass == unescape(passTable[i]))
			{
			//alert("matched password at " + i);
			document.usrIDX = usrIDX = i;
			passfound = true;
			// set most recently used login
			Set_Cookie("cms_mru",usrIDX,expiry);
			}
		  break; // matched user, but not password -- just quit.
		  }
		}
	}
if (!userfound)
	{
	msg = "Choose OK to login as a new student. Choose Cancel to re-enter your name and password.";
	result = confirm(msg);
	if (result)
		{
		// new user
		state="login_new";
		writeuser(name,pass,false);
		}
	}
else if (!passfound)
  {
  //alert("password error");
	msg="The name and password do not match. You may have mis-typed your password, or another student " +
		"with the same name may have taken this course on this computer. Choose OK to re-enter your " +
		"password,or to try a different name (you might want to use your e-mail address, since " +
		"it should be unique). Choose Cancel if you have forgotten your password and wish to " +
		"change it.";
	result = confirm(msg);
	if (!result)
		{
		msg = "Are you sure you want to reset the password for student " + name + "? " +
			"Choose OK to reset the password, or Cancel to enter a different name.";
		result = confirm(msg);
		if (result)
			{
			state="login_return";
			// update cookie with new password information
			writeuser(name,pass,true);
			}
		}
  //alert("Your e-mail or password were not recognized.\n" +
  //  "Please try again, or click the \"Register\" button to register again " +
  //  "(you will lose your bookmark information if you do this).");
  }
else
  {
	state = "login_return";
  }

// returning user -- bookmark option
if (state == "login_return")
	{
	if ("null" != bookTable[usrIDX])
		{
	    bookCheck(bookTable[usrIDX]);
		}
	else
		{
		// oops. can't find their bookmark?
		state = "login_new";
		}
	}

// new user -- nav to Welcome
if ((state == "visitor") || (state == "login_new"))
	{
    makeNewWindow('M0L0S005.htm',795,575);
    bookmarkLocation = 'M0L0S005';
	}

return;

}

// write or rewrite user data
function writeuser(name,pass,override)
{
// FALSE to add new user
// TRUE to overwrite old data (reset password)
   if (!override)
    {// add new element to the end of the table
    i = userTable.length //if user table has five entries, it's 0 1 2 3 4
    }
  // else use the value of i that was already set!
  // escape/unescape in case there is an ampersand anywhere in the email (unlikely!) or password
  userTable[i] = escape(name);
  passTable[i] = escape(pass); 
  // don't overwrite bookTable if override
  if (!override)
    {
    bookTable[i] = "null";
    }
  // join back into strings
  userlist = userTable.join("&");
  passlist = rot13(passTable.join("&"));
  booklist = rot13(bookTable.join("&"));
  dlinklist = dlinkTable.join("&");

  Set_Cookie("cms_users",userlist,expiry);
  Set_Cookie("cms_pass",passlist,expiry);
  Set_Cookie("cms_book",booklist,expiry);
  Set_Cookie("cms_dlink",dlinklist,expiry);
  Set_Cookie("cms_mru",i,expiry);
  // set usrIDX as property 
  document.usrIDX = usrIDX = i;
}
