﻿$(document).ready(function() {

    var COOKIENAME = "Shoothill.SLTrack";
    var TRACKCOOKIE = "Shoothill.TrackDownloadAttempt";
    var REQUIREDSLVERSION = "2.0.30226.2";
    var settings = null;

    jQuery.SilverlightTracker = function(options) {

        var defaults = {
            InstallAction: function(status) {
                // Do nothing
            },
            RequiredSilverlightVersion: REQUIREDSLVERSION,
            AttachClickEvents: function(logSilverlightDownload) {
                $(".slinstall").click(logSilverlightDownload);
            },
            ApplicationId: "100001",
            ServiceAddress: "http://projects.shoothill.com/SLLog/",
            PageName: "TestPage",
            ShowDebugMessages: false,
            GatPageTracker: null,
            InstalledCheck: SilverlightInstalled
        }
        settings = jQuery.extend(defaults, options);
        var cookieValue = CookieValue(COOKIENAME);
        if (cookieValue == null) {
            var cookieValue = CreateCookie(COOKIENAME);
            if ($("#siteVisitTrack").length == 0) {
                var requestHolder = generateRequestHolder("siteVisitTrack", "SITEVISIT", cookieValue, settings.PageName);
                $("body").append(requestHolder);
                AnalyticsLog("SITEVISIT");
            }
        }
        if (settings.InstalledCheck(settings.RequiredSilverlightVersion) == false) {
            LogSilverlightNotInstalled();
            settings.InstallAction("NotInstalled");
        } else {
            LogSilverlightInstalled();
            settings.InstallAction("Installed");
        }
    }

    function LogDownloadSilverlight() {
        var cookieValue = CookieValue(COOKIENAME);
        // Create a track cookie
        CreateCookie(TRACKCOOKIE);
        var requestHolder = generateRequestHolder("downloadTracker", "DOWNLOADSILVERLIGHT", cookieValue, settings.PageName);
        if ($("#downloadTracker").length == 0) {
            $("body").append(requestHolder);
            AnalyticsLog("DOWNLOADSILVERLIGHT");
            debugAlert("Added silverlighttracker");
        }
    }

    // Determine if Silverlight is installed
    function SilverlightInstalled(version) {
        var isVersionSupported = false;
        var container = null;

        try {
            var control = null;

            try {
                control = new ActiveXObject('AgControl.AgControl');
                if (version == null) {
                    isVersionSupported = true;
                }
                else if (control.IsVersionSupported(version)) {
                    isVersionSupported = true;
                }
                control = null;
            }
            catch (e) {
                var plugin = navigator.plugins["Silverlight Plug-In"];
                if (plugin) {
                    if (version === null) {
                        isVersionSupported = true;
                    }
                    else {
                        var actualVer = plugin.description;
                        if (actualVer === "1.0.30226.2")
                            actualVer = "2.0.30226.2";
                        var actualVerArray = actualVer.split(".");
                        while (actualVerArray.length > 3) {
                            actualVerArray.pop();
                        }
                        while (actualVerArray.length < 4) {
                            actualVerArray.push(0);
                        }
                        var reqVerArray = version.split(".");
                        while (reqVerArray.length > 4) {
                            reqVerArray.pop();
                        }

                        var requiredVersionPart;
                        var actualVersionPart
                        var index = 0;


                        do {
                            requiredVersionPart = parseInt(reqVerArray[index]);
                            actualVersionPart = parseInt(actualVerArray[index]);
                            index++;
                        }
                        while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);

                        if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) {
                            isVersionSupported = true;
                        }
                    }
                }
            }
        }
        catch (e) {
            isVersionSupported = false;
        }
        if (container) {
            document.body.removeChild(container);
        }

        return isVersionSupported;
    }

    function LogSilverlightNotInstalled() {
        var cookieValue = CookieValue(COOKIENAME);
        if (cookieValue != null) {
            var requestHolder = generateRequestHolder("notInstalledTrack", "NOSILVERLIGHT", cookieValue, settings.PageName);
            if ($("#notInstalledTrack").length == 0) {
                $("body").append(requestHolder);
                AnalyticsLog("NOSILVERLIGHT");
            }
            settings.AttachClickEvents(LogDownloadSilverlight);
            // Attach attempt download logger to controls
        }
    }

    function LogSilverlightInstalled() {
        var cookieValue = CookieValue(COOKIENAME);
        if (cookieValue != null) {
            var trackDownloadCookie = CookieValue(TRACKCOOKIE);
            // if we have added track cookie then log an installed flag
            if (trackDownloadCookie != null) {
                var requestHolder = generateRequestHolder("InstalledTrack", "SILVERLIGHTINSTALLED", cookieValue, settings.PageName);
                if ($("#InstalledTrack").length == 0) {
                    $("body").append(requestHolder);
                    AnalyticsLog("SILVERLIGHTINSTALLED");
                }
            }
        }
    }

    function generateRequestHolder(tracker, eventType, cookieValue, pageDescription) {
        return $("<img />").attr("id", tracker).attr("src", settings.ServiceAddress + "SLEventLog.ashx?op=" + eventType + "&CookieID=" + cookieValue + "&PageDescription=" + pageDescription + "&ApplicationID=" + settings.ApplicationId);
    }

    function AnalyticsLog(eventName) {
        if (settings.GatPageTracker != null)
            settings.GatPageTracker._trackEvent("SilverlightLogger", eventName);
    }

    function CookieValue(cookieName) {
        return $.cookie(cookieName);
    }

    function CreateCookie(cookieName) {
        var cookieValue = guid();
        var options = { path: '/', expires: 50 };
        $.cookie(cookieName, cookieValue, options);
        return cookieValue;
    }

    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    function guid() {
        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    }

    function debugAlert(message) {
        if (settings.ShowDebugMessages)
            alert(message);
    }

});
