﻿
if (!window.Silverlight) {
    window.Silverlight = {};
    Silverlight.disableAutoStartup = true;
}

var OperatingSystem;
var SLBrowser;

var PromptFinishInstall = "";
var PromptInstall = "";
var PromptUpgrade = "";
var PromptFinishUpgrade = "";
var PromptRestart = "";
var PromptNotSupported = "";
var RedirectNotSupported = "";

// Logger code

if (!window.SLS)
    window.SLS = {};

SLS.logCount = 0;

SLS.statusShowInstall = 1; // install screen shown to user
SLS.statusShowUpgrade = 2; // upgrade screen show to user
SLS.statusShowUnsupported = 3; // unsupported platform shown to user (eg PPC Mac)
SLS.statusShowRestart = 4; // Show "restart required" after upgrade
SLS.statusChooseInstall = 5; // user chose to install
SLS.statusChooseUpgrade = 6; // user chose to upgrade
SLS.statusChooseReject = 7; // user selected a "no thanks" option
SLS.statusChooseAbandon = 8; // user abandoned (navigate away / close browser)

SLS.statusSuccess = 10; // successful installation

// deployment settings
//SLS.hqPlayerSlUri = "http://go.microsoft.com/fwlink/?linkid=124807";
//SLS.hqPlayerMsLogUri = "";
SLS.hqPlayerMsLogDelay = 1250;
SLS.hqPlayerLogHandler = function(category, eventName, label, value) { alert("Debug Log Handler: " + eventName); };
SLS.hqPlayerErrorHandler = function(source, error) { alert("Oops! An unexpected error occurred.\n\nSource: " + source + "\nDescription: " + error.description); };

SLS.onUnhandledSilverlightError = SLS.hqPlayerErrorHandler;

SLS.entryFlowCookieName = function() {
    return SLS.appName + "entryFlow";
}

SLS.appIdCookieName = function() {
    return SLS.appName + "appId";
}

SLS.installFlowCookieName = function() {
    return SLS.appName + "installFlow";
}

// common functions
SLS.getClientState = function() {
    if (!SLS.clientState) {
        var o = {};
        o.uid = SLS.getUid();
        o.isLogEntryFlowCookieDefined = SLS.isCookieDefined(SLS.entryFlowCookieName(), "1");
        o.isLogInstallFlowCookieDefined = SLS.isCookieDefined(SLS.installFlowCookieName(), "2");
        o.isSlVersionInstalled = Silverlight.isInstalled(SLS.minSlVersion);
        o.isSlVersionSupported = Silverlight.supportedUserAgent(SLS.minSlVersion.substring(0, 1).concat(".0"));
        o.isSlUpgradeRequired = !o.isSlVersionInstalled && Silverlight.isInstalled(null);
        SLS.clientState = o;
    }

    return SLS.clientState;
};

SLS.onPlayerPageBeforeUnload = function() {
    // log abandoned install on badge
    if (SLS.installState == SLS.statusShowInstall || SLS.installState == SLS.statusShowUpgrade) {
        SLS.logInstallFlow(SLS.statusChooseAbandon);
    }

    // log app event
    if (SLS.hqAppSessionId)
        alert("logAppEvent");
    //SLS.logAppEvent();

    // force delay to allow logging to complete
    var date = new Date();
    while (new Date() - date < SLS.hqPlayerMsLogDelay) { }
};


SLS.isCookieDefined = function(name, value) {
    var cookieValue = SLS.getCookieValue(name);
    return SLS.equals(cookieValue, value);
};

SLS.getCookieValue = function(name, caseSensitive) {
    var cookie = document.cookie;

    if (cookie && cookie.length > 0) {
        var items = cookie.split(";");
        return SLS.getParamValue(items, name, caseSensitive);
    }
};

SLS.getParamValue = function(items, name, caseSensitive) {
    for (i = 0; i < items.length; i++) {
        var item = items[i].split("=");

        if (SLS.equals(SLS.trim(unescape(item[0])), name, caseSensitive))
            return item[1] ? unescape(item[1]) : item[1];
    }
};

