/************************************************************
SFC Login Utilities

Platforms: IE 5.5+ 

Dependencies
jbe_cookies.js; jbe_jslib.js; jbe_forms.js

To Do
- None at this time

Revision History
Keys: [NEW] New Feature
      [FIX] Bug fix
      [COM] Comment
      [IMP] Improvement

05/07/2007 Rick Englert
[NEW] Combined old jbe_login.js and config_login.js into this new sfc_login.js when updating to new course standard.  Configuration
	vars now set in config_login.js in each course folder.

11/18/03 Rick Englert
[COM] Initial Release
*/

//////////////////// CONFIGURATION VARIABLES //////////////////////
//  These vars are declared here, and given default values defensively, but actual values for each course are set 
//  in config_login.js in each course folder - DO NOT SET THEM HERE.

var	pisRecordUserToServer = false;  //whether or not to record current user data to server - causes add_user() function to call recordUserToServer() , defined in each course's config_login.js file
//alert("sfc-pisRecordUserToServer="+pisRecordUserToServer)
var psCourseIDSplitBefore = 'cbt/c';    //the unique (but same for every course) part of the url immediately preceding the course id
var psCourseIDSplitAfter = '-';  //the unique (but same for every course) part of the url immediately following the course id
var gsPopupBlockedMsg = 'It looks like the course window has been blocked by popup blocking software.';
	gsPopupBlockedMsg += '\n\nThis course makes use of popups throughout, but don\'t worry, none of them contain any advertising...';
	gsPopupBlockedMsg += '\n\nIn order to access the course, click the "To open the course again, click here" link.';
	gsPopupBlockedMsg += '\n\nIf you get this message again, you\'ll have to set your popup blocking software to allow popups from this web address first (or your CD-ROM drive - see your popup blocker documentation), and then click the "To open the course again, click here" link.';
var psCourseID = '07';    //set this as a backup failsafe if you want (in CONFIG_LOGIN.JS-NOT HERE)- it is only used if above splits fail
var sStartPage = 'start.htm';  //the filename of the first page user sees - the "welcome" page.  Storing this filename here ensures all functions that may send user there go to correct page.

var oCourseWin;
var psUserID;
var psTrackID;


function on_load() {
	var temp = get_querystring_value(document.location.search, 'UserID');
	if (temp) {psUserID=temp}
	temp = get_querystring_value(document.location.search, 'CourseID');
	if (temp) {psCourseID=temp}
	else {
		temp = document.location.toString()
		if (psCourseIDSplitBefore && psCourseIDSplitAfter && temp.split(psCourseIDSplitBefore).length>1 && temp.split(psCourseIDSplitAfter).length>1) {
			psCourseID = temp.split(psCourseIDSplitBefore)[1].split(psCourseIDSplitAfter)[0];
		}
	}
	temp = get_querystring_value(document.location.search, 'TrackID');
	if (temp) {psTrackID=temp}
	if (on_load_this_course) on_load_this_course();  //found in config_login.js, not in this file for executing course-specific onloads
	if (on_load_this_page) on_load_this_page();  //found on each page, not in this file for executing page-specific onloads
}

function create_querystring() {
	var qs = '';
	if (psUserID) qs +="UserID="+psUserID+"&";
	if (psCourseID) qs +="CourseID="+psCourseID+"&";
	if (psTrackID) qs +="TrackID="+psTrackID;
	if (qs) qs = "?"+qs;
	return qs;
}

function launch_course() {
psCourseID=psCourseID.replace(/\D+/g,"")
	oCourseWin = window.open('../system/frameset.htm?UserID='+psUserID+'&CourseID='+psCourseID+'&TrackID='+psTrackID, 'c'+psCourseID,'toolbar=no,location=no,status=yes,menubar=no,scrollbars=no,resizable=yes,width=789,height=536,left=0,top=0');
setTimeout("verify_window_open(oCourseWin)", 2000);  //after 2 seconds, make sure course window exists - not blocked by popup blocker
}

