//Création de l'univers sans connection SCORM
var un = {

//Etat de la formation : 0 = non initialisée, 1=initialisée, 2=terminée.
fStatus : 0,

//Root de toutes les variables de l'instance : initialisé à vide.
sc : {},

//Api Scorm
fApiScorm : null,

//Api Senari LMS
fApiScenariLms : null,

//Environnement HTA
fHta : false,

//Flag passé à true lors toute modif de l'instance.
fModif : false,

//Lecture d'une variable de l'instance. Retourne "" si la variable n'existe pas.
getVal : function (pCd) {
	var vFields=pCd.split(".");
	var vCur = this;
	for(var i=0, imax=vFields.length; i<imax; i++) {
		var vF = vCur[vFields[i]];
		if(!vF) return "";
		vCur = vF;
	}
	return vCur;
},

//Lecture d'une variable de l'instance. Retourne null si la variable n'existe pas.
getValIfExist : function (pCd) {
	var vFields=pCd.split(".");
	var vCur = this;
	for(var i=0, imax=vFields.length; i<imax; i++) {
		var vF = vCur[vFields[i]];
		if(!vF) return null;
		vCur = vF;
	}
	return vCur;
},

//Stockage d'une variable dans l'instance
setVal : function (pCd,pVal) {
	var vFields=pCd.split(".");
	var vCur = this;
	var imax = vFields.length-1;
	for(var i=0; i<imax; i++) {
		var vF = vCur[vFields[i]];
		if(!vF) vCur = vCur[vFields[i]] = {}; else vCur = vF;
	}
	this.fModif = true;
	vCur[vFields[imax]] = pVal;
},

//Suppression d'une variable dans l'instance
removeVal : function (pCd) {
	var vFields=pCd.split(".");
	var vCur = this;
	var imax = vFields.length-1;
	for(var i=0; i<imax; i++) {
		var vF = vCur[vFields[i]];
		if(!vF) return false;
		vCur = vF;
	}
	this.fModif = true;
	if(vCur[vFields[imax]]) return delete vCur[vFields[imax]];
	return false;
},

//Quitte la formation sans confirmation de l'utilisateur, ni fermeture de la fenetre (
//Fonction utilisée sur l'évenement onunload du body de la page contexte.
quit :function () {
	//alert("un.quit(); status="+this.fStatus+" - hta="+this.fHta+" - scorm="+this.fApiScorm);
	if(this.fStatus==1) {
		ih.xSaveBeforeQuit();
		if(this.fHta) {
			var vFile = null;
			try {
				vFile = this.fHtaFso.CreateTextFile(this.fHtaFileName,true);
				var vS="this.sc={"+this.xSaveObjJs(this.sc)+"};";
				//alert("ecriture="+vS);
				vFile.write(vS);
			} finally {
				if(vFile) vFile.close();
			}
		} else if(this.fApiScorm) {
			var vS="this.sc={"+this.xSaveObjJs(this.sc)+"};";
			this.fApiScorm.LMSSetValue("cmi.suspend_data", vS); 
			this.fApiScorm.LMSFinish("");
		} else if(this.fApiScenariLms) {
			window.clearInterval(this.fThreadSave);
			this.xSaveDataScenariLms();
			this.fApiScenariLms.finish(window);
		}
		this.fStatus = 2;
	}
},

//Quitte la formation. Fonction appelée par ih.quit().
xQuit :function () {
	if( ! this.fHta){
		ih.xClose();
	}
	this.quit();
	if(! this.fApiScorm && ! this.fApiScenariLms) window.close();
},

//Retour à l'accueil. Fonction appelée par ih.retouraccueil().
xRetouraccueil :function () {
	//
},

//Sérialize un objet comportant des données au format JS
xSaveObjJs : function(pObj){
	var vBuf="";
	for (var vKey in pObj){
		if(vBuf!="") vBuf+=",";
		var vObj = pObj[vKey];
		if(vObj instanceof Object){
			vBuf+=vKey+":{"+this.xSaveObjJs(vObj)+"}";
		} else {
			var vVal = escape(vObj);
			if(vVal==vObj) {
				vBuf+=vKey+":'"+vVal+"'";
			} else {
				vBuf+=vKey+":unescape('"+vVal+"')";
			}
		}
	}
	return vBuf;
},

/** Sérialize un objet comportant des données au format Xml. */
xSaveObjXml : function(pObj){
	var vBuf="";
	for (var vKey in pObj){
		var vObj = pObj[vKey];
		if(vObj instanceof Object){
			vBuf+="<"+vKey+">"+this.xSaveObjXml(vObj)+"</"+vKey+">";
		} else {
			var vVal = vObj.toString();
			vVal = vVal.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
			vBuf+="<"+vKey+">"+vVal+"</"+vKey+">";
		}
	}
	return vBuf;
},

/** Charge les productions à partir d'un flux xml. */
xParseTagXml : function(pXml, pIndex, pObjRoot, pCurrentTag){
	var vIndex = pIndex;
	//On cherche le tag suivant
	var vObj = null;
	while(true) {
		var vStart = pXml.indexOf("<", vIndex);
		if(vStart<0) return pXml.length;
		var vFirstCar = pXml.charAt(vStart+1);
		if(vFirstCar=='!' && pXml.charAt(vStart+2)=='-' && pXml.charAt(vStart+3)=='-') {
			vIndex = pXml.indexOf("-->", vStart)+3;
			if(vIndex==2) return pXml.length;
			continue;
		}
		var vEnd = pXml.indexOf(">", vStart);
		if(vEnd<0) return pXml.length;
		if(vFirstCar=="/") {
			if(vObj == null) pObjRoot[pCurrentTag] = pXml.substring(pIndex, vStart).replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">");
			return vEnd+1;
		}
		var vNameTag = pXml.substring(vStart+1, vEnd);
		if(vNameTag.charAt(vNameTag.length-1)=="/"){
			if(vObj == null){
				vObj = {};
				pObjRoot[pCurrentTag] = vObj;
			}
			vObj[vNameTag.substring(0, vNameTag.length-1)] = "";
			vIndex = vEnd+1;
			continue;
		}
		if(vObj == null){
			vObj = {};
			pObjRoot[pCurrentTag] = vObj;
		}
		vIndex = this.xParseTagXml(pXml, vEnd+1,vObj, vNameTag);
	}
},