SLS.equals = function(s1, s2, caseSensitive) {
    if (s1 == s2)
        return true;
    else if (s1 == null || s2 == null || caseSensitive)
        return false;
    else
        return s1.toLowerCase() == s2.toLowerCase();
};

SLS.trim = function(s) {
    return s.replace(/^\s+|\s+$/g, "");
};

SLS.setCookie = function(name, value, hours) {
    if (hours) {
        var expDate = new Date(new Date().getTime() + hours * 60 * 60 * 1000);
        document.cookie = name + "=" + value + ";expires=" + expDate.toGMTString();
    }
    else {
        document.cookie = name + "=" + value;
    }
};

SLS.clearCookie = function(name) {
    document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
};

SLS.getUid = function() {
    var uid = SLS.getCookieValue(SLS.appIdCookieName());

    if (!uid) {
        uid = Math.uuid();
        SLS.setCookie(SLS.appIdCookieName(), uid);
    }

    return uid;
};

SLS.getParamValue = function(items, name, caseSensitive) {
    for (i = 0; i < items.length; i++) {
        var item = items[i].split("=");

        if (SLS.equals(SLS.trim(unescape(item[0])), name, caseSensitive))
            return item[1] ? unescape(item[1]) : item[1];
    }
};

SLS.appendScript = function(index, src) {
    try {
        var script = document.createElement("script");
        script.id = "script" + index;
        script.src = src;
        script.type = "text/javascript";

        var head = document.getElementsByTagName("head")[0];
        head.appendChild(script);
    }
    catch (e) {
        SLS.hqPlayerErrorHandler("SLS.appendScript", e);
    }
};

SLS.removeScript = function(index) {
    try {
        var script = document.getElementById("script" + index);
        var head = document.getElementsByTagName("head")[0];
        head.removeChild(script);
    }
    catch (e) {
        SLS.hqPlayerErrorHandler("SLS.removeScript", e);
    }
};

SLS.setAppSessionId = function(id) {
    SLS.hqAppSessionId = id;
};

SLS.getStatusText = function(status) {

    /*
    
        SLS.statusShowInstall = 1; // install screen shown to user
        SLS.statusShowUpgrade = 2; // upgrade screen show to user
        SLS.statusShowUnsupported = 3; // unsupported platform shown to user (eg PPC Mac)
        SLS.statusShowRestart = 4; // Show "restart required" after upgrade
        SLS.statusChooseInstall = 5; // user chose to install
        SLS.statusChooseUpgrade = 6; // user chose to upgrade
        SLS.statusChooseReject = 7; // user selected a "no thanks" option
        SLS.statusChooseAbandon = 8; // user abandoned (navigate away / close browser)

        SLS.statusSuccess = 10; // successful installation
    
    */
    
    switch(status){
        case SLS.statusShowInstall:
            return "STATUS_SHOWINSTALL";
        case SLS.statusShowUpgrade:
            return "STATUS_SHOWUPGRADE";
        case SLS.statusShowUnsupported:
            return "STATUS_SHOWUNSUPPORTED";
        case SLS.statusShowRestart:
            return "STATUS_SHOWRESTART";
        case SLS.statusChooseInstall:
            return "STATUS_CHOOSEINSTALL";
        case SLS.statusChooseUpgrade:
            return "STATUS_CHOOSEUPGRADE";
        case SLS.statusChooseReject:
            return "STATUS_CHOOSEREJECT";
        case SLS.statusChooseAbandon:
            return "STATUS_CHOOSEABANDON";
        case SLS.statusSuccess:
            return "STATUS_SUCCESS";
    }

    return "STATUS_UNKNOWN";
};

//SLS.logAppEvent = function() {
//	try {
//		// svc parameters
//		var u = SLS.hqAppSessionId;
//		var i = SLS.logCount++;
//		var t = new Date().getTime();
//
//		// append script tag
//		var src = SLS.hqPlayerMsLogUri + "/appevent.svc/parms?u=" + u + "&i=" + i + '&t=' + t + '&an=' + SLS.appName + '&av=' + SLS.appVersion;
//		SLS.appendScript(i, src);
//	}
//	catch (e) {
//		SLS.hqPlayerErrorHandler("SLS.logAppEvent", e);
//	}
//};

