/* SCORM 1.2 LMS functions */

var findAPITries = 0;

/*
	Function: actionsFindAPI
	Arguments: the current window
	Description: check to see if win contains the SCORM 1.2 API adaptor
	Returns: null if SCORM 1.2 API could not be located
			 a handle to SCORM 1.2 API adapter is returned if the API was located
*/
function actionsFindAPI(win)
{
   /* Check to see if the window (win) contains the SCORM 1.2 API
      if the window (win) does not contain the API and
     the window (win) has a parent window and the parent window  
     is not the same as the window (win)
   */ 
   while ( (win.API == null) && 
           (win.parent != null) && 
           (win.parent != win) )
   {
      /* increment the number of findAPITries */
      findAPITries++;

      /* note: 7 is an arbitrary number, but would be more than sufficient */
      if (findAPITries > lms_num_tries)
      {
         return null;
      }

      /* set the variable that represents the window being 
         being searched to be the parent of the current window
         then search for the API again
	  */	 
      win = win.parent;
   }
   return win.API;
}

/*
	Function: actionsGetAPI
	Arguments: none
	Description: locate the SCORM 1.2 API adaptor
	Returns: null if SCORM 1.2 API could not be located
			 a handle to API adapter is returned if the API was located
*/
function actionsGetAPI()
{
   /* start by looking for the SCORM 1.2 API in the current window */
   var theAPI = actionsFindAPI(window);
   /* if the API is null (could not be found in the current window)
	  and the current window has an opener window
   */ 
   if ( (theAPI == null) && 
        (window.opener != null) && 
        (typeof(window.opener) != "undefined") )
   {
      /* try to find the API in the current window's opener */
      theAPI = actionsFindAPI(window.opener);
   }
   /* if the API is null (could not be found in the current window,
      or the current windows opener) see if the opener of the topmost
      window contains the api
      and the current window has an opener window
   */	  
   if ( (theAPI == null) && 
        (window.top.opener != null) && 
        (typeof(window.top.opener) != "undefined") )
   {
      // try to find the API in the current window's opener
      theAPI = actionsFindAPI(window.top.opener);
   }
   return theAPI;
}

/*
	Function: actionsLMSInitialize
	Arguments: none		
	Description: initializes the LMS API
	Returns: boolean for success of initialization
*/
function actionsLMSInitialize()
{
	/* if LMS API adaptor exists */
	if(LMSAPI != null){
		/* attempt to initialize API */
		var result = LMSAPI.LMSInitialize("");
		/* report on the error if API not initialized */
		if(result == "false") {
			actionsLMSError("LMSInitialize","");
		}
	}
	return result;
}

/*
	Function: actionsLMSFinish
	Arguments: none		
	Description: executes final LMS calls on exit of the course
	Returns: nothing
*/
function actionsLMSFinish()
{
	/* check that the code has not already executed */
	if(!document.courseFinished)
	{
		/* if LMS API adaptor exists */
		if(LMSAPI != null){
			/* attempt to finish up with the LMS */
			var less_status = actionsLMSGetValue('cmi.core.lesson_status');			
			/* check status completion flag variable */
			if((less_status == lms_pass_status1) || (less_status == lms_pass_status2)){			
				/* do nothing */
			}else{					
				 actionsLMSSetValue('cmi.core.lesson_status',lms_fail_status);
			}			
			/* set tracking data on closing course */
			recordPercentComplete(document.currentSection, document.subsectionCount, false);
			/* set the session time */
			courseWriteTimer(false);
			/* commit date to the LMS */
			actionsLMSCommit();			
			LMSAPI.LMSFinish('');
			document.courseFinished = true;
		}
	}
}

/*
	Function: actionsLMSCommit
	Arguments: none
	Description: commits the current value to the LMS
	Returns: nothing
*/
function actionsLMSCommit()
{
	/* if LMS API adaptor exists */
	if(LMSAPI != null){
		/* commit the currently stored values to the LMS */
		LMSAPI.LMSCommit('');
		/* if there is an error with the LMS communication report on it */
		actionsLMSError("LMSCommit","");		
	}
}

