// © Edu-Performance Canada Inc., 1997-2007 (All rights reserved.)
// Warning : This computer program is protected by copyright law and 
// international treaties. Unauthorized reproduction or distribution 
// of this program, or any portion of it, may result in severe civil  
// and criminal penalties, and will be prosecuted to the maximum 
// extent possible under the law.

// © Edu-Performance Canada inc., 1997-2007 (Tous droits réservés.)
// Avertissement : ce logiciel est protégé par la loi du copyright et
// par les conventions internationales. Toute reproduction ou distribution
// partielle ou totale du logiciel, par quelque moyen que ce soit, est 
// strictement interdite. Toute personne ne respectant pas ces dispositions
// se rendra coupable du délit de contrefaçon et sera passible des sanctions
// pénales prévues par la loi.

///////////////////////////////////////////////////////////////////
// anciennement dans general.js
///////////////////////////////////////////////////////////////////

var isSCOLaunchedOuterWindow = true;
var isFinishLMSSessionAlreadyCalled = false;

var runTimeEnvNone = 0; // None
var runTimeEnvAICC = 1; // AICC
var runTimeEnvSCORM12 = 2; // SCORM 1.2
var runTimeEnvSCORM13 = 3; // SCORM 1.3

var LMS_API_MODE = 0;
var TACTIC_JAVA_API_MODE = 1;
var TACTIC_XML_HTTP_API_MODE = 2;
var trackingAPIMode = LMS_API_MODE;

var tocManager = null;

//////////////////////////////////////////////
// Paramètres de navigateurs

// Versions de fureteurs
var IE_NONE = "0"; // Aucun
var IE_5_0 = "5.0"; // IE 5.0
var IE_5_5 = "5.5"; // IE 5.5
var IE_6_0 = "6.0"; // IE 6.0
var IE_7_0 = "7.0"; // IE 7.0

var is_ie4up = false;
var is_nav4up = false;
var is_nav5up = false;
var is_ie4 = false;

function initBrowserParams(){
  this.browserName = navigator.userAgent.toLowerCase();
  if(this.browserName.indexOf('msie')>=0)
    this.cursorPointer = "hand";
}

function browserParamsMgr()
{
  this.browserName;
  this.cursorPointer = "pointer";

  this.init = initBrowserParams;
}

var browserParamsManager = new browserParamsMgr();
browserParamsManager.init();

//////////////////////////////////////////////

function checkForCorrectBrowser(stringToDisplay, stringToDisplayForIE)
{
  // convert all characters to lowercase to simplify testing 
  var agt=navigator.userAgent.toLowerCase(); 
  var is_major = parseInt(navigator.appVersion); 
  var is_minor = parseFloat(navigator.appVersion); 

  // Note: Opera and WebTV spoof Navigator.  We do strict client detection. 
  // If you want to allow spoofing, take out the tests for opera and webtv. 
  var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1) 
              && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1) 
              && (agt.indexOf('webtv')==-1)); 
  is_nav4up = (is_nav && ((is_minor >= 4.04))); 
  is_nav5up = (is_nav && (is_major >= 5)); 

  var is_ie   = (agt.indexOf("msie") != -1); 
  is_ie4up  = (is_ie  && (is_major >= 4)); 
  is_ie4 = (is_ie && (is_major == 4));
  
  if ( !is_ie4up && !is_nav4up)
  {
    document.write('<CENTER><H1>'+stringToDisplay+'</H1></CENTER>');
  }
  else if (is_ie && parseFloat(pubIEVersion) > getIEVersion())
  {
    document.write('<CENTER><H1>'+stringToDisplayForIE.replace(/@@@/i, pubIEVersion)+'</H1></CENTER>');
  }
}

function getIEVersion()
{
	// convert all characters to lowercase to simplify testing 
	var agt=navigator.userAgent.toLowerCase(); 
	var is_ie   = (agt.indexOf("msie") != -1);
	var IEVersion = 0;
	if (is_ie)
		IEVersion = parseFloat(navigator.appVersion.substr(navigator.appVersion.indexOf("MSIE")+5,3));
	
	return   IEVersion;
}

function ResizeWin(){
	if(!window.saveInnerWidth ){ 
		window.onresize = resize;
		window.saveInnerWidth = window.innerWidth;
		window.saveInnerHeight = window.innerHeight;
	}
}

function resize(){ 
	if (saveInnerWidth < window.innerWidth || 
	    saveInnerWidth > window.innerWidth || 
	    saveInnerHeight > window.innerHeight || 
	    saveInnerHeight < window.innerHeight ){ 
			window.location.reload(); 
	}
}

function CloseSession(win)
{
	if(!isSCOLaunchedOuterWindow && (win.parent != null) && (win.parent.TOC != null))
		win.parent.TOC.FinishLMSSession();
	else
		win.top.close(); 
}

///////////////////////////////////////////////////////////////////
// Communication AICC/SCORM via xml-http
///////////////////////////////////////////////////////////////////

function extractFromAICCDataStr(aiccTable, param)
{
	var i;
	for(i=0; i<aiccTable.length; i++)
	{
		var aiccLineUpperCase = aiccTable[i].toUpperCase();
		var paramUpperCase = param.toUpperCase();
		if(aiccLineUpperCase.indexOf(paramUpperCase) != -1)
		{
			if((param == "[CORE_LESSON]") || (param == "[SUSPEND_DATA]"))
			{
				if(aiccTable[i+1].length == 1)
					return "";
				return aiccTable[i+1];
			}
			else
			{
				var dataStartIndex = aiccTable[i].indexOf("=")+1;
				var dataEndIndex = aiccTable[i].length;
				return aiccTable[i].substring(dataStartIndex, dataEndIndex);
			}
		}
	}
	
	return "";
}

function xmlHttpLMSInitialize()
{
	var commandValue = "getparam";
	var aiccData = "";
	var strXMLCmd = this.postUrl +"?command="+ commandValue +"&session_id="+ this.sessionId +"&version="+ this.versionValue +"&aiccdata="+ aiccData
	this.oXMLHTTP.open("GET", strXMLCmd, false)
	this.oXMLHTTP.send()
	var aiccData = new String(this.oXMLHTTP.responseText);
//alert(aiccData);
	aiccData.replace(aiccData, "\r\n", "\n");
	var aiccTable = aiccData.split("\n");
	this.lesson_status = this.extractAICCData(aiccTable, "Lesson_Status");
	this.lesson_location = this.extractAICCData(aiccTable, "Lesson_Location");
	this.score = this.extractAICCData(aiccTable, "Score");
	this.time = this.extractAICCData(aiccTable, "Time");
	this.suspend_data = this.extractAICCData(aiccTable, "[SUSPEND_DATA]");
	if(this.suspend_data == "")
		this.suspend_data = this.extractAICCData(aiccTable, "[CORE_LESSON]");								
}

function xmlHttpLMSFinish()
{
	var commandValue = "exitau";
	var strXMLCmd = this.postUrl +"?command="+ commandValue +"&session_id="+ this.sessionId +"&version="+ this.versionValue +"&aiccdata="
	this.oXMLHTTP.open("POST", strXMLCmd, false)
	this.oXMLHTTP.send()
}

function xmlHttpLMSSetValue(param, value)
{
	if(param == "cmi.core.lesson_status")
		this.lesson_status = value;
	else if(param == "cmi.core.lesson_location")
		this.lesson_location = value;
	else if(param == "cmi.core.score.raw")
		this.score = value;	
	else if(param == "cmi.core.time")
		this.time = value;		
	else if(param == "cmi.suspend_data")
		this.suspend_data = value;
	else if(param.indexOf("cmi.interactions")>-1)	
	{
// Interactions non-supportées
/*
		var splitInteraction = param.split(".");
		var interactionNo = splitInteraction[2];
		if(this.interactions.length == interactionNo)
			this.interactions[interactionNo] = new interaction;
		if(splitInteraction[3] == "type")
			this.interactions[interactionNo].type = value;
		if(splitInteraction[3] == "id")
			this.interactions[interactionNo].id = value;
		if(splitInteraction[3] == "correct_responses.0.pattern")
			this.interactions[interactionNo].correct_responses_0_pattern = value;
		if(splitInteraction[3] == "student_response")
			this.interactions[interactionNo].student_response = value;
		if(splitInteraction[3] == "result")
			this.interactions[interactionNo].result = value;
*/
	}
}

function xmlHttpLMSCommit()
{
	var commandValue = "putparam";
// suspend_data vs core_lesson
//	var aiccData = escape("[core]\r\nlesson_status="+this.lesson_status+"\r\nlesson_location="+this.lesson_location+"\r\nscore="+this.score+"\r\ntime="+this.time+"\r\n[suspend_data]\r\n"+this.suspend_data+"\r\n");
	var aiccData = escape("[core]\r\nlesson_status="+this.lesson_status+"\r\nlesson_location="+this.lesson_location+"\r\nscore="+this.score+"\r\ntime="+this.time+"\r\n[core_lesson]\r\n"+this.suspend_data+"\r\n");
	var strXMLCmd = this.postUrl +"?command="+ commandValue +"&session_id="+ this.sessionId +"&version="+ this.versionValue +"&AICC_Data="+ aiccData
//alert(unescape(strXMLCmd));
	this.oXMLHTTP.open("POST", strXMLCmd, false)
	this.oXMLHTTP.send()
}

function xmlHttpLMSGetValue(param)
{
	if(param == "cmi.core.lesson_status")
		return this.lesson_status;
	else if(param == "cmi.core.lesson_location")
		return this.lesson_location;
	else if(param == "cmi.core.score.raw")
		return this.score;	
	else if(param == "cmi.core.time")
		return this.time;		
	else if(param == "cmi.suspend_data")
		return this.suspend_data;			
	else
		return "";
}

/*
function interaction()
{
	this.type = "";
	this.id = "";
	this.correct_responses_0_pattern = "";
	this.student_response = "";
	this.result = "";
}
*/

function xmlHttpAPI(lmsCatcherUrl, lmsSessionId)
{
	this.oXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP");
	this.sessionId = lmsSessionId;
	this.postUrl = lmsCatcherUrl;
	this.versionValue = "AICC+3.0.1";
	
	this.LMSInitialize = xmlHttpLMSInitialize;
	this.LMSFinish = xmlHttpLMSFinish;
	this.LMSSetValue = xmlHttpLMSSetValue;
	this.LMSGetValue = xmlHttpLMSGetValue;							
	this.LMSCommit = xmlHttpLMSCommit;
	
	this.extractAICCData = extractFromAICCDataStr;

	this.lesson_status = "";
	this.lesson_location = "";
	this.score = "";
	this.time = "";
	this.suspend_data = "";

//	this.interactions = new Array();
}

///////////////////////////////////////////////////////////////////


/******************************************************************************************
** Function isCMIContext(win)
** Inputs:	win
** Output:	boolean indicationg if it is a CMI context (the aicc_sid and the AICC_URL existe in URL)
** Description: This function determin if it is a CMI context or not, by parsing the 
**				window url. if it is CMI context, this function create un applet that contain 
**				an interface to comunicate with LMS.
**				supported window hierarchy, in the following order
**					1. The current window
**					2. All the parent of the current window
******************************************************************************************/
function isCMIContext(win) { 
	var URLQuery="", upperCaseURLQuery, aiccURL="", sessionID="", api=null, url=win.document.location+"";  
	pos=url.indexOf("#")
	if (pos==-1) pos=url.indexOf("?")
	if (pos>-1) URLQuery=url.substring(pos+1,url.length)
	URLQuery = unescape(URLQuery);
	upperCaseURLQuery=URLQuery.toUpperCase()
	if (upperCaseURLQuery.indexOf("AICC-SID")>-1) {
		alert("Lesson Server version incompatible.  Your administrator must upgrade to the latest version.");
		return false;
	}
	if ((pos=upperCaseURLQuery.indexOf("AICC_SID"))>-1) {
		sessionID=URLQuery.substring(pos+9,URLQuery.length)
		if (sessionID.indexOf("&")>0)
		sessionID=sessionID.substring(0,sessionID.indexOf("&"))
	}
	if ((pos=upperCaseURLQuery.indexOf("AICC_URL"))>-1) {
		aiccURL=URLQuery.substring(pos+9,URLQuery.length)
		if (aiccURL.indexOf("&")>0)
			aiccURL=aiccURL.substring(0,aiccURL.indexOf("&"))
		if ((aiccURL.indexOf("http://") == -1) && (aiccURL.indexOf("file://") == -1))
			aiccURL = "http://" + aiccURL; // on tente par http
	}
	if (aiccURL=="" || sessionID=="")
	{
		if (win == window.top) 
			return false;
		return isCMIContext(win.parent)
	}
	else 
	{
		if(trackingAPIMode == TACTIC_JAVA_API_MODE)
			document.write("<APPLET code=brwlms_api.class HEIGHT=0 ID=API NAME=API WIDTH=0 MAYSCRIPT='true'><PARAM NAME='url' VALUE='" + aiccURL + "'><PARAM NAME='sid' VALUE='" + sessionID + "'><PARAM NAME='version' VALUE='2.0'></APPLET>");
		else if(trackingAPIMode == TACTIC_XML_HTTP_API_MODE)
			document.API = new xmlHttpAPI(aiccURL, sessionID);
		else
			return false;			
		return true;
	}
} 

/******************************************************************************************
**
** Function findAPI(win)
** Inputs:	win - a Window Object
** Return:	If an API object is found, it is returned, otherwise null is returned.
**
** Description:
** This function looks for an object named API in the supported window hierarchy, 
** 
******************************************************************************************/
var _Debug = false;
function findAPI(win) 
{
   // Search the window hierarchy for an object named "API"  
   // Look in the current window (win) and recursively look in any child frames

   if (_Debug)
   {
      alert("win is: "+win.location.href);
   }

   if(runTimeEnvType >= runTimeEnvSCORM13)
   {
      if (win.API_1484_11 != null)
      {
         if (_Debug)
         {
            alert("found api in this window");
         }
         return win.API_1484_11;
      }
      // pour NS4
      else if (win.document.API_1484_11 != null)
      {
         if (_Debug)
         {
            alert("found api in this window");
         }
         return win.document.API_1484_11;
      }
   }

   if(runTimeEnvType <= runTimeEnvSCORM12)
   {
      if (win.API != null)
      {
         if (_Debug)
         {
            alert("found api in this window");
         }
         return win.API;
      }
      // pour NS4
      else if (win.document.API != null)
      {
         if (_Debug)
         {
            alert("found api in this window");
         }
         return win.document.API;
      }
   }

   if (win.length > 0)  // does the window have frames?
   {
      if (_Debug)
      {
         alert("looking for api in windows frames");
      }

      for (var i=0;i<win.length;i++)
      {
         if (_Debug)
         {
            alert("looking for api in frames["+i+"]");
         }
         var theAPI = findAPI(win.frames[i]);
         if (theAPI != null)
         {
            return theAPI;
         }
      }
   }

   if (_Debug)
   {
      alert("didn't find api in this window (or its children)");
   }
   return null;
}

/******************************************************************************************
**
** Function getAPI()
** Inputs:	none
** Return:	If an API object is found, it is returned, otherwise null is returned.
**
** Description:
** This function looks for an object named API, first in the current window's hierarchy, 
**  and then, if necessary, in the current window's opener window hierarchy (if there is
**  an opener window).
******************************************************************************************/
function getAPI()
{
//alert('getAPI called!');
   // start at the topmost window - findAPI will recurse down through
   // all of the child frames
   var theAPI = findAPI(this.top);

   if (theAPI == null)
   {
      // the API wasn't found in the current window's hierarchy.  If the
      // current window has an opener (was launched by another window),
      // check the opener's window hierarchy. 
      if (_Debug)
      {
         alert("checking to see if this window has an opener");
         alert("window.opener typeof is> "+typeof(window.opener));
      }

      if (typeof(this.opener) != "undefined")
      {
         if (_Debug)
         {
            alert("checking this windows opener");
         }
         if (this.opener != null)
         {
            if (_Debug)
            {
               alert("this windows opener is NOT null - looking there");
            }
            theAPI = findAPI(this.opener);
         }
         else
         {
            if (_Debug)
            {
               alert("this windows opener is null");
            }
         }
      }
   }

   return theAPI;
}


