
//-------------------------------------------------------------
//-----------------Do not edit the XML tags--------------------
//-------------------------------------------------------------

//<Document-Level>
//<ACRO_source>PDF SCORM wrapper</ACRO_source>
//<ACRO_script>
/*********** belongs to: Document-Level:PDF SCORM wrapper ***********/



//test code to resolve resume problem
var page_reset=true; 
//whether there is page reset required from page 1 
var location_obtained = undefined;
//===================================


//Doc level

var this_obj = this;
var isJSInitialized_bln= undefined; //checks for initialization of host container
var isScormInitialized = false;


//Needed for intial load of Cp SWF
var flashvars = Array();
flashvars["scorm_api"]=0.3;
flashvars["scorm_type"]=0;
var scormVersion = 0;


var entry = ""; //to check whether session is to be resumed or not
var interaction_count = 0;
var interaction_children = "id,timestamp,type,correct_responses,weighting,learner_response,result,latency";
var score_children = "raw,min,max,scaled";


//Queue related vars
var commandPDFpage = null;
var commandQueue = Array();//queue of requests from embedded SWF
var busy_bln= false; // indicates whether an element from the queue is being currently processed
var command_current=null; //the current command from swf being executed
var RMA_current=null; //the RMA currently being serviced by the queue


var RMAsSeen = new  Array(this.numPages); //this array stores the activation status of RMAs in the document
var RMAs = new Array(this.numPages); // stores the RMA objects in the document
var current_page =0;
var timeouts = new Array(this.numPages);

var RMAPollInterval = 50; //poll interval for RMA status in ms



var CpSWFs=  new Array(this.numPages);  //for each page get the RMA index for a Cp SWF object
//the default value is -1, denoting no Cp SWF on this page
for(var i =0; i<this.numPages;++i) CpSWFs[i]=-1;

var CpSWFsCompletionStatus = new Array(this.numPages);  //for each page store the completion status of Cp SWF in it
for(var i =0; i<this.numPages;++i) CpSWFsCompletionStatus[i]= ""; // if CpSWFs[i]==-1, the completion status doesnt matter	

var CpSWFsMax_Score = new Array(this.numPages);  //for each page store the max score of Cp SWF in it
for(var i =0; i<this.numPages;++i) CpSWFsMax_Score[i]= 0; // if CpSWFs[i]==-1, the max score doesnt matter		

var CpSWFsRaw_Score = new Array(this.numPages);  //for each page store the raw score of Cp SWF in it
for(var i =0; i<this.numPages;++i) CpSWFsRaw_Score[i]= 0; // if CpSWFs[i]==-1, the raw score doesnt matter

var CpSWF_suspend_data = new Array(this.numPages); //for each page store the suspend_data of Cp SWF in it
for(var i =0; i<this.numPages;++i) CpSWF_suspend_data[i]= ""; // if CpSWFs[i]==-1, the suspend_data doesnt matter				

var pagesSeen = new Array(this.numPages); //for each page record whether its seen or not
for(var i =0; i<this.numPages;++i) pagesSeen[i]= false;

var CpSWFs_ScoreType= new Array(this.numPages);  //for each page store whether %age or score is sent for Cp SWF in it
for(var i =0; i<this.numPages;++i) CpSWFs_ScoreType[i]= -1;  // if CpSWFs[i]==-1, the score type doesnt matter. 0 is score, 1 is %age		


//completion status codes - these are stored to be used during resume of session
var completion_status_id_map = new Array();
completion_status_id_map["completed"]="0";
completion_status_id_map["incomplete"]="1";
completion_status_id_map["not attempted"]="2";
completion_status_id_map["unknown"]="3";
completion_status_id_map["passed"]="4";
completion_status_id_map["failed"]="5";
completion_status_id_map["browsed"]="6";

var id_completion_status_map = new Array();
id_completion_status_map["0"]="completed";
id_completion_status_map["1"]="incomplete";
id_completion_status_map["2"]="not attempted";
id_completion_status_map["3"]="unknown";
id_completion_status_map["4"]="passed";
id_completion_status_map["5"]="failed";
id_completion_status_map["6"]="browsed";

var  jumpToPage_timeout = undefined;

function jumpToPage()
{
	if(this.pageNum!= location_obtained) this.pageNum= location_obtained;
	else app.clearInterval(jumpToPage_timeout);
}

function getFlashvars(type_str)
{       
    //if(type_str == "scorm_api")
//app.alert("In function getFlashvars, recieved arg:"+type_str+"; returning:"+flashvars[type_str]);
    return  flashvars[type_str];
}



/*Returns boolean for whether all RMAs in the current document/or 
current page (if the 'pg' param is passed) have been
viewed or not */
function allRMAsSeen(pg)
{
	//app.alert('called:'+pg)
	var seen = true;
	if(pg!=undefined && pg != null && pg >= 0)
		{
			if(RMAsSeen[pg].indexOf(false)!= -1) seen = false;
                    //app.alert("seen:"+ seen);
			return seen;
	}
	
	for(var  i in RMAsSeen) 
		{
			if(RMAsSeen[i].indexOf(false)!= -1)
				{
					seen = false;
				break;
				}
		}
	return seen;
}

//Is the RMA object a CpSWF
function isCpSWF(RMAObj)
{
if( RMAObj.callAS("cpEIGetValue","CaptivateVersion") ) return true;
    else return false;   
}

