// Licensed Materials - Property of IBM
// 5648-F10 (C) Copyright International Business Machines Corp. 2005, 2006
// All Rights Reserved
// US Government Users Restricted Rights - Use, duplication or disclosure
// restricted by GSA ADP Schedule Contract with IBM Corp.

// change the mouse cursor to look busy or normal
// isBusy: boolean
// doc: document reference
// returns: undefined
/*
function busyCursor(isBusy,doc) {
  try {
    try {
        if (typeof doc.body != "undefined" && typeof doc.body.style != "undefined" && typeof doc.body.style.cursor != "undefined") {
            if (isBusy)
                doc.body.style.cursor='wait';
            else
                doc.body.style.cursor='default';
        }
        else if (typeof doc.all != "undefined" && typeof doc.all.length != "undefined") {
            var i;
            for (i=0; i < doc.all.length; i++) {
                if (isBusy)
                    doc.all[i].style.cursor = 'wait';
                else
                    doc.all[i].style.cursor = 'default';
            }
        }
    } catch(e) {}
  } catch(e) { top.logException(e,arguments); }
}
*/

// determine if the file exists
// securityFcn: function = new Function('return window')
// fileName: string - full native file name
// returns: boolean
function secureFileExists(securityFcn,fileName)
{
    try {
        if ( top.isSecure(securityFcn) )
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
        file.initWithPath(fileName);
        if ( file.exists() )
            return true;
    } catch(e)
    {
        top.logException(e,arguments);
    }
    return false;
}

// determine if the directory exists
// securityFcn: function = new Function('return window')
// directory: string - full native directory name
// returns: boolean
function secureDirectoryExists(securityFcn, directory)
{
    var retVal = false;
    try
    {
        if ( top.isSecure(securityFcn) )
        {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");       
            var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
            file.initWithPath(directory);
     
            retVal = secureFileExists(securityFcn, directory) && file.isDirectory(); 
        }
    }
    catch (e)
    {     
        top.logException(e,arguments);
    }

    return retVal;
}

// gets the value of an environment variable
// securityFcn: function = new Function('return window')
// anyvar: string - name of variable
// returns: string - value of variable
//          undefined - variable is not defined
function secureGetEnv(securityFcn,anyvar)
{
    try {
        var v = null;
        try {
            if ( top.isSecure(securityFcn) )
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            if ( typeof Components.classes["@mozilla.org/process/environment;1"] != "undefined" )
            {
                var env = Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment); 
                v = env.get(anyvar);
            }
        } catch(e)
        {
        }
        try {
            if ( v == null )
            {
                var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
                v = process.getEnvironment(anyvar);
            }
        } catch(e)
        {
        }
        return v;
    } catch(e)
    {
        top.logException(e,arguments);
    }
    return top.UNDEFINED;
}

// sets the value of an environment variable
// securityFcn: function = new Function('return window')
// anyvar: string - name of variable
// value: string - new value of variable
// returns: boolean - success status
function secureSetEnv(securityFcn,anyvar,value)
{
    try {
        var v;
        if ( top.isSecure(securityFcn) )
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var env = Components.classes["@mozilla.org/process/environment;1"].getService(Components.interfaces.nsIEnvironment); 
        env.set(anyvar,value);
        return secureGetEnv(securityFcn,anyvar) == value;
    } catch(e)
    {
    }
    return false;
}

var elementArray = new Array();

// reenables a document element if the associated process has completed
// element: document element
// returns: undefined
function _enableElement()
{
    try {
        top.enableElement(elementArray.shift(), true);
    } catch(e)
    {
        top.logException(e,arguments);
    }
}

