if ( typeof inmediastudio == "undefined" ){
	var inmediastudio = {
		test: function(){
			console.log("inmediastudio existe");
			return;
		}
	};
}

inmediastudio.TRAZA = {

	mostrarSolucion: true,
	guardarRespuesta: false,
	moduloTraza: false,

	init: function() {

		inmediastudio.TRAZA.moduloTraza = new moduloTrazaObj();
		inmediastudio.TRAZA.moduloTraza.init();

		if ( inmediastudio.TRAZA.moduloTraza.tipoTraza == "AV" ){
			this.guardarRespuesta = true;
		}
		else if( inmediastudio.TRAZA.moduloTraza.tipoTraza == "SCORM" ){
			this.mostrarSolucion = false;
			this.guardarRespuesta = true;	
		}
		else if ( inmediastudio.TRAZA.moduloTraza.tipoTraza == "WC" ){
			this.mostrarSolucion = false;
			this.guardarRespuesta = true;
		}
		else {
			console.log( "inmediastudio.TRAZA.init > no hay traza" );
		}
		inmediastudio.RESULTADOS.init();
		return;
	},
};

inmediastudio.RESULTADOS = {
	
	init: function() {
	},

	guardarPuntuacion: function( puntuacion ){

		puntuacion = puntuacion*100;
		puntuacion = Math.round( puntuacion );
		if( puntuacion <0 ) {
			puntuacion = 0;
		}

		var idUnidad = getGET().unitId || "unitX";
		var idActividad = getGET().activityId || "activityX";
		var idRecurso = getGET().resourceId || "resourceX";

		inmediastudio.TRAZA.moduloTraza.recursoFinalizado( idUnidad, idActividad, idRecurso, puntuacion );
	}
};