replaceAll :function(inSTR, inTOK, inREP) {
	var s;
	s = inSTR + "";
	while (s.indexOf(inTOK) >= 0) {
 		s = s.replace(inTOK, "§");
	};
	while (s.indexOf("§") >= 0) {
		s = s.replace("§", inREP);
	};
	return s;
},

//Init du contexte, appelée sur le Onload de la page du contexte. L'univers doit être appelé en premier qui appelle à son tour l'Ihm.
init :function (pMode) {
	if(this.fStatus == 0){
		//Environnement HTA
		if(pMode) this.fHta = (pMode=="hta");
		if(this.fHta) {
			this.fHtaFso = new ActiveXObject("Scripting.FileSystemObject");
			var HTAfolder = window.location.href;
			HTAfolder = HTAfolder.substring(8, HTAfolder.lastIndexOf('/')+1);
			HTAfolder = un.replaceAll(HTAfolder, '%20', ' ');
			this.fHtaFileName = this.fHtaFso.GetAbsolutePathName(HTAfolder+"sauvegarde.js");
			if(this.fHtaFso.FileExists(this.fHtaFileName)){
				var vFile = null;
				try {
					vFile = this.fHtaFso.OpenTextFile(this.fHtaFileName,1);
					var vS = vFile.ReadAll();
					//alert("lecture="+vS);
					eval(vS);
				} finally {
					if(vFile) vFile.close();
				}
			}
		} else {
			//Environnement Scorm
			try {
				this.fApiScorm = this.xFindApiScorm(window);
				if(this.fApiScorm==null && window.opener!=null && typeof(window.opener)!="undefined" ) {
					this.fApiScorm = this.xFindApiScorm(window.opener)
				}
				if(this.fApiScorm) this.fApiScorm.LMSInitialize("");
			} catch (e) {this.fApiScorm = null;/*alert("Echec lors de l'initialisation Scorm : "+e.description);*/}
			if(this.fApiScorm) {
				var vS = this.fApiScorm.LMSGetValue("cmi.suspend_data");
				eval(vS);
			} else {
				//Environnement Scenari LMS
				try {
					this.fApiScenariLms = this.xFindApiScenariLms(window);
					if(this.fApiScenariLms==null && window.opener!=null && typeof(window.opener)!="undefined" ) {
						this.fApiScenariLms = this.xFindApiScenariLms(window.opener)
					}
					if(this.fApiScenariLms) {
						this.fApiScenariLms.init(window);
						this.fThreadSave = window.setInterval(un.xSaveDataScenariLms, 60000);
					}
				} catch (e) {this.fApiScenariLms = null;/*alert("Echec lors de l'initialisation Scenari : "+e.description);*/}
				if(this.fApiScenariLms) {
					var vInst = this.fApiScenariLms.getData(window, "instance");
					var vIndex = vInst ? vInst.indexOf("<sc>") : -1;
					if(vIndex>=0){
						this.xParseTagXml(vInst, vIndex+4, this, "sc");
					}
				}
			}
		}	
		this.fStatus = 1;
		//alert("un.init(): status="+this.fStatus+" - pMode="+pMode+" - fHta="+this.fHta+" - Scorm="+this.fApiScorm);
		ih.xInit();
	}
},

