//******************************************************************************
// FileName:	launch.js
// Description:	Provides functions for running applications and files from
//		HTML files.
//		Note: Requires LJHTMLContentFunctions.dll ActiveX 
//		component installed and registered.
//
// Version:	1.00.0015 - 	15/03/2007
// 
// Revision:	
//
//		1.00.0015 - UNC Path Fixes.
//					Modified RunLink to handle file paths using UNC format.
//					Modified GetCurrentPath to find a path using the href is one
//					exists. Change made to "RunLink", now references version 
//					1,0,0,6 of the LJHTMLContentFunctions.CAB file. 
//					See ID7029 for more details. (15/03/2007-DLP).
//		1.00.0014 - Allow optional parameter to be passed to the launch control 
//					that will activate license checking. Change made to "RunLink"
//					References version 1,0,0,5 of the LJHTMLContentFunctions.CAB 
//					file. See ID7025 for more details. (09/03/2007-DLP).
//		1.00.0013 - Modified to allow launch sequences to be used for each 
//					application type. (31/01/2007-DLP).
//		1.00.0012 - Added convertPathToWin to conert a url to a file path before 
//					passing it to the launching ActiveX control. 
//                  (03/01/2007-DLP).
//		1.00.0011 - Modified RunLink to prevent an issue in IE7 where "file:///" 
//					is passed to the application launching ActiveX control.
//					(19/12/2006-DLP).
//		1.00.0010 - Modified BuildDownloadLink function to include a reference 
//					to the system directory "../system/s_dwnldcontentfile.ASP" 
//					this will allow the function to be called from instructor
//					resources. (06/12/2006-DLP).
//		1.00.0009 - Modified Flash AddFlashLink to use GetContentDir instead of 
//					the BuildPath function around the URL. (27/09/2006-DLP).
//		1.00.0008 - Modified SetupRunObject to include an optional parameter that 
//					will cause the extra path to the CAB file to be ignored.
//			    	This is required for the multiple module from one disk mode 
//					of operation. (13/09/2006-DLP).
//		1.00.0007 - Added AddFlashLink function to call Flash simualtions in a 
//                  popup window.  Modified AddLookupRunLink to make use of the 
//					fucntion. (12/09/2006-DLP).
//		1.00.0006 - Added BuildDownloadLink function to runlink. No longer uses 
//					'popup' function for exes. (21/08/2006-DLP).
// 		1.00.0005 -	Changed the style sheet used in the equipment required 
//					message. (06/04/2006-DLP).
// 		1.00.0004 - Moved language specific text to language.js.  Added extra 
//					paramters to the runlink for install location and application 
//					type.  References version 1,0,0,3 of the 
//					LJHTMLContentFunctions.CAB file (29/03/2006-DLP).
//		1.00.0003 - References version 1,0,0,2 of the LJHTMLContentFunctions.CAB 
//					file. (06/02/2006-DLP).
//		1.00.0002 - Updated messages when unable to insert launch link 
//					(10/11/2005 - ST).
//		1.00.0001 - Added script for running SRS Lessons. (17/10/2005 - ST).
//		1.00.0000 - Created. (22/09/2005 - ST)
//
//******************************************************************************

function SetupRunObject(bIgnorePath)
//Setup the page to use the ActiveX component for running files.
//This must be called from all pages which wish to use the component.
{

  //Write out an error handler
  document.write('<script language="JavaScript"><!--window.onerror=window_error\/\/--><\/script>');

  // Do not set a path to the cab if the optional parameter is set.
  // Change made 13/09/2006 DLP.
  if ((bIgnorePath) && (bIgnorePath==true))
  {
    var sCabPath = '';
  }
  else
  {
    var sCabPath = '../theme/system/script/';
  }

  //Write out the application launch control object if IE4 or greater
  if(IsIE4orGreater())
  {
    document.write('<div style="visibility:hidden;position:absolute">');
    document.write('<OBJECT ID="RunApp" CLASSID="CLSID:0737D0B3-DE0A-42EF-9DEE-4E4766AD687F" CODEBASE="'+sCabPath+'LJHTMLContentFunctions.CAB#version=1,0,0,6" width=6 height=2>');
    document.write('<\/OBJECT><\/div>');
  }

}