function moduloTrazaObj(){

    //// SCORM ZONE ////
    var imst = {};  
    imst.UTILS = {};                                    
    imst.DEBUG = false;                                 
    imst.SCORM = {                                  
        version: null,                              
        API: { handle: null, 
               isFound: false },                    
        connection: { isActive: false },            
        handleCompletionStatus: true,               
        handleExitMode: true,                       
        data: { completionStatus: null,
                exitStatus: null,
                fechaInicio: 0,
                fechaFin: 0 },
        debug: {}           
    };
    // --- SCORM.API functions --- //
    imst.SCORM.isAvailable = function(){
        return true;     
    };
    imst.SCORM.API.find = function(win){
        var API = null,
            findAttempts = 0,
            findAttemptLimit = 500,
            traceMsgPrefix = "SCORM.API.find",
            trace = imst.UTILS.trace,
            scorm = imst.SCORM;
        while ((!win.API && !win.API_1484_11) &&
               (win.parent) &&
               (win.parent != win) &&
               (findAttempts <= findAttemptLimit)){

            findAttempts++; 
            win = win.parent;
        }
        if( scorm.version ){                                            //If SCORM version is specified by user, look for specific API
            switch(scorm.version){
                /*case "2004" : 
                    if(win.API_1484_11){
                        API = win.API_1484_11;
                    }
                    else {
                        trace(traceMsgPrefix +": SCORM version 2004 was specified by user, but API_1484_11 cannot be found.");
                    }
                    break;*/
                case "1.2" : 
                    if(win.API){
                        API = win.API;
                    } 
                    else {
                        trace(traceMsgPrefix +": SCORM version 1.2 was specified by user, but API cannot be found.");
                    }
                    break;
            }
        } 
        else {                                                  //If SCORM version not specified by user, look for APIs
            /*if(win.API_1484_11) {                                 //SCORM 2004-specific API.
                scorm.version = "2004";                             //Set version
                API = win.API_1484_11;
            } else*/
            if( win.API ){                                     //SCORM 1.2-specific API
                scorm.version = "1.2";                              //Set version
                API = win.API;
            }
        }
        if( API ){
            trace(traceMsgPrefix +": API found. Version: " +scorm.version);
            trace("API: "+API);
        } 
        else {
            trace(traceMsgPrefix +": Error finding API. \nFind attempts: " +findAttempts+". \nFind attempt limit: "+findAttemptLimit);
        }
        return API;
    };
    imst.SCORM.API.get = function(){
        var API = null,
            win = window,
            find = imst.SCORM.API.find,
            trace = imst.UTILS.trace; 
        if(win.parent && win.parent != win){ 
            API = find(win.parent); 
        } 
        if(!API && win.top.opener){ 
            API = find(win.top.opener); 
        } 
        if(API){  
            imst.SCORM.API.isFound = true;
        } else {
            trace("API.get failed: Can't find the API!");
        }
        return API;
    };
    imst.SCORM.API.getHandle = function() {
        var API = imst.SCORM.API;
        if(!API.handle && !API.isFound){
            API.handle = API.get();
        }
        return API.handle;
    };
    // --- pipwerks.SCORM.connection functions --------------------------------- //
    imst.SCORM.connection.initialize = function(){
        var success = false,
            scorm = imst.SCORM,
            completionStatus = imst.SCORM.data.completionStatus,
            trace = imst.UTILS.trace,
            makeBoolean = imst.UTILS.StringToBoolean,
            debug = imst.SCORM.debug,
            traceMsgPrefix = "SCORM.connection.initialize ";
        
        trace("connection.initialize called.");
        if(!scorm.connection.isActive){
            var API = scorm.API.getHandle(),
                errorCode = 0;
            if(API){
                switch(scorm.version){
                    case "1.2" : success = makeBoolean(API.LMSInitialize("")); break;
                    /*case "2004": success = makeBoolean(API.Initialize("")); break;*/
                }
                if(success){
                    //Double-check that connection is active and working before returning 'true' boolean
                    errorCode = debug.getCode();
                    if(errorCode !== null && errorCode === 0){
                        scorm.connection.isActive = true;
                        if(scorm.handleCompletionStatus){
                            //Automatically set new launches to incomplete 
                            completionStatus = imst.SCORM.status("get");
                            if(completionStatus){
                                switch(completionStatus){
                                    //Both SCORM 1.2 and 2004
                                    // ALEDout > case "not attempted": pipwerks.SCORM.status("set", "incomplete"); break;
                                    //SCORM 2004 only
                                    // ALEDout > case "unknown" : pipwerks.SCORM.status("set", "incomplete"); break;
                                    //Additional options, presented here in case you'd like to use them
                                    //case "completed"  : break;
                                    //case "incomplete" : break;
                                    //case "passed"     : break;    //SCORM 1.2 only
                                    //case "failed"     : break;    //SCORM 1.2 only
                                    //case "browsed"    : break;    //SCORM 1.2 only
                                }
                            }
                        }
                    }
                    else {
                        success = false;
                        trace(traceMsgPrefix +"failed. \nError code: " +errorCode +" \nError info: " +debug.getInfo(errorCode));
                    }
                }
                else {
                    errorCode = debug.getCode();
                    
                    if ( errorCode !== null && errorCode == "101" ){
                        trace(traceMsgPrefix +" AUTO: Recovering Active API SCORM.");
                        scorm.connection.isActive = true;
                        return true;
                    }

                    if( errorCode !== null && errorCode !== 0 ){
                        trace(traceMsgPrefix +"failed. \nError code: " +errorCode +" \nError info: " +debug.getInfo(errorCode));
                    }
                    else {
                        trace(traceMsgPrefix +"failed: No response from server.");
                    }
                }
            }
            else {
                trace(traceMsgPrefix +"failed: API is null.");
            }
        }
        else {
            trace(traceMsgPrefix +"aborted: Connection already active.");
        }
        return success;
    };
    imst.SCORM.connection.terminate = function(){
        var success = false,
            scorm = imst.SCORM,
            exitStatus = imst.SCORM.data.exitStatus,
            completionStatus = imst.SCORM.data.completionStatus,
            trace = imst.UTILS.trace,
            makeBoolean = imst.UTILS.StringToBoolean,
            debug = imst.SCORM.debug,
            traceMsgPrefix = "SCORM.connection.terminate ";
        if(scorm.connection.isActive){
            var API = scorm.API.getHandle(),
                errorCode = 0;
            if(API){
                if(scorm.handleExitMode && !exitStatus){
                    if(completionStatus !== "completed" && completionStatus !== "passed"){
                        switch(scorm.version){
                            case "1.2" : success = scorm.set("cmi.core.exit", "suspend"); break;
                            /*case "2004": success = scorm.set("cmi.exit", "suspend"); break;*/
                        }
                    }
                    else {
                        switch(scorm.version){
                            case "1.2" : success = scorm.set("cmi.core.exit", "logout"); break;
                            /*case "2004": success = scorm.set("cmi.exit", "normal"); break;*/
                        }
                    }
                }
                switch(scorm.version){
                    case "1.2" : success = makeBoolean(API.LMSFinish("")); break;
                    /*case "2004": success = makeBoolean(API.Terminate("")); break;*/
                }
                if(success){
                    scorm.connection.isActive = false;
                }
                else {
                    errorCode = debug.getCode();
                    trace(traceMsgPrefix +"failed. \nError code: " +errorCode +" \nError info: " +debug.getInfo(errorCode));
                }
            }
            else {
                trace(traceMsgPrefix +"failed: API is null.");
            }
        }
        else {
            trace(traceMsgPrefix +"aborted: Connection already terminated.");
        }
        return success;
    };
    // --- pipwerks.SCORM.data functions --------------------------------------- //
    imst.SCORM.data.get = function(parameter){
        var value = null,
            scorm = imst.SCORM,
            trace = imst.UTILS.trace,
            debug = imst.SCORM.debug,
            traceMsgPrefix = "SCORM.data.get(" +parameter +") ";
        if(scorm.connection.isActive){
            var API = scorm.API.getHandle(),
                errorCode = 0;
              if(API){
                switch(scorm.version){
                    case "1.2" : value = API.LMSGetValue(parameter); break;
                    /*case "2004": value = API.GetValue(parameter); break;*/
                }
                errorCode = debug.getCode();
                //GetValue returns an empty string on errors
                //Double-check errorCode to make sure empty string
                //is really an error and not field value
                if(value !== "" && errorCode === 0){
                    switch(parameter){
                        case "cmi.core.lesson_status": 
                        case "cmi.completion_status" : scorm.data.completionStatus = value; break;
                        case "cmi.core.exit": 
                        case "cmi.exit"     : scorm.data.exitStatus = value; break;
                    }
                }
                else {
                    trace(traceMsgPrefix +"failed. \nError code: " +errorCode +"\nError info: " +debug.getInfo(errorCode));
                }
            }
            else {
                trace(traceMsgPrefix +"failed: API is null.");
            }
        }
        else {
            trace(traceMsgPrefix +"failed: API connection is inactive.");
        }
        trace(traceMsgPrefix +" value: " +value);
        return String(value);
    };
    imst.SCORM.data.set = function(parameter, value){
        var success = false,
            scorm = imst.SCORM,
            trace = imst.UTILS.trace,
            makeBoolean = imst.UTILS.StringToBoolean,
            debug = imst.SCORM.debug,
            traceMsgPrefix = "SCORM.data.set(" +parameter +") ";
        if(scorm.connection.isActive){
            var API = scorm.API.getHandle(),
                errorCode = 0;
            if(API){
                switch(scorm.version){
                    case "1.2" : success = makeBoolean(API.LMSSetValue(parameter, value)); break;
                    /*case "2004": success = makeBoolean(API.SetValue(parameter, value)); break;*/
                }
                if(success){
                    if(parameter === "cmi.core.lesson_status" || parameter === "cmi.completion_status"){
                        scorm.data.completionStatus = value;
                    }
                }
                else {
                    trace(traceMsgPrefix +"failed. \nError code: " +errorCode +". \nError info: " +debug.getInfo(errorCode));
                }
            }
            else {
                trace(traceMsgPrefix +"failed: API is null.");
            }
        }
        else {
            trace(traceMsgPrefix +"failed: API connection is inactive.");
        }
        return success;
    };
    imst.SCORM.data.save = function(){
        var success = false,
            scorm = imst.SCORM,
            trace = imst.UTILS.trace,
            makeBoolean = imst.UTILS.StringToBoolean,
            traceMsgPrefix = "SCORM.data.save failed";
        if(scorm.connection.isActive){
            var API = scorm.API.getHandle();
            if(API){
                switch(scorm.version){
                    case "1.2" : success = makeBoolean(API.LMSCommit("")); break;
                    /*case "2004": success = makeBoolean(API.Commit("")); break;*/
                }
            }
            else {
                trace(traceMsgPrefix +": API is null.");
            }
        }
        else {
            trace(traceMsgPrefix +": API connection is inactive.");
        }
        return success;
    };
    imst.SCORM.status = function (action, status){
        var success = false,
            scorm = imst.SCORM,
            trace = imst.UTILS.trace,
            traceMsgPrefix = "SCORM.getStatus failed",
            cmi = "";
        if(action !== null){
            switch(scorm.version){
                case "1.2" : cmi = "cmi.core.lesson_status"; break;
                /*case "2004": cmi = "cmi.completion_status"; break;*/
            }
            switch(action){
                case "get": success = imst.SCORM.data.get(cmi); break;
                case "set": if(status !== null){
                                success = imst.SCORM.data.set(cmi, status);
                            } else {
                                success = false;
                                trace(traceMsgPrefix +": status was not specified.");
                            }
                            break;
                default   : success = false;
                            trace(traceMsgPrefix +": no valid action was specified.");
            }
        }
        else {
            trace(traceMsgPrefix +": action was not specified.");
        }
        return success;
    };
    // --- pipwerks.SCORM.debug functions -------------------------------------- //
    imst.SCORM.debug.getCode = function(){
        var API = imst.SCORM.API.getHandle(),
            scorm = imst.SCORM,
            trace = imst.UTILS.trace,
            code = 0;
        if(API){
            switch(scorm.version){
                case "1.2" : code = parseInt(API.LMSGetLastError(), 10); break;
                /*case "2004": code = parseInt(API.GetLastError(), 10); break;*/
            }
        }
        else {
            trace("SCORM.debug.getCode failed: API is null.");
        }
        return code;
    };
    imst.SCORM.debug.getInfo = function(errorCode){
        var API = imst.SCORM.API.getHandle(),
            scorm = imst.SCORM,
            trace = imst.UTILS.trace,
            result = "";
        if(API){
            switch(scorm.version){
                case "1.2" : result = API.LMSGetErrorString(errorCode.toString()); break;
                /*case "2004": result = API.GetErrorString(errorCode.toString()); break;*/
            }
        }
        else {
            trace("SCORM.debug.getInfo failed: API is null.");
        }
        return String(result);
    };
    imst.SCORM.debug.getDiagnosticInfo = function(errorCode){
        var API = imst.SCORM.API.getHandle(),
            scorm = imst.SCORM,
            trace = imst.UTILS.trace,
            result = "";
        if(API){
            switch(scorm.version){
                case "1.2" : result = API.LMSGetDiagnostic(errorCode); break;
                case "2004": result = API.GetDiagnostic(errorCode); break;
            }
        }
        else {
            trace("SCORM.debug.getDiagnosticInfo failed: API is null.");

        }
        return String(result);
    };
    // --- Shortcuts! ---------------------------------------------------------- //
    imst.SCORM.init = imst.SCORM.connection.initialize;
    imst.SCORM.get  = imst.SCORM.data.get;
    imst.SCORM.set  = imst.SCORM.data.set;
    imst.SCORM.save = imst.SCORM.data.save;
    imst.SCORM.quit = imst.SCORM.connection.terminate;
    // --- pipwerks.UTILS functions -------------------------------------------- //
    imst.UTILS.StringToBoolean = function(string){
         switch(string.toLowerCase()) {
              case "true": case "yes": case "1": return true;
              case "false": case "no": case "0": case null: return false; 
              default: return Boolean(string);
         }     
    };
    imst.UTILS.trace = function(msg){
        //pipwerks.debug.isActive
         if( imst.DEBUG ){
            //Firefox users can use the 'Firebug' extension's console.
            // && => ||
            if(window.console || window.console.firebug){
                console.log(msg);
            } else {
                //alert(msg);
            }
         }
    };
    imst.UTILS.logger = function() {
        if ( imst.DEBUG ) {
            miAlert = "cmi.core.student_id: "+imst.scorm.get("cmi.core.student_id")+"\n"+
                  "cmi.core.student_name: "+imst.scorm.get("cmi.core.student_name")+"\n"+
                  "cmi.core.lesson_location: "+imst.scorm.get("cmi.core.lesson_location")+"\n"+
                  "cmi.core.credit: "+imst.scorm.get("cmi.core.credit")+"\n"+
                  "cmi.core.lesson_status: "+imst.scorm.get("cmi.core.lesson_status")+"\n"+
                  "cmi.core.entry: "+imst.scorm.get("cmi.core.entry")+"\n"+
                  "cmi.core.score.raw: "+imst.scorm.get("cmi.core.score.raw")+"\n"+
                  "cmi.core.score.min: "+imst.scorm.get("cmi.core.score.min")+"\n"+
                  "cmi.core.score.max: "+imst.scorm.get("cmi.core.score.max")+"\n"+
                  "cmi.core.total_time: "+imst.scorm.get("cmi.core.total_time")+"\n"+
                  "cmi.core.lesson_mode: "+imst.scorm.get("cmi.core.lesson_mode")+"\n"+
                  "cmi.launch_data: "+imst.scorm.get("cmi.launch_data")+"\n"+
                  "cmi.comments: "+imst.scorm.get("cmi.comments")+"\n"+
                  "cmi.commnets_from_lms: "+imst.scorm.get("cmi.commnets_from_lms")+"\n"+
                  "cmi.suspend_data: "+imst.scorm.get("cmi.suspend_data")+"\n"+
                  "cmi.student_data.mastery_score: "+imst.scorm.get("cmi.student_data.mastery_score")+"\n"+
                  "cmi.student_data.max_time_allowed: "+imst.scorm.get("cmi.student_data.max_time_allowed")+"\n"+
                  "cmi.student_data.time_limit_action: "+imst.scorm.get("cmi.student_data.time_limit_action")+"\n"+
                  "cmi.student_preference.audio: "+imst.scorm.get("cmi.student_preference.audio")+"\n"+
                  "cmi.student_preference.language: "+imst.scorm.get("cmi.student_preference.language")+"\n"+
                  "cmi.student_preference.speed: "+imst.scorm.get("cmi.student_preference.speed")+"\n"+
                  "cmi.student_preference.text: "+imst.scorm.get("cmi.student_preference.text")+"\n"+
                  "" ;
            console.log( miAlert );
            cantidadObjetivos = imst.scorm.get("cmi.objectives._count");
            miMensaje = "cmi.objectives._count:"+cantidadObjetivos+"\n\n";
            for (var i = 0; i < cantidadObjetivos; i++) {
                miMensaje += ("cmi.objectives."+i+".id: "+imst.scorm.get("cmi.objectives."+i+".id")+"\n");
                miMensaje += ("cmi.objectives."+i+".status: "+imst.scorm.get("cmi.objectives."+i+".status")+"\n");
                miMensaje += ("cmi.objectives."+i+".score.raw: "+imst.scorm.get("cmi.objectives."+i+".score.raw")+"\n");
                miMensaje += ("cmi.objectives."+i+".score.max: "+imst.scorm.get("cmi.objectives."+i+".score.max")+"\n");
                miMensaje += ("cmi.objectives."+i+".score.min: "+imst.scorm.get("cmi.objectives."+i+".score.min")+"\n");
            }
            console.log( miMensaje );
            miMensaje = "";
            cantidadInteraciones = imst.scorm.get("cmi.interactions._count") ;
            miMensaje += ("cmi.interactions._count: "+cantidadInteraciones+"\n"+"\n");
            miMensaje += ("cmi.interactions._children: "+imst.scorm.get("cmi.interactions._children")+"\n");
            for (var i = 0; i < cantidadInteraciones; i++){
                miMensaje += ("cmi.interactions."+i+".id: "+imst.scorm.get("cmi.interactions."+i+".id")+"\n");
                miMensaje += ("cmi.interactions."+i+".time: "+imst.scorm.get("cmi.interactions."+i+".time")+"\n");
                miMensaje += ("cmi.interactions."+i+".type: "+imst.scorm.get("cmi.interactions."+i+".type")+"\n");
                miMensaje += ("cmi.interactions."+i+".weighting: "+imst.scorm.get("cmi.interactions."+i+".weighting")+"\n");
                miMensaje += ("cmi.interactions."+i+".result: "+imst.scorm.get("cmi.interactions."+i+".result")+"\n");
                miMensaje += ("cmi.interactions."+i+".latency: "+imst.scorm.get("cmi.interactions."+i+".latency")+"\n");
                miMensaje += ("cmi.interactions."+i+".student_response: "+imst.scorm.get("cmi.interactions."+i+".student_response")+"\n");
                cantidadInteracionesObjetivo = imst.scorm.get("cmi.interactions."+i+".objectives._count") ;                 
                miMensaje += ("cmi.interactions."+i+".objectives._count: "+cantidadInteracionesObjetivo+"\n");
                for ( var k = 0; k < cantidadInteracionesObjetivo; k++ ) {
                    miMensaje += "cmi.interactions."+i+".objectives."+k+".id: "+imst.scorm.get("cmi.interactions."+i+".objectives."+k+".id")+"\n" ;
                }
                cantidadInteracionesCorrectResponses = imst.scorm.get("cmi.interactions."+i+".corect_responses._count") ;
                miMensaje += ("cmi.interactions."+i+".correct_responses._count: "+cantidadInteracionesCorrectResponses+"\n");
                for ( var k = 0; k < cantidadInteracionesCorrectResponses; k++ ) {
                    miMensaje += "cmi.interactions."+i+".correct_responses."+k+".pattern: "+imst.scorm.get("cmi.interactions."+i+".correct_responses."+k+".pattern")+"\n" ;
                }
            }
            console.log( miMensaje );
        }
        return ;
    };
    imst.UTILS.duracion = function( hInicio, hFin ){
        duracionActividad = hFin - hInicio ;
        duracionAct = "";
        mivalor = (Math.floor(duracionActividad/3600000));
        if ( mivalor < 10 ) duracionAct += "0";
        duracionAct += mivalor+":" ;
        duracionActividad = duracionActividad%3600000;
        mivalor = (Math.floor(duracionActividad/60000));
        if ( mivalor < 10 ) duracionAct += "0";
        duracionAct += mivalor+":" ;
        duracionActividad = duracionActividad%60000;
        mivalor = (Math.floor(duracionActividad/1000));
        if ( mivalor < 10 ) duracionAct += "0";
        duracionAct += mivalor+"." ;
        duracionActividad = duracionActividad%1000;
        mivalor = (Math.floor(duracionActividad/10));
        duracionAct += mivalor ;
        return duracionAct;
    };
    //// #ZONA SCORM ////

    this.tipoTraza = false;
    this.scormUnidad = false;
    this.scormRecurso = false;
    this.horaInicio = false;
    this.cantidadInteraciones = 0;

    this.init = function(){
        var params = getGET();
        if( params.av == "true" ){
            this.tipoTraza = "AV";
            this.horaInicio = new Date().getTime()/1000;
        }
        else if( params.scorm == "true" ){
            try{
                imst.SCORM.init();
                if ( imst.SCORM.connection.isActive ){
                    this.tipoTraza = "SCORM";
                    this.horaInicio = new Date().getTime()/1000;
                    this.cantidadInteraciones = imst.SCORM.get("cmi.interactions._count") ;
                    if (imst.SCORM.get("cmi.core.entry") == "ab-initio") {
                        imst.SCORM.set("cmi.core.lesson_location", location.href ); // Me parece que no fuciona
                        imst.SCORM.set("cmi.core.lesson_status", "not attempted" ); // Me parece que moodle lo implementa mal... debería empezar así... Pero parece que no lo guarda... 8(
                        imst.SCORM.set("cmi.core.score.max", "100");
                        imst.SCORM.set("cmi.core.score.min", "0");
                        imst.SCORM.set("cmi.core.score.raw", "0");
                        imst.SCORM.set("cmi.objectives.0.id", "objetivo_0");
                        imst.SCORM.set("cmi.objectives.0.status", "incomplete");
                        imst.SCORM.set("cmi.objectives.0.score.max", "100");
                        imst.SCORM.set("cmi.objectives.0.score.min", "0");
                        imst.SCORM.set("cmi.objectives.0.score.raw", "0");
                        imst.SCORM.set("cmi.interactions."+ this.cantidadInteraciones +".id", "interaccion_0");
                        imst.SCORM.set("cmi.interactions."+ this.cantidadInteraciones +".objectives.0.id", "objetivo_0");
                        try {
                            imst.SCORM.save();
                        }
                        catch(e) {
                            alert( "Se produjo un error de SCORM al iniciar la actividad: "+ e );
                        }
                    }
                }
                else{
                    console.log( "init > Se indica que el tipo de traza a utilizar es SCORM pero no se encuentra el contenedor SCORM > no hay traza" ); 
                    this.tipoTraza = "SIN TRAZA";
                }
            }
            catch(e){
                console.log( "init > Se indica que el tipo de traza a utilizar es SCORM pero no se encuentra el contenedor SCORM > no hay traza" ); 
                this.tipoTraza = "SIN TRAZA";
            }
        }
        else if( params.trackId && params.trackId != "" && params.trackId != "undefined" ){
           this.tipoTraza = "WC";
           this.horaInicio = new Date().getTime()/1000;
        }
        else {
            this.tipoTraza = "SIN TRAZA";
        }
        if( this.tipoTraza == "SCORM" ){
            this.scormUnidad = params.unitId;
            if( params.activityId ){
                this.scormRecurso = params.activityId;
            }
        }
    };
    this.recursoAbierto = function( idUnidad, idActividad, idRecurso ){
	        console.log( "Se guarda en AV que se ha abierto el recurso de la UNIDAD: "+ idUnidad +" con ACTIVIDAD: "+ idActividad +" con ID: "+ idRecurso );
	        this.recursoFinalizado( "open"+idUnidad, "open"+idActividad, "open"+idRecurso, 100 );
    };
    this.unidadFinalizada = function( idUnidad ){
        console.log( "Se guarda en "+ this.tipoTraza +" que se ha leido completamente la UNIDAD: "+ idUnidad );
        if ( this.tipoTraza == "SCORM" ){
            this.recursoFinalizado( "Unidad_"+idUnidad, "READ_Unidad_"+idUnidad, "READ_Unidad_"+idUnidad, 100 );
        }
        if ( this.tipoTraza == "WC" ){
        	var _idUnidad = idUnidad.replace( "Unidad_", "" );
        	_idUnidad = _idUnidad.replace("Unidad", "");
        	_idUnidad = _idUnidad.replace("U_", "");
        	_idUnidad = _idUnidad.replace("U", "");
            this.recursoFinalizado( "Unidad_"+_idUnidad, "READ_Unidad_"+_idUnidad, "READ_Unidad_"+_idUnidad, 100 );
        }
        if ( this.tipoTraza == "AV" ){
        	var _idUnidad = idUnidad.replace( "Unidad_", "" );
        	_idUnidad = _idUnidad.replace("Unidad", "");
        	_idUnidad = _idUnidad.replace("U_", "");
        	_idUnidad = _idUnidad.replace("U", "");
            this.recursoFinalizado( _idUnidad, "READ_Unidad_"+_idUnidad, "READ_Unidad_"+_idUnidad, 100 );
        }
    };
    this.recursoFinalizado = function( idUnidad, idActividad, idRecurso, puntuacion ){
    
        console.log( "Se guarda en "+ this.tipoTraza +" que se ha realizado el recurso de la UNIDAD: "+ idUnidad +" con ACTIVIDAD:"+ idActividad +" con ID: "+ idRecurso +" con la puntuacion: "+ puntuacion );

        if ( this.tipoTraza == "AV" ){
            
            var avData = {};
            var _key =  "";

            var horaFin = new Date().getTime()/1000;
            var duracionActividad = Math.round( horaFin - this.horaInicio );
            this.horaInicio = new Date().getTime()/1000;

        	if ( ! (idActividad.indexOf( "READ_Unidad_" ) < 0) ){

        		console.log( "se guarda en AV que se ha leido una unidad" );

        		var _idUnidad = idUnidad.replace( "Unidad_", "" );
        		var _idInterno = idActividad.replace( "READ_Unidad_", "U" );

				avData.completado = "OK";
				avData.unidad = _idUnidad;
				avData.unidad_interna = _idInterno;
        		
        		_key = "U"+ _idUnidad;
        	}
        	else if ( ! (idActividad.indexOf( "open" ) < 0) ){

        		console.log( "se guarda en AV que se ha abierto un recurso" );

        		var _idRecurso = idRecurso.replace( "open", "" );
        		var _idUnidad = idUnidad.replace( "openUnidad_", "" );

				avData.abierto = "OK";
				avData.unidad = _idUnidad;
				avData.recurso = _idRecurso;

				_key = _idRecurso;
        	}
        	else {
        		
        		console.log( "se guarda en AV que se ha realizado una actividad" );

        		var _idUnidad = idUnidad.replace( "Unidad_", "" );
        		var _idActividad = idActividad.replace( "Actividad_", "" );

	            avData.unidad = _idUnidad;
	            avData.actividad = _idActividad;
	            avData.duracion = duracionActividad;
	            avData.calificacion = puntuacion;

	            _key = _idActividad;
        	}

            var jsonAVdata = JSON.stringify( avData );

            console.log( "se tiene este json que se va a mandar a AV \n"+ jsonAVdata+"\ncon key \n"+_key );
            // console.log( "se tiene una key que se va a mandar a AV que me he inventado sin piedad: keyX" );

            var miVentana = window;
            while( miVentana !== miVentana.parent ){
                miVentana = miVentana.parent;
            }
            miVentana.postMessage( { type:'setTraza', key: _key, info:jsonAVdata }, '*' );
        }
        else if ( this.tipoTraza == "WC" ){

            var horaFin = new Date().getTime()/1000;
            var duracionActividad = Math.round(horaFin - this.horaInicio);
            var _preHoraInicio = parseInt( this.horaInicio );
            this.horaInicio = new Date().getTime()/1000;

            // puntuacion = Math.round( puntuacion ) ;
            // if( puntuacion < 0 ) {
            //  puntuacion = 0;
            // }
            
            var oRAo = {};
            oRAo.r_minCalificacion = 0;
            oRAo.r_calificacion = puntuacion;
            oRAo.r_maxCalificacion = 100;
            oRAo.r_intentos = 1;
            oRAo.r_maxIntentos = 1;
            oRAo.r_estado = "FINALIZADO";   
            oRAo.r_uRLVerResultados = "";   
            oRAo.r_fechaHoraInicio = _preHoraInicio;
            oRAo.r_maxDuracion = 86400;
            oRAo.r_duracion = duracionActividad;

            var oRDo = {} ;
            oRDo.rd_idDetalle = "";
            oRDo.rd_idTipoDetalle = "PREGUNTA";
            oRDo.rd_descripcion = "Descripcion";
            oRDo.rd_minCalificacion = 0;
            oRDo.rd_calificacion = puntuacion ;
            oRDo.rd_maxCalificacion = 100;
            oRDo.rd_intentos = 1;
            oRDo.rd_maxIntentos = 1;
            oRDo.rd_peso = 1;
            oRDo.rd_info = "";
            oRDo.rd_fechaHoraInicio = _preHoraInicio;
            oRDo.rd_maxDuracion = 86400;
            oRDo.rd_duracion = duracionActividad;
            
            var aRD = [] ;
            aRD.push( oRDo );

            var oJSo = {} ;
            
            var esteToken = getGET().token || "";
            if ( esteToken && esteToken != '' ){
                oJSo.token = esteToken;
            }

            oJSo.trackId = getGET().trackId;
            oJSo.unitID = idUnidad;
            
            if ( idActividad.indexOf( "READ_Unidad_" ) < 0 ){
                // oJSo.activityID = 'Actividad_'+this.dataWCactividad;
                oJSo.activityID = idActividad;
            }

            oJSo.result = oRAo ;
            oJSo.detail = {} ;
            oJSo.detail.resultDetail = aRD ;

            oJSo = JSON.stringify( oJSo );

            $.ajax({
                  url: "/LicenseManager/tracking/",
                  //crossDomain: true,
                  type: "POST",
                  data: 'data='+oJSo,
                  //complete: enviado
            });
        }
        
        else if ( this.tipoTraza == "SCORM" ){
            
            var horaFin = new Date().getTime()/1000;
            var duracionActividad = horaFin - this.horaInicio ;
            this.horaInicio = new Date().getTime()/1000;
            
            var duracionAct = "";
            var mivalor = (Math.floor(duracionActividad/3600000));
            
            if ( mivalor < 10 ){
              duracionAct += "0";  
            } 
            duracionAct += mivalor+":" ;
            duracionActividad = duracionActividad%3600000;
            mivalor = (Math.floor(duracionActividad/60000));

            if ( mivalor < 10 ){
              duracionAct += "0";  
            } 
            duracionAct += mivalor+":" ;
            duracionActividad = duracionActividad%60000;
            mivalor = (Math.floor(duracionActividad/1000));
            if ( mivalor < 10 ) {
                duracionAct += "0";
            }
            duracionAct += mivalor+"." ;
            duracionActividad = duracionActividad%1000;
            mivalor = (Math.floor(duracionActividad/10));
            duracionAct += mivalor ;

            imst.SCORM.set("cmi.interactions."+this.cantidadInteraciones+".time", duracionAct);

            if (puntuacion >= 50 ){
                imst.SCORM.set("cmi.objectives.0.score.raw", puntuacion);
                imst.SCORM.set("cmi.objectives.0.status", "passed");
                imst.SCORM.set("cmi.core.lesson_status", "passed");
                imst.SCORM.set("cmi.core.score.raw", puntuacion);
            }
            else {
                imst.SCORM.set("cmi.objectives.0.score.raw", puntuacion);
                imst.SCORM.set("cmi.objectives.0.status", "failed");
                imst.SCORM.set("cmi.core.lesson_status", "failed");
                imst.SCORM.set("cmi.core.score.raw", puntuacion);
            }

            try {
                imst.SCORM.save();
            }
            catch(e) {
                alert("Se produjo un error al salvar la puntuacion obtenida en la actividad: "+e);
            }
            
            imst.SCORM.set("cmi.core.exit", "logout");
            imst.SCORM.save();
        }
    };
    
    return {
        init: this.init,
        recursoAbierto: this.recursoAbierto,
        unidadFinalizada: this.unidadFinalizada,
        recursoFinalizado: this.recursoFinalizado,
        tipoTraza: this.tipoTraza,
        scormUnidad: this.scormUnidad,
        scormRecurso: this.scormRecurso
    };
}

function getGET() {
    var get;
    if( typeof get === "undefined" ){
        get = {};
        var loc = document.location.href;
        if( loc.indexOf('?')>0 ){
            var getString = loc.split('?')[1];
            var GET = getString.split('&');
            for( var i = 0, l = GET.length; i < l; i++ ){
                var tmp = GET[i].split('=');
                get[ tmp[0] ] = unescape( decodeURI(tmp[1]) );
            }
        }
        return get;
    }
    else {
        return get;
    }
}