// executes an arbitrary command
// securityFcn: function = new Function('return window')
// topDir: string - CD mount point
// args: [strings] - command and parameters
// waitBoolean: boolean - foreground or background
// isHidden: boolean - visible window or silent
// element: document element - element to disable while running
// returns: int - return code
function secureRunProgram(securityFcn,topDir,args,waitBoolean,isHidden,element)
{
    try {
        if ( typeof waitBoolean == "undefined" || waitBoolean == null ) waitBoolean = false; // long running
        if ( typeof isHidden == "undefined" || isHidden == null ) isHidden = false; // since some things like notepad have to run in visible mode
        if ( typeof element != "undefined" && element != null ) top.enableElement(element,false);
        var processArgs = new Array();
        if ( waitBoolean == true )
            for ( var i=0; i < top.commandForegroundPrefix.length; i++ ) processArgs.push(top.commandForegroundPrefix[i]);
        else
            for ( var i=0; i < top.commandBackgroundPrefix.length; i++ ) processArgs.push(top.commandBackgroundPrefix[i]);
        args[0] = top.getFullFileName(topDir,args[0]);
        var commandStr = null;
        if ( waitBoolean == true )
        {
            if ( top.commandForegroundWrapperPrefix != null )
                commandStr = top.commandForegroundWrapperPrefix;
        }
        else
        {
            if ( top.commandBackgroundWrapperPrefix != null )
                commandStr = top.commandBackgroundWrapperPrefix;
        }
        if ( commandStr != null )
        {
            for ( var i=0; i < args.length; i++ )
            {
                var arg = args[i];
                var re = new RegExp(/^[!@+=%:\\\/\-a-zA-Z0-9_]+$/);
                if ( !re.test(arg) )
                {
                    if ( arg.indexOf('"') >= 0 )
                        arg = "'" + arg + "'";
                    else
                        arg = '"' + arg + '"';
                }
                commandStr += ' ' + arg;
            }
            processArgs.push(commandStr);
        }
        else
        {
            for ( var i=0; i < args.length; i++ )
                processArgs.push(args[i]);
        }
        if ( top.isSecure(securityFcn) )
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var FileFactory = new Components.Constructor("@mozilla.org/file/local;1","nsILocalFile","initWithPath");
        var program = new FileFactory(processArgs[0]);
        var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);

        //Since we prefix the command with /bin/bash, we'll almost never get an exception if the program the user
        //wants to run doesn't exist.  So, we have this check just in case.
        if (!secureFileExists(securityFcn, args[0])) {
          top.logMessage("LPV22041W", args[0]);
        }

        process.init(program);
        processArgs.shift();
        var rc = process.run(waitBoolean, processArgs, processArgs.length);
        if ( rc == 0 && waitBoolean == true )
            rc = process.exitValue;
        if ( typeof element != "undefined" && element != null )
        {
            if ( rc != 0 || waitBoolean == true )
                top.enableElement(element,true);
            else
            {
                elementArray.push(element);
                setTimeout('_enableElement()',5000);
            }
        }
        return rc;
    } catch(e)
    {
        try { if ( typeof element != "undefined" && element != null ) top.enableElement(element,true);} catch(e2)
        {
        };
        top.logException(e,arguments);
    }
    return top.UNDEFINED;
}

// read an external file
// securityFcn: function = new Function('return window')
// fileName: string - full native file name
// returns: [line strings]
function secureReadTextFile(securityFcn,fileName)
{
    try {
        var fileLines = new Array();
        if ( top.isSecure(securityFcn) )
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var nsILocalFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
        nsILocalFile.initWithPath( fileName );
        if ( nsILocalFile.exists() == false )
        {
            top.logMessage("LPV20022S", fileName);
        }
        var nsIFileInputStream = Components.classes["@mozilla.org/network/file-input-stream;1"]
        .createInstance( Components.interfaces.nsIFileInputStream);
        nsIFileInputStream.init( nsILocalFile, 0x01, 00004, null);
        var nsIBinaryInputStream = Components.classes["@mozilla.org/binaryinputstream;1"]
        .createInstance( Components.interfaces.nsIBinaryInputStream);
        nsIBinaryInputStream.setInputStream(nsIFileInputStream);
        var fileContents = top.UTF8toString(nsIBinaryInputStream.readBytes(nsIFileInputStream.available()));

        nsIFileInputStream.close();
        nsIBinaryInputStream.close();

        //Removes BOM characters from the beginning of the file
        if (fileContents.charCodeAt(0) == '65279' || fileContents.charCodeAt(0) == '65534')
        {
            fileContents = fileContents.substring(1,fileContents.length);   
        }

        fileLines = fileContents.split(/\r*\n/);
        if ( fileLines.length > 0 )
            if ( fileLines[fileLines.length-1].length == 0 )
                fileLines.pop();
        return fileLines;
    } catch(e)
    {
        top.logException(e,arguments);
    }
    return top.UNDEFINED;
}