function GetCurrentPath()
// This function will return the current directory
// that contains the loaded HTML file.
// Added by Daren 10/03/2006.
{
  if ((window.document.location) && (window.document.location.pathname))
  {
    var sPath = window.document.location.pathname;
  }
  else
  {
    var sPath = '';
  }

  // Modified to use href where available.
  // Change made 15/03/2007 DLP.
  if ((sPath.lastIndexOf(".")>=0) && (sPath.indexOf("\\")==-1))
  {
    if ((window.document.location) && (window.document.location.href))
    {
      var sPath = window.document.location.href;
    }
  }

  // If a path name is not returned, then look 
  // the location where the images are referenced.
  if ((sPath==null) || (sPath=='') || ((sPath.lastIndexOf(".")>=0) && (sPath.indexOf("\\")==-1)))
  {
    sPath = GetMediaDir();
  }
  else if (sPath.lastIndexOf(".")>=0)
  {
    sPath = sPath.substr(1, sPath.lastIndexOf("\\"));
  }
  return sPath;
}

function BuildFullPath(sPartPath)
// This function will check the specified path
// and add on the current directory if only
// path of the path is specified.
// Added by Daren 10/03/2006.
{

  if (sPartPath.indexOf(":")== -1)
  {
    
    //Find the full path of where the page is.
    var sCurrentPath = GetCurrentPath();
    sPartPath = sCurrentPath+sPartPath;
    
  }
  return sPartPath;
}

function AddEquipmentRequiredLink()
// This function will add a message in ClassCampus mode
// to say that the activity requires additional hardware.
// Added by Daren 10/03/2006.
{
  if (!bIsOnlineManual())
  {
    document.write('<table class="eqiprequired">'); 
    document.write('<tr>'); 
    document.write('<td>'); 
    document.write('<p class="screenBodyHighlight">'+sLncTxt_EquipmentRequired+'</p>'); 
    document.write('<\/td>'); 
    document.write('<\/tr>'); 
    document.write('<\/table>');
    document.write('<br\/>');
  }
}


function AddLookupRunLink(AppRef, sCaption, CommandLine, Search, Show, LocalFile, bLinkInClassAct)
// This function will run an application that matches the passed reference.
// Data used in this function comes from the custom.js file.
// Other parameters are optional.
// Function written by Richard Ewin.
// Modified by Daren.
{
  var bFound = false;
  
  for (var i=1;i<as_AppRef.length;i++)
  {
    if (as_AppRef[i].toLowerCase() == AppRef.toLowerCase())
    {
      
      if ((sCaption==null) || (sCaption==''))
      {
        sCaption = as_AppName[i];
      }
      
      //Build a default launch sequence to handle the old custom.js setting.
      var sDefaultSequence = "";
      if (LocalFile==null)
      {
        var LocalFile=as_LocalFile[i];
      }
      
      if (bFlashAlernativeExists(i))
      {
        sDefaultSequence += FLASH_SEQUENCE + ",";
      }
      else
      {
		sDefaultSequence += APP_RUN_3RD_PARTY + "," + PRESENTATION_SEQUENCE + ",";
      }

      //Find the launch code sequence for the current application.
      try 
      {
        if ((as_Launch==null) || (as_Launch[i]==null) || (as_Launch[i]==''))
        {
          if ((ai_Search==null) || (ai_Search[i]==null) || (ai_Search[i]==''))
          {
            var sCodes=""+sDefaultSequence+'7';
          }
          else
          {
            var sCodes=""+sDefaultSequence+ai_Search[i];
          }
        }
        else
        {
          var sCodes=as_Launch[i];
        }
      }
      catch(e)
      {
        var sCodes= ""+sDefaultSequence+'7';
      }
      
      //Work though the launch code sequence.
      var sSeq = sCodes.split(","); 
      if ((bFlagSet(sSeq[0], FL_FlashPopup)) && (bModeAllowed(sSeq[0])) && bFlashAlernativeExists(i))
      {
        AddFlashLink(i, sCaption)
      }
      else if ((bFlagSet(sSeq[0], FL_Popup)) && (bModeAllowed(sSeq[0])))
      {
        AddFileLink(LocalFile, sCaption, eval(bFlagSet(sSeq[0], FL_BuildPath)))
      }
      else
      {
        AddRunLink(sCaption, 
      			 as_AppFile[i], 
         		 CommandLine!=null ? CommandLine : as_Cmds[i], 
		 		 as_Shortcut[i], 
		 		 Search!=null ? Search : "'"+sCodes+"'", 
		 		 Show!=null ? Show : ai_Show[i], 
		 		 as_Install[i], 
		 		 as_AppType[i], 
		 		 LocalFile!=null ? LocalFile : as_LocalFile[i], 
				 bLinkInClassAct); 
      }
      bFound = true;
      break;  
    }
  }

  if (!bFound)
  {
    alert(sLncTxt_AppNotFound + '\n\n' + AppRef);
    document.write('<a href=\"javascript:alert(\'' + sLncTxt_AppNotFound + ' \'\\n\\n\' + AppName);\'\">' + sLncTxt_ErrorNoLink + '</a>');
  }
}