/*Aggregates score from diff Cp SWFs.
This function returns a raw score  and a max score of 0, as long as their
is some RMA yet to be activated or some page yet to beviewed. Else returns
a sum of the raw scores and sum of max scores in a 2 element array. */
function aggregateScore()
{	
	var curr_raw_score = 0;
	var curr_max_score = 0;
//var allscorestr = "[";
	if(allRMAsSeen() && allPagesSeen()){ 
		for (var i=0;i<this.numPages;++i)
	if(CpSWFs[i]!=-1)
				{//allscorestr = allscorestr + CpSWFsRaw_Score[i]+":";
					curr_raw_score +=CpSWFsRaw_Score[i];
		curr_max_score +=CpSWFsMax_Score[i];
				}
//allscorestr = allscorestr + "]";
         //app.alert("agg score is :"+curr_raw_score+", max score:"+curr_max_score+"=="+allscorestr);
        }
	return [curr_raw_score, curr_max_score]
}

/*Determines the completion or pass/fail status of the PDF.
Completed= pass. Inccomplete  = fail.
If there all RMAs have been activated and all pages have been seen and all CP SWFs have been passed, status = completed.
Else"incomplete" */
function pdfStatus()
{
        var fa = allRMAsSeen();
        var fb = allCPSWFsComplete();
        var fc = allPagesSeen();
      //app.alert("Status:RMA seen:"+fa+",SWFs complete:"+fb+",all pages seen:"+fc);

	if( fa && fb && fc) return "completed";
	else return "incomplete";

}


function allPagesSeen()
{
	if(pagesSeen.indexOf(false)!=-1) return false;
	else return true;
}



//do all Cp SWFs have status of "complete"?
function allCPSWFsComplete()
{
//var allscorestr = "[";
	var status = true;
	for(var i =0; i<this.numPages; ++i){
       //allscorestr = allscorestr + CpSWFsCompletionStatus[i]+":";
		if(CpSWFs[i]!=-1 && CpSWFsCompletionStatus[i]!="completed")
			{
			status = false;
				break;
			}
        }
//allscorestr = allscorestr + "]";
//app.alert("all swf complete status::"+allscorestr);
return status;
}


function dummyLMS(data_ary)
{
	var strFSCmd, strFSArg1="", strFSArg2="", strFSArg3="";
	var strErr = true;

	strFSCmd  =data_ary[0];
	if(data_ary.length > 1)
		strFSArg1 = data_ary[1];
	if(data_ary.length > 2)	
		strFSArg2 = data_ary[2];
	if(data_ary.length > 3)	
strFSArg3 = data_ary[3];
	
	if( strFSCmd == "LMSInitialize" || strFSCmd=="Initialize")
	{	
		onMessageFromJS(["true"]);
	}
	else if(strFSCmd =="LMSGetValue" || strFSCmd=="GetValue")
	{
		if( strFSArg1 == "cmi.launch_data" )
		{
			onMessageFromJS([""]);
		}
	else if( strFSArg1 == "cmi.objectives._count" )
		{
			onMessageFromJS(["0"]);
		}
		else if( strFSArg1 == "cmi.entry" )
		{
		onMessageFromJS([""]);
		}
		else if( strFSArg1 == "cmi.location" || strFSArg1 =="cmi.core.lesson_location")
		{
			onMessageFromJS(["0"]);
	}
		else if( strFSArg1 == "cmi.score.raw" || strFSArg1 == "cmi.core.score.raw" )
		{
			onMessageFromJS(["0"]);
		}
		else if( strFSArg1 == "cmi.score.min" || strFSArg1 == "cmi.core.score.min" )
		{
			onMessageFromJS(["0"]);
		}
		else if( strFSArg1 == "cmi.score.max" || strFSArg1 == "cmi.core.score.max" )
		{
			onMessageFromJS(["100"]);
		}
		else if( strFSArg1 == "cmi.score.scaled" )
		{
			onMessageFromJS(["1"]);
		}
		else if( strFSArg1 == "cmi.suspend_data" )
		{
		onMessageFromJS([""]);
		}
		else if( strFSArg1 == "cmi.score._children" )
		{
			onMessageFromJS(["raw,min,max,scaled"]);
	}
		else if( strFSArg1 == "cmi.interactions._children" )
		{
			onMessageFromJS(["id,timestamp,type,correct_responses,weighting,learner_response,result,latency"]);
		}
		else if( strFSArg1 == "cmi.interactions._count" )
		{
			onMessageFromJS(["0"]);
		}else{app.alert("some get Not handled!!!"+strFSArg1);
                }
	}
	else if(strFSCmd == "LMSSetValue" || strFSCmd=="SetValue")
{
		onMessageFromJS(["true"]);
	}
	else if(strFSCmd == "LMSGetLastError" || strFSCmd == "GetLastError")
	{
           //app.alert("GetLastError");
		onMessageFromJS(["0"]);
	}
	else if(strFSCmd == "LMSGetErrorString" || strFSCmd == "GetErrorString")
	{
	onMessageFromJS([""]);
	}
        else if(strFSCmd == "Commit")
        {//app.alert("command commit handled!!!"+strFSCmd);
           onMessageFromJS(["true"]);
        }else
        {app.alert("command Not handled!!!"+strFSCmd);
            }
       
}
var jscount = 0;
//calls functions on the container JS
function sendToJS(data_ary)
{
jscount++;
	/*dummyLMS(data_ary);
	return;*/
	var retval;
  if(this_obj.hostContainer != undefined && (data_ary[0] == "Initialize" || data_ary[0] == "LMSInitialize" || data_ary[0] == "GetScormVersion"|| isScormInitialized))
    {
        retval = this_obj.hostContainer.postMessage ( data_ary );
        /*if(data_ary[0] == "Initialize" && (retval == "true"||retval))
       {app.alert("initialize success");
                        onInitialize();
            }*/
    }
}	