/******************************************************************************************
** Function StringToArray(pathstr)
** Inputs:	String that represente the path of the document (e.g, [1,0,3])
** Output:	the convertion of the string to an initilized array object.
** Description: parses the string and create an array object initialized with the values
**				contained in the string (e.g, Array("1","0","3")).
******************************************************************************************/
function StringToArray(pathstr){
	arrpath = new Array();
	var i=0, pos, pos2, nb;
	pathstr=pathstr+"";
	pos = pathstr.indexOf("[");
	pathstr = pathstr.substring(parseInt(pos+1),pathstr.length);
	do{
		pos=pathstr.indexOf(",");
		if (pos == parseInt("-1")){	
			pathstr = pathstr.substring(0, pathstr.indexOf("]"));
			nb = pathstr;
		}else{
			nb = pathstr.substring(0,pos);
			pathstr = pathstr.substring(pos+1, pathstr.length);
		}

		// Netscape met des guillemets parfois, il faut les enlever
	        pos2 = nb.indexOf("\"");
	        if(pos2 != -1)
                   nb = nb.substring(parseInt(pos2)+1,nb.length-1);

		arrpath[i] = parseInt(nb);
		i++;
	}while( parseInt(pos) != parseInt("-1"));
	return arrpath;
}

/******************************************************************************************
** Function ConvertTimeToSecond()
** Inputs:
** Output: time in seconds elapsed since 01/01/1970 from now.
** Description: 
******************************************************************************************/
function ConvertTimeToSecond(){	
	var ss = new Date();

	return Math.round(ss/1000);
}

/******************************************************************************************
** Function getTimeDiff(startTime,endTime)
** Inputs: startTime and endTime in seconds since 01/01/1970.
** Output: time string as "HH:MM:SS"/ For SCORM1.3 PT..H..M..S
** Description: 
******************************************************************************************/
function getTimeDiff(s1,s2){
	var strTime = "",
		d = s2 - s1,
		hh = Math.floor(d/3600),
		mm = Math.floor(d/60) - hh*60,
		ss = d % 60;
	if((parent != null) && (parent.runTimeEnvType != null) &&  (parent.runTimeEnvType >= runTimeEnvSCORM13))
	{	
		strTime= "PT"
		if(hh>0)
			strTime+= hh + "H";
		if(mm>0)	
			strTime+= mm+ "M";
		if(ss>0)
			strTime+=  Math.round(ss*100)/100 + "S";
	}
	else
	{
		if(hh<10)
			strTime+= "0"; 
		strTime+= (hh +":");
		if(mm<10)
			strTime+= "0"; 
		strTime+= mm + ":";
		if(ss<10)
			strTime+= "0"; 
		strTime+= ss;
	}
	return strTime;
}


///////////////////////////////////////////////////////////////////////

function rollover(doc, id, newImg, isOver)
{
	if(doc.getElementById(id))
		doc.getElementById(id).src = newImg;
	if(isOver)
		doc.getElementById(id).style.cursor=browserParamsManager.cursorPointer;
	else
		doc.getElementById(id).style.cursor="default";
}


///////////////////////////////////////////////////////////////////////
// Banners


var TOP_BANNER = 0;
var BOTTOM_BANNER = 1;
var BANNER_PREV_DOC = 0;
var BANNER_NEXT_DOC = 1;
var BANNER_TACTIC_DOC = 2;
var ID_STANDARD_IMG = 0;
var ID_DISABLED_IMG = 1;
var ID_HOVER_IMG = 2;
var ID_SELECTED_IMG = 3;
var ID_ENABLED_CLASS = 0;
var ID_DISABLED_CLASS = 1;


// informations sur un bouton
function bannerButton(buttonId, buttonType, arrImg, arrClass)
{
	this.id = buttonId; // id du div
	this.buttonType = buttonType; // type du bouton prev/next
	this.arrImg = arrImg; // tableau des images (standard, disabled, hover, selected)
	this.arrClass = arrClass; // tableau des styles (actif, inactif)
}

function banner()
{
	this.arrButtons = null;
}

function bannerMgr()
{
	this.arrBanners = null;
	this.init = bannerInit;
	this.addButton = addBannerButton;
	this.updateButtons = updateBannerButtons;
	this.enableButton = enableBannerButton;
	this.disableButton = disableBannerButton;
}

function bannerInit()
{
	arrBanners = new Array();
	arrBanners[arrBanners.length] = new banner(); // top banner
	arrBanners[arrBanners.length] = new banner(); // bottom banner
	arrBanners[TOP_BANNER].arrButtons = new Array();
	arrBanners[BOTTOM_BANNER].arrButtons = new Array();	
}

// Ajouter un bouton au tableau
function addBannerButton(bannerId, buttonId, buttonType, arrImg, arrClass)
{	
	arrBanners[bannerId].arrButtons[arrBanners[bannerId].arrButtons.length] = new bannerButton(buttonId, buttonType, arrImg, arrClass);
}

// Processus d'activation/désactivation des boutons de la bannière
function updateBannerButtons(bannerFrame)
{	
	if((parent.TOC == null) || (parent.TacticDocument == null))
		return;

	// parcourir le tableau des boutons	
	var arrButtons = arrBanners[bannerFrame.bannerId].arrButtons;
	for (var i=0; i< arrButtons.length; i++)
	{	// objet div
		var button = bannerFrame.document.getElementById(arrButtons[i].id);
		var isButtonToUpdate = false;
		var bDisableButton = false;
		// traiter les boutons prev/next
		switch (arrButtons[i].buttonType)
		{	
			case 0 : // BANNER_PREV_DOC : activer le bouton si un document précédent existe
				if (!parent.TacticDocument.canGoPrevDoc()) // pas de document précédent
					bDisableButton = true;
				isButtonToUpdate = true;
				break;
			case 1 : // BANNER_NEXT_DOC : activer le bouton si un document suivant existe
				if (!parent.TacticDocument.canGoNextDoc()) // pas de document suivant
					bDisableButton = true;
				isButtonToUpdate = true;
				break;
//il n'y a plus de objLink et dans le modèle actuel on n'a plus la destination...
//			case 2 : // BANNER_TACTIC_DOC : activer le bouton si il y a une destination
//				if (objLink.href == "" || objLink.href == "#" || objLink.href == "javascript:void(0);") // pas de destination
//					bDisableButton = true;
//				isButtonToUpdate = true;
//				break;
		}


		// Selon le diagnostic ci-haut, activer/désactiver le bouton		
		if (isButtonToUpdate && bDisableButton)
			disableBannerButton(bannerFrame, button, arrButtons[i].arrImg[ID_DISABLED_IMG], arrButtons[i].arrClass[ID_DISABLED_CLASS]);
		else
			enableBannerButton(bannerFrame, button, arrButtons[i].arrImg, arrButtons[i].arrClass[ID_ENABLED_CLASS]);

	}
}

//désactiver un bouton : changer image(standard, hover,..), style
function disableBannerButton(bannerFrame, button, strDisableImg, strDisableStyle)
{
	var doc = bannerFrame.document;
	var objImg = doc.getElementById(button.id + 'img');
	objImg.src = strDisableImg;
	button.onmouseover = function(){rollover(doc, objImg.id, strDisableImg, false);};
	button.onmouseout  = function(){rollover(doc, objImg.id, strDisableImg, false);};
	button.onmousedown = function(){rollover(doc, objImg.id, strDisableImg, false);};
	button.onmouseup =   function(){rollover(doc, objImg.id, strDisableImg, false);};
}

//activer  un bouton 
function enableBannerButton(bannerFrame, button, arrImg, strEnableStyle)
{
	var doc = bannerFrame.document;
	var objImg = doc.getElementById(button.id + 'img');
	objImg.src = arrImg[ID_STANDARD_IMG];
	button.onmouseover = function(){rollover(doc, objImg.id, arrImg[ID_HOVER_IMG], true);};
	button.onmouseout  = function(){rollover(doc, objImg.id, arrImg[ID_STANDARD_IMG], false);};
	button.onmousedown = function(){rollover(doc, objImg.id, arrImg[ID_SELECTED_IMG], true);};
	button.onmouseup =   function(){rollover(doc, objImg.id, arrImg[ID_HOVER_IMG], true);};
}

////////////////////////////////////
// tocManager 

var TOC_TREE = 0;
var TOC_COMPACT = 1;
var TOC_NONE = 2;

function tocMgr(type){
	this.tocType = type;
	this.tocWidth = 0; // valeur par défaut
	this.showHideTOC = function (){
		if(this.tocType == TOC_NONE)
			return;
		if(document.getElementById("framesetMid").cols == "0,*")
			document.getElementById("framesetMid").cols = this.tocWidth + ",*";
		else
			document.getElementById("framesetMid").cols = "0,*";
	};
}


///////////////////////////////////////////////////////////////////
// tactic.js
///////////////////////////////////////////////////////////////////

var isPreview = false;
var previewMsgExerciseCannotNavigate;

var curMovingObject = null;
var synchroManager = null;
var LMSRESULT;
if((parent != null) && (parent.runTimeEnvType != null)){
if(parent.runTimeEnvType <= runTimeEnvSCORM12)
	LMSRESULT=new Array("neutral","wrong","correct");
else
	LMSRESULT=new Array("neutral","incorrect","correct");
}

function getCurrentLocalTime()
{
  var d = new Date();
  var hh = d.getHours(), mm = d.getMinutes(), ss = d.getSeconds();

  var curLocalTime = "";
  if(hh<10)
    curLocalTime += "0"; 
  curLocalTime += (hh +":");
  if(mm<10)
    curLocalTime += "0"; 
  curLocalTime += mm + ":";
  if(ss<10)
    curLocalTime += "0"; 
  curLocalTime += ss;

  return curLocalTime;
}

function getFullTimeStamp()
{
  var d = new Date();
  var dd = d.getDate();
  var mm = d.getMonth() + 1;

  var timestamp = "";  
  timestamp += d.getFullYear() + "-";
  if(mm<10)
    timestamp += "0"; 
  timestamp += mm + "-";
  if(dd<10)
    timestamp += "0"; 
  timestamp += dd;
  timestamp += "T";
  timestamp += getCurrentLocalTime();
  
  return timestamp;
}

///////////////////////////////////////////////////////////////////
// Scripts pour FF

var btnDeflate4ID = 0; // resize ThreeD class buttons
var btnDeflate8ID = 1; // resize Framed class buttons
function resizeToFF(obj, resizeID)
{
	if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
		return;

	var resizeWidth;
	var resizeHeight;
	if(resizeID == btnDeflate4ID)
	{
		resizeWidth = -4;
		resizeHeight = -4;
	}
	else if(resizeID == btnDeflate8ID)
	{
		resizeWidth = -8;
		resizeHeight = -8;
	}
	var newSizeObj = document.getElementById(obj);
	newSizeObj.style.width = (parseInt(newSizeObj.style.width) + resizeWidth) + "px";
	newSizeObj.style.height = (parseInt(newSizeObj.style.height) + resizeHeight) + "px";
}
///////////////////////////////////////////////////////////////////

function canGoNextDoc()
{
  if((parent.TOC != null) && parent.TOC.isTOCReady && parent.TOC.isFirstDocReady)
    return (parent.TOC.course.position.nextDoc != "");
  return false;
}

function canGoPrevDoc()
{
  if((parent.TOC != null) && parent.TOC.isTOCReady && parent.TOC.isFirstDocReady)
    return (parent.TOC.course.position.prevDoc != "");
  return false;
}

function goNextDoc()
{
  if(canGoNextDoc())
    parent.TacticDocument.location = parent.TOC.course.position.nextDoc + ".html";
}

function goPrevDoc()
{
  if(canGoPrevDoc())
    parent.TacticDocument.location = parent.TOC.course.position.prevDoc + ".html";
}


function feedback(destination, isPopup, left, top, width, height, isAutoClose) {
   this.destination = destination;
   this.isPopup = isPopup;
   this.isAutoClose = isAutoClose;
   this.left = left;
   this.top = top;
   this.width = width;
   this.height = height;
}

function onDonePressed() 
{
  if ( ! this.isDisabled) 
  {
    this.isArmed = true;
    this.obj.style.borderStyle = "inset";
    if (this.state == this.SOLUTION_STATE) 
    {
      document.getElementById(this.obj.id+'img').src="image/_solud.gif";
      this.state = this.CORRECTION_STATE;
      this.exercise.showCorrection();
    }
  }
}

function onDoneReleased()
{
  if ( ! this.isDisabled) 
  {
    this.isArmed = false;
    this.obj.style.borderStyle = "outset";
    if (this.state == this.CORRECTION_STATE) 
    {
      this.state = this.SOLUTION_STATE;
      this.exercise.showSolution();
      document.getElementById(this.obj.id+'img').src="image/_soluu.gif";
    }
    else if (this.state == this.TERMS_STATE)
    {
      var s = this.exercise.evaluate();
      if (this.exercise.finished || s) 
      {
        this.state = this.SOLUTION_STATE;
        if (!this.exercise.showUserSolution || s || !this.exercise.isSolutionShown) 
        {
          this.doneDisable();
	}
        else
        {
	  document.getElementById(this.obj.id+'img').src="image/_soluu.gif";
	}
      }
    }
  }
} 

function onDoneLeaved() 
{
  if (this.isArmed) 
  {
    this.isArmed = false;
    this.obj.style.borderStyle = "outset";
    if (this.state == this.CORRECTION_STATE) 
    {
      document.getElementById(this.obj.id+'img').src="image/_soluu.gif";
      this.state = this.SOLUTION_STATE;
      this.exercise.showSolution();
    }
  }
}

function doneDisable() {
  this.isDisabled = true;
  this.obj.firstChild.style.cursor = "default";
  if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
  {
    this.obj.filters[0].Enabled = true;
    this.obj.filters[0].clear();
    this.obj.filters[0].addAmbient(221,221,221,85);
  }
  else // FF
    this.obj.style.setProperty("-moz-opacity", 0.5, "");
}

function doneButton(exercise) {
   this.CORRECTION_STATE = 0;
   this.SOLUTION_STATE = 1;
   this.TERMS_STATE = 2;
   this.state = this.TERMS_STATE;
   this.exercise = exercise;
   this.obj = null;
   this.isDisabled = false;
   this.isArmed = false;

   this.onDonePressed = onDonePressed;
   this.onDoneReleased = onDoneReleased;
   this.onDoneLeaved = onDoneLeaved;
   this.doneDisable = doneDisable;
}

function setFired(hasFired) {
   this.hasFired = hasFired;
   this.refreshProposition(hasFired);
}
function hasLearnerAnswered() {
   return this.isEnabled && this.hasFired;
}
function isAnswerCorrect() {
   return false;
} 
function showPTerms() {
}
function _showPSolution() {
}
function showPSolution() {
  this._showPSolution();
  this.disableProposition();
}
function _showPIndication() {
}
function showPIndication() {
  if(this.hasFired) {
	this.showPSolution();
  } 
  this._showPIndication();
}
function showPCorrection() {
  this.showPSolution();
}
function disableProposition() {
  this.isEnabled = false;
  this.obj.firstChild.style.cursor="default";
}
function refreshProposition(hasFired) {
}
function onActiveProposition(){
   if (this.isEnabled) {
      this.isArmed = true;
      this.refreshProposition(true);
   }
}
function onLeaveProposition() {
   if (this.isArmed) {
      this.isArmed = false;
      this.refreshProposition(this.hasFired);
   }
}
function PReset() {
 this.hasFired = false;
 this.isArmed = false;
}
function proposition(hasFinalFeedback, label, finalFeedback, hasTryAgainFeedback, tryAgainFeedback) {
   this.hasFinalFeedback = hasFinalFeedback;
   this.label = label;
   this.finalFeedback = finalFeedback;
   this.hasTryAgainFeedback = hasTryAgainFeedback;
   this.tryAgainFeedback = tryAgainFeedback;
   this.obj = null;
   this.isEnabled = true;
   this.hasFired = false;
   this.isArmed = false;
   this.userAnswer = null;
   this.hasCorrectionDone = false;
   this.setFired = setFired;
   this.hasLearnerAnswered = hasLearnerAnswered;
   this.isAnswerCorrect = isAnswerCorrect;
   this.showPTerms = showPTerms;
   this.showPSolution = showPSolution;
   this._showPSolution = _showPSolution;
   this.showPIndication = showPIndication;
   this._showPIndication = _showPIndication;
   this.showPCorrection = showPCorrection;
   this.disableProposition = disableProposition;
   this.refreshProposition = refreshProposition;
   this.onActiveProposition = onActiveProposition;
   this.onLeaveProposition = onLeaveProposition;
   this.PReset = PReset;
}