// get a list of child directories
// securityFcn: function = new Function('return window')
// dir: string - parent directory
// returns: [directory name strings]
function secureGetDirectories(securityFcn,dir)
{
    try {
        if ( top.isSecure(securityFcn) )
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var nsILocalFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
        nsILocalFile.initWithPath( top.getNativeFileName(dir) );
        if ( nsILocalFile.exists() == true )
        {
            var entries = nsILocalFile.directoryEntries;
            var returnArray = new Array();
            while ( entries.hasMoreElements() )
            {
                var entry = entries.getNext();
                entry.QueryInterface(Components.interfaces.nsIFile);
                if ( entry.leafName != "." && entry.leafName != ".." )
                {
                    if ( entry.isDirectory() )
                    {
                        returnArray.push(entry.leafName);
                    }
                }
            }
            return returnArray;
        }
    } catch(e)
    {      
        top.logException(e,arguments);
    }
    return top.UNDEFINED;
}

// get a list of child files
// securityFcn: function = new Function('return window')
// dir: string - parent directory
// returns: [file name strings]
function secureGetFiles(securityFcn,dir)
{
    try {
        if ( top.isSecure(securityFcn) )
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var nsILocalFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
        nsILocalFile.initWithPath( dir );
        if ( nsILocalFile.exists() == true )
        {
            var entries = nsILocalFile.directoryEntries;
            var returnArray = new Array();
            while ( entries.hasMoreElements() )
            {
                var entry = entries.getNext();
                entry.QueryInterface(Components.interfaces.nsIFile);
                if ( entry.isFile() )
                {
                    returnArray.push(entry.leafName);
                }
            }
            return returnArray;
        }
    } catch(e)
    {
        top.logException(e,arguments);
    }
    return top.UNDEFINED;
}

/*
function setBooleanPreference(s,v) {
  try {
    //netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
    //var prefs = Components.classes["@mozilla.org/preferences-service;1"].createInstance(Components.interfaces.nsIPrefBranch);
    if (prefs.getBoolPref(s) != v) {
    prefs.setBoolPref(s,v);
    }
  } catch(e) { top.logException(e,arguments); }
  return top.UNDEFINED;
}
*/

// exit launchpad
// securityFcn: function = new Function('return window')
// returns: undefined
function secureExit(securityFcn)
{
    try {
        if ( top.isSecure(securityFcn) )
            window.close();
    } catch(e)
    {
        top.logException(e,arguments);
    }
}

top.OPENMODE = 0;
top.SAVEMODE = 1;
// private function for log.html
function chooseFileName(mode,defaultName)
{
    try {
        netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var nsIFilePicker = Components.interfaces.nsIFilePicker;
        var filePicker = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
        if ( mode == top.SAVEMODE )
            filePicker.init(window, null, nsIFilePicker.modeSave);
        else
            filePicker.init(window, null, nsIFilePicker.modeOpen);
        filePicker.defaultExtension  = defaultName.substring(defaultName.indexOf('.')+1);
        filePicker.defaultString  = defaultName.substring(0,defaultName.indexOf('.'));
        filePicker.appendFilters(nsIFilePicker.filterText);
        if ( filePicker.show() != nsIFilePicker.returnCancel )
        {
            return filePicker.file;
        }
    } catch(e)
    {
        top.logException(e,arguments);
    }
    return null;
}

