﻿/// <summary>
/// ajaxcore/lmsapi.js
/// scriptcode object for scormframe.aspx
/// objects for user, resource und sco
/// ---------------------------------------------------------------
/// Copyright by IM-Systems AG 2009
/// ---------------------------------------------------------------
/// 27.08.2009 MPI created
/// </summary>

var lmsapi = {};

lmsapi.resource = null;
lmsapi.resource_tracking = null;
lmsapi.user = {};
lmsapi.bckp = {};
lmsapi.notrack = {};

// ---------------------------------------------------------------------------------------
// TESTCASE
// ---------------------------------------------------------------------------------------
lmsapi.loadTest = function(arg)
{
  //alert("lmsapi.loadTest, arg:" + arg);
  
  try {
    var tl = "<tasklist><getuser /><getmpi /></tasklist>";
    var pl = "<params CLIENTID=\"xy\" />";
    var ol = "<objlist />";
    
    var ret = proxies.tracking.getMultiTabInf(tl, pl, ol);
    //alert(ret);
  } catch(e) {
    //alert("loadTest:" + e);
  }
  return (ret);
} // loadTest


// ---------------------------------------------------------------------------------------
// USER
// ---------------------------------------------------------------------------------------
/**
  * get userinformation with FIRSTNAME, LASTNAME, EMAIL, PROFILEID
  * and put it into the lmsapi.user-object.
  * @profilename: not used, always the current user [IMSUSER].
  * @return void
  */  
lmsapi.loadUser = function(profilename, notrack)
{
  //proxies.tracking.db("lmsapi.js:lmsapi.loadUser = function(profilename):" + profilename);
    
  try {
    var tl = "<tasklist><getuser /></tasklist>";
    var pl = "<params profilename=\"" + profilename + "\" />";
    var ol = "<objlist />";

    var root = ajax._getXMLDOM(proxies.tracking.getMultiTabInf(tl, pl, ol));

    if (root && root.firstChild) {
      var response = this.getRespObj(root.firstChild);
      if(response != null) {
        lmsapi.user.PROFILEID = response.getuser.user[0].PROFILEID;
        lmsapi.user.PROFILENAME = profilename; // PROFILENAME
        lmsapi.user.name = response.getuser.user[0].FIRSTNAME + " " + response.getuser.user[0].LASTNAME; // showname
        lmsapi.user.EMAIL = response.getuser.user[0].EMAIL;

        //Kein Tracking, wenn Tutor WBT besucht
        if(notrack != null) {
          lmsapi.notrack.notrack = notrack;
        }
        
        //Kein Tracking, beim Laden des ersten SCO/Objective
        lmsapi.notrack.theVeryFirst = 1;
      } else {
        //alert("no response!");
      }
    } else {
      //alert("root:" + root);
    }
  } catch(ex) {
    //alert("loadUser:" + ex);
  }
} // loadUser


// ---------------------------------------------------------------------------------------
// RESOURCE
// ---------------------------------------------------------------------------------------
/**
  * put the info for current user into the lmsapi.resource-, .resource_tracking-object.
  * getresource: get all infos as xml for a single resource.
  * getresourcetracking: get all infos as xml from trackingresource.
  * incrementresourceactivities: increase resource activities.
  *
  * @rid: current RESOURCEID
  * @return void
  */  
lmsapi.loadResourceFromCourse = function(rid)
{
  //proxies.tracking.db("lmsapi.js:lmsapi.loadResourceFromCourse = function(rid):" + rid);
  
  try {
    //var tl = "<tasklist><getcourse /><getresource /><getresourcetracking /><incrementresourceactivities /></tasklist>";
    var tl = "<tasklist><getresource /><getresourcetracking /></tasklist>";
    var pl = "<params RESOURCEID=\"" + rid + "\" PROFILEID=\"" + this.user.PROFILEID + "\" PROFILENAME=\"" + this.user.PROFILENAME + "\" />";
    var ol = "<objlist />";
    var root = ajax._getXMLDOM(proxies.tracking.getMultiTabInf(tl, pl, ol));

    if (root != null && root.firstChild) {
      var response = this.getRespObj(root.firstChild);
      if(response) {
        if(!response.error || response.error == "0") {
          lmsapi.resource = response.getresource.resource[0];
          lmsapi.resource_tracking = (response.getresourcetracking ? response.getresourcetracking.resource_tracking[0] : null);
        } else {
          //alert("response.error:" + response.error);
        }
      } else {
        //alert("no response");
      }
    } else {
      //alert("root:" + root);
    }
  } catch(e) {
    //alert("loadResourceFromCourse:" + e);
  }
} // loadResourceFromCourse