function bFlashAlernativeExists(index)
// Used to determine whether a flash alternative has
// been set for the indexed application or not.
// Added 13/09/2006 DLP.
{
  try
  {
    //if ((as_FlashFile[index]) && (as_FlashFile[index]!="") && !bIsOnlineManual())
    if ((as_FlashFile[index]) && (as_FlashFile[index]!=""))
    {
      return true;
    }
    else
    {
      return false;
    }
  }
  catch(err)
  {
    return false;
  }
}

function AddFlashLink(index, sCaption)
// This function will write a link to a Flash File.
// Added 12/09/2006 DLP.
{
  document.write('<a href="javascript:var newWin=window.open(\''+GetMediaDir()+'..\/theme\/system\/html\/flashwin.htm?index='+index+'\',\'_new\',\'location=no,resizable=yes,width=792,height=550\');var x=newWin.focus();">'+sCaption+'</a>');
}

function AddFileLink(sFile, sCaption, bAddDir)
// This function will write a link to a specifed File.
// Added 12/01/2007 DLP.
{
  if (bAddDir)
  {
    sFile=GetMediaDir()+sFile;
  }
  document.write('<a href="javascript:var newWin=window.open(\''+sFile+'\',\'_new\',\'location=no,resizable=yes,width=792,height=550\');var x=newWin.focus();">'+sCaption+'</a>');
}


function AddLookupPresentationLink(AppRef)
{
  //Adds an run presentation with a fixed caption from the language.js file.
  AddLookupRunLink(AppRef, sVieTxt_ClickToViewPres);
}


function AddDownLoadLink(sFilename, sCaption, sTarget)
{
  if ((sTarget==null) || (sTarget=='')) 
  {
    sTarget = '_self';
  }
  document.write('<a href="' + BuildDownloadLink(sFilename) + '" target="' +sTarget+ '">' + sCaption + '</a>');
}

function BuildDownloadLink(sFilename)
{
  // If running in ClassCampus, then make sure all the download files
  // are fed through a special ASP that is required for Windows 2003.
  // Added by Daren 17/03/2006.

  var sFullFilename = sFilename.toLowerCase();
  if ((!bIsOnlineManual()) && (sFullFilename.indexOf('.htm') == -1))
  {
    var sParentFilePath = sASPGetLocation();
    
    // Build the full path to the download link file.
    // Change made 27/03/2006.
    //var sFullFilename = BuildFullPath(sFilename);

    var sFullFilename = sFilename;
    
    // Only add the asp relocator if the file is running
    // off a server.  Change made 29/03/2006 DLP.
    // Also looks for the HTTPS version for secure servers.  Change made 28/07/2006 DLP.
    if ((sParentFilePath.toLowerCase().indexOf('http:') != -1) || (sParentFilePath.toLowerCase().indexOf('https:') != -1))
    {
      sFullFilename = sParentFilePath+'../../system/asp/s_dwnldcontentfile.ASP?File=' + sFullFilename;
    }
    else if ((sFullFilename.toLowerCase().indexOf('file:') == -1) && (sFullFilename.toLowerCase().indexOf('ftp:') == -1))
    {
      sFullFilename = 'file:///' + sFullFilename;
    }
  }
  else
  {
    var sFullFilename = sFilename;
  }
  return sFullFilename;
}