function onMessageDisclose()
{
    var return_bln = true;
    return return_bln;
}




//Sends out suspend data
function sendSuspendData()
{
	
	var scores = aggregateScore();
var raw_score = scores[0]; 
	var max_score = scores[1];
	var sscaled = 0;
	if(max_score != 0){
		sscaled = raw_score / max_score;
	}
	
	var status = pdfStatus();
	var pass_fail = (status == "completed")?"passed":"failed";
	var exit_status= (status == "completed")?"normal":"suspend";
var suspend_data = createSuspendData();
	
	
	if(scormVersion > 0.2)
	{
		pdfCallLMS("SetValue","cmi.exit",exit_status,"");

		pdfCallLMS("SetValue","cmi.score.min",0,"");// Whether scores needs to be sent as string ???
		pdfCallLMS("SetValue","cmi.score.max",max_score,"");
pdfCallLMS("SetValue","cmi.score.raw",raw_score,"");
		pdfCallLMS("SetValue","cmi.score.scaled",sscaled,"");

	pdfCallLMS("SetValue","cmi.completion_status",status,"");
		pdfCallLMS("SetValue","cmi.success_status",pass_fail,"");
	pdfCallLMS("SetValue","cmi.suspend_data",suspend_data,"");
		pdfCallLMS("SetValue","cmi.location",String(this.pageNum),"");
	pdfCallLMS("Commit","","","");
	}
	else if(scormVersion == 0.2)
	{//app.alert("sending 12 data");
		pdfCallLMS("LMSSetValue","cmi.core.exit",exit_status,"");

	if(max_score > 0){
                //app.alert("sending score scorm12. Max score > 0");	
                pdfCallLMS("LMSSetValue","cmi.core.score.min",0,"");// Whether scores needs to be sent as string ???
		pdfCallLMS("LMSSetValue","cmi.core.score.max",max_score,"");
		pdfCallLMS("LMSSetValue","cmi.core.score.raw",raw_score,"");

	}	pdfCallLMS("LMSSetValue","cmi.core.lesson_status",status,"");
	//pdfCallLMS("LMSSetValue","cmi.core.success_status",pass_fail,"");
		pdfCallLMS("LMSSetValue","cmi.suspend_data",suspend_data,"");
	pdfCallLMS("LMSSetValue","cmi.core.lesson_location",String(this.pageNum),"");
		pdfCallLMS("LMSCommit","","","");
	}
	
}

//get intial data on course launch
function getSuspendData()
{
	if(scormVersion > 0.2)
	{
		pdfCallLMS("GetValue","cmi.entry","","");
		pdfCallLMS("GetValue","cmi.suspend_data","","");
      pdfCallLMS("GetValue","cmi.interactions._count","","");
		
		pdfCallLMS("GetValue","cmi.location","","");

	}
	else if(scormVersion == 0.2)
	{
		pdfCallLMS("LMSGetValue","cmi.core.entry","","");
		pdfCallLMS("LMSGetValue","cmi.suspend_data","","");
		pdfCallLMS("LMSGetValue","cmi.interactions._count","","");
		pdfCallLMS("LMSGetValue","cmi.core.lesson_location","","");
	}
	//The actual processing of suspend data is done in  onMessageFromJS()
}





//===================================================
//Suspend data creation and parsing functions follow
//===================================================


/*this string becomes a part of the suspend data for the pdf
this string is a bit string with 1 denoting seen and 0 denoting notseen*/
function createPageViewString()
{
	var str = "";
	for(var i in pagesSeen)
		if(pagesSeen[i]) str+="1";
		else str+="0";
return str;

}

function parsePageViewString(str)
{
	for(var i =0; i<str.length; i++)
		pagesSeen[i] =  (str[i]=="1")?true:false;
}


/*thisstring becomes a part of the suspend data for the pdf
Concatentaion of the suspend_data of indivdual SWFs in the format "pg_index-suspend_data:...*/

function createSWFSuspendData()
{
	var all_suspend_data = new Array();
	for(var i=0;i<this.numPages;++i)
		if(CpSWFs[i]!=-1)
			all_suspend_data[all_suspend_data.length]= String(i)+"$%$"+CpSWF_suspend_data[i];
	return all_suspend_data.join(':');
}

function parseSWFSuspendData(str)
{
	if(!str || str=="") return;
	var temp = str.split(':');
	var elem;
	for(var i in temp)
		{
			elem = temp[i].split("$%$");
			CpSWF_suspend_data[parseInt(elem[0])] = elem[1];
		}
}


/*this string becomes a part of the suspend data for the pdf
Encodes the score  type of Cp SWFs in the format "pg_index - score_type: ... "
score_type can be 0 (send raw score) or 1 (send %age) */
function createScoreTypeString()
{
	var scoreTypes = new Array();
	for(var i=0;i<this.numPages;++i)
if(CpSWFs[i]!=-1)
			scoreTypes[scoreTypes.length]= String(i)+"-"+CpSWFs_ScoreType[i];
	//app.alert("joined scoreTypes:"+scoreTypes.join(':'));
    return scoreTypes.join(':');
    
}


function parseScoreTypeString(str)
{
	if(!str || str=="") return;
	var temp = str.split(':');
	var elem;
	var scoresType;
	for(var i in temp)
		{
			elem = temp[i].split("-");
			CpSWFs_ScoreType[parseInt(elem[0])] = parseInt(elem[1]);
		
		}
}








