/* SCORM 2004 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_1484_11 == 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_1484_11;
}

/*
	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()
{

    var theAPI = actionsFindAPI(window);

    if ((theAPI == null) && (parent != null) && (typeof(parent) != "undefined")){
        theAPI = actionsFindAPI(parent);
    }
    if ((theAPI == null) && (parent.parent != null) && (typeof(parent.parent) != "undefined")){
        theAPI = actionsFindAPI(parent.parent);
    }
    if ((theAPI == null) && (parent.parent.parent != null) && (typeof(parent.parent.parent) != "undefined")){
        theAPI = actionsFindAPI(parent.parent.parent);
    }
    if ((theAPI == null) && (parent.parent.parent.parent != null) && (typeof(parent.parent.parent.parent) != "undefined")){
        theAPI = actionsFindAPI(parent.parent.parent.parent);
    }
    if ((theAPI == null) && (window.opener != null) && (typeof(window.opener) != "undefined")){
        theAPI = actionsFindAPI(window.opener);
    }
    if ((theAPI == null) && (parent.window != null) && (parent.window.opener != null) && (typeof(parent.window.opener) != "undefined")){
        theAPI = actionsFindAPI(parent.window.opener);
    }
    if ((theAPI == null) && (top.opener != null) && (top.opener.top != null) && (top.opener.top.opener != null) && (typeof(top.opener.top.opener) != "undefined")){   
        theAPI = actionsFindAPI(top.opener.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.Initialize("");
		/* 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.completion_status');			
			/* check status completion flag variable */
			if((less_status == lms_pass_status1) || (less_status == lms_pass_status2)){			
				/* do nothing */
			}else{					
				 actionsLMSSetValue('cmi.completion_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.Finish('');
			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.Commit('');
		//console.log("commit sent")
		/* 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.SetValue(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.GetValue(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.GetLastError();
		if (result != 0) {
			var errorString = errLMS + errArg + "<br><br>" + result + " - " + LMSAPI.GetErrorString(result);
			var errorString2 = LMSAPI.GetDiagnostic(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)
{
    if(document.setScoreToLMS){
	   actionsLMSSetValue('cmi.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.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) 
{	
	//console.log("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.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.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.completion_status',lms_fail_status);
		int_tracking.int_lesson_status = lms_fail_status;
		actionsLMSSetValue('cmi.success_status',lms_success_unkown);
	}
	/* 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.completion_status',lms_pass_status1);
			int_tracking.int_lesson_status = lms_pass_status1;
			actionsLMSSetValue('cmi.success_status',lms_pass_status2);
		}
		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.completion_status');
}

/*
	Function: actionsLMSSetSessionTime
	Arguments: CMITimeSpan string
	Description: calls function to set the session time in the LMS
	Returns: none
*/
function actionsLMSSetSessionTime(n) 
{
	actionsLMSSetValue('cmi.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.learner_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.learner_name');
}



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

	
	if(result){
		intResult = "correct"
	}else{
		intResult = "incorrect"
	}
	
	intInteractionIndex = actionsLMSGetValue("cmi.interactions._count");
	
	
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".id", intID);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".type", intType);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".learner_response", userResponse);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".result", intResult);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".correct_responses.0.pattern", corrResponse);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".description", description);
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".weighting", intWeighting); 
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".objectives.0.id", strLOID)
	actionsLMSSetValue("cmi.interactions." + intInteractionIndex + ".timestamp", intTimeStamp);
	
}