/* utils.js
Version History
Version1.0	Shraddha Pai	20040504	formatTime(Date) method
*/

/* Words to the wise (Caveats) 

1. Cookies set by CGI have the "path" option set to "/" by default, even if not specified in the cookie definition. 
When setting/modifying/deleting such a cookie in JavaScript, "; path=/" must be appended to the end of the cookie setting string.
Otherwise, JavaScript will cause the creation of a second cookie with the same name instead of modifying the original object.

2. When pattern-matching the document.cookie string, ensure that the latter is unescaped.

*/

/* State variables ************************************************************************************************* */
var BLANK = '';
var bool_saveResults;
var bool_discardResults;
var clientStart;
var lastCheck;
var featureList = "location=0,menubar=0,resizable=0,toolbar=0,scrollbars=0,status=0";

/* Cookie format for interrupted resources 				
	-name => task_interrupted_queenB (where 'queenB' is user name)
	-value => _&&_resource1.cgi:Results_||_lastUpdated_&&_resource2.cgi:Results2_||_lastUpdated2_&&_resource3.cgi ...
Results are in "key=value" form with "___" as delimiter		
lastUpdated = secondsSinceEpoch	*/
var DELIM_RESOURCE = "_&&_";
var DELIM_FIELD = "_>>_";
var DELIM_DATA = "___";

var scriptList = ["tapping", "two_tapping", "rotating", "trail_making","color_matching","symbol_matching"];
var cookieExpiryDate;

/* Functions ****************************************************************************************************** */

/* Main entry-point into tests.
Checks for cookie indicating partially-completed task.
If found, invokes test-specific method to populate results; else, starts fresh test
NG 04-14-31: comment out partial test logic
*/
function init(type) {
	var constrPre = type == "test" ? "testInit" : "qInit";
	resetVars();
/*
	var userName;
	var localResults;
	if (document.cookie.match(/login=(.+?)($|;)/)) { 
		userName = RegExp.$1; 
//		alert(userName);
		document.getElementById("user_name").value = userName;
		var cookieRegex = new RegExp("task_interrupted_" + userName + "=(.+?)(;|$)");
		var currRegex = new RegExp(DELIM_RESOURCE + document.getElementById("curr_script").value + "\.cgi:(.+?)" + DELIM_FIELD + "(.+?)" + DELIM_RESOURCE);
//		alert("about to match:\n" + unescape(document.cookie) + "\nto:\n" + cookieRegex);
		if (document.cookie.match(cookieRegex)) { 
			localResults = RegExp.$1; 
		}
//		alert("about to match:\n" + unescape(localResults) + "\nto:\n" + currRegex);
		if (unescape(localResults).match(currRegex)) { 
			localResults = RegExp.$1;
			document.getElementById("partial_results").value = localResults;
			document.getElementById("test_start").value = RegExp.$2;
			//alert("utils.js::init(): " + document.getElementById("partial_results").value);
			eval(constrPre + "_partial()");
		}
		else {
			//alert("did not find local info in cookie:\n" + unescape(document.cookie));
			eval(constrPre + "_anew()");
		}
	}
	else {
		eval(constrPre + "_anew()");
	}
*/
  eval(constrPre + "_anew()");
//  signalLoaded();
}


/* Reset state variables */
function resetVars() {
	if (document.getElementById("test_start"))
        	document.getElementById("test_start").value = BLANK; // reset
	if (document.getElementById("test_end"))
       		document.getElementById("test_end").value = BLANK; // reset
	clientStart = new Date().getTime();
	bool_saveResults = 0;
	bool_discardResults = 0;
	cookieExpiryDate = new Date(); 
	cookieExpiryDate.setUTCMinutes(cookieExpiryDate.getUTCMinutes() + 15);
}

/* Response to 'Save' button */
function setSave() {
	bool_saveResults = 1;
//	deleteLocalCookie();	
//	signalUnloaded();
}

/* Response to 'Discard' button */
function setDiscard() {
	bool_discardResults = 1;
	if (getUserName()) {
//		deleteLocalCookie();
//		signalUnloaded();
	}
}

/* Response when test is submitted (read: "finished") */
function submitResults() {
	if (!bool_saveResults)
		return;
	if (document.getElementById("test_start").value == BLANK)  
                document.getElementById("test_start").value = new Date().getTime();
	if (document.getElementById("test_end").value == BLANK)  
                document.getElementById("test_end").value = new Date().getTime();
	setResults();
	document.getElementById("client_start").value = clientStart; 
	document.getElementById("client_end").value = new Date().getTime();
}