// private function for log.html
// write an external file
// securityFcn: function = new Function('return window')
// fileName: string - full native file name
// lines: array of text lines
// returns: true of written, null if no file given, and UNDEFINED if exception
function secureWriteTextFile(securityFcn,nsILocalFile,lines)
{
    try {
        if ( nsILocalFile == null ) return null;
        if ( top.isSecure(securityFcn) )
            netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        var nsIFileOutputStream = Components.classes["@mozilla.org/network/file-output-stream;1"]
        .createInstance( Components.interfaces.nsIFileOutputStream);
        nsIFileOutputStream.init( nsILocalFile, 0x40|0x20|0x08|0x02, 00004, null);
        for ( var i=0; i < lines.length; i++ )
        {
            var len = lines[i].length;
            var outlen = 0;
            while ( outlen < len )
                outlen += nsIFileOutputStream.write(lines[i].substring(outlen,len), len-outlen);
            if ( top.OSTYPE == "windows" )
            {            
                nsIFileOutputStream.write("\r", 1);
            }
            nsIFileOutputStream.write("\n", 1);
        }
        nsIFileOutputStream.flush();
        nsIFileOutputStream.close();
        return true;
    } catch(e)
    {
        top.logException(e,arguments);
    }
    return top.UNDEFINED;
}

netscape.security.PrivilegeManager.enablePrivilege('UniversalBrowserWrite');

if ( secureGetEnv(new Function('return window'), "LaunchPadToolbarEnable" ) !='true' )
{
    window.locationbar.visible = false;
    window.menubar.visible = false;
    window.personalbar.visible = false;
    window.scrollbars.visible = false;
    window.statusbar.visible = false;
    window.toolbar.visible = false;
}

/*
    var query = top.document.location.search;
    if (query.length > 1) {
        query = query.substring(1);
        var tokens = query.split(",");
        for (var q=0; q < tokens.length; q++) {
            var keyvalue = tokens[q].split("=");
            if (keyvalue[0].length > 0) {
                if (keyvalue[1].length > 0) {
            var envVarOverride = unescape(keyvalue[0]).toUpperCase();
            if (envVarOverride == "LOCALE")
            top.LOCALE = unescape(keyvalue[1]);
            if (envVarOverride == "CONTENTDIR")
            top.CONTENTDIR = unescape(keyvalue[1]);
            if (envVarOverride == "OSTYPE")
            top.OSTYPE = unescape(keyvalue[1]);
            if (envVarOverride == "OS")
            top.OS = unescape(keyvalue[1]);
        }
            }
        }
    }
*/

// Init log filter now that we have access to env vars
logInitFilter();

//The reason for modifying the locale we're passed is that we haven't yet 
//been able to map it using the locale mapping mechanism.  So we might
//receive "en_us" but it will eventually be resolved to "en"  For now, we just 
//assume that we don't need a regional dialect and just use the base language.
//If this assumption is in correct, the proper locale/global properites will be loaded
//in Mozilla/IExplore.html
if (typeof top.LOCALE == "undefined" || top.LOCALE == null)
    {    
      top.LOCALE = top.trim(secureGetEnv(new Function('return window'), "LaunchPadLocale" ));
      if (top.LOCALE.length > 2 && top.LOCALE.toLowerCase() != "pt_br" && top.LOCALE.toLowerCase() != "zh_tw") 
      {          
          top.LOCALE = top.LOCALE.substring(0,2);
      }
      if (top.LOCALE == "pt_br") 
      {
          top.LOCALE = "pt_BR";
      }
      if (top.LOCALE == "zh_tw") 
      {
          top.LOCALE = "zh_TW";
      }
    }
if (top.LOCALE == null) top.LOCALE = "en";

if ( typeof top.OSTYPE == "undefined" || top.OSTYPE == null ) top.OSTYPE = secureGetEnv(new Function('return window'), "LaunchPadOSType" );

if ( typeof top.OS == "undefined" || top.OS == null ) top.OS = secureGetEnv(new Function('return window'), "LaunchPadOS" );

top.ARCHITECTURE = secureGetEnv(new Function('return window'), "LaunchPadArch");

//Set the target OS/Arch variables    
top.TARGETOS = secureGetEnv(new Function('return window'), "LaunchPadTargetOS");
if (top.TARGETOS == "")
{
top.TARGETOS = top.OS;
}
top.TARGETOSTYPE = secureGetEnv(new Function('return window'), "LaunchPadTargetOSType");
if (top.TARGETOSTYPE == "") 
{
  top.TARGETOSTYPE = top.OSTYPE;
}
top.TARGETARCHITECTURE = secureGetEnv(new Function('return window'), "LaunchPadTargetArch");
if (top.TARGETARCHITECTURE == "") 
{
  top.TARGETARCHITECTURE = top.ARCHITECTURE;
}