function startup() {
	if (validate_userid(psUserID)) {
		launch_course();
	}
	else document.location = sStartPage;
}

function verify_window_open(oWin) {  //call this function with a setTimeout to verify that a new window was indeed opened and not blocked.  Determine what to do if blocked, not blocked in spaces below
	var isOpen = true;
	if (!oWin) isOpen = false;
	else if (oWin==null) isOpen = false;
	else if (oWin.closed) isOpen = false;
	//do the following if window was blocked
	if (!isOpen) {
		alert(gsPopupBlockedMsg);
	}
}

function click_new_user() {   //used in welcome.htm
	//check number of users in login cookie
	var sCurrentUsers = get_users_list();
	//if we're recording users to server, go ahead and add new account.  Otherwise (i.e. CD_ROM), check to make sure there aren't too many users (that would be FIVE!) for browsers' feeble little cookie size limits.
	if (sCurrentUsers=='' || pisRecordUserToServer) systemtest_navto('../login/newaccount.htm');  //if no current users in cookie
	else if (num_string_elements(sCurrentUsers, '_') < 5) systemtest_navto('../login/newaccount.htm');
	//if 5 or more users, redirect to delete which user page
	else systemtest_navto('../login/max_users.htm');
}

function click_existing_user()  {  //used in welcome.htm
	systemtest_navto('../login/login.htm');
}

function systemtest_navto(sTargetPage) {    //runs the system test if it hasn't been successfully run before, and navigates to sTargetPage.
	sTargetPage = longUrl(sTargetPage);
	sTargetPage += create_querystring();
	if (cookie_get_var('test', 'all')) {
		document.location=sTargetPage;
	}
	else { 
		document.location='../../common/system_test/system_test.htm?TargetPage='+escape(sTargetPage);
	}
}

function force_systemtest(sTargetPage) {   //runs the system test immediately and navigates to sTargetPage.
	sTargetPage = longUrl(sTargetPage);
	document.location='../../common/system_test/system_test.htm?TargetPage='+escape(sTargetPage);
}

function longUrl(sUrl) {  //make sure url is complete so systemtest can send back to correct course
	var splitOn = 'login/';
	if (sUrl.split(splitOn).length>1) {
		var front = document.location.toString();
		front = front.split(splitOn)[0];
		var end = sUrl.split(splitOn)[1];
		sUrl = front + splitOn + end;
	}
	return sUrl;
}

function populate_idlist(sMode) {  //used in login.htm & max_users.htm.  In login, it does more than just populate idlist, it popoulates and sets up the whole form
	if (!sMode) sMode = 'login'
	var sDelimiter = '_';
	var sCurrentUsers = get_users_list(sDelimiter);
	var sUserID, sUserFname, sUserLname, sUserDate;
	switch (sMode) {
		case 'login':
			if (sCurrentUsers) {
				for (var i = 0; i < num_string_elements(sCurrentUsers, sDelimiter); i++) {
					sUserID = get_string_element(sCurrentUsers, i, sDelimiter)
					add_option(frmLogin.lbUserID, sUserID, sUserID)
				}
			}
			if (document.frmLogin.lbUserID.selectedIndex > -1) {	//if dropdown is empty, selectedIndex is -1, which crashes the next line
				if (document.frmLogin.lbUserID.options[document.frmLogin.lbUserID.selectedIndex].value) {  //I guess this if() is really superfluous now(see above), but it works and I don't have time to test without it
					document.frmLogin.tbUserID.value = document.frmLogin.lbUserID.options[document.frmLogin.lbUserID.selectedIndex].value;
				}
			}
			if (document.frmLogin.tbUserID.value) document.frmLogin.pbPassword.focus();
			else document.frmLogin.tbUserID.focus();
			break;
		case 'delete_user':
			if (sCurrentUsers) {
				for (var i = 0; i < num_string_elements(sCurrentUsers, sDelimiter); i++) {
					sUserID = get_string_element(sCurrentUsers, i, sDelimiter);
					sUserFname = cookie_get_var(sUserID, 'Fname');
					sUserLname = cookie_get_var(sUserID, 'Lname');
					sUserDate = cookie_get_var(sUserID, 'Lastlogin');
					add_option(frmLogin.lbUserID, sUserID + ' ('+sUserFname+' '+sUserLname+') '+sUserDate, sUserID);
				}
			}
			else {
				alert('Problem reading login cookie.  Click Cancel to try again.');
			}
			break;
	}
}