/*this string becomes a part of the suspend data for the pdf
Encodes the raw score of Cp SWFs in the format "pg_index - raw_score/max_score: ... "*/
function createScoreString()
{
	var scores = new Array();
	for(var i=0;i<this.numPages;++i)
if(CpSWFs[i]!=-1)
			scores[scores.length]= String(i)+"-"+CpSWFsRaw_Score[i]+"/"+CpSWFsMax_Score[i];
	//app.alert("joined scores:"+scores.join(':'));
    return scores.join(':');
    
}

function parseScoreString(str)
{
	if(!str || str=="") return;
	var temp = str.split(':');
	var elem;
	var scores;
	for(var i in temp)
		{
			elem = temp[i].split("-");
			var scores = elem[1].split('/');
			CpSWFsRaw_Score[parseInt(elem[0])] = parseInt(scores[0]);
		CpSWFsMax_Score[parseInt(elem[0])] = parseInt(scores[1]);
		}
}

/*this string becomes a part of the suspend data for the pdf
Encodes the completion statuses of Cp SWFs in the format "pg_index-status: ... "
status is looked up from completion_status_id_map
*/
function createStatusString()
{
	var status = new Array();
	for(var i=0;i<this.numPages;++i)
		if(CpSWFs[i]!=-1)
			{
				var temp = (CpSWFsCompletionStatus[i]=="")?"":completion_status_id_map[CpSWFsCompletionStatus[i]];
				status[status.length]= String(i)+"-"+temp;
			}
			
	return status.join(':');


}


function parseStatusString(str)
{
	if(!str || str=="") return;
	var temp = str.split(':');
	var elem , status;
	for(var i in temp)
		{
			elem = temp[i].split("-");
			status = (elem[1]=="")?"":id_completion_status_map[elem[1]];
	CpSWFsCompletionStatus[parseInt(elem[0])] = status;
		}

}



/*this string becomes a part of the suspend data for the pdf
Encodes the activated statuses of RMAs in theformat "pg_index - bit_string_for_activation: ... "
bit_string_for_activation is a string of 1s and 0s. 1 denotes activation.
*/

function createActivatedString()
{
	var activated = new Array();
	var temp;
	for(var i in RMAsSeen)
		{
			temp="";
			if(RMAsSeen[i].length==0) continue;
			for(var j=0;j<RMAsSeen[i].length; ++j)
				temp = (RMAsSeen[i][j])?"1":"0";
			activated[activated.length] = String(i)+"-"+temp;
		}
	
	return activated.join(':');
}


function parseActivatedString(str)
{
	if(!str || str=="") return;
	var temp = str.split(':');
	var elem , bitstr;
	for(var i in temp)
		{
			elem = temp[i].split("-");	
			for(var j=0; j<elem[1].length; ++j)
				RMAsSeen[parseInt(elem[0])][j] = (elem[1][j]=="1")?true:false;
		}
}



/*this string becomes a part of the suspend data for the pdf
Encodes thelocation of CpSWFs in  the format "pg_index - RMA index: ... "
*/
function createCpSWFsString()
{
	var swf_locations = new Array();
	for(var i in CpSWFs)
	if(CpSWFs[i]!=-1)
			swf_locations[swf_locations.length]=String(i)+"-"+String(CpSWFs[i]);
	return swf_locations.join(':');

}

function parseCpSWFsString(str)
{
if(!str || str=="") return;
	var temp = str.split(':');
	var elem;
	for(var i in temp)
		{
			elem = temp[i].split('-');
		CpSWFs[parseInt(elem[0])] = parseInt(elem[1]);
		}		
}



/*this string is the suspend data for the pdf
Its the concatenation of suspend_data from swfs location ofCpSWfs(1)page views string (2)score string (3) status string (3) activated string.
The strings are delinmited by '#'
*/
function createSuspendData()
{
	var suspend_data_ary = new Array(6);
	suspend_data_ary[0] = createSWFSuspendData(); 
//app.alert("SWF suspend data:"+suspend_data_ary[0]);
	suspend_data_ary[1] = createCpSWFsString();
	suspend_data_ary[2] = createScoreString();
	suspend_data_ary[3] = createStatusString();
	suspend_data_ary[4] = createActivatedString();
	suspend_data_ary[5] = createScoreTypeString();
	suspend_data_ary[6] = createPageViewString();
	
	return suspend_data_ary.join('#'); 
}


/*Parses the initial suspend data requested from the LMS.
Assigns it to respective global variables */
function parseSuspendData(str)
{
	var suspend_data_ary = str.split("#");
	
	parseSWFSuspendData(suspend_data_ary[0]); 
	parseCpSWFsString(suspend_data_ary[1]);
	parseScoreString(suspend_data_ary[2]);
	parseStatusString(suspend_data_ary[3]);
	parseActivatedString(suspend_data_ary[4]);
	parseScoreTypeString(suspend_data_ary[5]);
	parsePageViewString(suspend_data_ary[6]);

}