if (navigator.userAgent.indexOf('Firefox') != -1)
{
  top.BROWSER = "Firefox";
}
else
{
  top.BROWSER = "Mozilla";
}

top.PATHSEPARATOR = top.getNativeFileSeparator();
top.STARTINGDIR = top.getStartingTopDir();
//    top.RELATIVEDIR = top.getStartingRelativeDir();

top.CONTENTDIR = secureGetEnv(new Function('return window'), "LaunchPadContentDirectory" );
top.SKINDIR = secureGetEnv(new Function('return window'), "LaunchPadSkinDirectory" );
top.STARTPAGE = secureGetEnv(new Function('return window'), "LaunchPadStartPage" );
top.COMPATIBILITYVERSION = secureGetEnv(new Function('return window'), "LaunchPadCompatibilityVersion" );
top.VIEWERPATH = secureGetEnv(new Function('return window'), "LaunchPadBrowser" );

top.commandBackgroundPrefix = [];
top.commandForegroundPrefix = []; 
// Wrappering is when the command needs to be sent as a single string instead of parsed arguments
// null means that it should be sent as parsed arguments
top.commandBackgroundWrapperPrefix = null;
top.commandForegroundWrapperPrefix = null;
if ( top.OSTYPE == "windows" )
{
    try {
        top.LaunchPadUSERPROFILE = secureGetEnv(new Function('return window'), "LaunchPadUSERPROFILE" );
        var profileOK;
        if ( typeof top.LaunchPadUSERPROFILE == "string" && top.LaunchPadUSERPROFILE != '' )
            profileOK = secureSetEnv(new Function('return window'), "USERPROFILE", top.LaunchPadUSERPROFILE);
        else
            profileOK = true;
        if ( !profileOK || !secureSetEnv(new Function('return window'), "MOZ_NO_REMOTE", '') )
        {
            top.COMSPEC = secureGetEnv(new Function('return window'), "ComSpec" );
            if ( typeof top.COMSPEC == "string" && top.COMSPEC != '' )
            {
                if ( !profileOK )
                    top.commandForegroundPrefix = [top.COMSPEC,"/c","set USERPROFILE="+top.LaunchPadUSERPROFILE,"&&","set MOZ_NO_REMOTE=&&"];
                else
                {
                    top.commandForegroundPrefix = [top.COMSPEC,"/c","set MOZ_NO_REMOTE=&&"];
                }
                top.commandBackgroundPrefix = top.commandForegroundPrefix;
            }
        }
    } 
    catch(e)
    {
    }    
    if ( typeof top.CURRENTPROFILE == "string" )
        secureRunProgram(new Function('return window'),top.STARTINGDIR,[top.RELATIVEDIR+'ScriptLauncher.exe',top.RELATIVEDIR+'MozillaPatch.bat',top.CURRENTPROFILE],false,true);
}
else if ( top.OSTYPE == "unix" )
{
    top.LaunchPadHOME = secureGetEnv(new Function('return window'), "LaunchPadHOME" );
    secureSetEnv(new Function('return window'), "LOGNAME", secureGetEnv(new Function('return window'), "LaunchPadLogName" ));

    if ( typeof top.LaunchPadHOME == "string" ) try
    {
        top.SHELL = secureGetEnv(new Function('return window'), "SHELL" );
        if ( typeof top.SHELL != "string" ) top.SHELL = "/bin/sh";
        top.commandForegroundPrefix = [top.SHELL,"-c"];
        top.commandBackgroundPrefix = top.commandForegroundPrefix;
        if ( secureSetEnv(new Function('return window'), "HOME", top.LaunchPadHOME) )
            top.commandForegroundWrapperPrefix = "";
        else
            top.commandForegroundWrapperPrefix = "HOME="+top.LaunchPadHOME;
        top.commandBackgroundWrapperPrefix = top.commandForegroundWrapperPrefix;
    }
    catch(e)
    {
    }
}