function get_users_list(sDelimiter) {
	if (!sDelimiter) sDelimiter = '_';
	var sCurrentUsers = cookie_get_var('login', 'users');
	if (sCurrentUsers) {
		if (sCurrentUsers.substr(0, 1) == sDelimiter) sCurrentUsers = sCurrentUsers.substr(1, sCurrentUsers.length);
		if (sCurrentUsers.substr(sCurrentUsers.length-1, 1) == sDelimiter) sCurrentUsers = sCurrentUsers.substr(0, sCurrentUsers.length-1);
		return sCurrentUsers;
	}
	return '';
}

function validate_userid(sUserID, sDelimiter) {
	if (!sUserID) return false;
	else {
		if (pisRecordUserToServer) {  //validate against users list on web server
			return isUserIDTakenOnServer(sUserID);	//returns true if userid already exists, false if not
		} else {  //validate against local users cookie
			if (!sDelimiter) sDelimiter = '_';
			if (cookie_get_var('login', 'users').indexOf(sDelimiter + sUserID + sDelimiter) == -1) return false;
			else return true;
		}
	}
}

function log_in(sUserID, sPassword, isRememberMe) {  //used in login.htm
	//isRememberMe is NOT CURRENTLY IMPLEMENTED.  The idea was to only add ids into the dropdown if this was checked.  It looks like it'll be a huge pain to implement, so I won't for now.
//alert(sUserID + " , " + sPassword + " , " + isRememberMe);

	sUserID = sUserID.toLowerCase();  //defensive programming- cookie code is case-sensitive
	var isLoginValid = true;
	//validate form
	if (sUserID == '') {
		isLoginValid = false;
		alert('You must enter a UserID.');
	} else if (sPassword == '') {
		isLoginValid = false;
		alert('You must enter a Password.');
	} else {  //passed local validation, attempt login either remotely or locally, depending on pisRecordUserToServer
		disable_submit(true);  //disable submit button to tell user something's happening and 
		if (pisRecordUserToServer) {  //remote login.  master user list is on server, local users cookie works like "remember me" feature, BUT course still gets userinfo from local cookie, so need to do the whole adduser thing here maybe
			var user = serverLogin(sUserID, sPassword);  //returns either user data or false. serverLogin() located in config_sever_communication.js
			if (user) {  //remote login successful, user var contains all user data., Now make sure this user is in a local cookie so course can find him (yes, only males can take this course :)
				var sCurrentUsers = cookie_get_var('login', 'users');
				if (sCurrentUsers.indexOf('_'+sUserID+'_') == -1) {  //not found in users list, add him in
					if (!sCurrentUsers) sCurrentUsers = '_' + sUserID + '_';  //if no local users at all, why not start a list of them now
					else sCurrentUsers = '_' + sUserID + sCurrentUsers;
					cookie_set_var('login', 120, '', 'users', sCurrentUsers);
					//create users personal cookie
					cookie_set_var(sUserID, 120, '', 'Fname', get_querystring_value(user, 'Fname'));
					cookie_set_var(sUserID, 120, '', 'Lname', get_querystring_value(user, 'Lname'));
					cookie_set_var(sUserID, 120, '', 'Email', get_querystring_value(user, 'Email'));
					cookie_set_var(sUserID, 120, '', 'P', sPassword); 
				}
				
			} else { //remote login failed, user == false
//			if (!serverLogin(sUserID, sPassword)) {
				isLoginValid = false;
				alert('The username and/or password you entered is incorrect.  Remember, passwords are CaSe SeNsItIvE.');
			}
		} else {  //original, local cookie only local login
			//check for uid in login cookie
			var sCurrentUsers = cookie_get_var('login', 'users');
			if (sCurrentUsers.indexOf('_'+sUserID+'_') == -1) {
				isLoginValid = false;
				alert('That UserID has not been registered.  Click the "I\'m a new user" button to register.');
			}
			else {  //UserID found - verify pwd in user cookie
		//		var sCookiePwd = unEncrypt(cookie_get_var(sUserID, 'Pwd'));  //get users password from cookie
		//	the encrypt/unencryupt seems to be unreliable so passwords are unencrypted in the cookie for now
				var sCookiePwd = cookie_get_var(sUserID, 'P');  //get users password from cookie
				if (sCookiePwd != sPassword) {  //if password entered is incorrect, say so
					isLoginValid = false;
					alert('That password is incorrect.  Remember, passwords are CaSe SeNsItIvE.');
				}
			}	
		}
	}
	//At this point, login is either successful or not.
	if (isLoginValid) {  //login successful, start course
		//record login date - this is used by max_users page to identify old accounts
		var sDateString = new Date().getMonth() + 1 + '/' + new Date().getDate()+ '/' + new Date().getFullYear().toString().substr(2,2);
		cookie_set_var(sUserID, 120, '', 'Lastlogin', sDateString);

		//launch course
		var url = 'curriculummenu.htm?UserID='+sUserID;
		if (psTrackID) { url += '&TrackID='+psTrackID }
		document.location=url
	} else {  //login failed
		disable_submit(false);
		return;
	}
}
function disable_submit(trueOrFalse) {
	if (document.frmLogin) {  //make sure form exists
		if (document.frmLogin.Submit) {  //make sure submit button exists
			document.frmLogin.Submit.disabled = trueOrFalse;  //re-enable submit button
		}
	}
}

