/*******************************************************************************
** 
** Filename: SCOFunctions.js modified implementation of ADLNet's SCOFunctions.js
**
*******************************************************************************/

var startDate;
var exitPageStatus;
var ObjectivesArray;

function loadPage( inTotalObjectives )
{
   var result = doLMSInitialize();

   var status = doLMSGetValue( "cmi.core.lesson_status" );

   if (status == "not attempted")
   {
	  // the student is now attempting the lesson
	  doLMSSetValue( "cmi.core.lesson_status", "incomplete" );
   }

   var jumpURL = doLMSGetValue("cmi.core.lesson_location");

   initObjectives( inTotalObjectives );

   if ( (status == "incomplete" || status == "failed") && jumpURL != "") {
	   if(confirm("Do you want to continue")){
				jumpToSlide(jumpURL);
	   }
		var ObjectivesCompleted = doLMSGetValue( "cmi.suspend_data" );
		putObjectivesCompleted(ObjectivesCompleted);
   }

   exitPageStatus = false;
   startTimer();
// Disabled by Rakesh (JDM) as on 28 May 2003 for putting into the unload function
//   doContinue("completed");

}

	function jumpToSlide(index) {
		parent.frames["bottom"].location.href=index;
	}

function startTimer()
{
   startDate = new Date().getTime();
}

function computeTime()
{
   if ( startDate != 0 )
   {
      var currentDate = new Date().getTime();
      var elapsedSeconds = ( (currentDate - startDate) / 1000 );
      var formattedTime = convertTotalSeconds( elapsedSeconds );
   }
   else
   {
      formattedTime = "00:00:00.0";
   }

   doLMSSetValue( "cmi.core.session_time", formattedTime );
}

function initObjectives(inTotalObjectives) {


	ObjectivesArray = new Array(inTotalObjectives);
	for ( var i = 0; i < ObjectivesArray.length ; i++ ) {
		ObjectivesArray[i] = false;
	}
	//TotalSlides=getDivCount(SlidePrefix);
	TotalObjectives=inTotalObjectives;
	


}

function getObjectivesCompleted( ) {
	var output = "";
	var index = 0;
	for ( i = 0; i < ObjectivesArray.length ; i++ ) {
		if ( ObjectivesArray[i] == true ) {
			index = i + 1;
			output += index + ",";
		}
	}
	output = output.substr(0,output.length-1);
	return output;
}

function setObjectivesCompleted(objectiveNumber) {
	 ObjectivesArray[objectiveNumber-1] = true 
}

function putObjectivesCompleted( input ) {
	//alert("Input is " +input);
	var ObjectivesCompleted = input.split(",");
	var index = 0;
	for ( i = 0; i < ObjectivesCompleted.length ; i++ ) {
		index = parseInt(ObjectivesCompleted[i]) - 1;
		ObjectivesArray[index] = true;
	}
}


function allObjectivesCompleted( ) {
	var flagCourseCompleted = true;
		for ( i = 0; i < ObjectivesArray.length ; i++ ) {
		 if ( ObjectivesArray[i] == false) {
				flagCourseCompleted = false;
			break;
		}
	}

	return flagCourseCompleted;
}

function doBack()
{
   doLMSSetValue( "cmi.core.exit", "suspend" );

   computeTime();
   exitPageStatus = true;
   
   var result;

   result = doLMSCommit();

	// NOTE: LMSFinish will unload the current SCO.  All processing
	//       relative to the current page must be performed prior
	//		 to calling LMSFinish.   
   
   result = doLMSFinish();

}

function doContinue( status )
{
   // Reinitialize Exit to blank
   doLMSSetValue( "cmi.core.exit", "" );

   var mode = doLMSGetValue( "cmi.core.lesson_mode" );

   if ( mode != "review"  &&  mode != "browse" )
   { 
      doLMSSetValue( "cmi.core.lesson_status", status );
	  doLMSSetValue( "cmi.core.lesson_location", "");
	  doLMSSetValue( "cmi.suspend_data", "" );
   }
 
   computeTime();
   exitPageStatus = true;
   
   var result;
   result = doLMSCommit();
	// NOTE: LMSFinish will unload the current SCO.  All processing
	//       relative to the current page must be performed prior
	//		 to calling LMSFinish.   

   result = doLMSFinish();

}

