// JavaScript Document
var startDate = 0;
var debug = false;
pipwerks.debug.isActive = debug;
pipwerks.SCORM.handleExitMode = false; // super importante para el LMS de succesFactor
/*
Se especifica la version de scorm a usar, se esta usando el warpper de pipwerks
*/
pipwerks.SCORM.version = "1.2";
var unloaded = false;
/**
 * Descripción funcion que se encargar de enviar los datos al lms
 * @method unloadHandler
 * @return 
 */
function unloadHandler() {
    if (pipwerks.SCORM.connection.isActive) {
        if (!unloaded) {
            var tiempo = computeTime();
            pipwerks.SCORM.set("cmi.core.session_time", tiempo);
            pipwerks.SCORM.save(); //save all data that has already been sent
            pipwerks.SCORM.quit(); //close the SCORM API connection properly
            unloaded = true;
        }
    }
}

/**
 * Descripción: Obtiene la ultima pantalla visitada
 * @method getLocation
 * @return visitada
 */
function getLocation() {
    if (pipwerks.SCORM.connection.isActive) {
        var visitada = eval(pipwerks.SCORM.get("cmi.core.lesson_location")) || 0;
        return visitada;
    } else {
        if (sessionStorage.getItem("offlinemp.intentos")) {
            return Number(sessionStorage.getItem("offlinemp.intentos"));
        }else{
            return 0;
        }
    }
}
/**
 * Descripción: Envia al LMS la pantlla actual o visitada
 * @return
 * @method setLocation
 * @param loc es un string con el valor de la pantalla a guardar
 * @return 
 */
function setLocation(loc) {
    if (pipwerks.SCORM.connection.isActive) {
        scorm = pipwerks.SCORM;
        if (scorm.connection.isActive) {
            var current = getLocation() || 0;
            if (Number(current) < Number(loc)) {
                var success = pipwerks.SCORM.set("cmi.core.lesson_location", loc);
                pipwerks.SCORM.save(); //save all data that has already been sent
            }
        }
    } else {
        sessionStorage.setItem("offlinemp.intentos", loc);
    }
}
/**
 * Descripción: Envia al LMS la calificación reportada por el sco
 * @return
 * @method setScore
 * @param score es un string con el valor calificacion en porcentaje
 * @return 
 */
function setScore(score) {
    if (pipwerks.SCORM.connection.isActive) {
        if( score >=  getScore()  ){
            pipwerks.SCORM.set("cmi.core.score.raw", score);
            pipwerks.SCORM.save();
        }
    }else{
        if( score >=  getScore()  ){
            sessionStorage.setItem("offlinemp.score", score);
        }
    }
}

function getScore() {
    if (pipwerks.SCORM.connection.isActive) {
        var currentScore = pipwerks.SCORM.get("cmi.core.score.raw") || 0;
        if (currentScore == "") {
            currentScore = 0;
        }
        return Number(currentScore);
    } else {
        if (sessionStorage.getItem("offlinemp.score")) {
            return Number(sessionStorage.getItem("offlinemp.score"));
        }else{
            return 0;
        }
    }

}
/**
 * Descripción: Inica el conteo del tiempo en el sco
 * @return
 * @method startTimer
 * @return 
 */
function startTimer() {
    startDate = new Date().getTime();
}
/**
 * Descripción: calucla el tiempo que el usuario permance en el sco
 * @method computeTime
 * @return formattedTime
 */
function computeTime() {
    var formattedTime = "00:00:00.0";
    if (startDate != 0) {
        var currentDate = new Date().getTime();
        var elapsedSeconds = ((currentDate - startDate) / 1000);
        formattedTime = convertTotalSeconds(elapsedSeconds);
    }
    return formattedTime;

}



/**
 * Descripción: convierte el tiempo en segundos
 * @method convertTotalSeconds
 * @param ts de tipo time
 * @return rtnVal
 */
function convertTotalSeconds(ts) {
    var Sec = (ts % 60);
    ts -= Sec;
    var tmp = (ts % 3600);
    ts -= tmp;
    if ((ts % 3600) != 0) var Hour = "00";
    else var Hour = "" + (ts / 3600);
    if ((tmp % 60) != 0) var Min = "00";
    else var Min = "" + (tmp / 60);
    Sec = "" + Sec
    Sec = Sec.substring(0, Sec.indexOf("."))
    if (Hour.length < 2) Hour = "0" + Hour;
    if (Min.length < 2) Min = "0" + Min;
    if (Sec.length < 2) Sec = "0" + Sec;
    var rtnVal = Hour + ":" + Min + ":" + Sec;
    return rtnVal;
}

/**
 * Descripción: envia al lms valores para guardar en suspend_data
 * @return
 * @method setSuspendData
 * @param data de tipo string
 * @return 
 */
function setSuspendData(data) {
    if (pipwerks.SCORM.connection.isActive) {
        var success = pipwerks.SCORM.set("cmi.suspend_data", data);
        pipwerks.SCORM.save();
    }
}
/**
 * Descripción: obtiene el valores del lms para suspend_data
 * @method getSuspendData
 * @return CallExpression
 */
function getSuspendData() {
    if (pipwerks.SCORM.connection.isActive) {
        var _data = pipwerks.SCORM.get("cmi.suspend_data");
        if (_data == "") {
            return null;
        } else {
            return _data;
        }

    } else {
        return null;
    }
}

/**
 * Description
 * @method getStudentName
 * @return CallExpression
 */
function getStudentName() {
    if (pipwerks.SCORM.connection.isActive) {
        var student_name = pipwerks.SCORM.get("cmi.core.student_name");
        if (!student_name) {
            student_name = "";
        }
        return student_name;
    } else {
        return null;
    }
}

/*
 cmi.core.lesson_status - indicates SCO completion - 
 returns one of the following: "passed", "completed", "failed", "incomplete", 
 "browsed", or "not attempted" 
*/
function getLessonStatus() {
    if (pipwerks.SCORM.connection.isActive) {
        return pipwerks.SCORM.get("cmi.core.lesson_status");
    } else {
        return "";
    }
}

function setLessonStatus(status) {
    if (pipwerks.SCORM.connection.isActive) {
        pipwerks.SCORM.set("cmi.core.lesson_status", status);
        pipwerks.SCORM.save(); //save all data that has already been sent
    }
}



function iniciarScorm() {
    var success = pipwerks.SCORM.init();
    var status = "";
    startTimer();
    if (success) {
        status = pipwerks.SCORM.get("cmi.core.lesson_status");
        if (!(status.localeCompare("completed") == 0 || status.localeCompare("passed") == 0)) {
            success = pipwerks.SCORM.set("cmi.core.lesson_status", "incomplete");
            if (success) {
                pipwerks.SCORM.save();
            }
        }
    }
}

//window.addEventListener("load", iniciarScorm);
window.addEventListener("beforeunload", unloadHandler);
window.addEventListener("unload", unloadHandler);