function validate_form() {  //used in newaccount.htm
//	return true if form valid, false otherwise
	var isFormValid = false;
	var sCurrentUsers = cookie_get_var('login', 'users');
	var sUserID = document.theForm.tbUID.value.toLowerCase();
	if (sUserID == '') alert('You must enter a User ID.');
	else if (sUserID.match(/\w+/) != sUserID || sUserID.match(/\_/)) alert('A User ID can only contain letters and numerals.  No spaces, underscores or other characters');
	else if (sCurrentUsers.indexOf(sUserID) >= 0) alert('The User ID you entered already exists.  Please enter another, or, if this is you, click the Back button on your browser and log in.');
	else if (document.theForm.pbPwd.value == '') alert('You must enter a password.');
	else if (document.theForm.pbPwd.value != document.theForm.pbPwd2.value) alert('The passwords you entered do not match.');
	else if (document.theForm.tbFname.value == '') alert('You must enter a First Name.');
//	else isFormValid = true;
	else isFormValid = validate_form_this_course ? validate_form_this_course() : true;  //validate_form_this_course() is in CONFIG_login.js.  It does the same thing as the alerts() above for any course-specific fields and then returns true if all are valid and false if not.  We only call it if it exists
	//OK, passed all those checks, now make sure userid isn't taken on the server, if applicable
	if (isFormValid && pisRecordUserToServer) {  //only go in here if all previous checks passed (so we only set isFormValid to false if this test fails AND we don't waste time waiting for a server roundtrip if a previous test already failed) and if we are using the record to server feature
		if (isUserIDTakenOnServer(sUserID)) {
			alert('The User ID you entered already exists.  Please enter another.  If this is you, click the Back button on your browser and log in.');
			isFormValid = false;
		}
	}
	return isFormValid;
}

