﻿var registeredClients = new Array(0);

function trackChapterExit(index, external, percent, playerCode) {
    var playerInstance = uvp(playerCode),
		chapterData = playerInstance.configParser.getChapterData(),
		currentChapter = (chapterData.chapters.length === 1 && index === -1) ? chapterData.chapters[0] : chapterData.chapters[index],
		category = (typeof currentChapter.id === 'undefined' ? '' : currentChapter.id + " ") + currentChapter.name,
		type = (external ? 'external' : 'internal');

    if (percent == null || isNaN(percent)) {
        percent = playerInstance.params.client.percentComplete;
    }

    if (playerInstance.params.m_GADebug) {
        uvp.log("TRACK EVENT: " + category + ", Exit, " + type + ", " + Math.round(percent * 100));
    }
    else {
        trackEvent(category, "Exit", type, Math.round(percent * 100));
    }
}

function registerClient(playerCode) {
    var localPerComplete = 0;

    var localClient = {
        id: 'client' + playerCode,
        perComplete: localPerComplete,

        uvpError: function(error) {
            uvp.log("uvpError: " + error);
        },

        uvpCurrentTimeChanged: function(chapterTime, chapterDuration, playerTime, playerDuration) {
            perComplete = chapterTime / chapterDuration;
        },

        uvpCuePoint: function(name, chapterTime, playheadTime) {
            console.log("name=" + name + " chapterTime=" + chapterTime + " playheadtime=" + playheadTime);
        },

        uvpChapterChanged: function(oldIndex, newIndex, chapterComplete) {
            var percent;

            if (oldIndex >= 0) {
                if (chapterComplete) {
                    percent = 1;
                }

                trackChapterExit(oldIndex, false, percent, '<%= PlayerCode %>');
            }
        }
    };
}
