﻿// Windows Live Messenger Content Themepack Downloader
// Copyright (c) VML, Inc. All rights reserved.

//  Constants
var CONTAINER_ID = 'MessengerContentInstallerContainer';

//  Global Variables
var DivContainerHtml  = '';
var MciHtmlAdded      = false;
var MsgrInstallResult = false;

//  Messenger Content Installer Object
DivContainerHtml += '<OBJECT id="MessengerContentInstaller" height="0" width="0" ';
DivContainerHtml += 'classid="clsid:F06608C7-1874-4EEA-B3B2-DF99EBB144B8" ';
DivContainerHtml += 'codeType="application/x-oleobject" VIEWASTEXT>';
DivContainerHtml += '</OBJECT>';

//  Messenger Content Installer Event Handler
DivContainerHtml += '<script for="MessengerContentInstaller" ';
DivContainerHtml += 'event="OnContentInstalled(lhrResult)" language="jscript">';
DivContainerHtml += 'OnContentInstalled(lhrResult);';
DivContainerHtml += '</script>';

//  Error Response
//  Note:  Move these to the dynamic page for rendering from localized content.
//var errRequestFailed = "The content installation failed.  Please try again.";
//var errUserCanceled  = "";
//var errUnknown       = "We could not find the requested themepack or there was a problem with the download.  Please try again later.";
//var errLogin         = "Please sign into Windows Live Messenger and try again";
//var errContent       = "We could not find the requested themepack.  Please try again later.";
//var errBusy          = "Please wait until the first download process is completed, then try again.";
//var errNotIE         = "Messenger theme download requires Microsoft Internet Explorer.";
//var strSuccess       = "The theme has been installed and is ready to use in Messenger.";

function AddMciHtml( elementId )
{
    /// <summary>
    /// Adds the Messenger Content Installer HTML snippet to the current document.
    /// </summary>
    /// <param name="elementId">
    /// Name of the element to reference by.  If does not exist, then a <div>
    /// element with the same ID is appended to the end the <body> node.
    /// </param>
    /// <returns>
    /// Element object for the Messenger Content Installer container.
    /// </returns>
    
    //  Get document element reference
    var Element = document.getElementById(elementId);
    
    //  If does not exist, then create one and add it
    if (Element == null)
    {
        var NewElement = window.document.createElement('div');
        NewElement.setAttribute('id', elementId);
        window.document.body.appendChild(NewElement);
        Element = document.getElementById(elementId);
    }
    
    //  Set container HTML snippet and mark as added.
    Element.innerHTML = DivContainerHtml;
    MciHtmlAdded = true;
    
    //  Return the element container in case for further modification.
    return Element;
}

function InstallTheme( relativePath )
{
    /// <summary>
    /// Installs the Messenger Content using the relative path.
    /// </summary>
    /// <param name="relativePath">
    /// Path of Messenger Content relative to the page being called from.
    /// </param>
    /// <returns>
    /// URL to Messenger Content location as string.
    /// </returns>
    
    //  Determine URL path to Messenger Content
    var CabUrl = '';
    if(relativePath.substring(0,1) == '/')
    {
        CabUrl = window.location.protocol + '//' + window.location.host + relativePath;
    }
    else
    {
        CabUrl = PathOnly(window.location.href) + relativePath;
    }
    
    //  Install content using URL
    InstallContent(CabUrl);
    
    //  Return the URL used
    return (CabUrl);
}

function InstallContent( strURL )
{
    /// <summary>
    /// Installs the Messenger Content using a URL.
    /// </summary>
    /// <param name="strURL">
    /// URL to the Messenger Content path.
    /// </param>
    
    //  Set Messenger Content Installed as false ahead of time
    MsgrInstallResult = false;
    
    //  Check if running Microsoft Internet Explorer
    if (navigator.appName.indexOf('Microsoft Internet Explorer') == -1)
    {
        InstallThemeError(errNotIE);
        return;
    }
    
    //  Check to see if it was added.  If not, add it.
    if (!MciHtmlAdded)
    {
        AddMciHtml(CONTAINER_ID);
    }
    
    //  Install Messenger Content
    try
    {
        if (typeof(MessengerContentInstaller) != 'undefined')
        {
            MessengerContentInstaller.InstallContent(strURL);
        }
        else
        {
            InstallThemeError(errLogin);
        }
    }
    catch( ex )
    {
        OnContentInstalled(ex.number);
    }
}

