﻿/* INSTALLATION SECTION */

function install() {
    // Try an early binding.  This is necessary for those pesky "onload" tracking events
    try {
        fireSpotlight = attachTracker(fireSpotlight, spotlightTracker);
    }
    catch (err) {
        // On a failure of early load, attempt to wait until the DOM is ready.
        // This will handle scripts included later in the page and may not be defined yet.
        window.onload = function() {
            fireSpotlight = attachTracker(fireSpotlight, spotlightTracker);
        }
    }

    // Attaches must be separated, since one can work while the other fails.
    // Failure to separate can cause functions to execute more than once.
    try {
        dcsMultiTrack = attachTracker(dcsMultiTrack, dcsTracker);
    }
    catch (err) {
        window.onload = function() {
            dcsMultiTrack = attachTracker(dcsMultiTrack, dcsTracker);
        }
    }
}

/* END INSTALLATION */

// Attach the tracker to the actual function.  This serves as a wrapper and intercepts the call to the function.
function attachTracker(target, tracker) {
    return function() {
        // Execute the tracker and output results to the console log.
        try {
            console.log(tracker(arguments, target));
        }
        catch (err) {
            console.log("[Installer]: Failure");
        }
    }
}

/* TRACKERS -- These are broken out to allow for customization in argument passing. */

// Spotlight Tracker -- Only uses the first argument to pass on to the spotlight function.
function spotlightTracker(argList, target) {
    var output = "";
    try {
        output += "[Spotlight Tracker]\n"
        output += "Arg List: " + outputArray(argList) + "\n"
        target(argList[0]);
        output += "Complete";
    }
    catch (err) {
        output += "Failure"
    }
    return output;
}

// Web Trends Tracker -- Simply passes on the entire argument list.
function dcsTracker(argList, target) {
    var output = "";
    try {
        output += "[Web Trends Tracker]\n"
        output += "Arg List: " + outputArray(argList) + "\n"
        target(argList);
        output += "Complete";
    }
    catch (err) {
        output += "Failure"
    }
    return output;
}

/* END TRACKERS */

/* HELPER FUNCTIONS */

function outputArray(arr) {
    var str = "";
    for (var i = 0; i < arr.length; i++) {
        str += arr[i] + ", ";
    }
    return str.slice(0, str.length - 2);
}

/* END HELPER FUNCTIONS */