function mcePRefresh(hasFired){
 if(hasFired){
  this.obj.style.border = "inset";     
  this.obj.style.borderWidth = "2px"; 
  if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
   this.obj.filters[0].Enabled = true;
  else
   this.obj.style.setProperty("-moz-opacity", 0.2, "");
  this.obj.style.backgroundColor='gray';
 } 
 else {
  this.obj.style.border = "outset"; 
  this.obj.style.borderWidth = "2px"; 
  if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
   this.obj.filters[0].Enabled = false;
  else
   this.obj.style.setProperty("-moz-opacity", 1.0, "");
  this.obj.style.backgroundColor='transparent';
 }
} 

function mceIsAnswerCorrect() {
   return ( ! this.isEnabled) || (this.isCorrect && this.hasFired) || (!this.isCorrect && !this.hasFired);
} 
function mceShowPTerms() {
 this.face.firstChild.src = "image/_facen.gif";
 this.refreshProposition(false);
}
function _mceShowPSolution() {
  if (this.isCorrect) {
     this.face.firstChild.src = "image/_faceg.gif";
  } else {
     this.face.firstChild.src = "image/_faceb.gif";
  }
}
function _mceShowPIndication() {
  if (this.hasFired && ! this.isCorrect) {
    this.setFired(false);
  }
}
function mceProposition(isCorrect, label, hasFinalFeedback, finalFeedback, hasTryAgainFeedback, tryAgainFeedback) {
   this.base = proposition;
   this.base(hasFinalFeedback, label, finalFeedback, hasTryAgainFeedback, tryAgainFeedback);
   this.isCorrect = display(isCorrect);
   this.isInitialPositionUsed = false;
   this.image = null;
   this.refreshProposition = mcePRefresh;
   this.isAnswerCorrect = mceIsAnswerCorrect;
   this.showPTerms = mceShowPTerms;
   this._showPSolution = _mceShowPSolution;
   this._showPIndication = _mceShowPIndication;
}

function findPRefresh(hasFired) {
  if (hasFired) {
	if(this.isAutomatic) {
	  show(this.frame);        
	} else {
	  show(this.frameNeutral);        
	}
  } else if ( !	this.isAutomatic){
	hidde(this.frameNeutral);        
  }
}
function findIsAnswerCorrect() {
   return ( ! this.isEnabled) || (this.isCorrect && this.hasFired) || (!this.isCorrect && !this.hasFired);
} 
function findShowPTerms() {
  this.refreshProposition(false);        
}
function findShowPCorrection() {
	if(this.hasFired) {
      show(this.frame); this.hasCorrectionDone=true;
	} else {
      hidde(this.frame);
	}
}
function _findShowPSolution() {
  if (this.isCorrect) {
    show(this.frame);
  } else if (this.hasFired) {
    show(this.frame);
  } else {
    hidde(this.frame);
	if ( ! this.isAutomatic) {hidde(this.frameNeutral);}
  }
}
function _findShowPIndication() {
  if (this.hasFired && ! this.isCorrect) {
    this.showPCorrection();
  }
}
function findProposition(isAutomatic, label, isCorrect, hasFinalFeedback, finalFeedback, hasTryAgainFeedback, tryAgainFeedback) {
   this.base = proposition;
   this.base(hasFinalFeedback, label, finalFeedback, hasTryAgainFeedback, tryAgainFeedback);
   this.isAutomatic = isAutomatic;
   this.isCorrect = display(isCorrect);
   this.isAnswerCorrect = findIsAnswerCorrect;
   this.refreshProposition = findPRefresh;
   this.showPTerms = findShowPTerms;
   this._showPSolution = _findShowPSolution;
   this._showPIndication = _findShowPIndication;
   this.showPCorrection = findShowPCorrection;
}
function formHasLearnerAnswered() {
	if (!this.isAutomatic) {
		this.setFired(true);	
	}
	answer = this.obj.value + "";	
	if (answer.length == 0)	{
		return (this.isEnabled && this.hasFired) && isAnswerCorrect(answer);
	} else {
		return (this.isEnabled && this.hasFired);
	}
}

function trim(str) {
	var firstLetter = 0;
	for (firstLetter = 0; firstLetter < str.length; firstLetter++) {
		if (str.charAt(firstLetter) != " ")
			break;
	}
	str = str.substr(firstLetter, str.length - firstLetter);
	
	var lastLetter = 0;
	for (lastLetter = (str.length-1); lastLetter >= 0; lastLetter--) {
		if (str.charAt(lastLetter) != " ")
			break;
	}
	str = str.substr(0, lastLetter+1);
	return str;
}
function removeSpace(str) {
	var strNoSpace = "";
	for (var currentChar = 0; currentChar < str.length; currentChar++) {
		if (str.charAt(currentChar) != " ")
		  strNoSpace = strNoSpace.concat(str.charAt(currentChar));
	}
	return strNoSpace;
}
function formIsAnswerCorrect() {
	identical = 1;
	var currentText = this.obj.value + "";	
	var userAnswer;
	if (this.checkSpace) {
		userAnswer = currentText;
		userAnswer = trim(userAnswer);
	} else {
		userAnswer = currentText;
		userAnswer = removeSpace(userAnswer);
	}
	for (var i = 0; i < this.answers.length; i++) {
		var correctAnswer;
		if (this.checkSpace) {
			correctAnswer = display(this.answers[i]);
		} else {
			var answer = display(this.answers[i]);
			correctAnswer = removeSpace(answer);
		}
		if (!this.checkCase) {
			userAnswer = userAnswer.toLowerCase();
			correctAnswer = correctAnswer.toLowerCase();
		}
		
		if (userAnswer == correctAnswer)
			identical = 0;
			
		if (!identical)
			break;
	}

	return !identical;
} 
function formShowPSolution() {
	this.isEnabled = false;
	var currentText = this.obj.value + "";
	this.obj.style.color = "white";
	this.obj.style.backgroundColor = this.correctColor;
	if (this.isAnswerCorrect()) {
		this.obj.value = currentText + "";	
	} else {
		if (this.answers.length > 0)
			this.obj.value = display(this.answers[0]);	
		else
			this.obj.value = "";
	}
}
function formShowPIndication() {
	if (this.exercise.giveClues) {
		if (this.hasLearnerAnswered()) {
			if (this.isAnswerCorrect()) {
				this.obj.style.color = "white";
				this.obj.style.backgroundColor = this.correctColor;
				this.isEnabled = false;
				this.obj.disabled = true;
			} else {
				this.obj.style.color = "white";
				this.obj.style.backgroundColor = this.incorrectColor;
			}
		}
	} else {
		this.setFired(false);
	}
}
function formShowPCorrection() {
	this.obj.value = this.userAnswer + "";
	if (!this.isAnswerCorrect()) {
		this.obj.style.color = "white";
		this.obj.style.backgroundColor = this.incorrectColor;
	}
}
function formDisableProposition() {
  this.isEnabled = false;
  this.obj.disabled=true;
}

function formProposition(answers, label, checkSpace, checkCase, isAutomatic, correctColor, incorrectColor){
   this.base = proposition;
   this.base(false, label, false, false, false);
   this.answers = answers;
   this.checkSpace = checkSpace;
   this.checkCase = checkCase;
   this.correctColor = correctColor;
   this.incorrectColor = incorrectColor;
   this.hasFired = false;
   this.userAnswer = "";
   this.isAutomatic = isAutomatic;
   this.hasLearnerAnswered = formHasLearnerAnswered;
   this.isAnswerCorrect = formIsAnswerCorrect;
   this.showPSolution = formShowPSolution;
   this.showPIndication = formShowPIndication;
   this.showPCorrection = formShowPCorrection;
   this.disableProposition = formDisableProposition;
}

function playFeedback(feedback) {
   if (feedback.isPopup) {
	   openPopup(feedback.destination, "Feedback", feedback.left, feedback.top, feedback.width, feedback.height, feedback.isAutoClose);
   } else {
     if(isPreview)
       {alert(previewMsgExerciseCannotNavigate);return;}
     var str = 'location.href = "' + feedback.destination + '";'
     setTimeout(str, 1);
   }
}

function evaluateExercice() 
{
}

function evaluate() {
   var s = false;
   this.nbAnswersToFind = 0;
   this.nbCorrectAnswers = 0;
   this.nbCorrectAnswersNotTrap = 0;
   this.nbLastTryErrors = 0;
   this.hasLearnerAnswered = false;
   
   this.evaluateExercice();
   
   var score = 0;
   
   if (this.isTest) {
      score = this.nbCorrectAnswers * this.testMaxScore;
      score /= this.nbAnswersToFind;
      if ( ! this.doesGivePointsWhenFail) {
         if (this.nbCorrectAnswers < this.nbAnswersToFind) score = 0.0;
      }
   }

   this.nbErrors += this.nbLastTryErrors;

   if (this.nbErrors > this.nbAllowedErrors) {
      if (this.nbAnswersToFind != this.propositions.length) {
         if (this.doesGivePointsWhenFail) {
            var negativeScore = (this.nbErrors - this.nbAllowedErrors) * this.testMaxScore;
            negativeScore /= this.nbAnswersToFind;
            score -= negativeScore;
            if (score < 0) score = 0.0;	// Pas de score négatif.
         } else {
            score = 0.0;
         }
      }
      this._putInteraction(score, this.EVALUATION_FAILED);
 	  this.showSolution();
      if (this.isAutomatic && this.lastActivatedChoiceNo != -1 && this.propositions[this.lastActivatedChoiceNo].hasFinalFeedback) {
        this.playFeedback(this.propositions[this.lastActivatedChoiceNo].finalFeedback);
      } else {
         this.playFeedback(this.givenFeedback);
      }
   }
   else if (this.nbCorrectAnswers == this.nbAnswersToFind) {
     this._putInteraction(score, this.EVALUATION_SUCCEEDED);
	 s = true;
     this.showSolution();

     if (this.isAutomatic && this.lastActivatedChoiceNo != -1 && this.propositions[this.lastActivatedChoiceNo].hasFinalFeedback) {
         this.playFeedback(this.propositions[this.lastActivatedChoiceNo].finalFeedback);
     } else {
         this.playFeedback(this.correctFeedback);
     }
   } else if ( (! this.allOfMany) && (this.nbCorrectAnswersNotTrap > 0))  {
      this._putInteraction(this.testMaxScore, this.EVALUATION_SUCCEEDED);
      s = true;
      this.showSolution();
      if (this.isAutomatic && this.lastActivatedChoiceNo != -1 && this.propositions[this.lastActivatedChoiceNo].hasFinalFeedback) {
         this.playFeedback(this.propositions[this.lastActivatedChoiceNo].finalFeedback);
      } else {
         this.playFeedback(this.correctFeedback);
      }
   } else if ( ! this.hasLearnerAnswered)
   { } else if (this.nbLastTryErrors > 0) {
     this._putInteraction(score, this.EVALUATION_NOT_COMPLETED);
      if (this.giveClues) {
        this.showIndication();
      } else {
        this.showTerms();
      }
      if (this.isAutomatic && this.lastActivatedChoiceNo != -1 && this.propositions[this.lastActivatedChoiceNo].hasTryAgainFeedback) {
         this.playFeedback(this.propositions[this.lastActivatedChoiceNo].tryAgainFeedback);
      } else {
         this.playFeedback(this.tryAgainFeedback);
      }
   } else {
      this._putInteraction(score, this.EVALUATION_NOT_COMPLETED);
      if (this.giveClues) {
        this.showIndication();
      } else {
        this.showTerms();
      }
      if (this.isAutomatic && this.lastActivatedChoiceNo != -1 && this.propositions[this.lastActivatedChoiceNo].hasTryAgainFeedback) {
         this.playFeedback(this.propositions[this.lastActivatedChoiceNo].tryAgainFeedback);
      } else {
         this.playFeedback(this.partlyCorrectFeedback);
      }
   }
   return s;
}
function _putInteraction(score, state){
   this.state = state;
   this.sendInteractionToLMS();
   if (!isStandAlone && parent.TOC.isTOCReady && !isPreview) {
     parent.TOC.course.onInteraction(path, this.exID, this.isTest, score, 
                        this.isTest ? this.testMaxScore : 0, state);
                        
   }
}
function registerProposition(proposition){
   this.propositions[this.propositions.length] = proposition;
}
function onClickChoice(choiceNo){
   var p = this.propositions[choiceNo];
   if (p.isEnabled && p.isArmed) {
      this.lastActivatedChoiceNo = choiceNo;
      p.isArmed = false;
      p.setFired(! p.hasFired);
      if (this.isAutomatic) {
         this.evaluate();
      }
   }
}

function showTerms()
{
  for (var i = 0; i < this.propositions.length; i++) {
    this.propositions[i].showPTerms();
    this.propositions[i].PReset();
  }
}
function showSolution() {
   this.finished = true;
   this.disable();
   if (this.isSolutionShown) {
     for (var i = 0; i < this.propositions.length; i++) {
        this.propositions[i].showPSolution();
     }
   }
   this.refreshPassFlag(this.state);
}

function showIndication() {
    for (var i = 0; i < this.propositions.length; i++) {
		var p = this.propositions[i].showPIndication();
	}
}

function showCorrection() {
    for (var i = 0; i < this.propositions.length; i++) {
		var p = this.propositions[i].showPCorrection();
	}
}

function disable() {
   for (var i = 0; i < this.propositions.length; i++) {
     this.propositions[i].disableProposition();
   }
}

function refreshPassFlag(exerciseState) {
  if (this.showPassFlag) {
    if (exerciseState == this.EVALUATION_FAILED) {
      this.pass.src='image/_passf.gif';
    }
    else if (exerciseState == this.EVALUATION_SUCCEEDED) {
      this.pass.src='image/_passs.gif';
    }
  }
}

function refreshState(exerciseState) {
  this.refreshPassFlag(exerciseState);
  if (this.isCertification && exerciseState != this.EVALUATION_NOT_COMPLETED) {
    show(this.completed);
    this.disable();
    if ( ! this.isAutomatic)
    {
      this.doneButton.doneDisable();
    }    
 }
}

function exercise(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
                  isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
                  isSolutionShown,
                  correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback)
{
   this.EVALUATION_NOT_COMPLETED = 0;
   this.EVALUATION_FAILED = 1;
   this.EVALUATION_SUCCEEDED = 2;

   this.obj = null;
   this.pass = null;
   this.propositions = new Array;

   this.isAutomatic = isAutomatic;
   this.nbAllowedErrors = nbAllowedErrors;
   this.giveClues = giveClues;
   this.showPassFlag = showPassFlag;
   this.allOfMany = allOfMany;
   this.correctFeedback = correctFeedback;
   this.partlyCorrectFeedback = partlyCorrectFeedback;
   this.givenFeedback = givenFeedback;
   this.tryAgainFeedback = tryAgainFeedback;
   this.nbErrors = 0;
   this.isTest = isTest;
   this.isCertification = isCertification;
   this.testMaxScore = testMaxScore;
   this.doesGivePointsWhenFail = doesGivePointsWhenFail;
   this.exID = exID;
   this.doneButton = null;
   
   this.isSolutionShown = isSolutionShown;
   this.lastActivatedChoiceNo = -1;
   this.finished = false;
   this.state = this.EVALUATION_NOT_COMPLETED;
   this.showUserSolution = false;

   this.registerProposition = registerProposition;
   this.playFeedback = playFeedback;
   this.refreshState = refreshState;
   this.refreshPassFlag = refreshPassFlag;
   this.evaluate = evaluate;

   this.onClickChoice = onClickChoice;
   this.showTerms = showTerms;
   this.showSolution = showSolution;
   this.showIndication = showIndication;
   this.showCorrection = showCorrection;
   this.disable = disable;
   this.evaluateExercice = evaluateExercice;
   this._putInteraction = _putInteraction
   this._sendInteractionToLMS = _sendInteractionToLMS;
   this.interactionBeginningTime = ConvertTimeToSecond();
}