function AddLookupInstallLink(AppRef)
// This function will write an install link to the passed application.
// Data used in this function comes from the custom.js file.
// Function written by Daren.
{

  var bFound = false;

  for (var i=1;i<as_AppRef.length;i++)
  {
    if (as_AppRef[i].toLowerCase() == AppRef.toLowerCase())
    {
      AddInstallLink(as_Install[i],as_AppType[i]);

      bFound = true;
      break;  
    }
  }

  if (!bFound)
  {
    alert(sLncTxt_AppNotFound + '\n\n' + AppRef);
    document.write('<a href=\"javascript:alert(\'' + sLncTxt_AppNotFound + ' \'\\n\\n\' + AppName);\'\">' + sLncTxt_ErrorNoLink + '</a>');
  }
}

function AddInstallLink(InstallFile, AppType)
// This function will write a link to the installation page.
// Added by Daren 13/03/2006.
{
  InstallFile = InstallFile.replace(/[\\]/g, "\\\\");
  
  if (InstallFile.toLowerCase().indexOf('.exe') != -1)
  {
    document.write('<a href="javascript:BuildDownloadLink(\''+InstallFile+'\');" taget="_self">'+sLncTxt_InstallAppNow+' '+AppType+'<\/a>');
  }
  else
  {
    document.write('<a href="javascript:BuildDownloadLink(\''+InstallFile+'\');" taget="_new">'+sLncTxt_InstallAppNow+' '+AppType+'<\/a>');
  }
}

function AddRunLink(AppName, AppFile, Cmds, Shortcut, Search, Show, InstallFile, AppType, LocalFile, bLinkInClassAct)
//Add an appropriate Run Link to the page - if the control can't be used
//add a message to use the shortcut
{
  if (AppType==null) AppType = '';
  if (InstallFile==null) InstallFile = '';
  if (LocalFile==null) LocalFile = '';
  if (bLinkInClassAct==null) bLinkInClassAct=true;


 // bLinkInClassAct = (bLinkInClassAct || (!bIsOnlineManual()));
  if (bLinkInClassAct)
  {
    //if able to use the launch control
    if (CanLaunch())
    {
      document.write('<a href="javascript:RunLink(\'' + AppFile.replace(/[\\]/g, "\\\\") 
						  + '\',\'' + Cmds.replace(/\\/g, "\\\\") 
						  + '\',\'' + Shortcut.replace(/\\/g, "\\\\")
						  + '\','   + Search 
						  + ','     + Show 
						  + ',\''   + InstallFile.replace(/[\\]/g, "\\\\") 
						  + '\',\'' + AppType 
						  + '\',\'' + LocalFile.replace(/[\\]/g, "\\\\") 
						  + '\')">' + AppName + '<\/a>');

    }
    //control can't be used - display a message indicating what to run
    else
    {
      var ShortcutLink='';

      //shortcut passed so write out the shortcut location - check shortcut is created within LJ Technical
      //Systems folder
      if (Shortcut != '')
      {
        ShortcutLink =  ' ('+sLncTxt_StartMenu+' <b>'+sLncTxt_Programs+'\\';

        //Add in the LJ Technical Systems folder if required
        if(Shortcut.substr(0,2) != '..')
          ShortcutLink = ShortcutLink + 'LJ Technical Systems\\';
        else
          Shortcut = Shortcut.substring(3, Shortcut.length);

        ShortcutLink = ShortcutLink + Shortcut + '<\/b>)';
      }
  
      //write out the application name including shortcut if specified
      document.write('<b>' + AppName + '<\/b>' + ShortcutLink );
    }
  }
  else
  {
    //Only the name is required.
    document.write(AppName);
  }
}

function convertPathToWin(sPath)
{
  //Convert a url into a windows compatible file path.
  var sToReplace = '\/\\\/\/g';
  sPath = sPath.replace(eval(sToReplace), "\\");
  sPath = unescape(sPath);
  return sPath;
}

function bFlagSet(data, flag)
{
  return ((data & flag)==flag);
}

function bModeAllowed(sCode)
{
  if (bFlagSet(sCode, FL_OnlyOLM) && !bIsOnlineManual())
  {
   	return false;
  }
  else if (bFlagSet(sCode, FL_OnlyCC) && bIsOnlineManual())
  {
    return false;
  }
  else
  {
    return true;
  }
}