/*The following functions polls RMAs on the page it is invoked from to check
whether they have been activated */
function pollRMAStatus(invokingPage)
{
	//app.alert("In poll func " + invokingPage+","+current_page);
    if(invokingPage!=current_page) 
		{
 			app.clearInterval( timeouts[invokingPage]);
timeouts[invokingPage] = undefined;
                        //dnayak: why not returning here ???
                        return;
		}
	if(allRMAsSeen( invokingPage )) 
	{
		
		//app.alert("All RMAs on this page seen: "+ invokingPage);
		//if(allRMAsSeen()) app.alert("All RMAs on this document seen");
		//else app.alert("All RMAs on this document NOT seen");
		app.clearInterval(timeouts[invokingPage]);
		timeouts[invokingPage] = undefined;
		return;
	}
	//dnayak: currentRMAs are declared multiple times in each page enter. why not declare once in GLOBAL section ?
	for(var i=0; i< currentRMAscount; ++i )
	{
		//app.alert("RMA no "+i+" is in status "+ currentRMAs[i].activated);
            if(currentRMAs[i].activated) 
		{
					if( CpSWFs[invokingPage]==-1 && isCpSWF(currentRMAs[i]) ) CpSWFs[invokingPage]=i;
					RMAsSeen[invokingPage][i] = true;
					//app.alert('act '+RMAsSeen[invokingPage]);        
				}
	}
	
}	



//==========================================
//Queue related functions/Data Structures
//==========================================


//command_element creates an object that stores details of the command/call invoked by SWF
//These objects are used for synchronization, and are enqueued
function commandElement()
{
	this.command =  null;
	this.parameter = null;
	this.value = null;
	this.variable = null;
	this.PDFpage = null;
        this.source = "0";
}


function commandElement(command, parameter, value, variable, PDFpage, source)
{
	this.command =  command;
	this.parameter = parameter;
	this.value = value;
	this.variable = variable;
	this.PDFpage = PDFpage;
this.source = source;
}


function enqueue(command, parameter, value, variable, PDFpage, source)
{
	var SWFcommand = new commandElement(command, parameter, value, variable, PDFpage, source);
	commandQueue[commandQueue.length] = SWFcommand;
}
var qstr="";
function dequeue()
{
	busy_bln = false;
	//pdfdebugStr = pdfdebugStr + ","+commandQueue.length;
	if(commandQueue.length==0) 
	{
		commandPDFpage = null;
		return;
	}
	var SWFcommand = commandQueue.shift();
	commandPDFpage = SWFcommand.PDFpage;
while(commandPDFpage != this.pageNum)
{
SWFcommand = commandQueue.shift();
commandPDFpage = SWFcommand.PDFpage;
}
qstr = qstr + ",["+SWFcommand.source+","+commandQueue.length+"]";
        if(SWFcommand.source == "0")
            cpCallLMS(SWFcommand.command, SWFcommand.parameter, SWFcommand.value, SWFcommand.variable);
        else 
            pdfCallLMS(SWFcommand.command, SWFcommand.parameter, SWFcommand.value, SWFcommand.variable);
}

//==========================================
//JS Communication functions/data-structures
//==========================================