/**
 * @deprecated
 */
lmsapi.onGetResourceFromCourse = function(sn, response, error)
{
  //proxies.tracking.db("lmsapi.js:lmsapi.onGetResourceFromCourse: NOT WANTED");
  try {
    if (response) {
      if(!response.error || response.error == 0) {
        lmsapi.resource = response.getresource.resource[0];
        lmsapi.resource_tracking = response.getresourcetracking.resource_tracking[0];
      }
    } else {
      //alert(error);
    }
  } catch(e) {
    //alert("onGetResourceFromCourse:" + e);
  }
} // onGetResourceFromCourse


// ---------------------------------------------------------------------------------------
// SCO EXTERNAL
// ---------------------------------------------------------------------------------------
lmsapi.loadScoEx = function(sco_id, player, scotitle)
{
  //proxies.tracking.db("lmsapi.js:lmsapi.loadScoEx = function(sco_id)" + sco_id);

  try {
    this.resource = player.resource;
    this.resource_tracking = player.resource_tracking;
    this.user = player.user;
    this.sco = player.sco;
    
    //for MULTI-SCO
    //this.sco.LOCALSESSIONTIME = new Date();
    if(scotitle == null) {
      scotitle = "SCOID=" + sco_id;
    }
    
    this.sco.TRACKINGSCONAME = scotitle;
    this.sco.isUpdated = true;

    this.updateScoTracking();
    this.updateResourceTracking();
    
    var tl = "<tasklist><getsco /><getscotracking /><getobjectives /></tasklist>";
    var pl = "<params SCOIDENTIFIER=\"" + sco_id + "\" RESOURCEID=\"" + player.resource.RESOURCEID + "\" PROFILEID=\"" + player.user.PROFILEID + "\" PROFILENAME=\"" + this.user.PROFILENAME + "\" />";
    var ol = "<objlist />";

    var root = ajax._getXMLDOM(proxies.tracking.getMultiTabInf(tl, pl, ol));
    if (root != null && root.firstChild) {
      var response = this.getRespObj(root.firstChild);
      if(response) {
        this.onGetSco("sn", response, "error");
      }
    } else {
      //alert("root:" + root);
    }
  } catch(e) {
    //alert("loadSco:" + e);
  }
}

// ---------------------------------------------------------------------------------------
// SCO
// ---------------------------------------------------------------------------------------
lmsapi.loadSco = function(sco_id)
{
  //proxies.tracking.db("lmsapi.js:lmsapi.loadSco = function(sco_id)" + sco_id);

  try {
    //var tl = "<tasklist><getsco /><getscotracking /><getobjectives /><incrementscoactivities /></tasklist>";
    var tl = "<tasklist><getsco /><getscotracking /><getobjectives /></tasklist>";
    var pl = "<params SCOIDENTIFIER=\"" + sco_id + "\" RESOURCEID=\"" + this.resource.RESOURCEID + "\" PROFILEID=\"" + this.user.PROFILEID + "\" PROFILENAME=\"" + this.user.PROFILENAME + "\" />";
    var ol = "<objlist />";

    var root = ajax._getXMLDOM(proxies.tracking.getMultiTabInf(tl, pl, ol));
    if (root != null && root.firstChild) {
      var response = this.getRespObj(root.firstChild);
      if(response) {
        this.onGetSco("sn", response, "error");
      }
    } else {
      //alert("root:" + root);
    }
  } catch(e) {
    //alert("loadSco:" + e);
  }
} // loadSco