function RunLink(AppFile, Cmds, Shortcut, Search, Show, InstallFile, AppType, LocalFile)
//Launch the passed application using the passed parameters
{

  var Success = 0;
  var BaseShortcut = 'LJ Technical Systems\\';
  var sLastRunLine = '';
  var sPathToRun = '';
  
  //if IE4 or greater
  if (IsIE4orGreater())
  {	
    //If the application type has not been defined, then use the default one.
    if ((AppType==null) || (AppType==''))
    {
      AppType = sLncTxt_DefaultAppType;
    }

    //Get the object used for running the application
    var objLaunch = document.all['RunApp'];
    
    //Check that the Launch object exists
    if(objLaunch)
    {
      if(objLaunch.object != null)
      {
        //Setup the shortcut to use the LJ Technical Systems folder
        if(Shortcut != '')
        {
          Shortcut = BaseShortcut + Shortcut;
        }
	    
        var sSeq = Search.split(","); 
        for (var s = 0; s < sSeq.length; s++)
        { 
   	      var sCode = sSeq[s];
  
  	      
          Success = false;
   	      if (bModeAllowed(sCode))
   	      {
  
    		// Only allow the application to run in ClassCampus mode if the 
    		// Module ID Cookie has been set.  Added 05/03/2007 DLP.

    		if ((!bIsOnlineManual()) && (bFlagSet(sCode, FL_RunAT)) && (!bHasModID()))
    		{
      		  window.alert(sLncTxt_NoLicense);

      		  // Do not attempt to run alternatives.
      		  Success=true;  
    		}
 	        
 	        // If a source directory has been specified, then attempt to
	        // run the content from that location.
	        else if ((LocalFile!='') && bFlagSet(sCode, FL_RunLocal))
	        {
              if (bFlagSet(sCode, FL_BuildPath))
              {
                LocalFile = BuildFullPath(LocalFile)
              }
             
              // Strip off any "file:" reference before attempting to run the presentation.
              // Modified to support UNC format paths.
              // Change made 15/03/3007 DLP.
              if (LocalFile.toLowerCase().indexOf('file:')>=0) 
              {
                if (LocalFile.toLowerCase().lastIndexOf(':')>LocalFile.toLowerCase().indexOf(':'))
                {
                  sPathToRun = convertPathToWin(LocalFile.substr(8));
                }
                else
                {
                  sPathToRun = "\\\\"+ convertPathToWin(LocalFile.substr(7));
                }
			  }
			  else
			  {
                sPathToRun = convertPathToWin(LocalFile);
			  }   
          
              //Attempt to run the application relative to the ljcai/apps directory.
          	  var iCode = ""+(eval(0+(sCode) & 127));
      		  if ((!bIsOnlineManual()) && (bFlagSet(sCode, FL_RunAT)) && (bHasModID()))
      		  {
        		Success = objLaunch.Run(sPathToRun, Cmds, '', iCode, Show, true);
                        sLastRunLine = "'" + sPathToRun + "', '" + Cmds + "', '', '" + iCode + "', '" + Show +"', true";
      		  }
     		  else
      		  {
        		Success = objLaunch.Run(sPathToRun, Cmds, '', iCode, Show);
                        sLastRunLine = "'" + sPathToRun + "', '" + Cmds + "', '', '" + iCode + "', '" + Show +"'";
      		  }
            }
            else
            {
          	  var iCode = ""+(eval(0+(sCode) & 127));
      		  if ((!bIsOnlineManual()) && (bFlagSet(sCode, FL_RunAT)) && (bHasModID()))
      		  {
        		Success = objLaunch.Run(AppFile, Cmds, Shortcut, iCode, Show, true);
                        sLastRunLine = "'"+ AppFile + "', '" + Cmds + "', '" + Shortcut+ "' , '" + iCode + "', '" + Show + "', true";
      		  }
      		  else
      		  {
        		Success = objLaunch.Run(AppFile, Cmds, Shortcut, iCode, Show);
                        sLastRunLine = "'"+ AppFile + "', '" + Cmds + "', '" + Shortcut+ "' , '" + iCode + "', '" + Show + "'";
      		  }
            }
          }

          //If the application can run, then stop the sequence.
          if (Success)
          {
            break;
          }
         }
        
        // If the application cannot run, 
        // then inform the user that is will need to be re-installed.
        if (!Success)
        {
          // If the install file exists, then ask the user 
          // if he/she wishes to use it.
          if ((InstallFile!=null) && (InstallFile!=''))
          {
            if (confirm(sLncTxt_ErrorCannotRun+' '+AppType+'\n\n'+sLncTxt_ErrorInstallAppNow+' '+AppType))
            {
              debugMessage("About to run '"+BuildDownloadLink(InstallFile)+"'");
              window.location.href=(BuildDownloadLink(InstallFile));
            }
          }
          else if (!bFlagSet(sCode, FL_NoMessage))
          {
            alert(sLncTxt_ErrorCannotRun+' '+AppType+'\n\n'+sLncTxt_ErrorCheckInstall);
          }
          Success  = -1;
        }
        else
        {
          if (sLastRunLine!='')
          {
            debugMessage("Running "+sLastRunLine);
            //window.alert("Running "+sLastRunLine);
          }
        }
      }
    }
  }  

  //Display an error if unable to launch the application
  if (Success == 0)
    DisplayLaunchError(Shortcut, AppType);
}

