//  Controller baseline established 10/9/2007

//
//  The code that follows assumes that the following variables
//  have been defined before sourcing in this file:
//
//     var thisAU;
//     var links;
//     var parameterMode;
//
var InternetExplorer    = navigator.appName.indexOf("Microsoft") != -1;
var acceptsCookies      = false;
var initialstatus       = "incomplete";
var project             = "UNKNOWN";
var pkg                 = "UNKNOWN";
var cookiePath          = (links == "NONE") ? "" : "/";
var urlParams           = parseURLParameters();
var userType            = "EndUser";

var reviewerMode        = 0;
var showTextEditMode    = 0;
var accessibilityMode   = 0;
var debug508            = 0;
var debugMode           = 0;
var debugBehavior       = 0;

initialize();

function initialize() {

	acceptsCookies = testCookies();

	setProjectPkg();

	reviewerMode      = (urlParams["reviewerMode"]      == undefined)  ? 0 : urlParams["reviewerMode"];
	showTextEditMode  = (urlParams["showTextEditMode"]  == undefined)  ? 0 : urlParams["showTextEditMode"];
	accessibilityMode = (urlParams["accessibilityMode"] == undefined)  ? 0 : urlParams["accessibilityMode"];
	debugMode         = (urlParams["debugMode"]         == undefined)  ? 0 : urlParams["debugMode"];
	debugBehavior     = (urlParams["debugBehavior"]     == undefined)  ? 0 : urlParams["debugBehavior"];
	reviewerMode      = (userType                       == "External") ? 0 : reviewerMode;

	if (parameterMode == "LMS") {
		LMSInitialize();
	}
}


