﻿var APPLICATIONID = "100001";
var COOKIENAME = "Shoothill.SLTrack";
var TRACKCOOKIE = "Shoothill.TrackDownloadAttempt";
var CLICKCONTROLS = new Array("#SilverlightImage");
var SERVICEADDRESS = "http://projects.shoothill.com/SLLogv2/";
var APPNAME = "DeepMoon";

$(document).ready(function() {

    var cookieValue = CookieValue(COOKIENAME);
    if (cookieValue == null) {
        var cookieValue = CreateCookie(COOKIENAME);
        if ($("#siteVisitTrack").length == 0) {
            var requestHolder = generateRequestHolder("siteVisitTrack", "SITEVISIT", cookieValue, APPNAME);
            $("body").append(requestHolder);
        }
    }
});

function LogSilvelightNotInstalled() {
	var cookieValue = CookieValue(COOKIENAME);
	if (cookieValue != null) {
		var requestHolder = generateRequestHolder("notInstalledTrack", "NOSILVERLIGHT", cookieValue, APPNAME);
		if ($("#notInstalledTrack").length == 0) {
			$("body").append(requestHolder);
        }
        // Attach attempt download logger to controls
        for (i = 0; i < CLICKCONTROLS.length; i++) {
            $(CLICKCONTROLS[i]).click(function() {
                var cookieValue = CookieValue(COOKIENAME);
                // Create a track cookie
                CreateCookie(TRACKCOOKIE);
                var requestHolder = generateRequestHolder("downloadTracker", "DOWNLOADSILVERLIGHT", cookieValue, APPNAME);
                if ($("#downloadTracker").length == 0) {
                    $("body").append(requestHolder);
                }
            });
        }
	}
}

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, APPNAME);
            if ($("#InstalledTrack").length == 0) {
                $("body").append(requestHolder);
            }
        }
	}
}

function generateRequestHolder(tracker, eventType, cookieValue, pageDescription) {
    return "<img id=\"" + tracker + "\" src=\"" + SERVICEADDRESS + "SLEventLog.ashx?op=" + eventType + "&CookieID=" + cookieValue + "&PageDescription=" + pageDescription + "&ApplicationID=" + APPLICATIONID + "\">";
}

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());
}