lmsapi.onGetSco = function(sn, response, error)
{
  //proxies.tracking.db("lmsapi.js:lmsapi.onGetSco = function(sn, response, error)");
 
  try {
    this.tmpsco = null;
    if (response) {
      if(!response.error || response.error == 0) {
        lmsapi.tmpsco = response.getsco.sco[0];
        lmsapi.tmpsco.isFinished = false;
        lmsapi.tmpsco.isInitialized = false;
        lmsapi.tmpsco.sessionState = "NotInitialized";
        lmsapi.tmpsco.isUpdated = false;
        lmsapi.tmpsco.tracking = response.getscotracking.sco_tracking[0];
        
        lmsapi.tmpsco._bckp_total_time = response.getscotracking.sco_tracking[0].TOTALTIME;
        lmsapi.tmpsco._start_date_time = new Date();

        lmsapi.tmpsco.objectives = new Array();

        if(response.getobjectives != null && response.getobjectives.objectives.length > 0) {
          lmsapi.tmpsco.objectives = response.getobjectives.objectives;
          for(var i = 0; i < lmsapi.tmpsco.objectives.length; i++) {
            lmsapi.tmpsco.objectives[i]._local_SESSIONTIME = 0;
          }
        }
      }
    } else {
      //alert("onGetSco:" + error);
    }
  } catch(e) {
    //alert("onGetSco:" + e);
  }
} // onGetSco


// ---------------------------------------------------------------------------------------
// END
// ---------------------------------------------------------------------------------------
lmsapi.updateResourceTracking = function ()
{
  //proxies.tracking.db("lmsapi.js:lmsapi.updateResourceTracking = function ()");

  try {
    var tl = "<tasklist><updateresourcetracking /><getresourcetracking /></tasklist>";
    var pl = "<params RESOURCEID=\"" + this.resource.RESOURCEID + "\" PROFILEID=\"" + this.user.PROFILEID + "\" PROFILENAME=\"" + this.user.PROFILENAME + "\" />";
    var ol = "<objlist>";
    ol += this.setRequestXml("resource_tracking", this.resource_tracking);
    ol += "</objlist>";
    var root = ajax._getXMLDOM(proxies.tracking.getMultiTabInf(tl, pl, ol));
    if (root != null && root.firstChild) {
      var response = this.getRespObj(root.firstChild);
      if(response) {
        this.onUpdateResourceTracking("sn", response, "error");
      }
    } else {
      //alert("root:" + root);
    }
  } catch(e) {
    //alert("updateResourceTracking:" + e);
  }
} // updateResourceTracking


lmsapi.onUpdateResourceTracking = function(sn, response, error)
{
  //proxies.tracking.db("lmsapi.js:lmsapi.onUpdateResourceTracking = function(sn, response, error)");

  try {
    if(response.getresourcetracking != null) {
      if(response.getresourcetracking.resource_tracking[0] != null) {
        this.resource_tracking = response.getresourcetracking.resource_tracking[0];
      }
    }
  } catch(e) {
    //alert("onUpdateResourceTracking:" + e);
  }
} // onUpdateResourceTracking