/* Updates local cookie to reflect test state information */
/* NG 04-12-31: commented out */
/*
function pageSwitch() {
var userName = getUserName();
	if (!userName) {return;}
// alert("pageSwitch::" + userName);
	var results = getResultString();
//alert("Got results: " + getResultString());
	var cookieRegex = new RegExp("task_interrupted_" + userName + "=(.+?)(;|$)");
	var currRegex = new RegExp("(.*?)" + DELIM_RESOURCE + document.getElementById("curr_script").value + "\.cgi:"
					+ "(.+?)" + DELIM_FIELD + "(.+?)"
					+ DELIM_RESOURCE + "(.*?)");				// "last_updated" would be RegExp.$3

//	alert("Cookie has:\n" + document.cookie + "\n\n and Regex is:\n" + cookieRegex + "\n");

	var tempCookie;
	if (document.cookie.match(cookieRegex)) { 			// cookie exists
		localResults = RegExp.$1; 
//		alert("Found cookie, now looking for local results:\ncookie has:\n " + localResults+ "\n\nand regex is:\n"+ currRegex);
	
		if (unescape(localResults).match(currRegex)) {	// cookie has entry for this test ...
//			alert("Found entry for this task and have\n1: " + unescape(RegExp.$1) + "\n3: " + unescape(RegExp.$4) );

			tempCookie = "task_interrupted_" + userName + "=" + escape(RegExp.$1 + DELIM_RESOURCE);
			tempCookie += escape(document.getElementById("curr_script").value + "\.cgi:"); 
			tempCookie += escape(results + DELIM_FIELD + RegExp.$3 + DELIM_RESOURCE + RegExp.$4);
		}
		else {						// append to end
			var now = new Date().getTime();
//			alert("Found cookie but nothing for this test");
			tempCookie = "task_interrupted_" + userName + "=" + localResults;
			tempCookie +=  escape(document.getElementById("curr_script").value + "\.cgi:"); 
			tempCookie +=  escape(results + DELIM_FIELD + now + DELIM_RESOURCE);
		}
	}
	else {
		var now = new Date().getTime();
//		alert("Sorry! No cookies here");
		tempCookie = "task_interrupted_" + userName + "=" + escape(DELIM_RESOURCE); 
		tempCookie += escape(document.getElementById("curr_script").value + "\.cgi:");
		tempCookie += escape(results + DELIM_FIELD + now + DELIM_RESOURCE);
//		alert(tempCookie);
	}


document.cookie = tempCookie + ";expires="+ cookieExpiryDate.toUTCString() + "; path=/";
// alert("Updated: \n" + unescape(document.cookie));
}
*/

/* Deletes local cookie that stores partial test results */
/* NG 04-12-31: commented out */
/*
function deleteLocalCookie() {
	var cookieRegex = new RegExp("task_interrupted_" + getUserName() + "=(.*?)" + DELIM_RESOURCE + document.getElementById("curr_script").value + "\.cgi:(.+?)" + DELIM_RESOURCE + "(.*?)(;|$)");
	var emptyCookie = new RegExp("task_interrupted_" + getUserName() + "=" + DELIM_RESOURCE + "(;|$)");

// alert("Trying to find: " + cookieRegex + "\nin\n\n:" + document.cookie);
	var changeString = "";
	if (unescape(document.cookie).match(cookieRegex)) {
//              alert("1: " + RegExp.$1 + "\n2: " + RegExp.$3 + "\n");
		changeString = "task_interrupted_" + getUserName() + "=" + escape(RegExp.$1 + DELIM_RESOURCE + RegExp.$3) + ";expires=" + cookieExpiryDate.toUTCString() + "; path=/";
		document.cookie = changeString;

//              alert("Cookie is: \n" + document.cookie + "\nRegex: \n" + emptyCookie);

	if (unescape(document.cookie).match(emptyCookie)) {             // remove cookie entirely if it has no more substance!
		// alert("Empty cookie! Yoddle ay hee hoo!");
		var expire = new Date();
		var today = new Date();
      expire.setTime(today.getTime() - (36 * 60 * 60 * 1000));
		changeString = "task_interrupted_" + getUserName() + "=" + escape("etc") + "; path=/; expires=" + expire.toUTCString() + "; ";
		document.cookie = changeString;
	}
}
// alert("Going to change to: "+ changeString);
// alert("Cookie set to: " + document.cookie);
}

function checkLoggedOut() {
	if (document.cookie.indexOf("login") == -1) {
		alert("Sorry!\nTo access the secure pages, you will have to log in again.");
		window.open("interactive.cgi","_top");
	}
}
*/
/* NG 04-12-31: commented out */
/*
function signalLoaded() {
var tempCookie;	
	tempCookie = "task_loaded_" + getUserName() + "=" + escape(document.getElementById("curr_script").value + "\.cgi"); 
	document.cookie = tempCookie + ";expires="+ cookieExpiryDate.toUTCString() + "; path=/";
// alert("Post loaded: " + document.cookie);
}

function signalUnloaded() {
var loadCookie = new RegExp("task_loaded_" + getUserName() + "=(.+?)($|;)");
	if (unescape(document.cookie).match(loadCookie)) {
		var expire = new Date();
		var today = new Date();
      expire.setTime(today.getTime() - (36 * 60 * 60 * 1000));
		document.cookie = "task_loaded_" + getUserName() +"=" + escape("etc") + "; path=/; expires=" + expire.toUTCString() + "; "; 
	}
//alert("Post unloaded: " + document.cookie);
}
*/

/* Writes time out in digit-only human-friendly format: YYYY-MM-DD HH:MM:SS */
function formatTime(t) {
	
	tString = t.getUTCFullYear() + "-";
	
	var b = t.getUTCMonth();
	b++;
	b = (b < 10) ? "0" + b : b + "";
	tString += b + "-";

	b = t.getUTCDate();
	b = (b < 10) ? "0" + b : b + "";
	tString += b + " ";
		
	b = t.getUTCHours();
	b = (b < 10) ? "0" + b : b + "";
	tString += b + ":";

	b = t.getUTCMinutes();
	b = (b < 10) ? "0" + b : b + "";
	tString += b + ":";

	b = t.getUTCSeconds();
	b = (b < 10) ? "0" + b : b + "";
	tString += b + "";

	// alert(tString);
	return tString;
} 

/* resize popup windows. NG 04-10-09 */
function resizePopup(popup_type,extraWidth,extraHeight) {
  winWidth=document.getElementById('bodyArea').offsetWidth; 
  winHeight=document.getElementById('bodyArea').offsetHeight; 
  window.resizeTo(winWidth+extraWidth,winHeight+extraHeight);
  window.status=popup_type;
  window.focus();
}