function OnContentInstalled( lhrResult )
{
    /// <summary>
    /// Event called after Messenger Content is installed.
    /// </summary>
    /// <param name="lhrResult">
    /// HRESULT return value from installation as long.
    /// </param>

    //  Break down the HRRESULT to head and tail portions
    var tail = (lhrResult & 0xFFFF);
    var head = ((lhrResult >> 16) & 0xFFFF);
    
    //  Use tail value to determine error message or if successful.
    switch (tail)
    {
        case 0x01B6:
        {
            //Messenger not running
            //0x800A01B6
            InstallThemeError(errLogin);
            break;
        }
        
        case 0x036c:
        {
            //http request failed
            //MSGR_E_P4_HTTP_DOWNLOAD
            InstallThemeError(errRequestFailed);
            break;
        }
        
        case 0x038B:
        {
            //user clicked cancel
            //MSGR_E_USER_CANCEL_DOWNLOAD
            //0x8100038B
            InstallThemeError(errUserCanceled);
            break;
        }
        
        case 0x4005:
        {
            //generic fail
            //E_FAIL
            //0x80004005
            InstallThemeError(errUnknown);
            break;
        }
        
        case 0xFFFF:
        {
            //unexpected error
            //E_UNEXPECTED
            InstallThemeError(errUnknown);
            break;
        } 
        
        case 0x031E:
        {
            //user offline
            //MSGR_E_NOT_LOGGED_ON
            InstallThemeError(errLogin);
            break;
        }
         
        case 0x0057:
        {
            //download url empty
            //E_INVALIDARG
            InstallThemeError(errContent);
            break;
        }
        
        case 0x0007:
        {
            //size of the wink cab file is more than 200kb
            //CONTENT_SIZE_TOO_LARGE
            //0x83000007
            InstallThemeError(errRequestFailed);
            break;
        }
        
        case 0x0005:
        {
            //there's already a download in place
            //E_ACCESSDENIED
            //0x80000005
            InstallThemeError(errBusy);
            break;
        }
        
        case 0x0046:
        {
            //Permission denied (ActiveX control)
            //CTL_E_PERMISSIONDENIED
            //0x800A0046
            InstallThemeError(errLogin);
            break;
        }
        
        case 0x000D:
        {
            //The data is invalid
            //ERROR_INVALID_DATA
            //0x8007000D
            InstallThemeError(errUnknown);
            break;
        }
         
        case 0:
        {
            InstallThemeSuccess(strSuccess);
            break;
        }
        
        default:
        {
            InstallThemeError(errUnknown);
        }
    }
}

function InstallThemeError( message )
{
    /// <summary>
    /// Displays an installation error message.
    /// </summary>
    /// <param name="message">
    /// Message to display as string.
    /// </param>

    //  Display message
    //alert(message);
    DisplayAlert(message);
}

function InstallThemeSuccess( message )
{
    /// <summary>
    /// Displays an installation success message
    /// </summary>
    /// <param name="message">
    /// Message to display as string.
    /// </param>

    //  Set Messenger Content Installation as success.
    MsgrInstallResult = true;
    
    //  Display message
    //alert(message);
    DisplayAlert(message);
}

function PathOnly( inString )
{
    /// <summary>
    /// Retrieves the path only from a given URL, 
    /// removing any file and argument references.
    /// </summary>
    /// <param name="inString">
    /// URL use to retrieve path from.
    /// </param>
    /// <returns>
    /// Returns path taken from URL in form of
    /// <protocol>://<host>/[path].
    /// </returns>
    
    //  Find the last slash and pull out text up to the last slash.
    var LastSlash = inString.lastIndexOf('/', inString.length-1);
    var OutString = inString.substring(0, LastSlash+1);
    
    //  Return URL with path only
    return (OutString); 
}