/*Looks at the current command to see whether it shouldbe blocked.
If it must be blocked, it sends the appropriate response to the SWF, dequeues, and returns strErr.
If it is not to be blocked, returns null. 
Those calls are said to be 'blocked' which are returned some predetermined fixed value. 
They are not processed in any manner.*/
function callBlock(command, parameter, value, variable)
{ //app.alert("Entered Callblock: "+command+" "+parameter+" "+value+" "+variable);
	var strFSCmd, strFSArg1, strFSArg2, strFSArg3;
	var strErr = true;

	strFSCmd  = command;
	strFSArg1 = parameter;
	strFSArg2 = value;
	strFSArg3 = variable;
	
	var isBlocked = true;
	//app.alert("callblock:"+strFSCmd+"RMACur:"+RMA_current);
//cpdebugStr = cpdebugStr + ",[callblock-"+strFSCmd+","+RMA_current+","+strFSArg3+"]";
	if( strFSCmd == "LMSInitialize" || strFSCmd=="Initialize")
	{	
		RMA_current.callAS("SetScormVariable", strFSArg3, "true");
                //app.alert("Sending init toswf:"+RMA_current+":"+strFSArg3);
        var maxscore = RMA_current.callAS("getQuizMaxScore");
		var temp = String(RMA_current.callAS("getQuizScoreAsPercent"));
		//app.alert("score type:"+temp);
                //app.alert("Max score is:"+maxscore);
                if(maxscore != undefined && maxscore != null)
                {
                    CpSWFsMax_Score[commandPDFpage] = parseInt(maxscore);
                } else app.alert("getQuizMaxScore failed");
				
				if(temp != undefined && temp != null)
				{
					if(temp=="true") CpSWFs_ScoreType[commandPDFpage] = 1;
					else CpSWFs_ScoreType[commandPDFpage] = 0;
					//app.alert("CpSWFs_ScoreType[commandPDFpage]:"+CpSWFs_ScoreType[commandPDFpage]);
				}else app.alert("getQuizScoreAsPercent failed");
	}
	else if(strFSCmd == "LMSFinish" || strFSCmd=="Terminate")
	{
		RMA_current.callAS("SetScormVariable", strFSArg3, "true");
	}
	else if (strFSCmd == "LMSCommit" || strFSCmd=="Commit")
	{
		RMA_current.callAS("SetScormVariable", strFSArg3, "true");
	}
	else if(strFSCmd == "LMSGetValue" || strFSCmd=="GetValue")
	{
		if( strFSArg1 == "cmi.launch_data" )
		{
			RMA_current.callAS("SetScormVariable", strFSArg3, "");
		}
		else if( strFSArg1 == "cmi.objectives._count" )
		{
			RMA_current.callAS("SetScormVariable", strFSArg3, "1");
		}
		else if( strFSArg1 == "cmi.entry" || strFSArg1 == "cmi.core.entry" )
		{
			RMA_current.callAS("SetScormVariable", strFSArg3, "");
		}
		else if( strFSArg1 == "cmi.location" || strFSArg1 =="cmi.core.lesson_location")
		{
	RMA_current.callAS("SetScormVariable", strFSArg3, "0");
		}
		else if( strFSArg1 == "cmi.score.raw" || strFSArg1 == "cmi.core.score.raw" )
		{
			RMA_current.callAS("SetScormVariable", strFSArg3, "0");
		}
		else if( strFSArg1 == "cmi.score.min" || strFSArg1 == "cmi.core.score.min" )
		{
			RMA_current.callAS("SetScormVariable", strFSArg3, "0");
		}
		else if( strFSArg1 == "cmi.score.max" || strFSArg1 == "cmi.core.score.max" )
		{
			RMA_current.callAS("SetScormVariable", strFSArg3, "100");
		}
		else if( strFSArg1 == "cmi.score.scaled" )
		{
			RMA_current.callAS("SetScormVariable", strFSArg3, "0");
		}
		else if( strFSArg1 == "cmi.suspend_data")
		{
		//RMA_current.callAS("SetScormVariable", strFSArg3, "");
		isBlocked = false;
		}
		else if(strFSArg1 == "cmi.core._children")//1.2 only
		{
		RMA_current.callAS("SetScormVariable", strFSArg3, "student_id,student_name,lesson_location,lesson_status,score,session_time");
		}
		else if(strFSArg1 == "cmi.core.score._children" )//1.2 only
		{
		RMA_current.callAS("SetScormVariable", strFSArg3, "raw,min,max");
		}
		else if( strFSArg1 == "cmi.score._children" )
		{
		    RMA_current.callAS("SetScormVariable", strFSArg3, "raw,min,max,scaled");
		}
		else if( strFSArg1 == "cmi.interactions._children" )
		{
            if(scormVersion > 0.2)
                RMA_current.callAS("SetScormVariable", strFSArg3, "id,timestamp,type,correct_responses,weighting,learner_response,result,latency");
            else if(scormVersion == 0.2)
                RMA_current.callAS("SetScormVariable", strFSArg3, "id,time,type,correct_responses,weighting,student_response,result,latency");
			
		}
		else if( strFSArg1 == "cmi.interactions._count" )
		{
			RMA_current.callAS("SetScormVariable", strFSArg3, "0");
		}
		else
		{
			isBlocked = false;
		}
	}
	else if(strFSCmd == "LMSSetValue" || strFSCmd=="SetValue")
	{
		if( strFSArg1 == "cmi.success_status"  )
		{
                        if(RMA_current != undefined && RMA_current != null)
			RMA_current.callAS("SetScormVariable", strFSArg3, "true");
		}
		else if( strFSArg1 == "cmi.core.lesson_location" || strFSArg1 == "cmi.location" )
		{if(RMA_current != undefined && RMA_current != null)
	RMA_current.callAS("SetScormVariable", strFSArg3, "true");
		}
		else if( strFSArg1 == "cmi.core.session_time" || strFSArg1 == "cmi.session_time" )
		{if(RMA_current != undefined && RMA_current != null)
			RMA_current.callAS("SetScormVariable", strFSArg3, "true");
		}
		else if( strFSArg1 == "cmi.exit" || strFSArg1 == "cmi.core.exit")
		{if(RMA_current != undefined && RMA_current != null)
			RMA_current.callAS("SetScormVariable", strFSArg3, "true");
		}else
                {
                    isBlocked = false;
                }
	}
        else if(strFSCmd == "LMSGetLastError" || strFSCmd=="GetLastError")
        {if(RMA_current != undefined && RMA_current != null)
            RMA_current.callAS("SetScormVariable", strFSArg3, "0");
        }
        else if(strFSCmd == "LMSGetErrorString" || strFSCmd=="GetErrorString")
        {if(RMA_current != undefined && RMA_current != null)
            RMA_current.callAS("SetScormVariable", strFSArg3, "");
        }
        else
	{	
		isBlocked = false;
	}
	
	if( isBlocked )
	{
		//dequeue();
	}
	
	
	
	return isBlocked;

}