/*
	Function: actionsLMSSetValue
	Arguments: 
		arg: database field e.g. cmi.core.session_time
		val: value for the database field
	Description: sets the database field value in the LMS and commits it to the LMS			 
	Returns: nothing
*/
function actionsLMSSetValue(arg,val)
{
	/* if LMS API adaptor exists */
	if(LMSAPI != null){	
		LMSAPI.LMSSetValue(arg,val);
		/* if there is an error with the LMS communication report on it */
		actionsLMSError("LMSSetValue",arg);		
	}
	/* ensure value is updated in LMS on tablet or phone but not in the Saba LMS app */
	if(!isWeb){
		if(androidApp == false && iOSApp == false){
			actionsLMSCommit();
		}
	}
}

/*
	Function: actionsLMSGetValue
	Arguments: 
		arg: database field e.g. cmi.core.session_time
	Description: obtains the database field value from the LMS				 
	Returns: value of the database field
*/
function actionsLMSGetValue(arg)
{
	var result = "";
	/* if LMS API adaptor exists */
	if(LMSAPI != null){
		result = LMSAPI.LMSGetValue(arg);		
		/* if there is an error with the LMS communication report on it */
		actionsLMSError("LMSGetValue",arg);
	}
	return result;
}

/*
	Function: actionsLMSError
	Arguments: 
		errLMS: code to indicate the type of LMS call that was attempted
		errArg: database field e.g. cmi.core.session_time or a code for a database field
	Description: obtains the error code from LMSGetLastError() and uses this to obtain 
				 further details to display in an error pop up if error occurred
	Returns: none
*/
function actionsLMSError(errLMS,errArg)
{
	var result = 0;	
	if (errArg != "") 
	{ 
		if (errLMS != "") {	errLMS = errLMS + ": "; }
		errArg = errArg + " "; 
	}	
	/* if LMS API adaptor exists */
	if(LMSAPI != null){
		result = LMSAPI.LMSGetLastError();
		if (result != 0) {
			var errorString = errLMS + errArg + "<br><br>" + result + " - " + LMSAPI.LMSGetErrorString(result);
			var errorString2 = LMSAPI.LMSGetDiagnostic(result);
			showErrorMessage("Error", errorString, errorString2, "");
		}
	}
	/* if LMS API adaptor does not exist */
	else {	
		var errorString = lms_error_dat["lms_error_1"][0].text1;
		var errorString2 = lms_error_dat["lms_error_1"][0].text2;
		showErrorMessage("Error", errorString, errorString2, "");
	}
}

/*
	Function: actionsLMSSetScore
	Arguments: integer for score
	Description: calls function to set the score in the LMS
	Returns: none
*/
function actionsLMSSetScore(n)
{
	var score = actionsLMSGetScore()
	
	if(n >= score){
		actionsLMSSetValue('cmi.core.score.raw',n);
	}
}

/*
	Function: actionsLMSGetScore
	Arguments: none
	Description: calls function to get the score from the LMS
	Returns: integer for score
*/
function actionsLMSGetScore()
{
	return actionsLMSGetValue('cmi.core.score.raw');
}

/*
	Function: actionsLMSSetSuspendData
	Arguments: string for suspend data
	Description: calls function to set the suspend data in the LMS
	Returns: none
*/
function actionsLMSSetSuspendData(n) 
{
	actionsLMSSetValue('cmi.suspend_data', n);
}

/*
	Function: actionsLMSGetSuspendData
	Arguments: none
	Description: calls function to get the suspend data from the LMS
	Returns: string for suspend data
*/
function actionsLMSGetSuspendData() 
{
	return actionsLMSGetValue('cmi.suspend_data');
}

/*
	Function: actionsLMSSetLessonLocation
	Arguments: string for lesson location
	Description: calls function to set the lesson location in the LMS
	Returns: none
*/
function actionsLMSSetLessonLocation() 
{
	actionsLMSSetValue('cmi.core.lesson_location', int_tracking.int_lesson_location);	
}

/*
	Function: actionsLMSGetLessonLocation
	Arguments: none
	Description: calls function to get the lesson location from the LMS
	Returns: string for lesson location
*/
function actionsLMSGetLessonLocation() 
{
	return actionsLMSGetValue('cmi.core.lesson_location');	
}

