/*config_server_communication.js ***THIS FILE DOES NOT HAVE AN SFC_ COUNTERPART***
Contains configurable functions for storing user/course data on a server.
When using different server technologies for different courses/clients, this is the only file affected.
The course calls functions here and these functions provide results back to the course.  The course doesn't know or care what happens in between

Revision History
Keys: [NEW] New Feature
      [FIX] Bug fix
      [COM] Comment
      [IMP] Improvement
	  
To do: Call connect_to_server in login phase to set a (not-yet-created) var identifying if server available.  This will prevent errors in CD_ROM copies without net connection, just like it already does within the course

2007/12/14 [NEW] Created this file - brought together server related functions and variables from sfc_login, sfc_system and sfc_system_htm
*/

//////////////////// INCLUDE OTHER JAVASCRIPT FILES //////////////////////
//
document.writeln('<script language="JavaScript" src="../../common/scripts/dojo-release-1.0.2/dojo/dojo.js"></scr'+'ipt>');  //DOJO AJAX toolkit - all dojo stuff below comes from here 

//////////////////// STARTUP //////////////////////
// On startup, if pisConnectServerAtStartup is true (in config_system.js), we need to call netConnectionConnected, to tell stage area that the server side is available
// This was originally implemented because FMS needs to establish a server connection before communication is possible
// It was left in because it's a convenient way to detect server side (in case a CD_ROM was burned, server may not be available but rest of course will) Another benefit is it still allows FMS as a server side technology.  Besides, we can turn it on/off with pisConnectServerAtStartup variable.

//////////////////// CONFIGURATION FUNCTIONS //////////////////////
//
var startupStatusMsg = "";  //the startup msgs displayed in stage area - this var used directly only by statusMsg function.  Always call it
function connect_to_server() {  //called by system_startup() in sfc_system_htm.js - part of course startup procedure ONLY, and ONLY if pisConnectServerAtStartup (in config_system.js) is true.  Callback must call poSystemWin.netConnectionConnected(isSuccessful) with a boolean.  Originally implemented to accomodate FMS' need to first establish a net connection before communicating, it also tells course whether server backend is available by setting isNetConnectionConnected. This allows a CD_ROM version of course to function with no modification, if all functions here check poSystemWin.isNetConnectionConnected before proceeding.
	var myContent = {};  //the array of name:value pairs to be POSTed to the server
	myContent['operation'] = 'checkID';//it doesn't_matter_what_we_send,_we_only_care_if_a_response_comes_back_or_not, but checkID operation will send either "true" or "false" - no chance of an empty string being returned
	dojo.xhrPost({
		 url: "../configuration/server_manageUsers.asp?",
		 sync : false,
		 content : myContent,
		 load: function (data, transport) {
			poSystemWin.netConnectionConnected(true);  
			statusMsg("OK.");
		 },
		 error: function (data) {
			poSystemWin.netConnectionConnected(false);  
			statusMsg("Failed. Starting course locally.");
		 }
	 });
	statusMsg("Connecting...");
}
function statusMsg(s) {  //APPENDS s to current startup status msg in Stage Area. THIS APPLIES ONLY TO COURSE STARTUP CONDITION - NOT LOGIN, NOT REST OF COURSE
	startupStatusMsg += s;
	document.StageArea.SetVariable("yourVarName", startupStatusMsg);  //"yourVarName" has to be the dumbest name ever for a status display variable
}

function isUserIDTakenOnServer(sUID) {  //called by validate_form() and validate_user() in sfc_login.js.  Expects a synchronous boolean(either true or false) response, so if using an asynchronous server call, you'll have to make it wait for the callback, get the answer and set it as the return value.
	var returnValue = false;  //assume userid is not taken.  This changes to true later on if it is
	var myContent = {};  //the array of name:value pairs to be POSTed to the server
	myContent['userid'] = sUID;
	myContent['operation'] = 'checkID';
	dojo.xhrPost({
		 url: "../configuration/server_manageUsers.asp?",
		 sync : true,
		 content : myContent,
		 load: function (data, transport) {
			if (data.toLowerCase().match(/true/i)) {
				returnValue = true;
			}
		 }
	 });

	return returnValue;
}

function recordUserToServer() {  //called by add_user() in sfc_login.js.  No arguments are passed because all user data from new account form is in querystring.  add_user() expects no response.

	var myContent = {};  //the array of name:value pairs to be POSTed to the server
	myContent['CSVheader'] = querystring_to_csv_names(null, 2).replace(/tb/g,"").replace(/dd/g,"").replace(/pb/g,"");
	myContent['CSVcontents'] = querystring_to_csv_values(null, 2);
	myContent['operation'] = 'addNew';
	dojo.xhrPost({
		 url: "../configuration/server_manageUsers.asp?",
		 sync : true,
		 content : myContent,
		 load: function (data, transport) {
		 }
	 });
}

