// © Edu-Performance Canada Inc., 1997-2002 (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-2002 (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.

var is_ie4up = false;
var is_nav4up = false;
var is_nav5up = false;
var is_ie4 = false;

var runTimeEnvNone = 0; // None
var runTimeEnvAICC = 1; // AICC
var runTimeEnvSCORM12 = 2; // SCORM 1.2

var disableGetAPI = 1;

/******************************************************************************************
** Function getLMSFrame()
** Inputs: -
** Output: boolean
** Description: This function determins if lesson was launched in LMS'frame or child window
**     true : a frame of the LMS
**     false : a window (default)
******************************************************************************************/
function getLMSFrame() { 
    var URLQuery="", upperCaseURLQuery, lmsFrame="", url=window.document.location+""  
    var 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 ((pos=upperCaseURLQuery.indexOf("LMSFRAME"))>-1) {
        lmsFrame=URLQuery.substring(pos+9,URLQuery.length)
        if (lmsFrame.indexOf("&")>0)
        lmsFrame=lmsFrame.substring(0,lmsFrame.indexOf("&"))
     }
     if (lmsFrame=="TRUE")
        return true
    else
        return false
} 

function checkForCorrectBrowser(stringToDisplay)
{
  // 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>');
  }
}

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 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 = "http://" + aiccURL;
	}
	if (aiccURL=="" || sessionID==""){
		if (win == window.top) return false;
		return isCMIContext(win.parent)
	} else {
		//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>");
		document.write("<APPLET code=brwlms_api.class HEIGHT=0 ID=API NAME=API WIDTH=0 MAYSCRIPT='true'><PARAM NAME='url' VALUE='" + aiccURL + "'><PARAM NAME='webAppRep' VALUE='epc_relais'><PARAM NAME='sid' VALUE='" + sessionID + "'><PARAM NAME='version' VALUE='2.0'></APPLET>");

		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 (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.top);
         }
         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"
** 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(hh<10)
		strTime+= "0"; 
	strTime+= (hh +":");
	if(mm<10)
		strTime+= "0"; 
	strTime+= mm + ":";
	if(ss<10)
		strTime+= "0"; 
	strTime+= ss;

	return strTime;
}
 