function bHasModID()
// Check a module ID has been set.
// Added 09/03/2007 DLP.
{
  try
  {
    return (unescape(GetCookieStr('LJModID='))!='');
  }
  catch(e)
  {
    return false;
  }
}

function AddSRSLessonLink(ModuleID, ChapterNumber, SRSLessonCaption)
//Add an appropriate Link to the page to enable a SRS lesson to be started
{

  //if able to use the launch control
  if (CanLaunch())
    document.write('<a href="javascript:RunSRSLesson(' + ModuleID + ',' + ChapterNumber + ')">' + SRSLessonCaption + '<\/a>');

}


function RunSRSLesson(ModuleID, ChapterNumber, InstallFile)
//Attempt to start the SRS lesson with the passed lesson IDs
{
  var Success = 0;

  //if IE4 or greater
  if (IsIE4orGreater())
  {	
    //Get the object used for running the application
    var objLaunch = document.all['RunApp'];

    //Check that the Launch object exists
    if(objLaunch)
    {
      if(objLaunch.object != null)
      {
        //Attempt to launch the SRS lesson
        Success = objLaunch.LaunchSRSLesson(ModuleID, ChapterNumber);
      }
    }
  } 

  //Display an error if the SRS lesson can't be started
  if (Success == 0)
    alert(sLncTxt_ErrorNoSRS);
}


function DisplayLaunchError(Shortcut, AppType)
//Display an error to indicate that the application could not be launched
{

  //if a shortcut exists
  if (Shortcut != '')
    alert(sLncTxt_ErrorCannotRun+' '+AppType+'\n\n'+sLncTxt_ErrorStartMenu+' ' + unescape(Shortcut));

  //no shortcut display a message to indicate the application could not be run
  else
    alert(sLncTxt_ErrorCannotRun+' '+AppType+'\n\n'+sLncTxt_ErrorCheckInstall);
		
}


function CanLaunch()
//Return whether the HTML launch object can be used
{
  var LaunchControlAvailable = false;

  //if IE4 or greater
  if(IsIE4orGreater())
  {
    var objTestLaunch = document.all['RunApp'];

    //Check that the object exists
    if(objTestLaunch)
      if(objTestLaunch.object != null)
        LaunchControlAvailable = true; 
  }

  //return whether the launch control is available
  return LaunchControlAvailable;
}

function IsIE4orGreater()
//Return whether browser is IE4 or greater
{
  var BrowserIsIE4 = false;

  //Check to see if IE 4 or greater
  if (navigator.appName == 'Microsoft Internet Explorer')
    if(parseFloat(navigator.appVersion) >= 4)
      BrowserIsIE4 = true;

  return BrowserIsIE4;
}

function window_error()
//ignore all errors
{ 
  return true; 
}

function debugMessage(message)
// This function will display a debug
// message using the method coded in LJDebug.js
// (if defined).
// Added 29/01/2007 DLP.
{
  try
  {
    showDebugMessage(message)
  }
  catch(e)
  {
  }
}