function _sendInteractionToLMS(interactionType){
  if ((parent != null) && (parent.api != null)){

	var correctResponse="", studentResponse="", nbCorrectPropositions=0, nbStudentPropositions=0;
	var nbPropositions = this.propositions.length;
	if(parent.runTimeEnvType < runTimeEnvSCORM12){
		var separateur=", ";
	
		if (!this.allOfMany)	separateur="; ";
		for (var i=0; i<nbPropositions; i++){
			var p = this.propositions[i];
			if (p.isCorrect){
				if (nbCorrectPropositions > 0)	correctResponse +=separateur;
				correctResponse += p.label;
				nbCorrectPropositions++;
			}
			if (p.hasLearnerAnswered()){
				if (nbStudentPropositions > 0)	studentResponse += ", ";
				studentResponse += p.label;
				nbStudentPropositions++;
			}
		}
		if ( (nbCorrectPropositions > 1) && (this.allOfMany))	correctResponse = "{" + correctResponse + "}";
		if (nbStudentPropositions > 1)	studentResponse = "{" + studentResponse + "}";
	}
	else if(parent.runTimeEnvType == runTimeEnvSCORM12){
		var separateur=",";
		
		for (var i=0; i<nbPropositions; i++){
			var p = this.propositions[i];
			if (p.isCorrect){
				if (nbCorrectPropositions > 0)	correctResponse +=separateur;
				correctResponse += p.label;
				nbCorrectPropositions++;
			}
			if (p.hasLearnerAnswered()){
				if (nbStudentPropositions > 0)	studentResponse +=separateur;
				studentResponse += p.label;
				nbStudentPropositions++;
			}
		}
		if ( (nbCorrectPropositions > 1) && (this.allOfMany))	correctResponse = "{" + correctResponse + "}";
		if (nbStudentPropositions > 1)	studentResponse = "{" + studentResponse + "}";
	}
	else if(parent.runTimeEnvType >= runTimeEnvSCORM13){
		var separateur="[,]";
		
		for (var i=0; i<nbPropositions; i++){
			var p = this.propositions[i];
			if (p.isCorrect){
				if (nbCorrectPropositions > 0)	correctResponse +=separateur;
				correctResponse += p.label;
				nbCorrectPropositions++;
			}
			if (p.hasLearnerAnswered()){
				if (nbStudentPropositions > 0)	studentResponse +=separateur;
				studentResponse += p.label;
				nbStudentPropositions++;
			}
		}
	}
	
	// Set Values des interactions
   	var elt = "cmi.interactions." + parent.TOC.course.nbInteraction + ".";

	if(parent.runTimeEnvType <= runTimeEnvSCORM12){
	  parent.api.LMSSetValue(elt+"id", parent.TOC.course.getLEFrom(path).name.replace(/ /g, "_") + "-" + this.exID + "-" + nbStudentPropositions);
	  parent.api.LMSSetValue(elt+"type",interactionType);
	  parent.api.LMSSetValue(elt+"time", getCurrentLocalTime());
	  parent.api.LMSSetValue(elt+"latency", getTimeDiff(this.interactionBeginningTime, ConvertTimeToSecond()));
	  this.interactionBeginningTime = ConvertTimeToSecond();
	  parent.api.LMSSetValue(elt+"weighting", this.testMaxScore);
	  parent.api.LMSSetValue(elt+"correct_responses.0.pattern", correctResponse);
	  parent.api.LMSSetValue(elt+"student_response", studentResponse);
	  parent.api.LMSSetValue(elt+"result", LMSRESULT[this.state]);
	}
	else if(parent.runTimeEnvType >= runTimeEnvSCORM13){
	  parent.api.SetValue(elt+"id", parent.TOC.course.getLEFrom(path).name.replace(/ /g, "_") + "-" + this.exID + "-" + nbStudentPropositions);
	  parent.api.SetValue(elt+"type",interactionType);
  	  parent.api.SetValue(elt+"timestamp", getFullTimeStamp());
 	  parent.api.SetValue(elt+"latency", getTimeDiff(this.interactionBeginningTime, ConvertTimeToSecond()));
	  this.interactionBeginningTime = ConvertTimeToSecond();
	  parent.api.SetValue(elt+"weighting", this.testMaxScore);
	  parent.api.SetValue(elt+"correct_responses.0.pattern", correctResponse);
	  parent.api.SetValue(elt+"learner_response", studentResponse);
	  parent.api.SetValue(elt+"result", LMSRESULT[this.state]);
    }
	//Envoyer egalement lesson_id, date et time
	parent.TOC.course.nbInteraction++;
  }
}

function mceEvaluateExercice() {
   for (var i = 0; i < this.propositions.length; i++) {
      var p = this.propositions[i];
      if (p.isCorrect) {
         this.nbAnswersToFind += 1;
         if (p.isAnswerCorrect()) {
            this.nbCorrectAnswers += 1;
            this.nbCorrectAnswersNotTrap += 1;
         }
      }
      if ( p.hasLearnerAnswered() ) {
		this.hasLearnerAnswered = true;
		if ( ! p.isAnswerCorrect()) {
		   this.nbLastTryErrors += 1;
		}
	  }
   }
}
function random(limit) {
	return(Math.floor(Math.random()*limit));
}
function mceFindNextProposition(i, propositions) {
    var j = 0;
    if (i != (propositions.length - 1)) {
       j = random(propositions.length - i);
    }
    var k = -1;
    var ii = -1;
    do {
       ii++;
       if ( ! propositions[ii].isInitialPositionUsed) { k++; }
    }
    while (k != j)
    return ii;
}

var mceNextTab = 1;
function mceShuffle() 
{
  for (var i = 0; i < this.propositions.length; i++) 
  {
     this.propositions[i].face.initialTop = -1;
  }

  for (var i = 0; i < this.propositions.length; i++) 
  {
    var ii = mceFindNextProposition(i, this.propositions);
    this.propositions[ii].isInitialPositionUsed = true;

    if (this.propositions[ii].face.initialTop == -1) 
    {
      this.propositions[ii].obj.initialTop = this.propositions[ii].obj.style.top;
      this.propositions[ii].obj.initialLeft = this.propositions[ii].obj.style.left;
      this.propositions[ii].face.initialTop = this.propositions[ii].face.style.top;
      this.propositions[ii].face.initialLeft = this.propositions[ii].face.style.left;
      this.propositions[ii].text.initialTop = this.propositions[ii].text.style.top;
      this.propositions[ii].text.initialLeft = this.propositions[ii].text.style.left;

      if (this.propositions[ii].image != null)
      {
        this.propositions[ii].image.initialTop = this.propositions[ii].image.style.top;
        this.propositions[ii].image.initialLeft = this.propositions[ii].image.style.left;
      }
    }

    this.propositions[i].obj.initialTop = this.propositions[i].obj.style.top;
    this.propositions[i].obj.initialLeft = this.propositions[i].obj.style.left;
    this.propositions[i].obj.style.top = this.propositions[ii].obj.initialTop;
    this.propositions[i].obj.style.left = this.propositions[ii].obj.initialLeft;

    this.propositions[i].face.initialTop = this.propositions[i].face.style.top;
    this.propositions[i].face.initialLeft = this.propositions[i].face.style.left;
    this.propositions[i].face.style.top = parseFloat(this.propositions[ii].obj.initialTop) + parseFloat(parseFloat(this.propositions[i].face.initialTop) - parseFloat(this.propositions[i].obj.initialTop)) + "px";
    this.propositions[i].face.style.left = parseInt(this.propositions[ii].obj.initialLeft) + parseInt(parseInt(this.propositions[i].face.initialLeft) - parseInt(this.propositions[i].obj.initialLeft)) + "px";

    this.propositions[i].text.initialTop = this.propositions[i].text.style.top;
    this.propositions[i].text.initialLeft = this.propositions[i].text.style.left;
    this.propositions[i].text.style.top = parseInt(this.propositions[ii].obj.initialTop) + parseInt(parseInt(this.propositions[i].text.initialTop) - parseInt(this.propositions[i].obj.initialTop)) + "px";
    this.propositions[i].text.style.left = parseInt(this.propositions[ii].obj.initialLeft) + parseInt(parseInt(this.propositions[i].text.initialLeft) - parseInt(this.propositions[i].obj.initialLeft)) + "px";

    if (this.propositions[i].image != null)
    {
      this.propositions[i].image.initialTop = this.propositions[i].image.style.top;
      this.propositions[i].image.initialLeft = this.propositions[i].image.style.left;
      this.propositions[i].image.style.top =  parseInt(this.propositions[ii].obj.initialTop.substring(0,this.propositions[ii].obj.initialTop.length-2)) + parseInt(parseInt(this.propositions[i].image.initialTop.substring(0,this.propositions[i].image.initialTop.length-2)) - parseInt(this.propositions[i].obj.initialTop.substring(0,this.propositions[i].obj.initialTop.length-2))) + "px";
      this.propositions[i].image.style.left = parseInt(this.propositions[ii].obj.initialLeft.substring(0,this.propositions[ii].obj.initialLeft.length-2)) + parseInt(parseInt(this.propositions[i].image.initialLeft.substring(0,this.propositions[i].image.initialLeft.length-2)) - parseInt(this.propositions[i].obj.initialLeft.substring(0,this.propositions[i].obj.initialLeft.length-2))) + "px";
    }

    this.propositions[i].obj.tabIndex = mceNextTab + ii;
  }

  mceNextTab += this.propositions.length;
}

function mceDisable() {
   for (var i = 0; i < this.propositions.length; i++) {
     this.propositions[i].disableProposition();
   }       
   if ( ! this.isAutomatic)
   {
     this.doneButton.doneDisable();
   }    
}

function mceExercise(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
             isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
             isSolutionShown,
             correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback)
{
   this.base = exercise;
   this.base(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
             isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
             isSolutionShown,
             correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback);

   this.shuffle = mceShuffle;

   this.disable = mceDisable;
   this.evaluateExercice = mceEvaluateExercice;
   this.sendInteractionToLMS= mceSendInteractionToLMS;
}

function trueFalseSendInteractionToLMS(){
	this._sendInteractionToLMS("true-false");
}

function trueFalseExercise(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
             isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
             isSolutionShown,
             correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback)
{
   this.base = mceExercise;

   this.base(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
             isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
             isSolutionShown,
             correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback);

   this.sendInteractionToLMS= trueFalseSendInteractionToLMS;
}


function matchSendInteractionToLMS(){
  if ((parent != null) && (parent.api != null)){
	var correctResponse="", studentResponse="", nbCorrectPropositions=0, nbStudentPropositions=0;
	var nbPropositions = this.propositions.length;
	if(parent.runTimeEnvType < runTimeEnvSCORM12){
		var separateur=", ";
	
		if (!this.allOfMany)	separateur="; ";
		for (var i=0; i<nbPropositions; i++){
			var p = this.propositions[i];
			if (p.correctSinkZone != null){
				if (nbCorrectPropositions > 0)	correctResponse +=separateur;
				correctResponse = correctResponse + p.label + "." + p.correctSinkZone.label;
				nbCorrectPropositions++;
			}
			if (p.hasLearnerAnswered()){
				if (nbStudentPropositions > 0)	studentResponse += ", ";
				studentResponse = studentResponse + p.label + "." + p.currentSinkZone.label;
				nbStudentPropositions++;
			}
		}
		if ( (nbCorrectPropositions > 1) && (this.allOfMany))	correctResponse = "{" + correctResponse + "}";
		if (nbStudentPropositions > 1)	studentResponse = "{" + studentResponse + "}";
	}
	if(parent.runTimeEnvType == runTimeEnvSCORM12){
		var separateur=",";
	
		for (var i=0; i<nbPropositions; i++){
			var p = this.propositions[i];
			if (p.correctSinkZone != null){
				if (nbCorrectPropositions > 0)	correctResponse +=separateur;
				correctResponse = correctResponse + p.label + "." + p.correctSinkZone.label;
				nbCorrectPropositions++;
			}
			if (p.hasLearnerAnswered()){
				if (nbStudentPropositions > 0)	studentResponse +=separateur;
				studentResponse = studentResponse + p.label + "." + p.currentSinkZone.label;
				nbStudentPropositions++;
			}
		}
		if ( (nbCorrectPropositions > 1) && (this.allOfMany))	correctResponse = "{" + correctResponse + "}";
		if (nbStudentPropositions > 1)	studentResponse = "{" + studentResponse + "}";
	}
	else if(parent.runTimeEnvType >= runTimeEnvSCORM13){
		var separateur="[,]";
		
		for (var i=0; i<nbPropositions; i++){
			var p = this.propositions[i];
			if (p.correctSinkZone != null){
				if (nbCorrectPropositions > 0)	correctResponse +=separateur;
				correctResponse = correctResponse + p.label + "[.]" + p.correctSinkZone.label;
				nbCorrectPropositions++;
			}
			if (p.hasLearnerAnswered()){
				if (nbStudentPropositions > 0)	studentResponse +=separateur;
				studentResponse = studentResponse + p.label + "[.]" + p.currentSinkZone.label;
				nbStudentPropositions++;
			}
		}
	}
	
	// Set Values des interactions
   	var elt = "cmi.interactions." + parent.TOC.course.nbInteraction + ".";
	if(parent.runTimeEnvType <= runTimeEnvSCORM12){
	  parent.api.LMSSetValue(elt+"id", parent.TOC.course.getLEFrom(path).name.replace(/ /g, "_") + "-" + this.exID + "-" + nbStudentPropositions);
	  parent.api.LMSSetValue(elt+"type", "matching");
	  parent.api.LMSSetValue(elt+"time", getCurrentLocalTime());
	  parent.api.LMSSetValue(elt+"latency", getTimeDiff(this.interactionBeginningTime, ConvertTimeToSecond()));
	  this.interactionBeginningTime = ConvertTimeToSecond();
	  parent.api.LMSSetValue(elt+"weighting", this.testMaxScore);
	  parent.api.LMSSetValue(elt+"correct_responses.0.pattern", correctResponse);
	  parent.api.LMSSetValue(elt+"student_response", studentResponse);
	  parent.api.LMSSetValue(elt+"result", LMSRESULT[this.state]);
	}
	else if(parent.runTimeEnvType >= runTimeEnvSCORM13){
	  parent.api.SetValue(elt+"id", parent.TOC.course.getLEFrom(path).name.replace(/ /g, "_") + "-" + this.exID + "-" + nbStudentPropositions);
	  parent.api.SetValue(elt+"type", "matching");
  	  parent.api.SetValue(elt+"timestamp", getFullTimeStamp());
 	  parent.api.SetValue(elt+"latency", getTimeDiff(this.interactionBeginningTime, ConvertTimeToSecond()));
	  this.interactionBeginningTime = ConvertTimeToSecond();
	  parent.api.SetValue(elt+"weighting", this.testMaxScore);
	  parent.api.SetValue(elt+"correct_responses.0.pattern", correctResponse);
	  parent.api.SetValue(elt+"learner_response", studentResponse);
	  parent.api.SetValue(elt+"result", LMSRESULT[this.state]);
    }
	//Envoyer egalement lesson_id, date et time
	parent.TOC.course.nbInteraction++;
  }
}

function onMatchActiveProposition()
{
  if (this.isEnabled && ((!this.exercise.curLinkingProposition) || (this.exercise.curLinkingProposition == this))) 
  {
     this.isArmed = true;
     this.refreshProposition();
  }
}