function writeFlashEmbed_OLD(controllerPath) {
	document.write('<HTML>');
	document.write('<HEAD>');
	document.write('<META http-equiv="Pragma" CONTENT="no-cache" />');
	document.write('</HEAD>');
	document.write('<TITLE>' + title + '</TITLE>');
	document.write('<BODY BGCOLOR="' + bgColor + '" LEFTMARGIN="0" TOPMARGIN="0" MARGINWIDTH="0" MARGINHEIGHT="0" onunload="unloadPage()">');
	document.write('<OBJECT CLASSID="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
	document.write('    ID="CarneyContentShell"');
	document.write(' WIDTH="' + flashwidth + '" HEIGHT="' + flashheight + '"');
	document.write(' CODEBASE="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=5,0,30,0">');
	document.write(' <PARAM NAME="MOVIE" VALUE="' + controllerPath + '">');
	document.write(' <PARAM NAME="menu" VALUE="False">');
	document.write(' <PARAM NAME="allowScriptAccess" VALUE="always">');
	document.write(' <PARAM NAME="quality" value="' + movieQuality + '">');
	document.write(' <PARAM NAME="bgcolor" value="' + bgColor + '">');
	document.write(' <EMBED SRC="' + controllerPath + '"');
	document.write('  WIDTH="' + flashwidth + '" HEIGHT="' + flashheight + '" ');
	document.write('  swLiveConnect="true"');
	document.write('  NAME="CarneyContentShell"');
	document.write('  allowScriptAccess="always" ');
	document.write('  MENU="false"');
	document.write('  TYPE="application/x-shockwave-flash" ');
	document.write('  PLUGINSPAGE="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash">');
	document.write('</OBJECT>');
	document.write('</BODY>');
	document.write('</HTML>');
}

function writeFlashObject(url) {
	document.write('<HTML>');
	document.write('  <HEAD>');
	document.write('    <META http-equiv="Pragma" CONTENT="no-cache" />');
	document.write('    <TITLE>' + title + '</TITLE>');
	document.write('  </HEAD>');
	document.write('<BODY BGCOLOR="' + bgColor + '" LEFTMARGIN="0" TOPMARGIN="0" MARGINWIDTH="0" MARGINHEIGHT="0" onunload="unloadPage()">');
	document.write('<div id="flashcontent">');
	document.write('</div>');

	var so = new SWFObject(url, "CarneyContentShell", flashwidth, flashheight, "7", bgColor, false, "High");
	so.addParam("AllowScriptAccess", "always");
//	so.addParam("scaleMode",         "noscale");
	so.write("flashcontent");

	document.write('</BODY>');
	document.write('</HTML>');
}

function setShowtextOn (){
	var winHeight, d=document;
	if (typeof window.innerWidth!='undefined') {
		winHeight = window.innerHeight;
	} else if ( d.documentElement && typeof d.documentElement.clientWidth!='undefined' && d.documentElement.clientWidth!=0 ) {
		winHeight = d.documentElement.clientHeight;
	} else if ( d.body && typeof d.body.clientWidth!='undefined') {
		winHeight = d.body.clientHeight;
	}
	if(winHeight < flashheight){
//MAKE THIS A PARAM.  TDS
		window.resizeBy(0, 85);
	}
}

function setShowtextOff (){
	var winHeight, d=document;
	if (typeof window.innerWidth!='undefined') {
		winHeight = window.innerHeight;
	} else if ( d.documentElement && typeof d.documentElement.clientWidth!='undefined' && d.documentElement.clientWidth!=0 ) {
		winHeight = d.documentElement.clientHeight;
	} else if ( d.body && typeof d.body.clientWidth!='undefined') {
		winHeight = d.body.clientHeight;
	}

	if(winHeight == flashheight){
//MAKE THIS A PARAM.  TDS
		window.resizeBy(0, -85);
	}
}

function unloadPage() {
	if (parameterMode == "LMS") {
		LMSExit();
	}
}

function markModuleComplete() {
	if (parameterMode == "LMS") {
		LMSMarkModuleComplete();
	}
}

function setSCOCompletionStatus(status) {
	if (parameterMode == "LMS") {
		LMSSetLessonStatus(status);
	}
}

function setSCOSuccessStatus(status) {
	if (parameterMode == "LMS") {
		LMSSetLessonStatus(status);
	}
}

function changeModule(url) {
	if (parameterMode == "LMS") {
		LMSChangeModule(url)
	}
	else {
		location.href=url;
	}
}

function exitModule(status) {
	if (parameterMode == "LMS") {
		LMSExit(status);
	}
	closeWindow();
}

function getStoredParameters() {
	if (parameterMode == "LMS") {
		return LMSGetParameters();
	}
	else if (parameterMode == "cookie") {
		var cookieName  = getParameterCookieName();
//var str = readCookie(cookieName);
//alert("READ: " + cookieName + " = " + str);
		return readCookie(cookieName);
	}
}

function storeParameters(args) {
	//  args should be a list of param name=value pairs delimited by ampersand
	if (parameterMode == "LMS") {
		LMSStoreParameters(args);
	}
	else if (parameterMode == "cookie") {
		var cookieName = getParameterCookieName();
//alert("storing " + cookieName + " = " + args);
//alert("storing with cookiePath: <" + cookiePath  + ">");
		setCookie(cookieName, args, cookieexpiration, cookiePath, null, null);
	}
}

//
// This function is used to print a completion certificate.
//
function certificate(myname) {
	var now    = new Date();
	var myYear = Number(now.getYear());

	if ((myYear >= 101) && (myYear <= 130)) {
		myYear += 1900;
	}

	var displaydate = (now.getMonth()+1) + "/" + now.getDate() + "/" + myYear;
	var page        = certificateURL + "?" + escape(displaydate) + escape("  ") + escape(myname);

	//  The date will be between 8 and 10 characters.  The two-spaces
	//  after the date ensures that the user name will appear on or
	//  after the 11th character.  All data-entry fields are restricted
	//  to be no more than 45 characters, thus the name will be between
	//  characters 11 and 57.

	openWin(page, 'certificate', 'width=621,height=652,resizable=0,menuBar=1,status=0,scrollbars=0');
}

function getLastVisitedModule() {
	var lastVisited = "";
	var cookieName  = getLinkParameterCookieName();
	var paramcookie = readCookie(cookieName);
	var idx         = -1;
	if (paramcookie) {
		idx = paramcookie.indexOf("LastVisitedModule=");
	}
	if (idx >= 0) {
		  lastVisited = paramcookie.substring(idx + "LastVisitedModule=".length);
	}
	idx = lastVisited.indexOf("&");
	if (idx >= 0) {
		lastVisited = lastVisited.substring(0, idx);
	}
	return lastVisited;
}

//
// REVISIT
//
//  The parseParameters() function and URLSearchParam()/setParamVal() functions do
//  esstentially the same thing.  Decide which to use and eliminate the other.
//  Also, can't we just do the same thing with custom split?
//
function parseURLParameters() {
	var params   = new Object();
	var paramStr = unescape(window.location.search.substring(1));
	var pairs    = paramStr.split("&");
	for(var i = 0; i < pairs.length; i++ ) {
		var pos = pairs[i].indexOf('=');
		if (pos != -1) {
			var paramName  = unescape(pairs[i].substring(0, pos));
			var paramValue = unescape(pairs[i].substring(pos + 1));
			params[paramName] = paramValue;
		}
	}
	return params;
}

//
//  This function evaluates the URL and uses it to determine the correct
//  values for the folowing variables:
//
//       project
//       pkg
//       userType
//
function setProjectPkg() {
	var projIdx = -1;
	var size    = customSplit(location.href, "/", "dirs");
	for (var i = 0; i < size; i++) {
		if (dirs[i] == "projects") {
			projIdx = i + 1;
			break;
		}
		else if (dirs[i] == "ContentShell") {
			projIdx = i;
			break;
		}
		if (dirs[i].indexOf("teamcarney") > 0) {
			//  Classify the user as External for now.
			//  If we find a "dev" or "qa" dir below we will
			//  reclassify as Internal.
			userType = "External";
		}
	}
	project = dirs[projIdx];
	if (dirs[projIdx + 1] == "dev") {
		pkg      = "Development";
		userType = "Internal";
		return;
	}
	if (dirs[projIdx + 1] == "qa") {
		pkg      = dirs[projIdx + 2];
		userType = "Internal";
		return;
	}
}


/////////////////////////////////////////////////
//
//  Functions that support cookie operations
//
/////////////////////////////////////////////////


function getParameterCookieName() {
	if ((paramSetName == null) || (paramSetName == "")) {
		paramSetName = thisAU + "_params";
	}
	return paramSetName;
}

function checkcookies() {
	setCookie('teststoredcookies','test',48,'/', null, null);
	setCookie('testpersessioncookies','test');
	var cookietest = readCookie('testpersessioncookies');
	if (cookietest == false) {
		return false;
	}
	else {
		return true;
	}
}

function testCookies() {
	if (document.cookie == '') {
		//  Try to set a cookie.
		document.cookie = 'CarneyCookieTest=yes';
		if(document.cookie.indexOf('CarneyCookieTest=yes') != -1) {
			return true;
		}
	}
	else {
		//  There was already a cookie.
		return true;
	}
	return false;
}

function setCookie (name, value, hours, path, domain, secure) {
	if (acceptsCookies) {
		var not_NN2 = (navigator && navigator.appName
				&& (navigator.appName == 'Netscape')
				&& navigator.appVersion
				&& (parseInt(navigator.appVersion) == 2))?false:true;

                //
                //  Netscape Navigator 2 can not handle dates.
                //
		if(hours && not_NN2) {
			if ((typeof(hours) == 'string') && Date.parse(hours) ) {
			        //  Already a Date string
				var numHours = hours;
			} else if (typeof(hours) == 'number') {
				//  Calculate the date from the number of hours
				var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
			}
		}
		document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':''); // Set the cookie, adding any parameters that were specified.
	}
}


function readCookie(name) {
	if (document.cookie == '') {
		//
		//  There's no cookie by this name.
		//
		return false;
	}
	else {
		var c = document.cookie;
		//
		//  Find the start of 'name'
		//
		var idx1 = c.indexOf(name);
		var idx2 = idx1 + name.length;
		if((idx1 != -1) && (c.charAt(idx2) == '=')) {
			//
			//  Found the cookie.
			//

			// skip 'name' and '='
			idx1 += name.length + 1;

			// Find the end of the value string (i.e. the next ';').
			idx2 = c.indexOf(';', idx1);

			if(idx2 == -1) {
				idx2 = c.length;
			}
			return unescape(c.substring(idx1, idx2));
		} else {
			//
			//  If there was no cookie of that name, return false.
			//
			return false;
		}
	}
}

function deleteCookie(name, path, domain) {
 	// We need the value to delete the cookie
	var theValue = readCookie(name);
	if(theValue) {
	 	//   Set an the expiration date so that the cookie is already expired.
		document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'');
	}
}