/*The following function uses calls from SWFs to modify certain global properties, or read from some global properties,
of the PDF SCO. The calls maybe either a "get" or a "set". The call is responded to with the appropriate value.
Note that not all calls are suitable for aggregation. If a call is suitable for aggregation, this function returns true,
else false.*/
function aggregate(command, parameter, value, variable)
{
	var strFSCmd, strFSArg1, strFSArg2, strFSArg3;
	var result;
	var isAggregated= true;
	strFSCmd  = command;
	strFSArg1 = parameter;
	strFSArg2 = value;
	strFSArg3 = variable;
	
	
	if(strFSCmd == "SetValue" || strFSCmd == "LMSSetValue")
	{
//app.alert("set value from SWF:"+strFSArg1+",value:"+strFSArg2);
		if(strFSArg1 == "cmi.completion_status" || strFSArg1 == "cmi.core.lesson_status") 
		{//app.alert("set status:"+commandPDFpage+","+strFSArg2);
if(strFSArg2 == "passed")
{strFSArg2 = "completed";}
else if(strFSArg2 == "failed"){strFSArg2 = "incomplete";}
				CpSWFsCompletionStatus[commandPDFpage] = strFSArg2;
                            if(RMA_current != undefined && RMA_current != null)
				RMA_current.callAS("SetScormVariable", strFSArg3, "true");
			}
		else if( strFSArg1 == "cmi.score.raw" || strFSArg1 == "cmi.core.score.raw")	//raw --delted strFSArg1 == "cmi.score.raw" ||  from condition
			{
				if(CpSWFs_ScoreType[commandPDFpage]==1) CpSWFsRaw_Score[commandPDFpage]= CpSWFsMax_Score[commandPDFpage]*parseFloat(strFSArg2)/100;
				else CpSWFsRaw_Score[commandPDFpage]= parseInt(strFSArg2);
                //app.alert("handling cmi.score.raw:"+CpSWFsRaw_Score[commandPDFpage]);
                            if(RMA_current != undefined && RMA_current != null)
				RMA_current.callAS("SetScormVariable", strFSArg3, "true");
			}
		else if(strFSArg1 == "cmi.score.scaled")	//scaled
			{
                //app.alert('scaled:'+strFSArg2);
				var max_score = CpSWFsMax_Score[commandPDFpage];
                                var traw_score = parseFloat(strFSArg2)* max_score;
                               
                                if(RMA_current != undefined && RMA_current != null)
				    RMA_current.callAS("SetScormVariable", strFSArg3, "true");
			}
		else if(strFSArg1 == "cmi.suspend_data")	//suspend_data
			{//app.alert("set suspend data:"+commandPDFpage+","+strFSArg2);
				CpSWF_suspend_data[commandPDFpage] = strFSArg2 ;
                            if(RMA_current != undefined && RMA_current != null)
				RMA_current.callAS("SetScormVariable", strFSArg3, "true");
                            sendSuspendData();
			}
                else if(strFSArg1 == "cmi.core.score.max"||strFSArg1 == "cmi.score.max"||strFSArg1 == "cmi.score.min"||strFSArg1 == "cmi.core.score.min")	//max - delted strFSArg1 == "cmi.score.max" ||  in condition
			{
				/*
				var tmax = parseFloat(strFSArg2);
				//app.alert("CpSWFsMax_Score: "+CpSWFsMax_Score[commandPDFpage]+" , "+tmax);
				if(CpSWFsMax_Score[commandPDFpage] != tmax)
				{
					
				}*/
				
                            if(RMA_current != undefined && RMA_current != null)
								RMA_current.callAS("SetScormVariable", strFSArg3, "true");
			}
                else if(strFSArg1.indexOf("cmi.interactions.") != -1)
                {
                    isAggregated = false;
                }
				else{
				app.alert("SetValue aggregate unhandled:"+strFSArg1);
				}				
				
	}
	else if(strFSCmd == "GetValue" || strFSCmd == "LMSGetValue")
	{
		if(strFSArg1 == "cmi.suspend_data" )
		{	var sdata = CpSWF_suspend_data[commandPDFpage];
                        if(sdata == null)sdata="";
			RMA_current.callAS("SetScormVariable", strFSArg3, sdata);
                        //app.alert("Send s data :"+sdata+",commandPDFpage,"+commandPDFpage);
		}
		else app.alert("In GetValue in callblock - SetScormVariable isnt set");
	}
	
	else
	{
		isAggregated = false;
	}

	if( isAggregated )
	{
		//dequeue();
	}
	
	return isAggregated;
	
	
	
}


/*
Note that sendToJS is either invoked by sendSuspendData(), getSuspendData() or reRoute()
Accordingly handle meesages from container.
*/
var handlecount = 0;
function onMessageFromJS(result_ary)
{

    var result  = result_ary[0];
	var strFSCmd, strFSArg1, strFSArg2, strFSArg3;

	strFSCmd  = command_current.command;
	strFSArg1 = command_current.parameter;
	strFSArg2 = command_current.value;
	strFSArg3 = command_current.variable;
	
	//app.alert("onMessageFromJS:"+result_ary+",     cmd:"+strFSCmd+"   :Dataelement: "+strFSArg1);
	
	if(strFSCmd=="GetValue" || strFSCmd=="LMSGetValue")
	{
	if(strFSArg1 == "cmi.entry" || strFSArg1 == "cmi.core.entry")
		{
		//this was requested by getSuspendData()
			entry = result;
			//app.alert("get entry:"+entry);
		}
		else if(strFSArg1 == "cmi.suspend_data")
		{		
			//this was requested by getSuspendData()
			if(entry == "resume") parseSuspendData(result);
		}
		else if(strFSArg1 == "cmi.core.lesson_location" || strFSArg1 == "cmi.location")	
		{
                        location_obtained = result;
						
			if(entry == "resume"){ 
				this.pageNum = parseInt(result);
				jumpToPage_timeout = app.setInterval( "jumpToPage()",  30);  
				//app.alert("rsuming to page :"+result);
			}
		}
		else if(strFSArg1 == "cmi.interactions._count")
		{
			interaction_count = parseInt(result);
                        //app.alert("int count..:"+result_ary[0]+",parsed:"+interaction_count);
		}
		else RMA_current.callAS("SetScormVariable",strFSArg3, result);
	}
	else if(strFSCmd=="SetValue" || strFSCmd=="LMSSetValue")
	{
		if(RMA_current!=undefined && RMA_current!=null)
			RMA_current.callAS("SetScormVariable", strFSArg3, "true");
	}
	else if (strFSCmd == "LMSInitialize" || strFSCmd=="Initialize")
	{
		if(result != "true")
		{
			app.alert("SCORM API Initialization failed.");
		}
		else
		{
			onInitialize();
		}
	}
	else if ( strFSCmd == "LMSCommit" || strFSCmd=="Commit")
	{
		if(result != "true") app.alert("SCORM API Initialization failed.");
	}
	else if ( strFSCmd == "GetScormVersion")
	{
		//app.alert("pdf GetScormVersion......");
		if(result != false || result!= "false")
		{
			scormVersion = parseFloat(result);
			flashvars["scorm_api"] = scormVersion;
			//app.alert("Scorm version is:"+result+","+scormVersion);
			onScormAPI();
		}
		else
			isScormInitialized = false;
	}
	else if (result == "final_data")
	{
		app.alert("sending final data!!!");
		sendSuspendData();
	}
	
handlecount++;
	dequeue();
	
}