/** Enregistre les contenus en tache de fond.*/
xSaveDataScenariLms : function(){
	window.status = "";
	if(un.fModif && ! un.fSavePending) {
		try {
			window.status = "Enregistrement en cours...";
			un.fSavePending = true;
			un.fModif = false;
			var vS="<sc>"+un.xSaveObjXml(un.sc)+"</sc>";
			un.fApiScenariLms.setData(window, "instance", vS);
			window.status = "Enregistrement réalisé.";
		} catch (e){
			window.status = "Echec à l'enregistrement : "+e.description;
		}
		un.fSavePending = false;
	}
},

//Recherche l'API scorm
xFindApiScorm : function (pWin) {
	var vWin = pWin;
	var vDeep = 0;
	while(vWin.API==null && vWin.parent!=null && vWin.parent!=vWin) {
		if (vDeep > 10){
			return null;
		}
		vDeep++;
		vWin = vWin.parent;
	}
	return vWin.API;
},

//Recherche l'API Scenari Lms
xFindApiScenariLms : function (pWin) {
	var vWin = pWin;
	var vDeep = 0;
	while(vWin.apiScenariLms==null && vWin.parent!=null && vWin.parent!=vWin) {
		if (vDeep > 10){
			return null;
		}
		vDeep++;
		vWin = vWin.parent;
	}
	return vWin.apiScenariLms;
},

xEscapeTextXml : function(pContent){
    var chaine = new String(pContent);
	if (chaine){
		return chaine.replace('/&/g', "&amp;").replace('/</g', "&lt;").replace('/>/g', "&gt;");
	}else{
		alert('reponse vide');
		return '';
	}
}


} //Fin de la définition de l'univers.


/** Fonctions spécifiques à cette IHM. **/

/** Annotation des pages.*/
un.getAnnot = function (pIdPage) {
	return this.getVal("sc.annot.zz"+pIdPage);
}
un.setAnnot = function (pIdPage, pContenu) {
	this.setVal("sc.annot.zz"+pIdPage, pContenu);
	if(this.fApiScenariLms) {
		var vEvt = "<annot ctx=\""+pIdPage+"\">"+this.xEscapeTextXml(pContenu)+"</annot>";
		this.fApiScenariLms.handleEvent(window, "annot", vEvt);
	}
}

/** Flag des pages. Utilisation des 4 premiers bits :
 * 1 = page marquée
 * 2 = page vue
 * 4 = page/dossier acquis (suite à positionnement)
 * 8 = page/dossier non acquis (suite à positionnement)
 * Pour désaffecter le flag, passer une valeur négative (-1, -2, -4, -8).
 */
un.getFlag = function (pIdPage) {
	return this.getVal("sc.flag.zz"+pIdPage);
}
un.setFlag = function (pIdPage, pFlag) {
	var vVal = this.getVal("sc.flag.zz"+pIdPage);
	if(!vVal) vVal = 0;
	vVal = (pFlag>=0) ? vVal | pFlag : vVal &~ -pFlag;
	this.setVal("sc.flag.zz"+pIdPage, vVal);
	//ih.fireChangeFlag(pIdPage, pFlag);
	if(this.fApiScenariLms) {
		var vEvt = null;
		if(pFlag == 1) this.fApiScenariLms.handleEvent(window, "coche", "<coche ctx=\""+pIdPage+"\"/>");
		else if(pFlag == -1) this.fApiScenariLms.handleEvent(window, "decoche", "<decoche ctx=\""+pIdPage+"\"/>");
		//else if(pFlag == 2) this.fApiScenariLms.handleEvent(window, "vue", "<vue ctx=\""+pIdPage+"\"/>");
	}
}
/** Cas particulier du flag "Acquis" à trois positions.*/
un.setFlagAquis = function (pIdPage, pBool) {
	var vVal = this.getVal("sc.flag.zz"+pIdPage);
	if(!vVal) vVal = 0;
	if(pBool) vVal = vVal | 4 &~ 8; else vVal = vVal | 8 &~ 4; 
	this.setVal("sc.flag.zz"+pIdPage, vVal);
	//ih.fireChangeFlag(pIdPage, (pBool) ? 4 : 8);
}