SLS.logEntryFlow = function() {
    try {
        var state = SLS.getClientState();

        if (!state.isLogEntryFlowCookieDefined) {
            // set the session cookie to avoid multiple calls
            SLS.setCookie(SLS.entryFlowCookieName(), "1");

            if (SLS.logInstall || SLS.logEntryflow) {
                // svc parameters
                var sls, sle, p;
                var u = state.uid;
                var r = encodeURIComponent(document.referrer);
                var i = SLS.logCount++;
                var t = new Date().getTime();

                // Silverlight install state
                if (state.isSlVersionInstalled)
                    sls = "SL_INSTALLED";
                else if (state.isSlUpgradeRequired)
                    sls = "SL_UPGRADEREQUIRED";
                else
                    sls = "SL_NOTINSTALLED";

                // Silverlight support state
                if (state.isSlVersionSupported)
                    sle = "SL_SUPPORTED";
                else if (SLBrowser == "Chrome" && OperatingSystem == "Windows")
                    sle = "SL_SUPPORTED"; // treating this as a fully supported platform
                else
                    sle = "SL_NOTSUPPORTED";

                if (SLS.hqPlayerLogHandler)
                    SLS.hqPlayerLogHandler(SLS.appName, sls + "/" + sle, "entryflow/ref/" + r, i);
            }
        }
    }
    catch (e) {
        SLS.hqPlayerErrorHandler("SLS.logEntryFlow", e);
    }
};

SLS.logInstallFlow = function(action) {
    SLS.installState = action;
    try {
        // attempting to run silverlight install
        if (action == SLS.statusChooseInstall || action == SLS.statusChooseUpgrade)
            SLS.setCookie(SLS.installFlowCookieName(), "2", 1);
        // install success
        else if (action == SLS.statusSuccess || action == SLS.statusChooseReject || action == SLS.statusChooseAbandon)
            SLS.clearCookie(SLS.installFlowCookieName());

        var state = SLS.getClientState();

        // make the uid stick around for up to 24 hours if we're in an install cycle
        if (action == SLS.statusChooseReject || action == SLS.statusChooseAbandon) {
        } else {
            SLS.setCookie(SLS.appIdCookieName(), state.uid, 24);
        }
        if (SLS.logInstall) {
            // svc parameters
            var u = state.uid;
            var a = action;
            var i = SLS.logCount++;
            var t = new Date().getTime();

            if (SLS.hqPlayerLogHandler)
                SLS.hqPlayerLogHandler(SLS.appName, SLS.getStatusText(a), "InstallState", i);
        }
    }
    catch (e) {
        SLS.hqPlayerErrorHandler("SLS.logInstallFlow", e);
    }
};

function onLauncherPageLoad() {
    // ensure that if browser is closed/page left it gets tracked
    window.onbeforeunload = SLS.onPlayerPageBeforeUnload;

    // would be good to track install version at this point but need to resolve perf issue
    SLS.logEntryFlow();

    Silverlight.__startup()
}

function onSilverlightError(sender, args) {
    // 8001 code for upgrade required
    // 8002 code for restart required
    // 5014 code for improper installation (also fires if sl1.0 is installed)
    if ((args.ErrorCode == 8001) || (args.ErrorCode == 5014)) {
        // ignore as should be captured via silverlight.js events
    } else if (args.ErrorCode == 8002) {
        Silverlight.onRestartRequired()
    } else {
        if (SLS.onUnhandledSilverlightError)
            SLS.onUnhandledSilverlightError(sender, args);
        else
            alert("Debug:  Error Code = " + args.ErrorCode);
    }
}

function onSilverlightLoad(sender) {

    Silverlight.IsVersionAvailableOnLoad(sender);

    var state = SLS.getClientState();

    if (state.isSlVersionInstalled) {
        // log successful install
        if (state.isLogInstallFlowCookieDefined) {
            SLS.logInstallFlow(SLS.statusSuccess);
        }
    }
}

function showSlate(slate) {
    if (SLS.showSlates) {
        document.getElementById(SilverlightControlHost).innerHTML = slate
    }
}

