/*******************************************************************************
**
** Filename: SCOwrapper.js
**
** File Description: This file contains several JavaScript functions that are
**                   used by the SCORM enabled Flash Courses.
**                   These functions encapsulate actions that are taken when the
**                   user navigates between SCOs, or exits the Lesson by creating a bridge between
**                   AIPwrapper.js provided by Concurrent Technologies Corporation (CTC)
**
** Author: Hurix Systems Technical Team
**
** References: ADL SCORM
**
********************************************************************************/

var initLoadVars = "";

function loadPage(){
var result = initializeCommunication();
exitPageStatus = false; // To check if exit function is called already
lessonStatus = "incomplete"; // To set the corrent lesson status
exitStatus = "suspend"; // to save the exit status, suspend means user is going to attempt the course again
current_page = ""; // to store current location of user

lessonStatus = LMSGetValue("cmi.completion_status");
//alert("initLoadVars "+initLoadVars)
if (lessonStatus == "not attempted" || lessonStatus != "completed" ) {
		// the student is now attempting the lesson
		LMSSetValue("cmi.completion_status","incomplete");
		lessonStatus = "incomplete";
		persistData();
   }

   exitPageStatus = false;
   startTimer();

   return initLoadVars
}

//////////////////////////timer functions////////////////////////////////////
 function startTimer()
 {
    startDate = new Date().getTime();
 }
 
 function computeTime()
 {
 	var formattedTime;
 	if ( startDate != 0 )
 	{
		 var currentDate = new Date().getTime();
		 var elapsedSeconds = ( (currentDate - startDate) / 1000 );
		 formattedTime = getduration( elapsedSeconds );
 	}
 	else
 	{
 		formattedTime = "0000:00:00.0";
 	}
 	
 	LMSSetValue( "cmi.session_time", oldform2cs(formattedTime) );
 	
 	
 }
 
 function fSetDecimalPoints(num){
 	var Numvalue = String (Math.round(num * 100) / 100);
 	var dot = Numvalue.indexOf(".");
 	if(dot == -1){
 Numvalue += ".0";
 	}
 	var temp = Numvalue.split(".");
 	var addDecimals = 2 - temp[1].length;
 	for(i=1; i<= addDecimals; i++){
 Numvalue += "0";
 	}
 	return Numvalue;
 };
 function getduration(ts){
       var strTime="";
       var Hour = Math.floor(ts/3600);
       var Min   = Math.floor((ts-Hour*3600)/60);
       var Sec   = ts-Hour*3600 - Min*60;
 Sec=fSetDecimalPoints(Sec)
       if(Hour<10){
 strTime+="000";
       }else if (Hour<100){
 strTime+="00";
       }else if (Hour<1000){
 strTime+="0";
       }else{
 	Hour=9999
       }
       strTime+= Hour + ":";
       if(Min<10) strTime+="0";
       strTime+= Min + ":";
       if(Sec<10) strTime+="0";
       strTime+= Sec;
      return strTime;
 }
 
 
 //Scorm 1.2 > 2004 [TIME FORMAT]
 
 function oldform2cs(str)
 {
 	n = SCORM12DurationToCs(str);
 	if (!isNaN(n))
 	{
 		return centisecsToISODuration(n);
 	}
 }
 
 function SCORM12DurationToCs(str)
 {
 	var a=str.split(":");
 	var nS=0, n=0;
 	var nMult = 1;
 	var bErr = ((a.length < 2) || (a.length > 3));
 	if (!bErr)
 	{
 		for (i=a.length-1;i >= 0; i--)
 		{
 			n = parseFloat(a[i]);
 			if (isNaN(n))
 			{
 				bErr = true;
 				break;
 			}
 			nS += n * nMult;
 			nMult *= 60;
 		}
 	}
 	if (bErr)
 	{
 		trace ("Incorrect format: " + str + "\n\nFormat must be [HH]HH:MM:SS[.SS]");
 		return NaN;
 	}
 	return Math.round(nS * 100);
 }
 
 function centisecsToISODuration(n, bPrecise)
 {
 	var str = "P";
 	var nCs=n;
 	var nY=0, nM=0, nD=0, nH=0, nMin=0, nS=0;
 	n = Math.max(n,0);
 	var nCs = n;
 	with (Math)
 	{
 		if (bPrecise == true)
 		{
 			nD = floor(nCs / 8640000);
 		}
 		else
 		{
 			nY = floor(nCs / 3155760000);
 			nCs -= nY * 3155760000;
 			nM = floor(nCs / 262980000);
 			nCs -= nM * 262980000;
 			nD = floor(nCs / 8640000);
 		}
 		nCs -= nD * 8640000;
 		nH = floor(nCs / 360000);
 		nCs -= nH * 360000;
 		var nMin = floor(nCs /6000);
 		nCs -= nMin * 6000
 	}
 	// Now we can construct string
 	if (nY > 0) str += nY + "Y";
 	if (nM > 0) str += nM + "M";
 	if (nD > 0) str += nD + "D";
 	if ((nH > 0) || (nMin > 0) || (nCs > 0))
 	{
 		str += "T";
 		if (nH > 0) str += nH + "H";
 		if (nMin > 0) str += nMin + "M";
 		if (nCs > 0) str += (nCs / 100) + "S";
 	}
 	if (str == "P") str = "PT0H0M0S";
 	// technically PT0S should do but SCORM test suite assumes longer form.
 	return str;
}