/**
 * Temps passé sur une page (en millisecondes).
 */
un.setElapseTime = function (pIdPage, pTime){
	if(this.fApiScenariLms) {
		this.fApiScenariLms.handleEvent(window, "time", "<vue ctx=\""+pIdPage+"\" ms=\""+pTime+"\"/>");
	}
}

/** Valeur d'un exercice d'un agent.*/
un.getExo = function (pIdAgent, pNomChamp) {
	return this.getVal("sc.exo.zz"+pIdAgent+"."+pNomChamp);
}
un.setExo = function (pIdAgent, pNomChamp, pContenu) {
	this.setVal("sc.exo.zz"+pIdAgent+"."+pNomChamp, pContenu);
	if(this.fApiScenariLms) {
		var vEvt = "<exo ctx=\""+pIdAgent+"\" champ=\""+pNomChamp+"\">"+this.xEscapeTextXml(pContenu)+"</exo>";
		this.fApiScenariLms.handleEvent(window, "exo", vEvt);
	}
}
un.getSolExoVu = function (pIdAgent, pNomChamp) {
	return this.getVal("sc.solexovu.zz"+pIdAgent+"."+pNomChamp);
}
un.setSolExoVu = function (pIdAgent, pNomChamp, pOpen) {
	this.setVal("sc.solexovu.zz"+pIdAgent+"."+pNomChamp, pOpen);
	if(this.fApiScenariLms) {
		var vEvt = "<solexovu ctx=\""+pIdAgent+"\" champ=\""+pNomChamp+"\">"+this.xEscapeTextXml(pOpen)+"</solexovu>";
		this.fApiScenariLms.handleEvent(window, "solexovu", vEvt);
	}
}

/** Réponse pour les Agents auto-évalués. La session permet de spécifier des contextes différents. Null si non renseigné. */
un.getRep = function (pIdAgent, pSession, pNomChamp) {
	return this.getValIfExist("sc.rep.zz"+pIdAgent+"."+pSession+"."+pNomChamp);
}
un.setRep = function (pIdAgent, pSession, pNomChamp, pContenu) {
	this.setVal("sc.rep.zz"+pIdAgent+"."+pSession+"."+pNomChamp, pContenu);
	if(this.fApiScenariLms) {
		var vEvt = "<rep ctx=\""+pIdAgent+"\" session=\""+pSession+"\" champ=\""+pNomChamp+"\">"+this.xEscapeTextXml(pContenu)+"</rep>";
		this.fApiScenariLms.handleEvent(window, "rep", vEvt);
	}
}
un.removeRep = function (pIdAgent, pSession, pNomChamp) {
	return this.removeVal("sc.rep.zz"+pIdAgent+"."+pSession+"."+pNomChamp);
	if(this.fApiScenariLms) {
		var vEvt = "<rep ctx=\""+pIdAgent+"\" session=\""+pSession+"\" champ=\""+pNomChamp+"\"/>";
		this.fApiScenariLms.handleEvent(window, "rep", vEvt);
	}
}

/** Note obtenue pour les Agents auto-évalués. La session permet de spécifier des contextes différents. Null si non renseigné. */
un.getNote = function (pIdAgent, pSession) {
	return this.getValIfExist("sc.note.zz"+pIdAgent+"."+pSession);
}
un.setNote = function (pIdAgent, pSession, pNote) {
	this.setVal("sc.note.zz"+pIdAgent+"."+pSession, pNote);
}
un.removeNote = function (pIdAgent, pSession) {
	return this.removeVal("sc.note.zz"+pIdAgent+"."+pSession);
}