/////////////////////////////////////////////////
//
//  General Utility Functions
//
/////////////////////////////////////////////////

//
//  This version of unEncode replaces the old, longer version of unEncode.
//  REVISIT:
//      1.  See if we can simply use unescape instead.  the original version of
//          unEncode() replaced %22 (") with '-', not '"'.
//      2.  The original version of unEncode() only converted and returned the
//          first 56 characters of the input.
//
//  Use these var's for tetsing:
//
//      var str1 = 'a b!c#d$e%f^g&h(i)j~k`l=m{n}o[p]q|r:s;t"-u?v<w>x,y-';
//      var str2 = "a%20b%21c%23d%24e%25f%5Eg%26h%28i%29j%7Ek%60l%3Dm%7Bn%7Do%5Bp%5Dq%7Cr%3As%3Bt%22-u%3Fv%3Cw%3Ex%2Cy-";
//
function unEncode(input) {
	var idx = input.search(/%22/);
	while (idx >= 0) {
		input = input.substring(0, idx) + "-" + input.substring((idx+3));
		idx = input.search(/%22/);
	}
	return unescape(input);
}


function centerWindowOnScreen(w, h) {
	var x = (self.screen.width - w) / 2;
	var y = (self.screen.height - h) / 2
	self.window.moveTo(x, y);
}