function add_user() {  //used in newaccount2.htm
	var sUserID = get_querystring_value(document.location.search, 'tbUID').toLowerCase();
	var sPassword = get_querystring_value(document.location.search, 'pbPwd');
	var sCurrentUsers = cookie_get_var('login', 'users');
	//add user to login cookie - the list of current users on this computer
	if (!sCurrentUsers) sCurrentUsers = '_' + sUserID + '_';
	else sCurrentUsers = '_' + sUserID + sCurrentUsers;
	cookie_set_var('login', 120, '', 'users', sCurrentUsers);
	//create users personal cookie
	cookie_set_var(sUserID, 120, '', 'Fname', get_querystring_value(document.location.search, 'tbFname'));
	cookie_set_var(sUserID, 120, '', 'Lname', get_querystring_value(document.location.search, 'tbLname'));
	cookie_set_var(sUserID, 120, '', 'Email', get_querystring_value(document.location.search, 'tbEmail'));
//	cookie_set_var(sUserID, 120, '', 'Pwd', Encrypt(sPassword));  //NOTE PASSWORD IS ENCRYPTED - it must be unencrypted when extracting from cookie
//the encrypt/unencrtpt code seems to be unreliable - so pwds are unencrypted in cookie for now
	cookie_set_var(sUserID, 120, '', 'P', sPassword); 
	if (pisRecordUserToServer) {
		recordUserToServer();  //this function MUST be synchronous, or else the log_in below could look for the new user before this function has finished adding him, 
	}
	//login
	log_in(sUserID, sPassword, false);
}

function delete_user(sUserID) {
	var sCurrentUsers, sUpdatedUsers;
	sUserID = sUserID.toLowerCase();  //defensive programming- cookie code is case-sensitive
	if (!sUserID) {alert('No account selected');return}
	sCurrentUsers = cookie_get_var('login', 'users')
	if (sCurrentUsers.indexOf('_'+sUserID+'_') != -1) {
		sUpdatedUsers = sCurrentUsers.replace('_'+sUserID+'_', '_')
		cookie_set_var('login', 120, '', 'users', sUpdatedUsers);
		set_cookie(sUserID, '', 0, '')  //delete user info cookie
		set_cookie(sUserID+psCourseID+'history', '', 0, '')  //delete history cookie 
		set_cookie(sUserID+psCourseID+'keys', '', 0, '')  //delete keys cookie
		click_new_user();
	}
	else { alert('Cannot remove user "' + sUserID + '" - not found in login cookie') }
	
}

//Utility functions
function MM_openBrWindow(theURL,winName,features) { //v2.0 - 
  window.open(theURL,winName,features);
}

////********** Encryption code from internet ****************
// Original:  David Salsinha (david.salsinha@popsi.pt) 
// This script and many more are available free online at 
// The JavaScript Source!! http://javascript.internet.com 

function Encrypt(theText) {
	output = new String;
	Temp = new Array();
	Temp2 = new Array();
	TextSize = theText.length;
	for (i = 0; i < TextSize; i++) {
		rnd = Math.round(Math.random() * 122) + 68;
		Temp[i] = theText.charCodeAt(i) + rnd;
		Temp2[i] = rnd;
	}
	for (i = 0; i < TextSize; i++) {
		output += String.fromCharCode(Temp[i], Temp2[i]);
	}
	return output;
}

function unEncrypt(theText) {
	output = new String;
	Temp = new Array();
	Temp2 = new Array();
	TextSize = theText.length;
	for (i = 0; i < TextSize; i++) {
		Temp[i] = theText.charCodeAt(i);
		Temp2[i] = theText.charCodeAt(i + 1);
	}
	for (i = 0; i < TextSize; i = i+2) {
		output += String.fromCharCode(Temp[i] - Temp2[i]);
	}
	return output;
}
////****************** End encryption code from internet *****************