/*
	Function: actionsLMSSetLessonStatus
	Arguments: 
		m: string for lesson status to set
		n: boolean to indicate if lesson status should be set in the LMS
	Description: calls function to set the lesson status in a local variable
				 and/or in the LMS
	Returns: none
*/
function actionsLMSSetLessonStatus(m,n)
{
	/* if the lesson status is incomplete then set it in the LMS */
	if (m == "incomplete")
	{
		actionsLMSSetValue('cmi.core.lesson_status',lms_fail_status);
		int_tracking.int_lesson_status = lms_fail_status;
	}
	/* if the lesson status is completed then set it in the LMS only if indicated by n */
	else if (m == "completed")
	{
		if (n == true)
		{
			actionsLMSSetValue('cmi.core.lesson_status',lms_pass_status1);
			int_tracking.int_lesson_status = lms_pass_status1;
		}
		else
		{
			int_tracking.int_lesson_status = lms_pass_status1;
		}	
	}
}

/*
	Function: actionsLMSGetLessonStatus
	Arguments: none
	Description: calls function to get the lesson status from the LMS
	Returns: string for lesson status
*/
function actionsLMSGetLessonStatus()
{
	return actionsLMSGetValue('cmi.core.lesson_status');
}

/*
	Function: actionsLMSSetSessionTime
	Arguments: CMITimeSpan string
	Description: calls function to set the session time in the LMS
	Returns: none
*/
function actionsLMSSetSessionTime(n) 
{
	actionsLMSSetValue('cmi.core.session_time',n);
}

/*
	Function: actionsLMSGetStudentId
	Arguments: none
	Description: calls function to get the student id from the LMS
	Returns: a string of the student id
*/
function actionsLMSGetStudentId() 
{
	return actionsLMSGetValue('cmi.core.student_id');
}

/*
	Function: actionsLMSGetStudentName
	Arguments: none
	Description: calls function to get the student name from the LMS
	Returns: a string of the student name
*/
function actionsLMSGetStudentName() 
{
	return actionsLMSGetValue('cmi.core.student_name');
}




function recordInteractions(intID, userResponse, result, corrResponse, description, intType, intWeighting, intTimeStamp, strLOID){
	
	var intInteractionIndex;
	
	var intResult = "";
	
	

	
	if(result == true){
		intResult = "correct"
	}else if(result == false){
		intResult = "wrong"
	}else if(result == "neutral"){
		intResult = "neutral"
	}
	
	intInteractionIndex = actionsLMSGetValue("cmi.interactions._count");
	
	
	if(LMSAPI != null){	
		
		LMSAPI.LMSSetValue("cmi.interactions." + intInteractionIndex + ".id", intID);
		actionsLMSError("LMSSetValue","cmi.interactions." + intInteractionIndex + ".id");		
		
		LMSAPI.LMSSetValue("cmi.interactions." + intInteractionIndex + ".type", intType);
		actionsLMSError("LMSSetValue","cmi.interactions." + intInteractionIndex + ".type");
		
		LMSAPI.LMSSetValue("cmi.interactions." + intInteractionIndex + ".learner_response", userResponse);
		actionsLMSError("LMSSetValue","cmi.interactions." + intInteractionIndex + ".learner_response");
		
		LMSAPI.LMSSetValue("cmi.interactions." + intInteractionIndex + ".result", intResult);
		actionsLMSError("LMSSetValue","cmi.interactions." + intInteractionIndex + ".result");
		
		//LMSAPI.LMSSetValue("cmi.interactions." + intInteractionIndex + ".description", description);
		//actionsLMSError("LMSSetValue","cmi.interactions." + intInteractionIndex + ".description");
		
		LMSAPI.LMSSetValue("cmi.interactions." + intInteractionIndex + ".weighting", intWeighting); 
		actionsLMSError("LMSSetValue","cmi.interactions." + intInteractionIndex + ".weighting");
		
		LMSAPI.LMSSetValue("cmi.interactions." + intInteractionIndex + ".objectives.0.id", strLOID)
		actionsLMSError("LMSSetValue","cmi.interactions." + intInteractionIndex + ".objectives.0.id");
		
		if(intResult != "neutral"){
			LMSAPI.LMSSetValue("cmi.interactions." + intInteractionIndex + ".correct_responses.0.pattern", corrResponse);
			actionsLMSError("LMSSetValue","cmi.interactions." + intInteractionIndex + ".correct_responses.0.pattern");
		}
		
		LMSAPI.LMSSetValue("cmi.interactions." + intInteractionIndex + ".timestamp", intTimeStamp);
		actionsLMSError("LMSSetValue","cmi.interactions." + intInteractionIndex + ".timestamp");
		
		LMSAPI.LMSCommit('');
		actionsLMSError("LMSCommit","");
		
	}
	
}