function customSplit(strvalue, separator, arrayName) {
	var n = 0;

	if (separator.length != 0) {
		while (strvalue.indexOf(separator) != -1) {
			eval("arr"+n+" = strvalue.substring(0, strvalue.indexOf(separator));");
			strvalue = strvalue.substring(strvalue.indexOf(separator)+separator.length, strvalue.length+1);
			n++;
		}
		eval("arr" + n + " = strvalue;");
		arraySize = n+1;
	}
	else {
		for (var x = 0; x < strvalue.length; x++) {
			eval("arr"+n+" = \"" + strvalue.substring(x, x+1) + "\";");
			n++;
		}
		arraySize = n;
	}

	eval(arrayName + " = new makeArray(arraySize);");

	for (var i = 0; i < arraySize; i++)
		eval(arrayName + "[" + i + "] = arr" + i + ";");
	return arraySize;
}

function makeArray(IntarrSize) {
	for (var n = 0; n < IntarrSize; n++) {
		this[n] = "";
	}
	return this;
}

function openWin( windowURL, windowName, windowFeatures ) {
	return window.open( windowURL, windowName, windowFeatures ) ;
}

function focusme() {
	window.focus();
}

function closeWindow() {
	if (windowCloseAction == "closeWindow") {
		window.close();
	}
	else if (windowCloseAction == "closeTop") {
		top.close();
	}
}

function printme() {
	var x = navigator.userAgent;
	//alert(x);
	if (x=="Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)"){
		alert("Your browser does not support automated printing.  Please select 'Print' from the File menu.");
	}
	else if (navigator.userAgent.indexOf(" 4.0")>0 ) {
		alert("Your browser does not support automated printing.  Please select 'Print' from the File menu.");
	}
	else {
		window.print();
	}
}


