// ***************************************************************************
// ver 05052005 -- 
// SCORM for Flash course only
// custom completion evaluation included in saveLMSdata() line 155

// could modify to support LMS or cookie by removing alert on line 78 in delayedLoadSCO()

// Designed to use the two unmodified wrapper files provided by www.adlnet.org
//
// APIWrapper.js
// SCOFunctions.js
//
// CMI object is used to store data whether using LMS or Cookies
// ***************************************************************************

var cSuspendData	= "SuspendData_";	//-Suspend_data cookie name
var cBookMark		= "Bookmark_";		//-Bookmark cookie name
var maxAttempts 	= 3;				//-Max times we attempt to connect to LMS
var numTrys 		= 0;				//-Tracks number of attempts to connect w/ LMS

// ***************************************************************************
// Starts communication w/ the LMS.  Called from onload of course frameset.
//
// If successful, creates the API object which lets us communicate w/ the LMS
// ***************************************************************************
function initLMS()
{
	//-Start debug log class
	log.start(_useLog);

	//-If we're in development, do not try to communicate the LMS
	if(_debug)
	{
		useLMS = false;													/*DEBUG*/ if(_DebugLMS){log.write("coursevars.js is setting useLMS=false, switching to cookie mode.", "lms_sco.js");}
	}

	numTrys	= 0;
	if(useLMS)
	{
		setTimeout("delayedLoadSCO()",1000);
	}
	else	//-cookie debug mode
	{
		//-Update the WBT with cookie data
		getLMSdata();
	}
}

// ***************************************************************************
// Tests communication w/ LMS.  Makes set number of timed attempts.
// ***************************************************************************
function delayedLoadSCO()
{
	numTrys++;
	var result = doLMSInitialize();										/*DEBUG*/ if(_DebugLMS){log.write("Result = "+result+"\r\n\r\nNumber of Trys = "+numTrys, "lms_sco.js");}

	if(result == "true")
	{
		var status = doLMSGetValue( "cmi.core.lesson_status" );			/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.lesson_status = "+status, "lms_sco.js");}
		if(status.toLowerCase() == "not attempted")
		{
			//-the student is now attempting the lesson
			doLMSSetValue( "cmi.core.lesson_status", "incomplete" );	/*DEBUG*/ if(_DebugLMS){log.write("setting cmi.core.lesson_status = 'incomplete'", "lms_sco.js");}
		}
		startTimer();	//-Start tracking session time					/*DEBUG*/ if(_DebugLMS){log.write("Starting session Time tracking", "lms_sco.js");}
		getLMSdata();	//-Update the WBT with LMS data
		return;
	}

	//-Connect to LMS failed, try again...
	if(numTrys < maxAttempts)
	{
		wait = numTrys * 2000;
		setTimeout("delayedLoadSCO()",wait);
	}

	//-Unable to connect!  Stop trying. Switch to cookie mode.
	if(numTrys == maxAttempts)
	{
		alert("Currently unable to establish communication with the LMS.  Your progress will NOT be tracked.");

		useLMS = false;	//-stop making further LMS calls				/*DEBUG*/ if(_DebugLMS){log.write("Unable to connect to LMS. Setting useLMS=false.", "lms_sco.js");}
		startTimer();	//-Start tracking session time					/*DEBUG*/ if(_DebugLMS){log.write("Starting session Time tracking", "lms_sco.js");}
		getLMSdata();	//-Update the WBT with LMS data
		return;
	}
}