// ---------------------------------------------------------------------------------------
// updateScoTracking
// ---------------------------------------------------------------------------------------
lmsapi.updateScoTracking = function()
{
  //proxies.tracking.db("lmsapi.js:lmsapi.updateScoTracking = function ()");

  try {
    var tmpOl = "";
    var isUpdated = false;
    var tl = "<tasklist>";
    var pl = "<params RESOURCEID=\"" + this.sco.RESOURCEID + "\" PROFILEID=\"" + this.user.PROFILEID + "\" PROFILENAME=\"" + this.user.PROFILENAME + "\" />";
    var ol = "<objlist>";

    if(this.sco.isUpdated) {
      ol += this.setRequestXml("sco_tracking", this.sco.tracking);
      isUpdated = true;
      this.sco.isUpdated = false;
      tl += "<updatescotracking /><computescormresourcetracking />";
      if(this.resource.RESOURCEID == this.sco.RESOURCEID) {
        tl += "<getresourcetracking />";
      }
    }

    for(var i = 0; i < this.sco.objectives.length; i++) {
      if(this.sco.objectives[i].isUpdated) {
        tmpOl += this.setRequestXml("objective", this.sco.objectives[i]);
        this.sco.objectives[i].isUpdated = false;
      }
    }

    if(tmpOl.length > 0) {
      ol += "<objectives>" + tmpOl + "</objectives>";
      tl += "<updateobjectives />";
      //proxies.tracking.db("lmsapi.js:lmsapi.updateScoTracking = OBJECTIVES will be updateted");
      isUpdated = true;
    }

    ///////////////////

    if(isUpdated) {
      tl += "</tasklist>";
      ol += "</objlist>";
      var root = ajax._getXMLDOM(proxies.tracking.getMultiTabInf(tl, pl, ol));
      if (root != null && root.firstChild) {
        var response = this.getRespObj(root.firstChild);
        if(response) {
          this.onUpdateScoTracking("sn", response, "error");
        }
      } else {
        //alert("root:" + root);
      }
    }
  } catch(e) {
    //alert("updateScoTracking:" + e);
  } // try

} // updateScoTracking


lmsapi.onUpdateScoTracking = function(sn, response, error)
{
  //proxies.tracking.db("lmsapi.js:lmsapi.onUpdateScoTracking = function(sn, response, error)");
  
  try {
    if(response.getresourcetracking != null) {
      if(response.getresourcetracking.resource_tracking[0] != null) {
        this.resource_tracking = response.getresourcetracking.resource_tracking[0];
      }
    }
  } catch (e) {
    //alert("onUpdateScoTracking:" + e);
  }
} // onUpdateScoTracking


// ---------------------------------------------------------------------------------------
// getObjective
// ---------------------------------------------------------------------------------------
lmsapi.getObjective = function(index)
{
  try {
    if(this.sco.objectives[index]) {
      //proxies.tracking.db("lmsapi.js:lmsapi.getObjective = function(index):" + index);
      //proxies.tracking.db("lmsapi.js:lmsapi.getObjective = objective._start_date_time USED " + this.sco.objectives[index]._start_date_time + " index:" + index);
      var obj = this.sco.objectives[index];
      return(obj);
    } else {
      var objective = {};
      objective.PROFILEID = this.user.PROFILEID;
      objective.RESOURCEID = this.resource.RESOURCEID;
      objective.SCOIDENTIFIER = this.sco.SCOIDENTIFIER;
      objective.OBJECTIVEID = "";
      objective.SCORESCALED = 0; // (-1...1) Number that reflects the performance of the learner for the objective
      objective.SCORERAW = 0; // Number that reflects the performance of the learner, for the objective, relative to the range bounded by the values of min and max
      objective.SCOREMIN = 0;
      objective.SCOREMAX = 0;
      objective.ACTIVITIES = 0;
      objective.COMPLETION = "3"; // =>"unknown"; objective done?
      objective.PROGRESSMEASURE = 0; // (0...1) Measure of the progress the learner has made toward completing the objective
      objective.SUCCESS = "2"; // =>"unknown"; objective successful done?
      objective.DESCRIPTION = "";
      objective.isUpdated = true;
      objective.SESSIONTIME = 0;
      objective.TOTALTIME = 0;
      objective._local_SESSIONTIME = 0;
      objective._start_date_time = new Date(); // default
      this.sco.objectives[index] = objective;
      //proxies.tracking.db("lmsapi.js:lmsapi.getObjective = function(index):" + index + " NEW objective");
      //proxies.tracking.db("lmsapi.js:lmsapi.getObjective = objective._start_date_time NEW " + this.sco.objectives[index]._start_date_time);
      return(this.sco.objectives[index]);
    }
  } catch(e) {
    //alert("getObjective:" + e);
  }
} // getObjective


// ---------------------------------------------------------------------------------------
// TRANSFORMER
// ---------------------------------------------------------------------------------------
/**
  * get a response object for multiple functions and multiple parameters.
  * @root response xml with result datasets and values, 
  *       recursive all root-nodes
  * @return json response object
  */  