function serverLogin(userid, password) {  //gets called by login() in sfc_login.js, which expects boolean true (login successful) or false (login failed) response, so this ajax call must be synchronous
	var returnValue = false;  //assume login will fail.  If server says login successful, this will change to true 
/*	var postVars = "userid="+userid;
	postVars += "&password="+password;
	postVars += "&operation=login";
	ajaxpack.postAjaxRequest("../configuration/server_manageUsers.asp", postVars, mtCallBack, "txt", true);
	if (ajaxpack.ajaxobj.responseText.toLowerCase() != "false") {
		returnValue = ajaxpack.ajaxobj.responseText;
	}
*/
	var myContent = {};  //the array of name:value pairs to be POSTed to the server
	myContent['userid'] = userid;
	myContent['password'] = password;
	myContent['operation'] = 'login';
	dojo.xhrPost({
		 url: "../configuration/server_manageUsers.asp?",
		 sync : true,
		 content : myContent,
		 load: function (data, transport) {
			if (data.toLowerCase() != "false") {
				returnValue = true;
			}
		 }
	 });

return returnValue;
}
function mtCallBack() {  //mt means "empty" - get it? - used by ajaxRequest that doesn't really need a callback in production.  It is useful for development/dubugging to make sure ajax call works properly
	if (isResultReady()) {  //utility function at end of file encapsulates the two steps to check for result readiness
//alert("ajaxpack.ajaxobj.responseText="+ajaxpack.ajaxobj.responseText);
	}
}

function recordCourseCookiesToServer(args) {  //called by put_course_data() if pisRecordCourseDataToServer in sfc_system_htm.js.  Replaces FMS data storage via Stage area.
/*args is an object and contains the following attributes (as defined in put_course_data):
	args.gsNotepad = sContents;
	args.gsProgressCookie = get_cookie(poSystemWin.gsUserID + poSystemWin.gsCourseID + 'history');
	args.gsKeysCookie = get_cookie(poSystemWin.gsUserID + poSystemWin.gsCourseID + 'keys');
*/
	var myContent = {};  //the array of name:value pairs to be POSTed to the server
	myContent['notepad'] = encodeURI(args.gsNotepad);
	myContent['progress'] = encodeURI(args.gsProgressCookie);
	myContent['keys'] = encodeURI(args.gsKeysCookie);
	myContent['userid'] = poSystemWin.gsUserID;
	myContent['courseid'] = poSystemWin.gsCourseID;
	myContent['operation'] = 'write';
	dojo.xhrPost({
		 url: "../configuration/server_manageCookies.asp?",
		 sync : false,
		 content : myContent,
		 load: function (data, transport) {
		 }
	 });

}

function getCourseCookiesFromServer() {  //
	var myContent = {};  //the array of name:value pairs to be POSTed to the server
	myContent['userid'] = poSystemWin.gsUserID;
	myContent['courseid'] = poSystemWin.gsCourseID;
	myContent['operation'] = 'read';
	dojo.xhrPost({
		 url: "../configuration/server_manageCookies.asp?",
		 sync : false,
		 content : myContent,
		 load: function (data, transport) {
			var notepad = data.split("<notepad>").length>1 ? data.split("<notepad>")[1].split("</notepad>")[0] : "";
			var progress = data.split("<progress>").length>1 ? data.split("<progress>")[1].split("</progress>")[0] : "";
			var keys = data.split("<keys>").length>1 ? data.split("<keys>")[1].split("</keys>")[0] : "";
			course_data_receiver(notepad, progress, keys);
		 }
	 });
}

function recordCourseResultsToServer(args) {  //gets called whenever OPQ is scored if pisRecordCourseResultsInOPQ is true
	/*The following lists the arguments sent from score_OPQ() function and their values as defined in sfc_inserts.js and OPQ page template (isModReview, pisPreTest and pisPostTest):
		args.isModReview = true;
		args.pisPreTest = pisPreTest;
		args.pisPostTest = pisPostTest;
		args.gsOPQReport = gsOPQReport;
		args.gsOPQCSV = gsOPQCSV;
		args.gsOPQCSVHeader = gsOPQCSVHeader;
		args.iScore = iScore;
		args.iNumCorrect = iNumCorrect;
		args.iNumQuestions = iNumQuestions;
		args.iNumScoredQuestions = iNumScoredQuestions;
	*/
	if (args.pisPreTest || args.pisPostTest) {  //only send data to server if this is a pre- or posttest
		var filename = args.pisPreTest ? "_results_pretest.txt" : "_results_posttest.txt";
		filename = "_course" + poSystemWin.gsCourseID + filename;

		var myContent = {};  //the array of name:value pairs to be POSTed to the server
		myContent['userid'] = poSystemWin.gsUserID;
		myContent['operation'] = 'getInfo';
		dojo.xhrPost({
			 url: "../configuration/server_manageUsers.asp?",
			 sync : false,
			 content : myContent,
			 load: function (data, transport) {
				var userinfo = data.split("<br>");  //userinfo holds user's info as two CSV lines - header and data, so split it into an array where the first element is header CSV and second element is data CSV
				
				//now take userinfo, addit to course results passed in arguments and write complete results to server - to TWO DIFFERENT FILES - one for pretest, one for posttest
				var myContent = {};  //the array of name:value pairs to be POSTed to the server
				myContent['contents'] = encodeURI(userinfo[1] + ',' + args.iScore + ',' + args.iNumCorrect + ',' + args.iNumScoredQuestions + ',' + args.gsOPQCSV);
				myContent['header'] = encodeURI(userinfo[0] + ',percentScore,totalCorrect,totalQuestions,' + args.gsOPQCSVHeader);
				myContent['operation'] = 'write';
				myContent['filename'] = filename;
				dojo.xhrPost({
					 url: "../configuration/server_writeResults.asp?",
					 sync : false,
					 content : myContent,
					 load: function (data, transport) {
					 }
				 });
	
			 }
		 });

		
	}
}