// ***************************************************************************
// This function retrieves data from the LMS then parses it and updates wbt
// ***************************************************************************
function getLMSdata()
{
	//-Update CMI object w/ data from either LMS or Cookie				/*DEBUG*/ if(_DebugLMS){log.write("Starting getLMSdata()\r\n\r\nuseLMS = "+useLMS, "lms_sco.js");}
	if(useLMS)
	{
		//-Get cmi.suspend_data from LMS (4096 max characters)
		cmi.suspend_data = getSCOSuspendData();							/*DEBUG*/ if(_DebugLMS){log.write("cmi.suspend_data:\r\n\r\n"+cmi.suspend_data, "lms_sco.js");}

		//-Get cmi.core.student_id from LMS
		cmi.core.student_id = getSCOStudentID();						/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.student_id:\r\n\r\n"+cmi.core.student_id, "lms_sco.js");}

		//-cmi.core.student_name from LMS
		cmi.core.student_name = getSCOStudentName();					/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.student_name:\r\n\r\n"+cmi.core.student_name, "lms_sco.js");}

		//-Get cmi.core.lesson_location from LMS (255 max characters)
		cmi.core.lesson_location = getSCOBookmark();					/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.lesson_location:\r\n\r\n"+cmi.core.lesson_location, "lms_sco.js");}

		//-Get cmi.core.credit from LMS (read-only)
		cmi.core.credit = getSCOcredit();								/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.credit:\r\n\r\n"+cmi.core.credit, "lms_sco.js");}

		//-Get cmi.core.lesson_status from LMS
		cmi.core.lesson_status = getSCOStatus();						/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.lesson_status:\r\n\r\n"+cmi.core.lesson_status, "lms_sco.js");}

		//-Get cmi.core.entry from LMS (read-only)
		cmi.core.entry = getSCOEntry();									/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.entry:\r\n\r\n"+cmi.core.entry, "lms_sco.js");}

		//-Get cmi.core.score from LMS
		cmi.core.score.raw = getSCOScore();								/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.score.raw:\r\n\r\n"+cmi.core.score.raw, "lms_sco.js");}

		//-Get cmi.core.total_time from LMS (read-only)
		cmi.core.total_time = getSCOTotalTime();						/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.total_time:\r\n\r\n"+cmi.core.total_time, "lms_sco.js");}

		//-Get cmi.core.lesson_mode from LMS (read-only)
		cmi.core.lesson_mode = getSCOLessonMode();						/*DEBUG*/ if(_DebugLMS){log.write("cmi.core.lesson_mode:\r\n\r\n"+cmi.core.lesson_mode, "lms_sco.js");}

	}
	else	//-Get data from Cookies (1 for suspend_data and 1 for lesson_location)
	{
		//-Get suspend_data cookie
		var suspendData = unescape(getCookie(cSuspendData));			/*DEBUG*/ if(_DebugLMS){log.write("suspend_data cookie:\r\n\r\n"+suspendData, "lms_sco.js");}
		if(suspendData.length > 0 ){cmi.suspend_data = suspendData;}

		//-Get lesson_location cookie
		var bookmarkData = unescape(getCookie(cBookMark));				/*DEBUG*/ if(_DebugLMS){log.write("lesson_location cookie:\r\n\r\n"+bookmarkData, "lms_sco.js");}
		if(bookmarkData.length > 0 ){cmi.core.lesson_location = bookmarkData;}
	}

	//** load flash variable after cmi is loaded
	var locationValue = cmi.core.lesson_location;
	/*DEBUG*/ if ( _debug ) { alert("locationValue = " + locationValue); }
	targetframe.setFlashVariables('controller', 'bookmarkTracking=' + locationValue);
}

// ***************************************************************************
// This function calls a menu function to get a formatted string of completion
// and score data to ship to the LMS.
//
// If not saving to an LMS, use TWO separate cookies to keep suspend_data
// and lesson_location data separate.  This way we use one set of functionality
// whether you're in the LMS or cookie-mode.
// ***************************************************************************
function saveLMSdata()
{
	var parsedStr = cmi.core.lesson_location.split("|");
	if ( parsedStr.length >= 2 && parsedStr[1].lastIndexOf("0") == -1)
	{
		cmi.core.lesson_status = "completed";
	}

	if(useLMS)
	{
		var result = "";

		//-Save cmi.suspend_data
		result = setSCOSuspendData(cmi.suspend_data);					/*DEBUG*/ if(_DebugLMS){log.write("Attempting to save suspend_data: "+cmi.suspend_data+"\r\n\r\nRESULT="+result, "lms_sco.js");}

		//-Save bookmark
		result = setSCOBookmark(cmi.core.lesson_location);				/*DEBUG*/ if(_DebugLMS){log.write("Attempting to save lesson_location: "+cmi.core.lesson_location+"\r\n\r\nRESULT="+result, "lms_sco.js");}

		//-Save status
		result = setSCOStatus(cmi.core.lesson_status);					/*DEBUG*/ if(_DebugLMS){log.write("Attempting to save lesson_status: "+cmi.core.lesson_status+"\r\n\r\nRESULT="+result, "lms_sco.js");}

		//-Save score (this value must go through as a string)
		result = setSCOScore(cmi.core.score.raw.toString());			/*DEBUG*/ if(_DebugLMS){log.write("Attempting to save score.raw: "+cmi.core.score.raw+"\r\n\r\nRESULT="+result, "lms_sco.js");}

		//-force the commit here
		doLMSCommit();
	} else {
		//-Save suspend_data (menu & test data) to cookie
		setCookie(cSuspendData,cmi.suspend_data,true);					/*DEBUG*/ if(_DebugLMS){log.write("Attempting to save suspend_data to cookie:\r\n\r\n"+cmi.suspend_data, "lms_sco.js");}

		//-Save lesson_location (bookmark) to separate cookie
		setCookie(cBookMark,cmi.core.lesson_location,true);				/*DEBUG*/ if(_DebugLMS){log.write("Attempting to save lesson_location to cookie:\r\n\r\n"+cmi.core.lesson_location, "lms_sco.js");}
	}
}