lmsapi.getRespObj = function(root)
{
	var attr = (root ? root.attributes : null);
	var elem = new Array();
	var empty = true;
	
	//proxies.tracking.db("lmsapi.js:lmsapi.getRespObj = function(root)");
	
	try {
	  // all attributes of the current node:
	  if (attr && attr.length > 0) {
	    empty = false;
	    for (var i = 0; i < attr.length; i++) {
	      elem[attr[i].nodeName] = attr[i].nodeValue;
	    } // for
	  }
    
    // recursive for all children in the hirarchy:
	  if (root && root.hasChildNodes()) {
		  var child = root.firstChild;
		  // simple value:
		  if (child.nodeType == 3) {
	      empty = false;
		    elem = child.nodeTypedValue;
	    } else {
		    while (child) {
			    if (child.nodeType == 1 && child.nodeName) {
	          empty = false;
			      if (child.nodeName == "row") { // multiple rows, no ".row"-node
			        elem.push(this.getRespObj(child));
			      } else {
			        elem[child.nodeName] = this.getRespObj(child);
			      }
			    }
			    child = child.nextSibling;				
		    } // while
		  }
	  }
  	
	  // no empty element
	  if (empty) {
	    elem = null;
	  }
	} catch(e) {
	  //alert("getRespObj:" + e);
	}
	return (elem);
} // getRespObj


/**
 * prepares a object to xml-notation.
 * @objname main tagname
 * @objList the object to transfor to attributes
 * @return xml request tag
 */
lmsapi.setRequestXml = function(objname, objList)
{
  var n, o, ret = "";
  
  //proxies.tracking.db("lmsapi.js:lmsapi.setRequestXml = function(objname, objList)");
  
  try {
    if(objname != null && objList != null) {
      ret += "<" + objname + " ";
      for (o in objList) {
        var nam = o;
        if (nam == null || nam == "") {
          continue;
        } else if (typeof(o) == "object") {

          ret += lmsapi.setRequestXml(nam, objList[o]);
        } else {
          ret += " " + nam + "=\"" + objList[o] + "\" ";
        }
      }
      ret += " />";
    }
  } catch(e) {
    //alert("setRequestXml:" + e);
  }
  return(ret);
} // setRequestXml


// ---------------------------------------------------------------------------------------
// New 24.11.2009
// ---------------------------------------------------------------------------------------
lmsapi.UpdateScoLocation = function(value)
{
  var i;
  
  if(value != null) {
    this.sco.tracking.location = value; // next visited

    //proxies.tracking.db("lmsapi.js:lmsapi.UpdateScoLocation = function(value):" + value);

	  for(i = 0; i < this.sco.objectives.length; i++) {
      if(this.sco.objectives[i].OBJECTIVEID == value) {
        if(this.sco.objectives[i].ACTIVITIES != null) {
          this.sco.objectives[i].ACTIVITIES++;
	      } else {
		      this.sco.objectives[i].ACTIVITIES = 1;
	      }
	      this.sco.objectives[i].isUpdated = true;
      }
    }
    
    
  } // value
} // UpdateScoLocation


// ---------------------------------------------------------------------------------------
// New 24.11.2009
// ---------------------------------------------------------------------------------------
/**
 * maybe a tutor has a look to the WBT.
 * If so, trackinginformations must be deleted at database after api-commit.
 */
lmsapi.checkResourceTracking = function ()
{
  if(this.notrack != null && this.notrack.notrack == "1") {
    //proxies.tracking.db("lmsapi.js:lmsapi.checkResourceTracking = function()");
    try {
      var tl = "<tasklist><deleteResourceTracking /></tasklist>";
      var pl = "<params PROFILEID=\"" + this.user.PROFILEID + "\" RESOURCEID=\"" + this.resource.RESOURCEID + "\" PROFILENAME=\"" + this.user.PROFILENAME + "\" />";
      var ol = "<objlist />";
      //var root = ajax._getXMLDOM(proxies.tracking.getMultiTabInf(tl, pl, ol));
    } catch(ex) {
      //alert("checkResourceTracking: " + ex);
    }
  } // notrack
} // checkResourceTracking