function onMatchLeaveProposition() 
{
  if (this.isArmed) 
  {
     this.isArmed = false;       
     this.refreshProposition();
  }
}

function matchPRefresh()
{
  if(this.isArmed)
  {
    this.obj.style.borderColor = this.exercise.colors[1]; 
    document.body.style.cursor = browserParamsManager.cursorPointer;
  }
  else
  {
    this.obj.style.borderColor = this.exercise.colors[0]; 
    document.body.style.cursor = "default";
  }
}

function matchPResetLine()
{
  if(!this.isEnabled)
    return;
  
  this.line.style.visibility = "visible"; 

  var x = window.event.x;
  var y = window.event.y;
  this.line.style.posLeft = x + document.body.scrollLeft;
  this.line.style.posTop = y + document.body.scrollTop;  
  this.line.firstChild.from = "0px,0px";
  this.line.firstChild.to = "0px,0px";

  document.body.style.cursor = browserParamsManager.cursorPointer;

  curMovingObject = this.exercise;
  this.exercise.curLinkingProposition = this;
}

function matchPMoveLine()
{
  if(!this.isEnabled)
    return;

  if(this.line.style.visibility == "visible")
  {
    var x = window.event.x + document.body.scrollLeft - this.line.style.posLeft + this.exercise.offsetXFromCursor;
    var y = window.event.y + document.body.scrollTop - this.line.style.posTop + this.exercise.offsetYFromCursor;
    this.line.firstChild.to = x.toString() + "px," + y.toString() + "px";
    this.line.firstChild.strokeColor = "RGB(75,75,75)";            
      
    document.body.style.cursor = browserParamsManager.cursorPointer;
  }
}

function matchPSetCurrentSinkZone()
{
  this.currentSinkZone = null;
  this.hasFired = false;  
  
  for(var i=0; i < this.exercise.matchSinkZones.length; i++)
  {
    if((window.event.srcElement.id == this.exercise.matchSinkZones[i].obj.id) ||
		(window.event.srcElement.parentElement.id == this.exercise.matchSinkZones[i].obj.id))
    {
      this.hasFired = true;
      this.currentSinkZone = this.exercise.matchSinkZones[i];
    }
  }
}

function matchPRefreshCurrentLink()
{
  if(this.currentSinkZone)
  {
    var x1,y1;
    var x2,y2;
    x1 = this.obj.style.posLeft + this.obj.style.posWidth;
    y1 = this.obj.style.posTop + (this.obj.style.posHeight/2);
    x2 = this.currentSinkZone.obj.style.posLeft - x1;
    y2 = this.currentSinkZone.obj.style.posTop + (this.currentSinkZone.obj.style.posHeight/2) - y1;
    this.line.style.posLeft = x1;
    this.line.style.posTop = y1;  
    this.line.firstChild.to = x2.toString() + "px," + y2.toString() + "px";
    this.line.style.visibility = "visible";    
  }
  else
    this.line.style.visibility = "hidden";
}

function matchPEndMoveLine()
{
  if(!this.isEnabled)
    return;

  document.body.style.cursor = "default";
  this.matchPSetCurrentSinkZone();
  this.matchPRefreshCurrentLink();
  if(this.exercise.isAutomatic)
	this.exercise.evaluate();
  
  if(this.currentSinkZone)
    this.currentSinkZone.matchRefreshSinkZone(false);
  
  curMovingObject = null;
  this.exercise.curLinkingProposition = null;  
}

function matchIsAnswerCorrect()
{
  return (this.currentSinkZone == this.correctSinkZone);
}

function matchShowPSolution()
{
  if(this.correctSinkZone)
  {
    var x1,y1;
    var x2,y2;
    x1 = this.obj.style.posLeft + this.obj.style.posWidth;
    y1 = this.obj.style.posTop + (this.obj.style.posHeight/2);
    x2 = this.correctSinkZone.obj.style.posLeft - x1;
    y2 = this.correctSinkZone.obj.style.posTop + (this.correctSinkZone.obj.style.posHeight/2) - y1;
    this.line.style.visibility = "visible";
    this.line.firstChild.strokeColor = this.exercise.colors[4];
    this.line.style.posLeft = x1;
    this.line.style.posTop = y1;	
    this.line.firstChild.to = x2.toString() + "px," + y2.toString() + "px";
  }
  else
    this.line.style.visibility = "hidden";
    
  this.obj.style.borderColor = this.exercise.colors[4];    
}

function matchShowPCorrection()
{
  if(this.currentSinkZone)
  {
    var x1,y1;
    var x2,y2;
    x1 = this.obj.style.posLeft + this.obj.style.posWidth;
    y1 = this.obj.style.posTop + (this.obj.style.posHeight/2);
    x2 = this.currentSinkZone.obj.style.posLeft - x1;
    y2 = this.currentSinkZone.obj.style.posTop + (this.currentSinkZone.obj.style.posHeight/2) - y1;
    this.line.style.visibility = "visible";
    if(this.isAnswerCorrect())
      this.line.firstChild.strokeColor = this.exercise.colors[4];            
    else
      this.line.firstChild.strokeColor = this.exercise.colors[5];                
    this.line.style.posLeft = x1;
    this.line.style.posTop = y1;	
    this.line.firstChild.to = x2.toString() + "px," + y2.toString() + "px";
  }
  else
    this.line.style.visibility = "hidden";
    
  if(this.isAnswerCorrect())
    this.obj.style.borderColor = this.exercise.colors[4];
  else
    this.obj.style.borderColor = this.exercise.colors[5];
}

function matchShowPIndication()
{
  if(this.isAnswerCorrect())
  {
    this.line.firstChild.strokeColor = this.exercise.colors[4];  
    this.isEnabled = false;              
  }
  else
  {
    this.line.firstChild.strokeColor = this.exercise.colors[5];              
    this.PReset();
  }
}

function matchProposition(correctSinkZone, label, hasFinalFeedback, finalFeedback, hasTryAgainFeedback, tryAgainFeedback) 
{
  this.base = proposition;
  this.base(hasFinalFeedback, label, finalFeedback, hasTryAgainFeedback, tryAgainFeedback);

  this.isInitialPositionUsed = false;
  this.refreshProposition = matchPRefresh;
  this.onActiveProposition = onMatchActiveProposition;
  this.onLeaveProposition = onMatchLeaveProposition;

  this.line = null;
  this.matchPResetLine = matchPResetLine;
  this.matchPMoveLine = matchPMoveLine;
  this.matchPEndMoveLine = matchPEndMoveLine;

  this.currentSinkZone = null;
  this.matchPSetCurrentSinkZone = matchPSetCurrentSinkZone;
  this.matchPRefreshCurrentLink = matchPRefreshCurrentLink;

  this.correctSinkZone = correctSinkZone;
  this.isAnswerCorrect = matchIsAnswerCorrect;
  this.showPSolution = matchShowPSolution;
  this.showPCorrection = matchShowPCorrection;
  this.showPIndication = matchShowPIndication;
}

function matchFindNextProposition(i, propositions) {
    var j = 0;
    if (i != (propositions.length - 1)) {
       j = random(propositions.length - i);
    }
    var k = -1;
    var ii = -1;
    do {
       ii++;
       if ( ! propositions[ii].isInitialPositionUsed) { k++; }
    }
    while (k != j)
    return ii;
}

var matchNextTab = 1;
function matchShuffle() 
{
  for (var i = 0; i < this.propositions.length; i++) 
  {
     this.propositions[i].obj.initialTop = -1;
  }

  for (var i = 0; i < this.propositions.length; i++) 
  {
    var ii = matchFindNextProposition(i, this.propositions);
    this.propositions[ii].isInitialPositionUsed = true;

    if (this.propositions[ii].obj.initialTop == -1) 
    {
      this.propositions[ii].obj.initialTop = this.propositions[ii].obj.style.top;
      this.propositions[ii].obj.initialLeft = this.propositions[ii].obj.style.left;
      this.propositions[ii].text.initialTop = this.propositions[ii].text.style.top;
      this.propositions[ii].text.initialLeft = this.propositions[ii].text.style.left;
    }

    this.propositions[i].obj.initialTop = this.propositions[i].obj.style.top;
    this.propositions[i].obj.initialLeft = this.propositions[i].obj.style.left;
    this.propositions[i].obj.style.top = this.propositions[ii].obj.initialTop;
    this.propositions[i].obj.style.left = this.propositions[ii].obj.initialLeft;
    
    this.propositions[i].text.initialTop = this.propositions[i].text.style.top;
    this.propositions[i].text.initialLeft = this.propositions[i].text.style.left;
    this.propositions[i].text.style.top = parseInt(this.propositions[ii].obj.initialTop) + parseInt(parseInt(this.propositions[i].text.initialTop) - parseInt(this.propositions[i].obj.initialTop));
    this.propositions[i].text.style.left = parseInt(this.propositions[ii].obj.initialLeft) + parseInt(parseInt(this.propositions[i].text.initialLeft) - parseInt(this.propositions[i].obj.initialLeft));

    this.propositions[i].obj.tabIndex = matchNextTab + ii;
  }

  matchNextTab += this.propositions.length;
}

function matchRefreshSinkZone(highlight)
{
  if(highlight && this.exercise.curLinkingProposition)
    this.obj.style.borderColor = this.exercise.colors[3]; 
  else
    this.obj.style.borderColor = this.exercise.colors[2]; 
}

function matchSinkZone(label)
{
  this.obj = null;
  this.label = label;
  this.matchRefreshSinkZone = matchRefreshSinkZone;
}

function matchRegisterSinkZone(sinkZone, label)
{
   this.matchSinkZones[this.matchSinkZones.length] = sinkZone;
}

function matchMoveLine()
{
  if(this.curLinkingProposition)
    this.curLinkingProposition.matchPMoveLine();
}

function matchEndMoveLine()
{
  if(this.curLinkingProposition)
    this.curLinkingProposition.matchPEndMoveLine();
}

function matchEvaluateExercice()
{
  for (var i=0; i < this.propositions.length; i++) 
  {
    var p = this.propositions[i];
    this.nbAnswersToFind += 1;
    
    if (p.isAnswerCorrect()) 
    {
      this.nbCorrectAnswers += 1;
      if(p.correctSinkZone)
        this.nbCorrectAnswersNotTrap += 1;
    }

    if ( p.hasLearnerAnswered() ) 
    {
	  this.hasLearnerAnswered = true;
	  if ( ! p.isAnswerCorrect())
	  {
	    this.nbLastTryErrors += 1;
	  }
	}
  }  

  if((this.propositions.length == 1) && this.propositions[0].isAnswerCorrect())
    this.hasLearnerAnswered = true;
}

function matchExercise(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
             isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
             isSolutionShown,
             correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback)
{
   this.base = exercise;
   this.base(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
             isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
             isSolutionShown,
             correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback);

   this.shuffle = matchShuffle;
   
   this.curLinkingProposition = null;
   this.matchMoveLine = matchMoveLine;
   this.matchEndMoveLine = matchEndMoveLine;
   this.offsetXFromCursor = -5;
   this.offsetYFromCursor = -5;
   
   this.matchSinkZones = new Array;
   this.matchRegisterSinkZone = matchRegisterSinkZone;
   
   this.colors = null;
   this.showUserSolution = true;
   this.evaluateExercice = matchEvaluateExercice;   

   this.sendInteractionToLMS = matchSendInteractionToLMS;
}

function mceSendInteractionToLMS(){
	this._sendInteractionToLMS("choice");
}

function findEvaluateExercice() {
   for (var i = 0; i < this.propositions.length; i++) {
      var p = this.propositions[i];
      if (p.isCorrect) {
         this.nbAnswersToFind += 1;
         if (p.isAnswerCorrect()) {
            this.nbCorrectAnswers += 1;
            this.nbCorrectAnswersNotTrap += 1;
         }
      }
      if ( p.hasLearnerAnswered() ) {
		this.hasLearnerAnswered = true;
		if ( ! p.isAnswerCorrect())
		{
		   this.nbLastTryErrors += 1;
		}
	  }
   }
}

function findExercise(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
             isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
             isSolutionShown,
             correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback)
{
   this.base = exercise;
   this.base(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
             isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
             isSolutionShown,
             correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback);

   this.showUserSolution = true;
   this.evaluateExercice = findEvaluateExercice;
   this.sendInteractionToLMS = findSendInteractionToLMS;
}

function findSendInteractionToLMS(){
	this._sendInteractionToLMS("choice");
}

function formEvaluateExercice() {
   for (var i = 0; i < this.propositions.length; i++) {
        this.nbAnswersToFind += 1;
		var p = this.propositions[i];
		if (p.disabled)
			break;
 	    if ((this.isAutomatic) && (this.lastActivatedChoiceNo != i )) {
 	    	if (p.isAnswerCorrect() &&  p.hasFired) {
			    this.nbCorrectAnswers += 1;
			}
 			continue;
 		}
		p.userAnswer = p.obj.value + "";
		if (p.isAnswerCorrect()) {
		    this.nbCorrectAnswers += 1;
			if (p.answers.length > 0 || p.answers[0].value != "") {
			     this.nbCorrectAnswersNotTrap += 1;
			}
		}
	    if ( p.hasLearnerAnswered() ){
			this.hasLearnerAnswered = true;
			if ( ! p.isAnswerCorrect()) {
			   this.nbLastTryErrors += 1;
			}
		}
   }
	if (this.propositions.length == 1 && this.propositions[0].isAnswerCorrect()) {
		this.hasLearnerAnswered = true;
	}
}

function formOnKeyPress(choiceNo, evt) { 
  var nKeyCode;
  if(evt.keyCode){  
    nKeyCode = evt.keyCode;
  }else{
    nKeyCode = evt.which; // pour FF
  }

  if (nKeyCode == 13) {
    if (this.isAutomatic) {
      var p = this.propositions[choiceNo];
      if (p.isEnabled) {
        this.lastActivatedChoiceNo = choiceNo;
        p.setFired(true);
        this.evaluate();
      }
    }
  }
}

function formOnChange(choiceNo)
{
	if (window.event.type != "keypress")  
	{
		if (this.isAutomatic) {
			var p = this.propositions[choiceNo];

			if (p.isEnabled) {
			   this.lastActivatedChoiceNo = choiceNo;
			   p.setFired(true);
  		       this.evaluate();
			}
		}
	}
}

function formExercise(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
                  isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
                  isSolutionShown,
                  correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback)
{
   this.base = exercise;
   this.base(exID, isAutomatic, nbAllowedErrors, giveClues, showPassFlag, allOfMany, 
             isTest, isCertification, testMaxScore, doesGivePointsWhenFail,
             isSolutionShown,
             correctFeedback, partlyCorrectFeedback, givenFeedback, tryAgainFeedback);

   this.showUserSolution = true;

   this.evaluateExercice = formEvaluateExercice;
   this.onKeyPress = formOnKeyPress;
   this.onChange = formOnChange;
   this.sendInteractionToLMS = formSendInteractionToLMS;
}