//////////////////////////////////////////////////////////
//
//  Generates today's date in a format that can be
//  inserted into a DATE field by ColdFusion Server.
//
//  originally in date.js
//
//////////////////////////////////////////////////////////
function getCFDate() {
	var m = new makeArray(12);
	m[0]  = "Jan";
	m[1]  = "Feb";
	m[2]  = "Mar";
	m[3]  = "Apr";
	m[4]  = "May";
	m[5]  = "Jun";
	m[6]  = "Jul";
	m[7]  = "Aug";
	m[8]  = "Sep";
	m[9]  = "Oct";
	m[10] = "Nov";
	m[11] = "Dec";

	var d = new Date();
	var month=d.getMonth();
	return d.getDate() + "-" + m[month] + "-" + d.getFullYear();
}





/////////////////////////////////////////////////
//
//  Other Utility Functions
//
/////////////////////////////////////////////////


function MM_swapImgRestore() { //v3.0
	var i,x,a=document.MM_sr;
  	for (i = 0; a && (i < a.length) && (x = a[i]) && x.oSrc; i++) {
  		x.src = x.oSrc;
  	}
}

function MM_preloadImages() { //v3.0
	var d=document;
	if(d.images) {
		if (!d.MM_p) {
			d.MM_p=new Array();
		}
		var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
		for(i=0; i<a.length; i++) {
			if (a[i].indexOf("#")!=0) {
				d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];
			}
		}
	}
}

function MM_findObj(n, d) { //v3.0
	var p,i,x;
	if (!d) {
		d = document;
	}
	if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
		d = parent.frames[n.substring(p+1)].document;
		n = n.substring(0,p);
	}
	if (!(x = d[n]) && d.all) {
		x = d.all[n];
	}
	for (i = 0;!x&&i<d.forms.length;i++) {
		x = d.forms[i][n];
	}
	for (i = 0; !x && d.layers && i < d.layers.length; i++) {
		x = MM_findObj(n, d.layers[i].document);
	}
	return x;
}

function MM_swapImage() { //v3.0
	var i,j=0,x,a=MM_swapImage.arguments;
	document.MM_sr = new Array;
	for(i=0; i < (a.length-2); i += 3) {
		if ((x = MM_findObj(a[i])) != null) {
			document.MM_sr[j++] = x;
			if (!x.oSrc) {
				x.oSrc = x.src;
				x.src  = a[i+2];
			}
		}
	}
}

/*

DELETE THESE

function URLSearchParam() {
	searchStr = unescape(window.location.search);
	var strVal = searchStr.substring(1, searchStr.length);
	var idx = strVal.indexOf("&");
	while (idx != -1) {
		nameVal = strVal.substring(0, idx);
		setParamVal(this, nameVal);
		strVal = strVal.substring(idx + 1, strVal.length);
		idx = strVal.indexOf("&");
	}
	setParamVal(this, strVal);
}

function setParamVal(o, nameVal) {
	var idx = nameVal.indexOf("=");
	if (idx != -1) {
		name = nameVal.substring(0, idx);
		val = nameVal.substring(idx + 1, nameVal.length);
		eval("o." + name + " = '" + val + "'");
	}
}

*/

/*  PENDING DELETE
function changeShowTextStatus(args) {
	if (args == "off") {
		showTextStatus = "off";
		setCookie('showtext','off', cookieexpiration, cookiePath, null, null);
		//  SHOULD WE ALSO TRY TO CLOSE THE WINDOW ???
	}
	else {
		showTextStatus = "on";
	}
}

function setShowTextTxt(args) {
	if (showTextStatus == "on") {
		var page = showTextURL + "?txt=" + escape(args);

		var showtextattributes = "width=" + showtextwidth + ",height=" + showtextheight;
		showtextattributes = showtextattributes + ",resizable=1,status=0,scrollbars=1";

		var showtextwindow = openWin(page, 'showtextwin', showtextattributes);
		showtextwindow.moveTo(0, 0);
	}
}
*/