lmsapi.finalize = function()
{
  try {
    //proxies.tracking.db("lmsapi.js:lmsapi.finalize = function()");
    
    var tl = "<tasklist><finalize /></tasklist>";
    var pl = "<params PROFILEID=\"" + this.user.PROFILEID + "\" RESOURCEID=\"" + this.resource.RESOURCEID + "\" PROFILENAME=\"" + this.user.PROFILENAME + "\" />";
    var ol = "<objlist />";
    var root = ajax._getXMLDOM(proxies.tracking.getMultiTabInf(tl, pl, ol));
  } catch(ex) {
    //alert("finalize: " + ex);
  }
} // finalize


// ---------------------------------------------------------------------------------------
// New 27.11.2009
// ---------------------------------------------------------------------------------------
lmsapi.UpdateObjectiveSessionTime = function(value)
{
  var i, diff = 0, olds, st, nt;
  
  if(value != null) { // last Objective visited
    //proxies.tracking.db("lmsapi.js:lmsapi.UpdateObjectiveSessionTime = function(value):" + value);

	  for(i = 0; i < this.sco.objectives.length; i++) {

      if(this.sco.objectives[i].OBJECTIVEID == value) {
  	    olds = parseInt(this.sco.objectives[i]._local_SESSIONTIME);
        st = this.sco.objectives[i]._start_date_time;
        nt = new Date();

    	  diff = parseInt(Math.round( (nt - st) / 1000 )); // to seconds
        if(diff > 0) {
          this.sco.objectives[i]._local_SESSIONTIME = olds + diff;
          if(this.sco.objectives[i].ACTIVITIES == null || this.sco.objectives[i].ACTIVITIES == 0) {
		        this.sco.objectives[i].ACTIVITIES = 1;
          }
	        this.sco.objectives[i].PROGRESSMEASURE = 1; // so far so good
          this.sco.objectives[i].isUpdated = true;
        }
      }
    } // for
  } // value
} // UpdateObjectiveSessionTime


// ---------------------------------------------------------------------------------------
// New 21.12.2009
// ---------------------------------------------------------------------------------------
lmsapi.SetObjectiveSessionTime = function(value)
{
  var i;
  
  if(value != null) {
    //proxies.tracking.db("lmsapi.js:lmsapi.SetObjectiveSessionTime = function(value):" + value);

	  for(i = 0; i < this.sco.objectives.length; i++) {
      if(this.sco.objectives[i].OBJECTIVEID == value) {
        this.sco.objectives[i]._start_date_time = new Date();
      }
    } // for
  }
} // SetObjectiveSessionTime


// ---------------------------------------------------------------------------------------
// New 20.12.2009
// ---------------------------------------------------------------------------------------
lmsapi.UpdateSCOSessionTime = function()
{
  var i, oldt, st;
  //proxies.tracking.db("lmsapi.js:lmsapi.UpdateSCOSessionTime = function()");
  
  this.sco.tracking.SESSIONTIME = Math.round(Math.abs(new Date() - this.sco._start_date_time) / 1000); // to Seconds
  this.sco.tracking.TOTALTIME = parseInt(lmsapi.sco._bckp_total_time) + 
                                parseInt(lmsapi.sco.tracking.SESSIONTIME);
  for(i = 0; i < this.sco.objectives.length; i++) {
    oldt = parseInt(this.sco.objectives[i].TOTALTIME);
    st = parseInt(this.sco.objectives[i]._local_SESSIONTIME);
    this.sco.objectives[i].TOTALTIME = oldt + st;
    this.sco.objectives[i].SESSIONTIME = st;
    this.sco.objectives[i].isUpdated = true;
  }
  this.sco.isUpdated = true;
  
} // UpdateSCOSessionTime

// ---------------------------------------------------------------------------------------
//    END
// ---------------------------------------------------------------------------------------