function formSendInteractionToLMS(){
	var correctResponse="", studentResponse="", nbStudentPropositions=0;
	var nbPropositions = this.propositions.length, separateur=", ";
	if(parent.runTimeEnvType < runTimeEnvSCORM12){
		if (!this.allOfMany)	separateur="; ";
		for (var i=0; i<nbPropositions; i++){
			var p = this.propositions[i];
			if (i > 0)	correctResponse += separateur;
			correctResponse += p.label + "=";
			if (p.checkCase)
				correctResponse += "<case> " +  display(p.answers[0]);
			else	
				correctResponse += display(p.answers[0]);
			if (p.hasLearnerAnswered()){
				if (nbStudentPropositions > 0)	
					studentResponse += ", ";
				studentResponse += p.label + "=";
				studentResponse += p.userAnswer;
				nbStudentPropositions++;
			}
		}
		if ((nbPropositions > 1) && (this.allOfMany))	correctResponse = "{" + correctResponse + "}";
		if (nbStudentPropositions > 1)	studentResponse = "{" + studentResponse + "}";
	}
	else if(parent.runTimeEnvType == runTimeEnvSCORM12){
		separateur=",";
		for (var i=0; i<nbPropositions; i++){
			var p = this.propositions[i];
			if (i > 0)	correctResponse += separateur;
			correctResponse += p.label + "=";
			if (p.checkCase)
				correctResponse += "{case_matters=true} " +  display(p.answers[0]);
			else	
				correctResponse += display(p.answers[0]);
			if (p.hasLearnerAnswered()){
				if (nbStudentPropositions > 0)	
					studentResponse += separateur;
				studentResponse += p.label + "=";
				studentResponse += p.userAnswer;
				nbStudentPropositions++;
			}
		}
		if ((nbPropositions > 1) && (this.allOfMany))	correctResponse = "{" + correctResponse + "}";
		if (nbStudentPropositions > 1)	studentResponse = "{" + studentResponse + "}";
	}
	else if(parent.runTimeEnvType >= runTimeEnvSCORM13){
//implantation doit différer des autres -> reporté
		separateur=",";
		for (var i=0; i<nbPropositions; i++){
			var p = this.propositions[i];
			if (i > 0)	correctResponse += separateur;
			correctResponse += p.label + "=";
			if (p.checkCase)
				correctResponse += "{case_matters=true} " +  display(p.answers[0]);
			else	
				correctResponse += display(p.answers[0]);
			if (p.hasLearnerAnswered()){
				if (nbStudentPropositions > 0)	
					studentResponse += separateur;
				studentResponse += p.label + "=";
				studentResponse += p.userAnswer;
				nbStudentPropositions++;
			}
		}
	}

	// Set Values des interactions	
	if ((parent != null) && (parent.api != null)){
		var elt = "cmi.interactions." + parent.TOC.course.nbInteraction + ".";
		if(parent.runTimeEnvType <= runTimeEnvSCORM12){
		  parent.api.LMSSetValue(elt+"id", parent.TOC.course.getLEFrom(path).name.replace(/ /g, "_") + "-" + this.exID + "-" + nbStudentPropositions);
		  parent.api.LMSSetValue(elt+"type", "fill-in");
		  parent.api.LMSSetValue(elt+"time", getCurrentLocalTime());
	 	  parent.api.LMSSetValue(elt+"latency", getTimeDiff(this.interactionBeginningTime, ConvertTimeToSecond()));
		  this.interactionBeginningTime = ConvertTimeToSecond();
		  parent.api.LMSSetValue(elt+"weighting", this.testMaxScore);
		  parent.api.LMSSetValue(elt+"correct_responses.0.pattern", correctResponse);
		  parent.api.LMSSetValue(elt+"student_response", studentResponse);
		  parent.api.LMSSetValue(elt+"result", LMSRESULT[this.state]);

                }
		else if(parent.runTimeEnvType >= runTimeEnvSCORM13){
		  parent.api.SetValue(elt+"id", parent.TOC.course.getLEFrom(path).name.replace(/ /g, "_") + "-" + this.exID + "-" + nbStudentPropositions);
		  parent.api.SetValue(elt+"type", "fill-in");
  		  parent.api.SetValue(elt+"timestamp", getFullTimeStamp());
	 	  parent.api.SetValue(elt+"latency", getTimeDiff(this.interactionBeginningTime, ConvertTimeToSecond()));
		  this.interactionBeginningTime = ConvertTimeToSecond();
		  parent.api.SetValue(elt+"weighting", this.testMaxScore);
		  parent.api.SetValue(elt+"correct_responses.0.pattern", correctResponse);
		  parent.api.SetValue(elt+"learner_response", studentResponse);
		  parent.api.SetValue(elt+"result", LMSRESULT[this.state]);
        }

		parent.TOC.course.nbInteraction++;
	}
}

function StopClock() {
	if(this.timerRunning)
		clearTimeout(this.timerID);
  	this.timerRunning = false;
}

function CloseChildPopups() {
	aPopupManager.ClosePopup();
}

function StartPopupTimer(timeShowing) {
	this.StopClock();
	if((timeShowing >= 2) && (this.autoClosePopup))
	{
		this.timerID=setTimeout("CloseChildPopups();", timeShowing);
		this.timerRunning = true;
	}
}

function AskPopupClose() {
	this.window.opener.CloseChildPopups();
}

function ClosePopup() {
	if(this.thePopup != null) {
		this.StopClock();
			// règle un bogue dans NS, sinon le popup ne peut plus s'ouvrir
			// lorsqu'on le ferme avec le X en haut à droite du popup
		if (!this.thePopup.closed)
			this.thePopup.close();
		//if (this.thePopup.closed)
		this.thePopup=null;	
	}
}
function _onUnloadPopup() {
  CloseChildPopups();
}
function PopupManager()
{
	this.thePopup			= null;
	this.timerID			= null;
	this.timerRunning		= false;
	this.autoClosePopup		= false;
	this.ClosePopup			= ClosePopup;
	this.StartPopupTimer	= StartPopupTimer;
	this.StopClock			= StopClock;
}

var	aPopupManager= new PopupManager();

function ConvertToBrowserWidth(marginLeft){
	return (parseInt(screen.width)-(ConvertToTopBrowserCoordinatesX(marginLeft)*2));
}

function ConvertToBrowserHeight(marginBottom){
	return (parseInt(screen.height)-ConvertToBrowserCoordinatesY(marginBottom)-70);
}

function ConvertToBrowserCoordinatesX(oldX)
{
	if(browserParamsManager.browserName.indexOf('msie')>=0) { // IE
		return (window.screenLeft + oldX) - document.body.scrollLeft;
	}else{
		return (parseInt(window.outerWidth - window.innerWidth) + oldX + window.screenX - 5);
	}
}

function ConvertToTopBrowserCoordinatesX(oldX)
{
  if ((parent.frames.length > 0) && !isStandAlone && parent.TOC.isTOCReady)
  {
      if (browserParamsManager.browserName.indexOf('msie')>=0)
      {
		return (parent.TOC.screenLeft + oldX);
      }
      else
      {
		return (parseInt(parent.window.outerWidth - parent.window.innerWidth) + oldX + parent.window.screenX - 5);
      }
  }
  else
  {
    return ConvertToBrowserCoordinatesX(oldX);
  }	
}


function ConvertToBrowserCoordinatesY(oldY)
{
	if (browserParamsManager.browserName.indexOf('msie')>=0){
		return (window.screenTop + oldY ) - document.body.scrollTop;
	}else{
		if(isStandAlone){
			return (parseInt(window.outerHeight - window.innerHeight ) + window.screenY + oldY - 25); 
		}else if(!parent.TopBanner){ 
			return (parseInt(parent.window.outerHeight - parent.window.innerHeight ) + oldY + parent.window.screenY - 25); 
		}else 
			return (parseInt(parent.window.outerHeight - parent.window.innerHeight ) + oldY + parent.window.screenY + parent.TopBanner.window.innerHeight - 25); 
	}
}

function openPopup(destination, name, left, top, width, height, isAutoclose) 
{
  pauseSynchro();

  var windowprops = "location=no,scrollbars=no,menubars=no,toolbars=no,resizable=no" + ",left=" + ConvertToBrowserCoordinatesX(left) + 
                    ",top=" + ConvertToBrowserCoordinatesY(top) + ",width=" + width + ",height=" + height;
  //aPopupManager.ClosePopup();
  aPopupManager.autoClosePopup = isAutoclose;
  aPopupManager.thePopup = window.open(destination, name, windowprops);
  aPopupManager.thePopup.onunload=ClosePopup;
  aPopupManager.thePopup.focus();
}

function GoLink(documentToGo)
{
	FindTopMostWindow(self).location=documentToGo;
}
function FindTopMostWindow(fenetre)
{
	if(fenetre == null)
		return fenetre;
	else
	{
		if(fenetre.opener != null)
			return FindTopMostWindow(fenetre.opener);
		else
			return fenetre;
	}
}

function SystemWindowsHandler()
{
	this.windowCounter = 0;
	this.windowsArray = new Array(25);
	this.windowsArray[0] = null;
	this.addSystemWindow = addSystemWindow;
	this.closeAllSystemWindow = closeAllSystemWindow;
}

function addSystemWindow(wndToAdd)
{
	this.windowsArray[this.windowCounter]=wndToAdd;
	this.windowCounter++;
}

function closeAllSystemWindow()
{
	for(var t=0;t<this.windowCounter;t++)
		this.windowsArray[t].close();
}

var aSystemWindowHandler=null;
aSystemWindowHandler = new SystemWindowsHandler();

function SystemWnd(title, styles, closeLabel)
{
	this.title = title;
	this.styles = styles;
	this.closeLabel = closeLabel;
	this.isWndCreated = false;
	this.close = closeSystemWnd;
}

function ObjectivesWnd(title, courseName, objectives, styles, closeLabel)
{
	this.base = SystemWnd;
	this.base(title, styles, closeLabel);
	this.courseName = courseName;
	this.objectives = objectives;
	this.open = openObjWnd;
	this.openedWindow = null;
}

function TestResultsWnd(wndName, title, textColor, resultsColor, results, styles, closeLabel)
{
	this.base = SystemWnd;
	this.base(title, styles, closeLabel);
	this.wndName = wndName;
	this.results = results;
	this.open = openTestResultsWnd;
	this.Results = Results;
	this.textColor = textColor;
	this.resultsColor = resultsColor;
}

function ExerciseResultsWnd(wndName, title, textColor, resultsColor, results, styles, closeLabel)
{
	this.base = SystemWnd;
	this.base(title, styles, closeLabel);
	this.wndName = wndName;
	this.results = results;
	this.open = openExerciseResultsWnd;
	this.Results = Results;
	this.textColor = textColor;
	this.resultsColor = resultsColor;
}

ObjectivesWnd.prototype = new SystemWnd;
TestResultsWnd.prototype = new SystemWnd;
ExerciseResultsWnd.prototype = new SystemWnd;

function openObjWnd()
{
	pauseSynchro();

	if((this.isWndCreated == false) || (objectivesWindow.closed == true))
	{
		aSystemWindowHandler.closeAllSystemWindow();
		objectivesWindow=open("","objectives","scrollbars=no,width=412,height=328,top="+parseInt(parseInt(screen.availHeight-328)/2)+",left=" + parseInt(parseInt(screen.availWidth-412)/2));
		objectivesWindow.document.open();
		objectivesWindow.document.write("<HEAD><TITLE>"+this.title+"</TITLE>"+this.styles+"</HEAD><BODY>");
		objectivesWindow.document.write("<B><FONT color=white size=+1>" + this.courseName + "</FONT></B>");
		objectivesWindow.document.write("<B><FONT color=white size=+1>" + this.objectives + "</FONT></B>");
		objectivesWindow.document.write("<DIV ID='closeBanner' STYLE='position:absolute; left:0px; top:276px; width:412px; height:50px; z-index:0; layer-background-color:rgb(243,244,247);background-color:rgb(243,244,247);border-color:rgb(243,244,247);border:outset 1px;visibility: visible;'><IMG SRC='image/_blank.gif' BORDER=0 WIDTH=409 HEIGHT=50></IMG></DIV>");
		objectivesWindow.document.write("<DIV ID='close' STYLE='position:absolute; left:342px; top:289px; width:50px; height:30px; z-index:1; visibility: visible;'>");
		objectivesWindow.document.write("<FORM><CENTER><INPUT TYPE=Button VALUE=");
		objectivesWindow.document.write(this.closeLabel);
		objectivesWindow.document.write(" STYLE='cursor: "+browserParamsManager.cursorPointer+";' onClick='opener.window.anObjWnd.close();'></CENTER></INPUT>");
		objectivesWindow.document.write("</FORM></DIV></BODY>");
		this.isWndCreated = true;
		this.openedWindow = objectivesWindow;
	}
	else
	{
		objectivesWindow.window.focus();
	}
}

function closeSystemWnd()
{
	if((this.isWndCreated == true) && (this.openedWindow.closed == false))
	{
		this.openedWindow.window.close();
		this.isWndCreated = false;
	}
}

function Results(leName, nbTests, nbCompletedTests, score)
{
	this.leName = leName;
	this.nbTests = nbTests;
	this.nbCompletedTests = nbCompletedTests;
	this.scoreString = score;
}

function openTestResultsWnd()
{
	pauseSynchro();

	if((this.isWndCreated == false) || (testResultsWindow.closed == true))
	{
		aSystemWindowHandler.closeAllSystemWindow();
		testResultsWindow=open("","testResults","scrollbars=no,width=480,height=328,top="+parseInt(parseInt(screen.availHeight-328)/2)+",left=" + parseInt(parseInt(screen.availWidth-480)/2));
		testResultsWindow.document.open();
		testResultsWindow.document.write("<HEAD><TITLE>"+this.title+"</TITLE>"+this.styles+"</HEAD><BODY>");

		resultsString = this.results;
		resultsString=resultsString.replace(/@@@/i, "<B><FONT color=" + this.textColor + " size=+2>" + this.leName +  "</FONT></B>");
		resultsString=resultsString.replace(/@@@/i, "<B><FONT color=" + this.resultsColor + " size=+1>" + this.nbTests +  "</FONT></B>");
		resultsString=resultsString.replace(/@@@/i, "<B><FONT color=" + this.resultsColor + " size=+1>" + this.nbCompletedTests +  "</FONT></B>");
		resultsString=resultsString.replace(/@@@/i, "<B><FONT color=" + this.resultsColor + " size=+1>" + this.scoreString +  "</FONT></B>");
		testResultsWindow.document.write(resultsString);
		testResultsWindow.document.write("<DIV ID='closeBanner' STYLE='position:absolute; left:0px; top:276px; width:480px; height:50px; z-index:0; layer-background-color:rgb(243,244,247);background-color:rgb(243,244,247);border-color:rgb(243,244,247);border:outset 1px;visibility: visible;'><IMG SRC='image/_blank.gif' BORDER=0 WIDTH=477 HEIGHT=50 ></IMG></DIV>");
		testResultsWindow.document.write("<DIV ID='close' STYLE='position:absolute; left:400px; top:289px; width:50px; height:30px; z-index:1; visibility: visible;'>");
		testResultsWindow.document.write("<FORM><CENTER><INPUT TYPE=Button VALUE=");
		testResultsWindow.document.write(this.closeLabel);
		testResultsWindow.document.write(" STYLE='cursor: "+browserParamsManager.cursorPointer+";' onClick='opener.window."+this.wndName+".close();'></CENTER></INPUT>");
		testResultsWindow.document.write("</FORM></DIV></BODY>");
		this.isWndCreated = true;
		this.openedWindow = testResultsWindow;
	}
	else
	{
		testResultsWindow.window.focus();
	}
}
function openExerciseResultsWnd()
{
	pauseSynchro();

	if((this.isWndCreated == false) || (exerciseResultsWnd.closed == true))
	{
		aSystemWindowHandler.closeAllSystemWindow();
		exerciseResultsWnd=open("","exerciseResults","scrollbars=no,width=412,height=328,top="+parseInt(parseInt(screen.availHeight-328)/2)+",left=" + parseInt(parseInt(screen.availWidth-412)/2));
		exerciseResultsWnd.document.open();
		exerciseResultsWnd.document.write("<HEAD><TITLE>"+this.title+"</TITLE>"+this.styles+"</HEAD><BODY>");

		resultsString = this.results;
		resultsString=resultsString.replace(/@@@/i, "<B><FONT color=" + this.textColor + " size=+2>" + this.leName +  "</FONT></B>");
		resultsString=resultsString.replace(/@@@/i, "<B><FONT color=" + this.resultsColor + " size=+1>" + this.nbTests +  "</FONT></B>");
		resultsString=resultsString.replace(/@@@/i, "<B><FONT color=" + this.resultsColor + " size=+1>" + this.nbCompletedTests +  "</FONT></B>");
		resultsString=resultsString.replace(/@@@/i, "<B><FONT color=" + this.resultsColor + " size=+1>" + this.scoreString +  "</FONT></B>");
		exerciseResultsWnd.document.write(resultsString);
		exerciseResultsWnd.document.write("<DIV ID='closeBanner' STYLE='position:absolute; left:0px; top:276px; width:412px; height:50px; z-index:0; layer-background-color:rgb(243,244,247);background-color:rgb(243,244,247);border-color:rgb(243,244,247);border:outset 1px;visibility: visible;'><IMG SRC='image/_blank.gif' BORDER=0 WIDTH=409 HEIGHT=50 ></IMG></DIV>");
		exerciseResultsWnd.document.write("<DIV ID='close' STYLE='position:absolute; left:342px; top:289px; width:50px; height:30px; z-index:1; visibility: visible;'>");
		exerciseResultsWnd.document.write("<FORM><CENTER><INPUT TYPE=Button VALUE=");
		exerciseResultsWnd.document.write(this.closeLabel);
		exerciseResultsWnd.document.write(" STYLE='cursor: "+browserParamsManager.cursorPointer+";' onClick='opener."+this.wndName+".close();'></CENTER></INPUT>");
		exerciseResultsWnd.document.write("</FORM></DIV></BODY>");
		this.isWndCreated = true;
		this.openedWindow = exerciseResultsWnd;
	}
	else
	{
		exerciseResultsWnd.window.focus();
	}
}