function doQuit()
{
   //alert("doQuit()");
   doLMSSetValue( "cmi.core.exit", "suspend" );

   var ObjectivesCompleted = getObjectivesCompleted();
   //alert("Output is " + ObjectivesCompleted);

   doLMSSetValue( "cmi.suspend_data", ObjectivesCompleted );
   computeTime();
   exitPageStatus = true;
   
   var result;

   result = doLMSCommit();

	// NOTE: LMSFinish will unload the current SCO.  All processing
	//       relative to the current page must be performed prior
	//		 to calling LMSFinish.   

   result = doLMSFinish();
}

/*******************************************************************************
** The purpose of this function is to handle cases where the current SCO may be 
** unloaded via some user action other than using the navigation controls 
** embedded in the content.   This function will be called every time an SCO
** is unloaded.  If the user has caused the page to be unloaded through the
** preferred SCO control mechanisms, the value of the "exitPageStatus" var
** will be true so we'll just allow the page to be unloaded.   If the value
** of "exitPageStatus" is false, we know the user caused to the page to be
** unloaded through use of some other mechanism... most likely the back
** button on the browser.  We'll handle this situation the same way we 
** would handle a "quit" - as in the user pressing the SCO's quit button.
*******************************************************************************/
function unloadPage()
{
	//This fucntion is called form the Main Frame set on Unload
	setBookmark();
	if ( allObjectivesCompleted() == true ) {
		doContinue("completed");
	} else if (exitPageStatus != true) {
		doQuit();
	}

	// NOTE:  don't return anything that resembles a javascript
	//		  string from this function or IE will take the
	//		  liberty of displaying a confirm message box.
	
}


// Written By Rakesh (JDM) 28 May 2003 for LRN Courses 

function UnloadComplete( ) {
	// put by Rakesh (JDM) as on 28 May 2003
	doContinue("completed");
	unloadPage();
}
// Written By Rakesh (JDM) 13 Sep 2002 for LRN Courses 

function UnloadCommit( ) {
	result = doLMSCommit();
}

function loadMultiPageInitStartup( ) {

   var result = doLMSInitialize();

   var status = doLMSGetValue( "cmi.core.lesson_status" );

   if (status == "not attempted")
   {
	  // the student is now attempting the lesson
	  doLMSSetValue( "cmi.core.lesson_status", "incomplete" );
   }

   var location = doLMSGetValue( "cmi.core.lesson_location" );
	
   exitPageStatus = false;
   startTimer();

	var url = window.location.href;
	var urlArry = url.split("/");

    if ( location != "" ) {
		window.location.href = location;
	}


}

function setBookmark(){
//Call this on Load of all start pages for the lesson
	url=parent.frames["bottom"].location.toString();
	var urlArry = url.split("/");
	doLMSSetValue( "cmi.core.lesson_location", urlArry[urlArry.length - 1]);
}

function loadMultiPageStartup( ) {

   var result = doLMSInitialize();

   var status = doLMSGetValue( "cmi.core.lesson_status" );

   if (status == "not attempted")
   {
	  // the student is now attempting the lesson
	  doLMSSetValue( "cmi.core.lesson_status", "incomplete" );
   }

	var url = window.location.href;
	var urlArry = url.split("/");
	doLMSSetValue( "cmi.core.lesson_location", urlArry[urlArry.length - 1]);

   startTimer();
   exitPageStatus = false;

}


/*******************************************************************************
** this function will convert seconds into hours, minutes, and seconds in
** CMITimespan type format - HHHH:MM:SS.SS (Hours has a max of 4 digits &
** Min of 2 digits
*******************************************************************************/
function convertTotalSeconds(ts)
{
   var sec = (ts % 60);

   ts -= sec;
   var tmp = (ts % 3600);  //# of seconds in the total # of minutes
   ts -= tmp;              //# of seconds in the total # of hours

   // convert seconds to conform to CMITimespan type (e.g. SS.00)
   sec = Math.round(sec*100)/100;
   
   var strSec = new String(sec);
   var strWholeSec = strSec;
   var strFractionSec = "";

   if (strSec.indexOf(".") != -1)
   {
      strWholeSec =  strSec.substring(0, strSec.indexOf("."));
      strFractionSec = strSec.substring(strSec.indexOf(".")+1, strSec.length);
   }
   
   if (strWholeSec.length < 2)
   {
      strWholeSec = "0" + strWholeSec;
   }
   strSec = strWholeSec;
   
   if (strFractionSec.length)
   {
      strSec = strSec+ "." + strFractionSec;
   }


   if ((ts % 3600) != 0 )
      var hour = 0;
   else var hour = (ts / 3600);
   if ( (tmp % 60) != 0 )
      var min = 0;
   else var min = (tmp / 60);

   if ((new String(hour)).length < 2)
      hour = "0"+hour;
   if ((new String(min)).length < 2)
      min = "0"+min;

   var rtnVal = hour+":"+min+":"+strSec;

   return rtnVal;
}


