<!--
/************************************************************************

FILE: kdx_install.js
DESCRIPTION: Functions and variables used KDM 4.02 during installation
and upgrade.

Copyright (c) 2004-2005 Kontiki Inc.

*************************************************************************/

//////////////////////////////////////////////////////////////////////////
//
// Static globals.
//
//////////////////////////////////////////////////////////////////////////

// Installation preferences.
var kPref_Installed            = "kdx.installed";
var kPref_CacheVersion         = "kdx.cacheVersion";

// Parameters from configuration XML file.
var kConfig_TrayIcon0          = "trayicon0";
var kConfig_TrayIcon1          = "trayicon1";
var kConfig_TrayIcon2          = "trayicon2";
var kConfig_FrameIcon          = "frameicon";
var kConfig_DesktopIcon        = "desktopicon";
var kConfig_TrayMenuPage       = "traypage";
var kConfig_CollectionPage     = "collpage";
var kConfig_CollectionStyle    = "collstyle";
var kConfig_TemplatePage       = "templatepage"; // for load
var kConfig_DefTemplate        = "deftemplate"; // for resurrection
var kConfig_TemplateStyle      = "templatestyle";
var kConfig_EventTemplate      = "eventtemplate";
var kConfig_EventTemplateStyle = "eventstyle";
var kConfig_UninstallIcon      = "unicon";
var kConfig_ErrorLog           = "errorlog";

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getProfileId()
//
// DESCRIPTION: Returns Profile parsed out from the Auth Token.
//
//////////////////////////////////////////////////////////////////////////
function getProfileId()
{
    var p = gAuthToken.split('|')[0];
    return p.replace(/^\W+/,'').replace(/\W+$/,'');
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDXInstallApi(i_netmanDomain, i_netmanMoid, i_forceUpgrade)
//
// DESCRIPTION: Instantiates the Install API object.
//
//////////////////////////////////////////////////////////////////////////
function KDXInstallApi(i_netmanDomain, i_netmanMoid, i_forceUpgrade)
{
    this.mProfileId = getProfileId();
    this.mNetmanDomain = i_netmanDomain;
    this.mNetmanMoid = i_netmanMoid;
    this.mXMLFile = "./config.xml";
    this.mXMLData = null;
    this.mCachedFileVector = null;
    this.mInstall = null;
    this.mRootDir = window.location.href.substr(0, window.location.href.lastIndexOf('/') + 1);

    this.mInstallObj  = null;

    // Installation info.
    this.mIsInstalled = false;
    this.mIsNewUser = false;
    this.mIsUpgrade = false;
    this.mIsOldClient = false; // If this is a KDX 2.2 must use old APIs.
    
    ///////////////////////////////////////
    // Public methods.
    ///////////////////////////////////////
    this.install = KDX_install;    
    
    this.getConfigParam  = KDX_getConfigParam;
    this.getInstallState = KDX_getInstallState;
    this.getInstallObj   = function () { return this.mInstallObj; }
    this.isInstalled = KDX_isInstalled;
    this.isUpgrade = KDX_isUpgrade;
    this.isNewUser = KDX_isNewUser;
    this.hasInstallPermissions = function () 
    {
        try
        {
            if (this.mInstallObj != null)
                return this.mInstallObj.hasInstallPermissions(); 
        }
        catch (e) {}
        return true;
    }
  
    ///////////////////////////////////////
    // Private methods.
    ///////////////////////////////////////
    this.readXML    = KDX_readXML;
    
    // Initialization.
    this.getInstallState();
    
    // Force upgrade.
    if (i_forceUpgrade)
        this.mIsUpgrade = true;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDX_getConfigParam(name)
//
// DESCRIPTION: Returns value for given "name" defined in config XML file.
//
//////////////////////////////////////////////////////////////////////////
function KDX_getConfigParam(name)
{
    return this.mXMLData[name];
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDX_install()
//
// DESCRIPTION: Does the installation or upgrade.
//
//////////////////////////////////////////////////////////////////////////
function KDX_install()
{
    // Do not install if user does not have permissions.
    if (this.hasInstallPermissions() == false)
        return false;
        
    this.readXML();

    this.mInstall = new ActiveXObject( "KDX.SecureInstall" );
    this.mInstall.authorize(gAuthToken, gAuthSignature);
    
    // New install only:
    if (!this.isInstalled() || this.isNewUser())
    {
        if(alertsMode) alert("Basic Install stuff...");
        
        //////////////////////////////////////////////////////////////////////////
        //
        // Install NetManager connection.
        //
        //////////////////////////////////////////////////////////////////////////
        try
        {
            this.mInstall.installNetman(this.mNetmanDomain, this.mNetmanMoid);
            if(alertsMode)
                alert("Installed Netman:\n" +
                this.mNetmanDomain + "\n" +
                this.mNetmanMoid);
        }
        catch(i_e)
        {
            if(alertsMode) alert("installNetman failed!");
            return false;
        }    
        
        
        //////////////////////////////////////////////////////////////////////////
        //
        // Install Error Log.
        //
        //////////////////////////////////////////////////////////////////////////
        try
        {
            this.mInstall.installErrorLog(this.mRootDir + this.mXMLData[kConfig_ErrorLog]);
        }
        catch(i_e)
        {
            if(alertsMode) alert("installErrorLog failed!");
        }    
        
        //////////////////////////////////////////////////////////////////////////
        //
        // Install Tray Icon.
        //
        //////////////////////////////////////////////////////////////////////////
        try
        {
            this.mInstall.installTrayIcons( this.mXMLData[kConfig_TrayIcon0],
                                            this.mXMLData[kConfig_TrayIcon1],
                                            this.mXMLData[kConfig_TrayIcon2],
                                            gShortTitle);
        }
        catch(i_e)
        {
            if(alertsMode) alert("installTrayIcon failed!");
        }    
        
        //////////////////////////////////////////////////////////////////////////
        //
        // Install Tray Icon support.
        //
        //////////////////////////////////////////////////////////////////////////
        try
        {
            this.mInstall.installTrayIconEvent(    "201",
                            this.mXMLData[kConfig_CollectionPage], 
                            this.mXMLData[kConfig_CollectionStyle] );
        
            this.mInstall.installTrayIconEvent( "204", 
                            this.mXMLData[kConfig_TrayMenuPage], 
                            "class=menu,position=16" );
                                            
            this.mInstall.installTrayIconEvent( "206", 
                            this.mXMLData[kConfig_TrayMenuPage],
                            "class=menu,visible=0" );                                        
        }
        catch(i_e)
        {
            if(alertsMode) alert("installTrayIconEvent failed!");
        }    
        
        //////////////////////////////////////////////////////////////////////////
        //
        // Install Frame Icon.
        //
        //////////////////////////////////////////////////////////////////////////
        try
        {
            this.mInstall.installFrameIcon(this.mXMLData[kConfig_FrameIcon]);
        }
        catch(i_e)
        {
            if(alertsMode) alert("installFrameIcon failed!");
        }    
    
    
        //////////////////////////////////////////////////////////////////////////
        //
        // Install Default Template.
        //
        //////////////////////////////////////////////////////////////////////////
        try
        {
            this.mInstall.installDefaultTemplate(   this.mXMLData[kConfig_DefTemplate],
                                                    this.mXMLData[kConfig_TemplateStyle]);
        }
        catch(i_e)
        {
            if(alertsMode) alert("installDefaultTemplate failed!");
        }      


        //////////////////////////////////////////////////////////////////////////
        //
        // Install Event Template.
        //
        //////////////////////////////////////////////////////////////////////////
        try
        {
            this.mInstall.installEventTemplate(   this.mXMLData[kConfig_EventTemplate],
                                                  this.mXMLData[kConfig_EventTemplateStyle]);
        }
        catch(i_e)
        {
            if(alertsMode) alert("installDefaultTemplate failed!");
        }      
        
        
        //////////////////////////////////////////////////////////////////////////
        //
        // Install Desktop Shortcut.
        //
        //////////////////////////////////////////////////////////////////////////
        try
        {
            this.mInstall.installDesktopShortcut(   gShortTitle,
                                                    this.mXMLData[kConfig_CollectionPage],
                                                    this.mXMLData[kConfig_CollectionStyle],
                                                    this.mXMLData[kConfig_DesktopIcon]);
        }
        catch( e )
        {
            if(alertsMode) alert("installDesktopShortcut failed!");
        }  
    
       
        //////////////////////////////////////////////////////////////////////////
        //
        // Install Uninstall Icon. Note: The icon MUST be cached for this to work.
        //
        //////////////////////////////////////////////////////////////////////////
        try
        {
            this.mInstall.installUninstallIcon( gShortTitle,
                                                this.mXMLData[kConfig_UninstallIcon]);
                                                    
        }
        catch( e )
        {
            if(alertsMode) alert("installUninstallIcon failed!");
        }  
 
    } // End stuff for new installs.
    
 
    //////////////////////////////////////////////////////////////////////////
    //
    // Install Cached Files. To update the local file cache, simply
    // increment the gCacheVersion in the init JS file. However, if this is a
    // CAB file upgrade, we assume that some HTML files changed and force
    // an upgdate to the local file cache.
    //
    //////////////////////////////////////////////////////////////////////////
    var cacheVersion;
    try
    {
        cacheVersion = this.mInstall.pref(kPref_CacheVersion);
    }
    catch(i_e) 
    {
        cacheVersion = 0;  // If pref does not exist, force an update.
    }
    
    if (cacheVersion < gCacheVersion || this.isUpgrade())
    {
        if(alertsMode) alert("File cache stuff...");
        try
        {
            // Build cache string.
            var cacheFileString = "";
            for (i=0; i<this.mCachedFileVector.length-1; i++)
                cacheFileString += this.mCachedFileVector[i] + ",";
            cacheFileString += this.mCachedFileVector[this.mCachedFileVector.length - 1];


            if(alertsMode) alert(cacheFileString);                
            this.mInstall.installCachedFiles( this.mRootDir, cacheFileString);
            this.mInstall.pref(kPref_CacheVersion) = gCacheVersion;
        }
        catch(i_e)
        {
            if(alertsMode) alert("During install or upgrade, installCachedFiles failed.");
        }
    }
    
    // Set the new user pref so we know that this user has been initialized.
    this.mInstall.pref(kPref_Installed) = 1;
  
    return true;
} // End KDX_Install.


//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDX_getInstallState()
//
// DESCRIPTION: Sets state variables that capture if user has an older
// KDX 2.x client installed, if user needs upgrade, if user is a new user,
// and if KDM 4.02 client is already installed.
//
//////////////////////////////////////////////////////////////////////////
function KDX_getInstallState()
{
    try
    {
        var tempObj = new ActiveXObject("KDX.Install");
        if(alertsMode) alert("Pre-4.0 Client detected.");  
        alert(gUpgradeMessage);
        tempObj.host().closeKHost(true);  // Shutdown khost and wait for it to finish.
        if(alertsMode) alert("Pre-4.0 Client shutdown complete.");
        this.mIsOldClient = true;
        this.mIsUpgrade = false;
        this.mIsNewUser = true;
        this.mIsInstalled = false;
    }
    catch(e)
    {
        if(alertsMode) alert("Pre-4.0 Client NOT detected.");
    }

    // If this is an old KDX 2.x client, do not even do these tests
    if (this.mIsOldClient == false)
    {
        try
        {
            this.mInstallObj = new ActiveXObject("KDX.SecureInstall");
            this.mInstallObj.authorize(gAuthToken, gAuthSignature);
            
            if (alertsMode && gUsePrevCab) alert("Using previous cab file for isNewerCab()");
            if (gUsePrevCab) gCabFile = gPrevCabFile;
            // If installObj is found, user is on a supported platform,
            // therefore you *could* read config information right now.
            if( this.mInstallObj.isNewerCab( gCabFile ) )
            {
                if (alertsMode) alert("isNewerCab: " + gCabFile );
                this.mIsUpgrade = true;
            }
            
            // If installObj is found, we must already be installed.
            this.mIsInstalled = true;
            
            // This will throw an exception if the pref is not present.
            var temp = this.mInstallObj.pref(kPref_Installed);
        }
        
        catch(e)
        {
            this.mIsNewUser = true;
        }
    }
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDX_isInstalled()
//
// DESCRIPTION: Returns true if KDM 4.02 client is already installed.
//
//////////////////////////////////////////////////////////////////////////

function KDX_isInstalled()
{
    return this.mIsInstalled;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDX_isUpgrade()
//
// DESCRIPTION: Returns true if KDX 2.2 or an older KDM 4.02 client is
// found to be installed.
//
//////////////////////////////////////////////////////////////////////////

function KDX_isUpgrade()
{
    return this.mIsUpgrade;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDX_isNewUser()
//
// DESCRIPTION: Returns true if user is a new user.
//
//////////////////////////////////////////////////////////////////////////

function KDX_isNewUser()
{
    return this.mIsNewUser;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDX_readXML()
//
// DESCRIPTION: Parses config XML file for installation values.
//
//////////////////////////////////////////////////////////////////////////
function KDX_readXML()
{
    var xmlDoc = new ActiveXObject("Msxml.DOMDocument");
    xmlDoc.async = false;
      
    var bOK = xmlDoc.load( this.mXMLFile );
    if( bOK )
    {
        var cacheCounter = 0;
        this.mXMLData = new Object();
        this.mCachedFileVector = new Array();
        var root = xmlDoc.documentElement;
        if( root != null )
        {
            var nodes = root.childNodes;
            if( nodes != null )
            {
                for( lNode=0; lNode<nodes.length; lNode++ )
                {
                    var key = nodes.item(lNode).nodeName;
                    var val = nodes.item(lNode).text;
                    // Store files for cache separately.
                    if (key == "cachedFiles")
                    {
                        var cacheNodes = nodes.item(lNode).childNodes;
                        if( cacheNodes != null )
                        {
                            for( i=0; i<cacheNodes.length; i++ )
                            {
                                if (cacheNodes.item(i).nodeName == "file")
                                {
                                    this.mCachedFileVector[cacheCounter++] = cacheNodes.item(i).text;
                                    //alert(this.mCachedFileVector[i] + " : " + cacheNodes.item(i).text);
                                }
                            }
                        }
                    }
                    else
                        this.mXMLData[ key ] = val;
                } // for
            }
            else
                alert( "no nodes" );
        }
        else
            alert( "no root" );
    } // Loaded.
    xmlDoc = null;
}

//-->