function show(obj)
{
  obj.style.visibility = "visible";
}
function hidde(obj)
{
  obj.style.visibility = "hidden";
}

function init() {
}

function _onUnloadDocument()
{
  if(anObjWnd)
    anObjWnd.close();
  CloseChildPopups(); 
  aSystemWindowHandler.closeAllSystemWindow();
}

isStandAlone = true;
if (self != top && 
    self.name == "TacticDocument" && parent.TOC != null)
{
  isStandAlone = false;
}

function display(str){
	s2 = "";
	while (str.length > parseInt(0)){
		pos = str.indexOf("%",0);
		if (parseInt(pos) > 0){
			s2 = s2 + str.substring(0,parseInt(pos));
		}
		car = str.substring(pos+1,pos+3);
		car = parseInt(car,16) - 2;
		str = str.substring(pos+3,str.length);
		s2 = s2 + String.fromCharCode(car);
	}
	if(s2 == "true" || s2 == "TRUE")	return true;
	if(s2 == "false" || s2 == "FALSE")	return false;
	return s2;
}


function pathAbsolut(str){
	
if(document.location.protocol == "file:")	
{	
	s0 = pathname = document.location.pathname;
	s1 = subpathname = pathname.substring(0,2);
	if(subpathname == "//")
	{
		pathname = document.location.href;
		pos = pathname.lastIndexOf("/");
		s2 = subsubname= pathname.substring(0,pos);
		pos = subsubname.lastIndexOf("/");
		s3 = newsubname = subsubname.substring(0,pos+1);
		newpathname = newsubname + str;
	
	}
	else
	{
		subsubname = (pathname.substring(1,2) + ":" + pathname.substring(3,pathname.length));
		pos = subsubname.lastIndexOf("/");
		newsubname = subsubname.substring(0,pos);
		pos = newsubname.lastIndexOf("/");
		subnewsubname = newsubname.substring(0,pos+1);
		newpathname = subnewsubname + str;
	}
}	
else
{
		pathname = document.location.href;
		pos = pathname.lastIndexOf("/");
		subsubname = pathname.substring(0,pos);
		pos = subsubname.lastIndexOf("/");
		newsubname = subsubname.substring(0,pos+1);
		newpathname = newsubname + str;
}
	return newpathname;
}

function getValueFromAPI(param)
{
	if (parent != null && parent.api != null){
		return parent.api.LMSGetValue(param);
	}
}

// PR : Cette fonction n'est présentement pas utilisée
// et n'a jamais été testée
function setValueToAPI(param, value)
{
	if (parent != null && parent.api != null){
		parent.api.LMSSetValue(param, value);
	}
}

function setEPCLessonScore(score)
{
  if (!isStandAlone && parent.TOC.isTOCReady)
	parent.TOC.course.epcLessonScore = score;
  else
        alert('Stand Alone Context !!!');
}

function setEPCLessonStatus(status)
{
  if (!isStandAlone && parent.TOC.isTOCReady)
	parent.TOC.course.epcLessonStatus = status;
  else
        alert('Stand Alone Context !!!');
}

///////////////////////////////////////////////////////////////////////

/* remplacé par synchroReload()
function synchroGoBeginning()
{
if(browserParamsManager.browserName.indexOf('msie')<0) // FF
  return;

	if(!this.timeline || (this.documentDur <= 0))
		return;

	if(this.playerObj && (this.isEnd || this.playerDiv.currTimeState.isActive)) // si le player n'est pas actif sur la ligne de temps, il y a erreur
	{
		this.playerObj.Stop();
		this.playerObj.currentPosition = 0;
	}
	// nécessaire dans le cas où la video s'est terminée avant la fin du temps du document
	if(this.playerDiv){
		this.playerDiv.style.visibility = "visible"; 
		if(this.playerDiv.firstChild)
			this.playerDiv.firstChild.style.visibility = "visible";
	}

	this.timeline.beginElement();
	if(window.parent.TopBanner)
		window.parent.TopBanner.timeline.beginElement();
	if(window.parent.BottomBanner)
		window.parent.BottomBanner.timeline.beginElement();
	this.isEnd = false;
}
*/

function synchroGoEnd()
{
if(browserParamsManager.browserName.indexOf('msie')<0) // FF
  return;

  if(!this.timeline || (this.documentDur <= 0))
    return;

  if(this.isEnd)
    return;

  if(this.playerObj && this.playerDiv.currTimeState.isActive) // si le player n'est pas actif sur la ligne de temps, il y a erreur
  {
    this.playerObj.Pause();
    this.playerObj.currentPosition = this.playerObj.duration;
  }
  this.timeline.pauseElement();
  this.timeline.seekTo(0,this.documentDur);

  this.isEnd = true;
}

function synchroPlay()
{
if(browserParamsManager.browserName.indexOf('msie')<0) // FF
  return;

	if(!this.timeline || (this.documentDur <= 0))
		return;

	if(this.isEnd || (this.timeline.currTimeState.activeTime >= this.documentDur)) 
		this.reload();//this.goBeginning();
	else
	{
		this.timeline.resumeElement();
		if(window.parent.TopBanner)
			window.parent.TopBanner.timeline.resumeElement();
		if(window.parent.BottomBanner)
			window.parent.BottomBanner.timeline.resumeElement();
		if(this.playerObj && (this.playerObj.PlayState == 1)) // pour A/V avec offset
			this.playerObj.Play();

	}
}

function synchroPause()
{
if(browserParamsManager.browserName.indexOf('msie')<0) // FF
  return;

	if(!this.timeline || (this.documentDur <= 0))
		return;

	this.timeline.pauseElement();
	if(window.parent.TopBanner)
		window.parent.TopBanner.timeline.pauseElement();
	if(window.parent.BottomBanner)
		window.parent.BottomBanner.timeline.pauseElement();
	if(this.playerObj && (this.playerObj.PlayState == 2)) // pour A/V avec offset
		this.playerObj.Pause();

}

function synchroReload(){
	window.location.reload(); 

if(browserParamsManager.browserName.indexOf('msie')<0) // FF
  return;

	if(window.parent.TopBanner)
		window.parent.TopBanner.timeline.beginElement();
	if(window.parent.BottomBanner)
		window.parent.BottomBanner.timeline.beginElement();
	this.isEnd = false;
}

function synchroMgr(isSynchro, documentDur, timeline)
{
  this.timeline = timeline;
  this.isSynchro = isSynchro;
  this.playerObj = null;
  this.playerDiv = null;
  this.documentDur = documentDur;
  this.isEnd = false;

  this.play = synchroPlay;
  this.pause = synchroPause;
  this.reload = synchroReload;
//  this.goBeginning = synchroGoBeginning;
  this.goEnd = synchroGoEnd;
}

function pauseSynchro()
{
if(browserParamsManager.browserName.indexOf('msie')<0) // FF
  return;

	if(synchroManager)
		synchroManager.pause();
	else if(parent && parent.TacticDocument && parent.TacticDocument.synchroManager)
		parent.TacticDocument.synchroManager.pause();
}

///////////////////////////////////////////////////////////////////////

var deg2radians = Math.PI * 2 / 360;
function SetRotation(obj, deg)
{
  rad = deg * deg2radians ;
  costheta = Math.cos(rad);
  sintheta = Math.sin(rad);

  obj.filters.item("DXImageTransform.Microsoft.Matrix").M11 = costheta;
  obj.filters.item("DXImageTransform.Microsoft.Matrix").M12 = -sintheta;
  obj.filters.item("DXImageTransform.Microsoft.Matrix").M21 = sintheta;
  obj.filters.item("DXImageTransform.Microsoft.Matrix").M22 = costheta;
}

///////////////////////////////////////////////
//ici MODIFS APRES VERSION 7.0
// modifs qui règlent le bogue d'afficher/masquer des textes et over sur les boutons dans FF
// En enlevant tous les appels à firstChild, il faut voir les impacts 
// à vérifier avec historique dans SS
//
///////////////////////////////////////////////////////////////////////
function showHide(obj, filterName, filterParams, isToggle, toShow, isHideForced)
{
	if(isHideForced)
	{
	      obj.style.visibility = "hidden";
	      if(obj.firstChild)
	        obj.firstChild.style.visibility = "hidden";
	}

	if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
	{
		if(synchroManager.documentDur>0)
		{
			if(timeline.currTimeState.activeTime<obj.begin || timeline.currTimeState.activeTime>obj.end)
				return;
		}
	}

	if (!isToggle)
	{
		if(toShow)
		{
			obj.style.visibility = "hidden";
//			if(obj.firstChild)
//				obj.firstChild.style.visibility = "hidden";
		}
		else
		{
			obj.style.visibility = "visible";
//			if(obj.firstChild)
//				obj.firstChild.style.visibility = "visible";

		}
	}

	if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
	{
		if (filterName!="")
		{
			var fullFilterName = "DXImageTransform.Microsoft." + filterName;
			obj.style.filter += "progid:" + fullFilterName + filterParams;
			var lastFilter = obj.filters.item(obj.filters.length-1);
			lastFilter.Apply();
		}
	}
 
	if(isToggle)
	{
		if(obj.style.visibility == "hidden")
		{
			obj.style.visibility = "visible";
//			if(obj.firstChild)
//				obj.firstChild.style.visibility = "visible";
		}
		else 
		{
			obj.style.visibility = "hidden";
//			if(obj.firstChild)
//				obj.firstChild.style.visibility = "hidden";
		}
	}
	else
	{
		if(toShow)
		{
			obj.style.visibility = "visible";
//			if(obj.firstChild)
//				obj.firstChild.style.visibility = "visible";
		}
		else
		{
			obj.style.visibility = "hidden";
//			if(obj.firstChild)
//				obj.firstChild.style.visibility = "hidden";
		}
	}
 
	if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
		if (filterName!="")
			lastFilter.Play();
}