/*******************************************************************************
** this function will check if the assessment is already taken and if so
** then will just echo the Score, Else it will post the score in the LMS 
** 
*******************************************************************************/

function postScore( rawScore ) {
	rawScore = parseInt(rawScore);
	//alert("rawScore = "+rawScore);
	var student_id = doLMSGetValue("cmi.core.student_id");
	if ( null != student_id && student_id != "" && student_id !='') {
	//if ( 1 == 1) {
		var oldrawScore = doLMSGetValue( "cmi.core.score.raw" );
		//alert("Old Raw Score "+oldrawScore );
		if ( oldrawScore == "" || null == oldrawScore ) {
			// No previous record setting the score 
			doLMSSetValue( "cmi.core.score.max", "100");
			doLMSSetValue( "cmi.core.score.raw", rawScore );
			doLMSCommit();
			displayMessage( "This lesson is complete. You have scored "+rawScore+" %");
		} else {
			displayMessage( "You have scored "+rawScore+" %. This score will not be recorded.<br>Your recorded score is "+oldrawScore+" %");
			//alert("You have already taken the assement and hence your score will not be counted again\nYou have answered "+rawScore+" % questions correctly in this session");
		}
		
	} else {
		if (_Debug == true ) {
			alert("Due to some error with the LMS Communication your score could not be posted \nYou have scored "+rawScore+" %");
		} else {
			alert("Due to some error with the LMS Communication your score could not be posted");
		}
	}



}

function displayMessage( message ) {
	document.write("<link href=\"../resources/all.css\" rel=\"stylesheet\" type=\"text/css\" />");
	document.write("<table class=\"messageBox\" width=\"100%\" height=\"100%\" align=\"center\">");
	document.write("<tr><td align=\"center\" valign=\"middle\">");
	document.write(message);
	document.write("</td></tr></table>");

}

/*******************************************************************************
** this function will check if the assessment is already taken and if so
** then will just echo the Score, Else it will post the score in the LMS 
** 
*******************************************************************************/

function postObjective( scoID,rawScore ) {
	rawScore = parseInt(rawScore);
	//alert("rawScore = "+rawScore);
	var student_id = doLMSGetValue("cmi.core.student_id");
	if ( null != student_id && student_id != "" && student_id !='') {

		//get the total no of objectives in the SCO till now.
		var objectiveCount = doLMSGetValue( "cmi.objectives._count");

		if ( null == objectiveCount || objectiveCount == "" ) {

			// This is the first Objective i.e objective no "0"

			objectiveCount = 0;

		} else {
			objectiveCount = parseInt(objectiveCount);
		}
		

		doLMSSetValue("cmi.objectives."+objectiveCount+".id", "SCO"+scoID+"_Objective"+objectiveCount+1);

		// getting the childrens of Objective
		var objectiveChildren = doLMSGetValue("cmi.objectives._children");

		if ( objectiveChildren.indexOf("status") != -1 ) {
			doLMSSetValue("cmi.objectives."+objectiveCount+".id", "completed");
		}

		if ( objectiveChildren.indexOf("score") != -1 ) {
			doLMSSetValue("cmi.objectives."+objectiveCount+".score.max", "100");
			doLMSSetValue("cmi.objectives."+objectiveCount+".score.min", "0");
			doLMSSetValue("cmi.objectives."+objectiveCount+".score.raw", rawScore);
			doLMSCommit( );
			//alert("Total no of objectives now : " +doLMSGetValue("cmi.objectives._count"));
		}

		if ( rawScore > 50 ) {
			displayMessage( "You have completed the Objective. Please continue with the lesson.<br>You have scored "+rawScore+" % " );
		} else {
			displayMessage( "You have not fared well in the Objective. It is suggested that you review this lesson" );
		}
		
	} else {
		if (_Debug == true ) {
			alert("Due to some error with the LMS Communication your score could not be posted \nYou have scored "+rawScore+" % ");
		} else {
			alert("Due to some error with the LMS Communication your score could not be posted");
		}
	}

}