function setLessonLocation(currentLocation, isCourseComplete){
	win_bookmark ("Q001",currentLocation);
	var current_page = currentLocation;
//	alert("lessonstatus: " + currentLocation + " : " + isCourseComplete);
	LMSSetValue("cmi.location", current_page);

	if(String(isCourseComplete) == "true"){
		lessonStatus = "completed";
		LMSSetValue("cmi.completion_status", lessonStatus);
	}
	
	persistData();
}



/*---------------------------------------------------------------------------------------------------------
// FUNCTION: to set Value of raw score obtained by user
---------------------------------------------------------------------------------------------------------*/
function setRawScore(rawScore, passingScore){
	LMSSetValue("cmi.score.raw", rawScore);
	persistData();
}
function setCourseCompleted()
{
	currlessonStatus = "completed";
//	if (LMSGetValue("cmi.completion_status") != "completed" ) 
	{
		LMSSetValue("cmi.completion_status", currlessonStatus);
		LMSSetValue("cmi.success_status", "passed");
		LMSSetValue("cmi.score.scaled",1);		
		LMSSetValue("cmi.score.max", 1);
               LMSSetValue('cmi.exit', 'normal');
	    setRawScore(1); //Setting Score to 1 temporarily for Prototype version
		
	}
	persistData();
    terminateCommunication();
}

function setScorePattern(maxScore,minScore){
	setMaxScore(maxScore);
	setMinScore(minScore);
}

/*---------------------------------------------------------------------------------------------------------
// FUNCTION: to set Value of minimum required score
---------------------------------------------------------------------------------------------------------*/
function setMinScore(minScore){
	LMSSetValue("cmi.score.min", minScore);
	persistData();
}

/*---------------------------------------------------------------------------------------------------------
// FUNCTION: to set Value of max possible score
---------------------------------------------------------------------------------------------------------*/
function setMaxScore(maxScore){
	LMSSetValue("cmi.score.max", maxScore);
	persistData();
}


/*---------------------------------------------------------------------------------------------------------
// FUNCTION: to set Value of max possible score
---------------------------------------------------------------------------------------------------------*/
function setSuspendData(suspendInfo,totalUserScore,totalCourseScore){
	LMSSetValue("cmi.suspend_data", suspendInfo);
	curUserScore = totalUserScore;
	curTotalScore = totalCourseScore;
	persistData();
}

/*---------------------------------------------------------------------------------------------------------
// FUNCTION: after user will complete entire course this function will be called
 // this function will sent status of the lesson and exit
---------------------------------------------------------------------------------------------------------*/
function completeSession(){
	exitStatus = "";
	lessonStatus = "completed";
	exitLesson();
}


function suspendSession(){
	exitStatus = "suspend";
	lessonStatus = "incomplete";
	exitLesson();
}


function exitLesson(){
	// check if exitLesson function was called before
    exitStatus = "";  /*temparary setting*/
	if(exitPageStatus == false){
		computeTime();
		if (LMSGetValue("cmi.completion_status") != "completed" ) {
			LMSSetValue("cmi.completion_status", lessonStatus);
		}
		LMSSetValue("cmi.exit", exitStatus);
		persistData();
		terminateCommunication();
		
		window.close();
		//window.opener.top.close()
		//top.close();
		exitPageStatus = true;

		
	}
}
function WriteCookie (cookieName, cookieValue, expiry) 
{  
	var expDate = new Date(); 
	if(expiry) 
	{ 
		expDate.setTime (expDate.getTime() + expiry); 
		document.cookie = cookieName + "=" + escape (cookieValue) + "; expires=" + expDate.toGMTString(); 
	} 
    else 
    { 
        document.cookie = cookieName + "=" + escape (cookieValue); 
    } 
} 

function win_bookmark(topid,catid)
{ 
	WriteCookie(topid, catid, 1000 * 60 * 60 * 24 * 2); 
} 

function win_SetScore(topid,catid)
{ 
	WriteCookie(topid, catid, 1000 * 60 * 60 * 24 * 2); 
}

function getcookie(cookiename) 
{
	var cookiestring=""+document.cookie;
	var index1=cookiestring.indexOf(cookiename);
	if (index1==-1 || cookiename=="") return ''; 
	var index2=cookiestring.indexOf(';',index1);
	if (index2==-1) index2=cookiestring.length; 
	//document.courseUI.SetVariable(flashVar, unescape(document.cookie))
	return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}

function exitPage(){

	exitLesson();
}

function openLink(page){
	windowWidth = 400;
	windowHeight = 150;
	lft = (screen.width - windowWidth)/2;
	tp =  (screen.height - windowHeight)/2;
	window.open(page,"link","width=" + windowWidth + ",height=" + windowHeight + ",left=" + lft + ",top=" + tp + ",scrollbar=no");
}
function closeWin(){
	window.top.close();
}