/////////////////////////////////////////////////////////////////////////////////////
function showHideFrame(obj, filterName, filterParams, isToggle, toShow, e, objParent)
{ 
	if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
	{
		if(synchroManager.documentDur>0)
		{
			if(timeline.currTimeState.activeTime<obj.begin || timeline.currTimeState.activeTime>obj.end)
				return;
		}
	}

	strId = obj.id;
	answerNo = parseInt(strId.substring(strId.indexOf("p")+1, strId.indexOf("f")));
	visibility = objParent.style.visibility;
	proposition = e.propositions[answerNo-1]
	if (proposition.hasFired || (e.finished &&
		proposition.isCorrect && e.isSolutionShown)){
		
		frame  = proposition.frame;
		frameNeutral = proposition.frameNeutral;
		
		if (e.isAutomatic)
		{objFrame = frame;}
		else
		{	if (proposition.hasCorrectionDone)
				{objFrame = frame; hidde(frameNeutral);}
			else
				{objFrame = frameNeutral; hidde(frame);}
		}		
				
		if (!isToggle){
		    if(toShow)
		      objFrame.style.visibility = "hidden";
		    else
		      objFrame.style.visibility = "visible";
		}
		else
		{
			if (visibility == "visible")
			      objFrame.style.visibility = "hidden";
			else
			      objFrame.style.visibility = "visible";
		}
	
	if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
	{
		if (filterName!=""){
			var fullFilterName = "DXImageTransform.Microsoft." + filterName;
			objFrame.style.filter += "progid:" + fullFilterName + filterParams;
			var lastFilter = objFrame.filters.item(objFrame.filters.length-1);
			lastFilter.Apply();
		}
	}
	
	objFrame.style.visibility = objParent.style.visibility;
	
	if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
	{
		if (filterName!="")
			lastFilter.Play();
		}
	}
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////
// Action Show/Hide

function showHideObjects()
{
	for(var i=0; i < this.targetObjects.length; i++)
	{
		var targetObj = this.targetObjects[i];
		if(targetObj.e == null)
			showHide(targetObj.obj, this.filterName, this.filterParams, this.isToggle, this.toShow, this.isHideForced);
		else
			showHideFrame(targetObj.obj, this.filterName, this.filterParams, this.isToggle, this.toShow, targetObj.e, targetObj.objParent);			
	}
}

function executeActionShowHide()
{
	if(browserParamsManager.browserName.indexOf('msie')>=0) // IE
		this.tActionIE.beginElement();
	else
		this.showHideObjects();
}

function targetObject(id, exerciseId, objParent)
{
	this.obj = document.getElementById(id);
	this.e = exerciseId;
	this.objParent = objParent;
}

function actionShowHide(filterName, filterParams, isToggle, toShow, isHideForced)
{
	this.filterName = filterName;
	this.filterParams = filterParams;
	this.isToggle = isToggle;
	this.toShow = toShow;
	this.isHideForced = isHideForced;

	this.tActionIE = null;
	this.targetObjects = new Array();

	this.execute = executeActionShowHide;
	this.showHideObjects = showHideObjects;
}


//////////////////////
// Action Scale

var arrObjScale=new Array();
var arrAction=new Array();
var curObjAction;

function action(actionId, direction,scalingH,scalingW,nbIncrements, isToggle, nbExtend, enableClip, visibleRegionW, visibleRegionH) {
   this.actionId=actionId;
   this.direction = direction;
   this.zoomValueH = scalingH;
   this.zoomValueW = scalingW;
   this.nbIncrements =nbIncrements;
   this.isToggle=isToggle;
   this.nbExtend=nbExtend;
   this.enableClip = enableClip;
   this.visibleRegionW = visibleRegionW;
   this.visibleRegionH = visibleRegionH;
 }


function objParam(actionIndex, obj, arrObj, toggle, nbExtend, arrX, arrY) {
   this.obj = obj;
   this.actionIndex=actionIndex;
   this.left = parseFloat(obj.style.left);
   this.top = parseFloat(obj.style.top);
   this.m11=obj.filters.item("DXImageTransform.Microsoft.Matrix").M11-1;
   this.m22=obj.filters.item("DXImageTransform.Microsoft.Matrix").M22-1;
   this.currentInc=0;
   this.active=true;
   this.arrObj=arrObj;
   this.arrX=arrX;
   this.arrY=arrY;
   this.toggle=toggle;	
   this.nbExtend=nbExtend;

   this.applyZoom=applyZoom;
}

function Scaling(actionId,obj,arrObj, visibleRegionH,visibleRegionW,scalingH,scalingW,direction, nbIncrements, isToggle, nbExtend, enableClip)
{	
	if(synchroManager.documentDur>0)
	{
		if(timeline.currTimeState.activeTime<obj.begin || timeline.currTimeState.activeTime>obj.end)
			return;
	}

	var arrX= new Array();
	var arrY= new Array();
	
	for (i=0;i<arrAction.length;i++)
		if(arrAction[i].actionId==actionId)
			break;
	
	if (i>=arrAction.length)
		arrAction[i]=new action(actionId, direction, scalingH, scalingW, nbIncrements, isToggle,nbExtend, enableClip, visibleRegionW, visibleRegionH);
	
	var actionIndex=i;
	
	if (obj.style.filter.indexOf("Matrix") ==-1)		
		obj.style.filter += "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand')";
	
	for (i=0; i< arrObj.length; i++)
	{
		if (arrObj[i].style.filter.indexOf("Matrix") ==-1)
			arrObj[i].style.filter += "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand')";
	}
	
	var nbExtend=0;
	var toggle=1;
	var exitFunction=0;
	var objIndex;
	
	for (i=0; i<arrObjScale.length; i++)
		if (arrObjScale[i].obj==obj && arrObjScale[i].actionIndex==actionIndex)
		{
			if (arrObjScale[i].active ==true)
				exitFunction=1;
			else
			{	
				nbExtend=arrObjScale[i].nbExtend; 
				toggle=arrObjScale[i].toggle;
			}
			break;
		}
	
	objIndex =i;	
	if (exitFunction==0){
		for (i=0; i< arrObj.length; i++)
		{
			arrX[i]=parseFloat(arrObj[i].style.left)-parseFloat(obj.style.left);
			arrY[i]=parseFloat(arrObj[i].style.top)-parseFloat(obj.style.top);
		}	

		if (arrAction[actionIndex].nbExtend==nbExtend)
		{
			if (arrAction[actionIndex].isToggle)
			{
				toggle=-arrObjScale[objIndex].toggle;
				nbExtend=1;
			}	
			else
				nbExtend++;	
		}else
			nbExtend++;	

		if (nbExtend<=arrAction[actionIndex].nbExtend)
		{
			arrObjScale[objIndex]= new objParam(actionIndex, obj, arrObj, toggle, nbExtend, arrX, arrY);
			curObjAction=objIndex;
			arrObjScale[objIndex].applyZoom();
		}
	}	
}


function applyZoom(){

if (arrObjScale[curObjAction].active==true){	

	var objToZoom=arrObjScale[curObjAction].obj;
	var arrObj=arrObjScale[curObjAction].arrObj;
	var actionIndex = arrObjScale[curObjAction].actionIndex;
	
	var nbIncrements=arrAction[arrObjScale[curObjAction].actionIndex].nbIncrements;
	var i=arrObjScale[curObjAction].currentInc;
	var zoomValueW=arrAction[actionIndex].zoomValueW;
	var zoomValueH=arrAction[actionIndex].zoomValueH;
	var direction=arrAction[actionIndex].direction;
	var m11=arrObjScale[curObjAction].m11;
	var m22=arrObjScale[curObjAction].m22;
	var toggle=arrObjScale[curObjAction].toggle;
	var arrX=arrObjScale[curObjAction].arrX;
	var arrY=arrObjScale[curObjAction].arrY;
	
	if (toggle<0) 
	{
		zoomValueH=10000/zoomValueH;
		zoomValueW=10000/zoomValueW;
	}
	
	var matrixDeltaH=(m22+1)*(zoomValueH-100)/(100*nbIncrements);
	var matrixDeltaW=(m11+1)*(zoomValueW-100)/(100*nbIncrements);
	
		i ++;
    if (i >= nbIncrements)
    {
        i = 0; objToZoom.onfilterchange = null;
        arrObjScale[curObjAction].active=false;
    }
    else
		objToZoom.onfilterchange =applyZoom;
		
	arrObjScale[curObjAction].currentInc=i;
	
	if (objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M11 +matrixDeltaW >0 &&
	objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M22 +matrixDeltaH >0)
	{
		objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M11 +=matrixDeltaW;
		objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M12 += 0;
		objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M21 += 0;
		objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M22 +=matrixDeltaH;
        
        if (arrAction[actionIndex].enableClip)
			SetClippingRegion(objToZoom,arrAction[actionIndex].visibleRegionH, arrAction[actionIndex].visibleRegionW, arrAction[actionIndex].direction)
		switch (direction)
		{
		case 0: //middle-top
			objToZoom.style.top=arrObjScale[curObjAction].top-parseFloat(objToZoom.style.height)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M22-m22-1);
			objToZoom.style.left=arrObjScale[curObjAction].left-parseFloat(objToZoom.style.width)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M11-m11-1)/2;
			break;
		case 1: //top-right
			objToZoom.style.top=arrObjScale[curObjAction].top-parseFloat(objToZoom.style.height)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M22-m22-1);
			break;
		case 2: //middle-right
			objToZoom.style.top=arrObjScale[curObjAction].top-parseFloat(objToZoom.style.height)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M22-m22-1)/2;
			break;
		case 3: //bottom-right
				break;
		case 4: //middle-bottom
			objToZoom.style.left=arrObjScale[curObjAction].left-parseFloat(objToZoom.style.width)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M11-m11-1)/2;
			break;
		case 5: //bottom-left
			objToZoom.style.left=arrObjScale[curObjAction].left-parseFloat(objToZoom.style.width)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M11-m11-1);
			break;
		case 6: // middle-left
			objToZoom.style.left=arrObjScale[curObjAction].left - parseFloat(objToZoom.style.width)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M11-m11-1);
			objToZoom.style.top=arrObjScale[curObjAction].top - parseFloat(objToZoom.style.height)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M22-m22-1)/2;
			break;
		case 7: //top-left
			objToZoom.style.left=arrObjScale[curObjAction].left-parseFloat(objToZoom.style.width)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M11-m11-1);
			objToZoom.style.top=arrObjScale[curObjAction].top-parseFloat(objToZoom.style.height)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M22-m22-1);
			break;
		case 8: //centered
			objToZoom.style.top=arrObjScale[curObjAction].top-parseFloat(objToZoom.style.height)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M22-m22-1)/2;
			objToZoom.style.left=arrObjScale[curObjAction].left-parseFloat(objToZoom.style.width)*(objToZoom.filters.item("DXImageTransform.Microsoft.Matrix").M11-m11-1)/2;
			break;	
		}
			
		//Faire le Zoom des sous-objets 
		for (var j=0; j<arrObj.length; j++)
		{	
			arrObj[j].filters.item("DXImageTransform.Microsoft.Matrix").M11 +=matrixDeltaW;
			arrObj[j].filters.item("DXImageTransform.Microsoft.Matrix").M12 += 0;
			arrObj[j].filters.item("DXImageTransform.Microsoft.Matrix").M21 += 0;
			arrObj[j].filters.item("DXImageTransform.Microsoft.Matrix").M22 +=matrixDeltaH;
			
			arrObj[j].style.left=arrX[j]/(m11+1)*(arrObj[j].filters.item("DXImageTransform.Microsoft.Matrix").M11)+parseFloat(objToZoom.style.left);
			arrObj[j].style.top=arrY[j]/(m22+1)*(arrObj[j].filters.item("DXImageTransform.Microsoft.Matrix").M22)+parseFloat(objToZoom.style.top);
			
			if (arrAction[actionIndex].enableClip)
				SetClippingRegion(arrObj[j], arrAction[actionIndex].visibleRegionH, arrAction[actionIndex].visibleRegionW, arrAction[actionIndex].direction)
		}
	}
	else
	{
		arrObjScale[curObjAction].active=false;
		objToZoom.onfilterchange=null;
	}
}
	curObjAction=curObjAction+1;
	if (curObjAction==arrObjScale.length)
		curObjAction=0;
	for (var k=curObjAction; k<arrObjScale.length; k++)
		if (arrObjScale[k].active==true)
			{
				curObjAction=k; 
				arrObjScale[curObjAction].obj.onfilterchange =applyZoom;
				break;
			}
}

function SetClippingRegion(obj,visibleRegionH, visibleRegionW, direction)
{
	height=parseInt(obj.style.height) * obj.filters.item("DXImageTransform.Microsoft.Matrix").M22;
	width = parseInt(obj.style.width) * obj.filters.item("DXImageTransform.Microsoft.Matrix").M11;
	clipLeft = width - visibleRegionW;
	clipTop = height - visibleRegionH;
	
	if (clipLeft < 0)
		clipLeft = 0;
	
	if (clipTop < 0)
		clipTop = 0;
	
	switch (direction)
	{
		case 0: //top-right
			obj.style.clip="rect("+ clipTop +", "+visibleRegionW+", auto, auto)";
			break;
		case 1: //top-left
			obj.style.clip="rect("+ clipTop + ",  auto, auto, " + clipLeft+ ")";
			break;
		case 2: //bottom-right
			obj.style.clip="rect(auto, " + visibleRegionW + ", " + visibleRegionH + ", auto)";
			break;
		case 3: //bottom-left
			obj.style.clip="rect(auto, auto," + visibleRegionH + ", " + clipLeft + ")";
			break;
		case 4: //centered
			obj.style.clip="rect(" + clipTop/2+", "+(visibleRegionW+clipLeft/2)+ ", "+(visibleRegionH+clipTop/2)+", " + clipLeft/2 + ")";
			break;	
		case 5: //middle-right
			obj.style.clip="rect(" + (clipTop/2) + ", " + visibleRegionW + ", " + (visibleRegionH+clipTop/2) + ", auto)";
			break;
		case 6: // middle-left
			obj.style.clip="rect(" + (clipTop/2) + ", auto, " + (visibleRegionH+clipTop/2)+ ", " + clipLeft + ")";
			break;
		case 7: //middle-top
			obj.style.clip="rect(" + clipTop+", "+(visibleRegionW+clipLeft/2)+ ", auto, " + clipLeft/2 + ")";
			break;
		case 8: //middle-bottom
			obj.style.clip="rect(auto, " +(visibleRegionW+clipLeft/2)+ ", "+ visibleRegionH + ", " + clipLeft/2 + ")";
			break;
	}
}

var matrixPrp=null;

function MatrixFilterPrp(m11, m22, m12, m21)
{
	this.M11=m11;
	this.M22=m22;
	this.M12=m12;
	this.M21=m21;
}

function GetMatrixFilterProperties(obj)
{ 
	if (obj.style.filter.indexOf("Matrix")!=-1)
	{
		matrixPrp = new MatrixFilterPrp(
			obj.filters.item("DXImageTransform.Microsoft.Matrix").M11,
			obj.filters.item("DXImageTransform.Microsoft.Matrix").M22,
			obj.filters.item("DXImageTransform.Microsoft.Matrix").M12,
			obj.filters.item("DXImageTransform.Microsoft.Matrix").M21);
	}
	else
		matrixPrp = null;
}


function SetMatrixFilterProperties(obj)
{
	if (matrixPrp!=null)
	{
		obj.filters.item("DXImageTransform.Microsoft.Matrix").M11 = matrixPrp.M11;
		obj.filters.item("DXImageTransform.Microsoft.Matrix").M22 = matrixPrp.M22;
		obj.filters.item("DXImageTransform.Microsoft.Matrix").M12 = matrixPrp.M12;
		obj.filters.item("DXImageTransform.Microsoft.Matrix").M21 = matrixPrp.M21;
	}
}

function move(obj, actionID)
{
	if(synchroManager)
		if(synchroManager.documentDur>0)
		{
			if(timeline.currTimeState.activeTime<obj.begin || timeline.currTimeState.activeTime>obj.end)
				return;
		}

	actionID.beginElement();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Plugin Flash
function AC_AddExtension(src, ext)
{
  if (src.indexOf('?') != -1)
    return src.replace(/\?/, ext+'?'); 
  else
    return src + ext;
}

function AC_Generateobj(objAttrs, params, embedAttrs) 
{ 
  var str = '<object ';
  for (var i in objAttrs)
    str += i + '="' + objAttrs[i] + '" ';
  str += '>';
  for (var i in params)
    str += '<param name="' + i + '" value="' + params[i] + '" /> ';
  str += '<embed ';
  for (var i in embedAttrs)
    str += i + '="' + embedAttrs[i] + '" ';
  str += ' ></embed></object>';

  document.write(str);
}

function AC_FL_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".swf", "movie", "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
     , "application/x-shockwave-flash"
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

function AC_SW_RunContent(){
  var ret = 
    AC_GetArgs
    (  arguments, ".dcr", "src", "clsid:166B1BCA-3F9C-11CF-8075-444553540000"
     , null
    );
  AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}

////////////////////////////////////////////////////////////////////////////////////////////////////
function AC_GetExtension(args){
	var taille = args.length;
	for (i = 0; i < taille; i=i+2){
		if (args[i] == 'src' || args[i] == 'movie'){
			deb = args[i+1].lastIndexOf('.') + 1;
			fin = args[i+1].length;
			return (args[i+1].substring(deb, fin).toLowerCase());
		}
	}
}

function AC_RunContent(){
	var ret = null;
	var fileExtension = AC_GetExtension(arguments);
	switch(fileExtension){
		case "wav":
		case "mid":
		case "midi":
		case "au":
		case "mp3":
		case "wma":
		case "avi":
		case "mpg":
		case "mpeg":
		case "mov":
		case "wmv":
		case "asf":
			if(browserParamsManager.browserName.indexOf('msie')>=0)
				ret = AC_GetArgs(arguments, "clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95", "application/x-oleobject"); // classid correspond WMP 6.4
			else
				ret = AC_GetArgs(arguments, null, "application/x-ms-wmp"); // FF et plugin WMP11
			break;
		case "swf":
			ret = AC_GetArgs(arguments,  "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000", "application/x-shockwave-flash");
			break;
		case "pdf":
			if(browserParamsManager.browserName.indexOf('msie')>=0)
				ret = AC_GetArgs(arguments, null, "application/pdf");
			else
				ret = AC_GetArgs(arguments, null, null);
			break;
		default:
			ret = AC_GetArgs(arguments, null, null);
			break;
	}
	if(ret)	
		AC_Generateobj(ret.objAttrs, ret.params, ret.embedAttrs);
}
////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////
function AC_GetArgs(args, classid, mimeType){
  var ret = new Object();
  ret.embedAttrs = new Object();
  ret.params = new Object();
  ret.objAttrs = new Object();
  for (var i=0; i < args.length; i=i+2){
    var currArg = args[i].toLowerCase();    

    switch (currArg){	
      case "classid":
        break;
      case "pluginspage":
        ret.embedAttrs[args[i]] = args[i+1];
        break;
      case "src":
      case "movie":	
        //args[i+1] = AC_AddExtension(args[i+1], ext);
        ret.embedAttrs["src"] = args[i+1];
        ret.params[args[i]] = args[i+1];
        break;
      case "onafterupdate":
      case "onbeforeupdate":
      case "onblur":
      case "oncellchange":
      case "onclick":
      case "ondblClick":
      case "ondrag":
      case "ondragend":
      case "ondragenter":
      case "ondragleave":
      case "ondragover":
      case "ondrop":
      case "onfinish":
      case "onfocus":
      case "onhelp":
      case "onmousedown":
      case "onmouseup":
      case "onmouseover":
      case "onmousemove":
      case "onmouseout":
      case "onkeypress":
      case "onkeydown":
      case "onkeyup":
      case "onload":
      case "onlosecapture":
      case "onpropertychange":
      case "onreadystatechange":
      case "onrowsdelete":
      case "onrowenter":
      case "onrowexit":
      case "onrowsinserted":
      case "onstart":
      case "onscroll":
      case "onbeforeeditfocus":
      case "onactivate":
      case "onbeforedeactivate":
      case "ondeactivate":
      case "codebase":
        ret.objAttrs[args[i]] = args[i+1];
        break;
      case "width":
      case "height":
      case "align":
      case "vspace": 
      case "hspace":
      case "class":
      case "title":
      case "accesskey":
      case "name":
      case "tabindex":
      case "style":
        ret.embedAttrs[args[i]] = ret.objAttrs[args[i]] = args[i+1];
        break;
      case "id":
		ret.objAttrs[args[i]] = args[i+1];
        ret.embedAttrs[args[i]] = args[i+1] + "embed"
        break;
	  case "showcontrols":
		if((browserParamsManager.browserName.indexOf('msie')<0) && (args[i+1] == '0'))
			ret.params["uiMode"] = "none";
		else
			ret.params[args[i]] = args[i+1];
		break;
      default:
        ret.embedAttrs[args[i]] = ret.params[args[i]] = args[i+1];
    }
  }
  if(classid)
	ret.objAttrs["classid"] = classid;
  if (mimeType) 
	ret.embedAttrs["type"] = ret.objAttrs["type"] = mimeType;
  return ret;
}