// ***************************************************************************
// SCO functions which directly call doLMSGetValue() and doLMSSetValue()
// in SCOFunctions.js
// ***************************************************************************
function getSCOStatus(){return doLMSGetValue( "cmi.core.lesson_status" );}

function getSCOSuspendData(){return doLMSGetValue( "cmi.suspend_data" );}

function getSCOStudentID(){return doLMSGetValue( "cmi.core.student_id" );}

function getSCOStudentName(){return doLMSGetValue( "cmi.core.student_name" );}

function getSCOBookmark(){return doLMSGetValue( "cmi.core.lesson_location" );}

function getSCOScore(){return doLMSGetValue( "cmi.core.score.raw" );}

function getSCOcredit(){return doLMSGetValue( "cmi.core.credit" );}

function getSCOEntry(){return doLMSGetValue( "cmi.core.entry" );}

function getSCOTotalTime(){return doLMSGetValue( "cmi.core.total_time" );}

function getSCOLessonMode(){return doLMSGetValue( "cmi.core.lesson_mode" );}



function setSCOScore(score){return doLMSSetValue( "cmi.core.score.raw", score );}

function setSCOBookmark(bookmark){return doLMSSetValue( "cmi.core.lesson_location", bookmark );}

function setSCOSuspendData(suspendData){doLMSSetValue( "cmi.suspend_data", suspendData );}

function setSCOStatus( status )
{
	var  result;

	//-If no status passed in, don't change it
	if(status != "")
	{
		result = doLMSSetValue( "cmi.core.lesson_status", status );
	}
}


// ****************************************************************************
// This function informs the LMS that the user is exiting the courseware
// ****************************************************************************
function exitLMS()
{
	//-Save user's current location & info (does "LMSCommit()")			/*DEBUG*/ if(_DebugLMS){log.write("Starting exitLMS().", "lms_sco.js");}
	saveLMSdata();

	if(useLMS)
	{
		//-Re-init Exit to blank
		doLMSSetValue( "cmi.core.exit", cmi.core.exit );				/*DEBUG*/ if(_DebugLMS){log.write("Attempting to save cmi.core.exit", "lms_sco.js");}
		computeTime();													/*DEBUG*/ if(_DebugLMS){log.write("Computing session time.", "lms_sco.js");}
		result = doLMSFinish();											/*DEBUG*/ if(_DebugLMS){log.write("Called doLMSFinish()\r\n\r\nResult = "+result, "lms_sco.js");}
	}
}


// ****************************************************************************
// This function sets a cookie to save LMS data
// ****************************************************************************
function setCookie(name, value, perm)
{
	var expDate = new Date();
	var expires = '';
	var cookieString = '';

	// sets expires to one year from now.
	if ( perm )
	{
		expDate.setTime(expDate.getTime() + (365 * 24 * 60 * 60 * 1000));
		expires = "; expires=" + expDate.toGMTString();
	}

	cookieString = escape(name) + clabel + "=" + escape(value) + "; path=/" + expires;
	document.cookie = cookieString;
}


// ****************************************************************************
// This function retrieves a cookie of LMS data.
// ****************************************************************************
function getCookie(name)
{
	var offset = -1;
	var search = escape(name) + clabel + "=";
	var end;

	//-if there are any cookies
	if( document.cookie.length > 0 )
	{
		//-verify that cookie exists
		offset = document.cookie.indexOf(search);						/*DEBUG*/ if(_DebugLMS){log.write("Attempting to get data from cookie named: "+search, "lms_sco.js");}
		if( offset != -1 )
		{
			//-find start position of cookie value
			offset += search.length;

			//-find end of cookie value
			end = document.cookie.indexOf(";", offset);
			if( end == -1 ){end = document.cookie.length;}

			//-return the cookie value
			return(unescape(document.cookie.substring(offset, end)));
		}
		else{return('');}
	}
	else{return('');}
}