var cpdebugStr = "";

function Captivate_DoExternalInterface(command, parameter, value, variable)
		{
			//app.alert("Captivate_DoExternalInterface:"+command+","+parameter);
                           cpdebugStr = cpdebugStr + ",["+command+","+parameter+","+value+","+variable+"]";
                                        var curpage = this.pageNum;
                                        commandPDFpage = this.pageNum;
					var RMA_idx= CpSWFs[curpage];
                                        if(RMA_idx != -1)
					    RMA_current = RMAs[curpage][RMA_idx];//todo
                                        //else - do remove hthe request . set busy_bln = false and return
					
				
			var strErr = "true";
			
			////if (!isAPI()) return;
			
			if(!callBlock(command, parameter, value, variable))  //is this call to be blocked?
			{
				if(!aggregate(command, parameter, value, variable)) //or, is it to be aggregated?
					{
						//reRoute(command, parameter, value, variable);  //or, is it to be re-routed?
						if((command == "SetValue" || command == "LMSSetValue") && (parameter.indexOf("cmi.interactions.") != -1))
						{
							if(parameter.indexOf(".id") != -1)
							{
								interaction_count++;
							}
							var intrarr = parameter.split(".");
                                                        var intindex = (interaction_count - 1);
							var nparameter = "cmi.interactions."+intindex+"."+intrarr[3];
							//app.alert("Routing interactions:Old param:"+parameter+":new param IS:"+nparameter);
							parameter = nparameter;
						}
                        cpCallLMS(command, parameter, value, variable);
                        if(RMA_current != undefined && RMA_current != null)
                        	RMA_current.callAS("SetScormVariable", variable, "true");
					}
			}
			
			return strErr; //verify with Deepak this is the right return value
		}


var cprouteStr = "";
function cpCallLMS(command, parameter, value, variable)
		{
			//app.alert("Captivate_DoExternalInterface:"+command+","+parameter);
                        cprouteStr = cprouteStr + ",["+command+","+parameter+","+busy_bln+","+commandQueue.length+"]";

			if(busy_bln)
			{
				enqueue(command, parameter, value, variable, this.pageNum,"0");
				return;
			}
			else
				{
					busy_bln = true;
					if(commandPDFpage==null) //this is the first call to this function
					{
				commandPDFpage = this.pageNum;
					}
					var RMA_idx= CpSWFs[commandPDFpage];
                                        if(RMA_idx != -1)
					    RMA_current = RMAs[commandPDFpage][RMA_idx];//todo
                                        //else - do remove hthe request . set busy_bln = false and return
					
				}	
				
			
			command_current = new commandElement(command, parameter, value, variable, commandPDFpage,"0");
                        sendToJS([command,parameter,value,variable]);
			
		}


var pdfdebugStr = "";
function pdfCallLMS(command, parameter, value, variable)
{
	//app.alert("pdfCallsToLMS:"+command+","+parameter);
        pdfdebugStr = pdfdebugStr + ",["+command+","+parameter+","+value+","+busy_bln+","+commandQueue.length+"]";
	if(busy_bln)
	{
		enqueue(command, parameter, value, variable, this.pageNum,"1");
		return;
	}
	else
	{
		busy_bln = true;
	}	
	
	command_current = new commandElement(command, parameter, value, variable, null,"1");
	
	sendToJS([command,parameter,value,variable]);
}

//==================================
//Initial calls and codes to be run
//==================================


//app.alert(allRMAsSeen());


 if (this_obj.hostContainer != undefined)
 {
    this_obj.hostContainer.messageHandler = {};
    this_obj.hostContainer.messageHandler["onMessage"] = onMessageFromJS;
    this_obj.hostContainer.messageHandler["onDisclose"] = onMessageDisclose;

	isJSInitialized_bln = true;
}


//fill in RMAsSeen, RMAs with intial values
var tempRMAs=undefined;
for(var i =0; i<this.numPages;++i)
{
   tempRMAs =  this.getAnnotsRichMedia(i);
   if(tempRMAs && tempRMAs.length>0) 
	{
		RMAs[i] = tempRMAs;
		RMAsSeen[i] = new Array(tempRMAs.length);
		for(var j=0; j < RMAsSeen[i].length;  ++j ) RMAsSeen[i][j]  = false;
    }
}


if(isJSInitialized_bln)
{
    //this_obj.hostContainer.postMessage ( ["Initialize","","",""] );
	pdfCallLMS("GetScormVersion","","","");
}

function onScormAPI()
{
	if(scormVersion > 0.2)
		pdfCallLMS("Initialize","","","");
	else if(scormVersion == 0.2)
		pdfCallLMS("LMSInitialize","","","");
   getSuspendData();
}

function onInitialize()
{
	isScormInitialized = true;
	sendSuspendData();
}