Silverlight.onRestartRequired = function() {
    SLS.logInstallFlow(SLS.statusShowRestart);
    showSlate(PromptRestart);
};

Silverlight.onUpgradeRequired = function() {
    SLS.logInstallFlow(SLS.statusShowUpgrade);
    if (CheckSupported(PromptUpgrade)) {
    }
};

Silverlight.onInstallRequired = function() {
    SLS.logInstallFlow(SLS.statusShowInstall);
    if (CheckSupported(PromptInstall)) {
    }
};

function UpgradeClicked() {
    SLS.logInstallFlow(SLS.statusChooseUpgrade);
    showSlate(PromptFinishUpgrade);
    // if user has Chrome on Windows link directly to exe (currently SL3 handler reports unknown platform but we handle the message via slate)
    if (SLBrowser == "Chrome" && OperatingSystem == "Windows") {
        Silverlight.followFWLink("156091");
    } else {
        Silverlight.followFWLink("149156&v=" + SLS.minSlVersion);
    }
    //window.location = "http://go.microsoft.com/fwlink/?LinkID=149156&v=" + SLS.minSlVersion;

}

function InstallClicked() {
    SLS.logInstallFlow(SLS.statusChooseInstall);
    showSlate(PromptFinishInstall);
    // if user has Chrome on Windows link directly to exe (currently SL3 handler reports unknown platform but we handle the message via slate)
    if (SLBrowser == "Chrome" && OperatingSystem == "Windows") {
        Silverlight.followFWLink("156091");
    } else {
        Silverlight.followFWLink("149156&v=" + SLS.minSlVersion);
    }
    //window.location = "http://go.microsoft.com/fwlink/?LinkID=149156&v=" + SLS.minSlVersion;
}

function CheckSupported(msg) {
    // check to ensure current version is supported (tests the 3.0 for instance)

    if (Silverlight.supportedUserAgent(SLS.minSlVersion.split(".")[0] + "." + SLS.minSlVersion.split(".")[1])) {
        // Do nothing
        showSlate(msg);
        return (true);
    } else if (SLBrowser == "Chrome" && OperatingSystem == "Windows") {
        // alert that Chrome isn't fully tested, but allow install
        // SLS.logInstallFlow(6); <-- we track this from the entries table
        if ((typeof (PromptNotTested) != "undefined") && (PromptNotTested != "")) {
            msg = msg.replace(/<!--warn-->/i, PromptNotTested);
        }
        showSlate(msg);
        if ((typeof (WarningNotTested) != "undefined") && (WarningNotTested != "")) {
            alert(WarningNotTested);
        }
        return (true);
    } else {
        SLS.logInstallFlow(SLS.statusShowUnsupported);
        if (RedirectNotSupported != "") {
            window.location = RedirectNotSupported;
        } else {
            showSlate(PromptNotSupported + "!" + RedirectNotSupported + "!");
        }
        return (false);
    }
}

/*
File: Math.uuid.js
Version: 1.3
Change History:
v1.0 - first release
v1.1 - less code and 2x performance boost (by minimizing calls to Math.random())
v1.2 - Add support for generating non-standard uuids of arbitrary length
v1.3 - Fixed IE7 bug (can't use []'s to access string chars.  Thanks, Brian R.)
v1.4 - Changed method to be "Math.uuid". Added support for radix argument.  Use module pattern for better encapsulation.

Latest version:   http://www.broofa.com/Tools/Math.uuid.js
Information:      http://www.broofa.com/blog/?p=151
Contact:          robert@broofa.com
----
Copyright (c) 2008, Robert Kieffer
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* Neither the name of Robert Kieffer nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

Math.uuid = (function() { var h = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); return function(f, c) { var d = h, a = [], g = Math.random; c = c || d.length; if (f) { for (var b = 0; b < f; b++) a[b] = d[0 | g() * c] } else { var e; a[8] = a[13] = a[18] = a[23] = '-'; a[14] = '4'; for (var b = 0; b < 36; b++) { if (!a[b]) { e = 0 | g() * 16; a[b] = d[(b == 19) ? (e & 0x3) | 0x8 : e & 0xf] } } } return a.join('').toLowerCase() } })();
