/* Minification failed. Returning unminified contents.
(16,47-48): run-time error JS1195: Expected expression: >
(16,76-77): run-time error JS1004: Expected ';': )
(28,52-53): run-time error JS1195: Expected expression: >
(119,2-3): run-time error JS1195: Expected expression: )
(121,21-22): run-time error JS1004: Expected ';': {
(215,1-2): run-time error JS1002: Syntax error: }
(218,47-48): run-time error JS1004: Expected ';': {
(1118,63-64): run-time error JS1195: Expected expression: >
(1121,6-7): run-time error JS1195: Expected expression: )
(2009,1-2): run-time error JS1002: Syntax error: }
(2547,46-47): run-time error JS1195: Expected expression: >
(2547,98-99): run-time error JS1004: Expected ';': )
 */
function shakaPlayListConcept(options) {
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.type = 'text/css';
    link.href = '/Content/js/AMPPlugins/amp-playlistConcept.css';
    document.getElementsByTagName('HEAD')[0].appendChild(link);
    var player = document.querySelector('video');
    var nextVideoFlag = false;
    var playlistFlag = false;
    var endplaylistFlag = false;
    var speakers;
    var myTimer;

    var index = 0;
    if (options.playList.length > 0) {
        var x = options.playList.findIndex(m => m.Item5 === options.videoId);
        if (x >= 0) {
            if (x + 1 != options.playList.length)
                index = x + 1;
            else
                index = 0;
        }
    }

    var vidContainer = $("#player_section");
    var keyPointHtml = "<div id='NextVideoTop-Right' class='playlistPopupRegion'></div><div id='videoEndPlaylist' class='playlistPopupRegion'></div>";
vidContainer.append(keyPointHtml);
    player.addEventListener('timeupdate', (event) => {
    //console.log(`1.--------${player.duration}`)
    if (player.duration > 0) {
        var percentagePlayed = Math.abs(player.duration - (5 * 60));
        //console.log(`2.--------${Math.ceil(player.currentTime)},${Math.ceil(percentagePlayed)},${nextVideoFlag}`);
        if (Math.ceil(player.currentTime) == Math.ceil(percentagePlayed) && nextVideoFlag == false) {
           // console.log(`3.--------${player.currentTime}`);
            if (!$('#NextVideoTop-Right').is(':visible')) {
                if (options.playList.length > 0)
                    showKeyPoint(options.playList[index].Item4);
            }
        }

        var endPercentagePlayed = Math.abs(player.duration - (1 * 21));
       // console.log(`4.======${Math.abs(player.currentTime)},${endPercentagePlayed},${endplaylistFlag},${playlistFlag}`);
        if (Math.abs(player.currentTime) >= endPercentagePlayed && endplaylistFlag == false && playlistFlag == false) {
            //console.log(`4.--------${player.currentTime}`);
            if (options.playList.length > 0) {
               // console.log(`5.--------${player.currentTime}`);
                myTimer = setInterval(func, 20000);
                playlistFlag = true;
                const img = new Image(200, 150);
                img.src = options.playList[index].Item3;
                img.id = "thumbnailImage";
                img.tabIndex = "0";
                img.title = options.playList[index].Item4;

                if (options.playList[index].Item7 != "" && options.playList[index].Item7 != undefined && options.playList[index].Item7 != null) {
                    var speakersList = options.playList[index].Item7.split(',');
                    if (speakersList.length > 2) {
                        speakers = speakersList[0] + ',' + speakersList[1] + '...';
                    }
                    else {
                        speakers = options.playList[index].Item7;
                    }
                }

                var titletext = $('<div id = "titletext" style="position: relative; padding-top: 2%;"><div id = "nexttitletext" aria-label = "Playing in few seconds" tabindex="0" >' + '<span class="playon" id="playingInText">Playing in </span>' + '<span class= "countdown"></span ><span class="second" id="secondText">' + 'seconds : ' + '</span></div>'
                    + '<div id = "nextVideoTitle" tabindex="0" title = ' + options.playList[index].Item4 + '>' + options.playList[index].Item4 + '</div></div><div id="speakerText" tabindex="0" title="Speaker(s):' + options.playList[index].Item7 + '">' + 'Speaker(s): ' + speakers + '</div><div id="descriptionBox" tabindex="0" title="' + options.playList[index].Item6 + '"><span class="description">' + options.playList[index].Item6 + '</span></div><div id="btndiv"><div class="panel-title " id="watchNowlink" class="btn btn-primary start pull-left x-hidden-focus" data-eleregion="CreateVideo" data-catagory="Preview" data-ai="true" title="Watch Now" tabindex="0">Watch now</a></div><div class="panel-title "  id="closelink" class="btn btn-primary start pull-left x-hidden-focus" data-eleregion="CreateVideo" data-catagory="Preview" data-ai="true" title="Cancel" tabindex="0">Cancel</a></div></div>');


                $("#videoEndPlaylist").append(titletext);
                $("#btndiv").append(img);
                $("#videoEndPlaylist").show();

                //track call of next video in playlist
                trackCallPlaylist(options, 'Popup shown', options.playList[index].Item1, 'playlist');

                if (speakers == '' || speakers == undefined || speakers == null) {
                    $("#speakerText").hide();
                }

                $("#watchNowlink").bind('click', function () {
                   // console.log(`watchNowlink window.parent.postMessage.--------`);
                    window.parent.postMessage({
                        type: "info",
                        data: {
                            videoId: options.videoGuId,
                            sentAction: "playlist-next",
                            nextVideoId: options.playList[index].Item1,
                            playerUrl: document.location.href
                        }
                    }, "*");
                    //console.log({ type: "info", data: { videoId: options.videoGuId, action: "playlist-next", nextVideoId: options.playList[index].Item1, playerUrl: document.location.href } });
                    //track call of next video in playlist
                    trackCallPlaylist(options, 'Watch Now', options.playList[index].Item1, 'playlist');

                });
                $("#closelink").bind('click', function () {
                    hidePlaylist();
                    //track call of next video in playlist
                    trackCallPlaylist(options, 'Cancel', options.playList[index].Item1, 'playlist');
                });
                var closeKp = $('<dt class="closebtn" tabIndex="0">×</dt>')
                closeKp.click(function () {
                    closePlaylist();
                    //track call of next video in playlist
                    trackCallPlaylist(options, 'Close', options.playList[index].Item1, 'playlist');
                });
                closeKp.keydown(function () {
                    if (event.which === 13) {
                        closePlaylist();
                        //track call of next video in playlist
                        trackCallPlaylist(options, 'Close', options.playList[index].Item1, 'playlist');
                    }
                })
                $("#videoEndPlaylist").append(closeKp);
            }
        }
    }

});

    function func() {
        //console.log(`func window.parent.postMessage.--------`);
        window.parent.postMessage({
            type: "info",
            data: {
                videoId: options.videoGuId,
                sentAction: "playlist-next",
                nextVideoId: options.playList[index].Item1,
                playerUrl: document.location.href
            }
        }, "*");
        //console.log({ type: "info", data: { videoId: options.videoGuId, action: "playlist-next", nextVideoId: options.playList[index].Item1, playerUrl: document.location.href } });
        //track call of next video in playlist
        trackCallPlaylist(options, 'Auto Redirect', options.playList[index].Item1, 'playlist');
    }

function showKeyPoint(title) {
    if (title != '' && title != undefined) {
        var closeKp = $('<dt class="closebtn" tabIndex="0">×</dt>')
        closeKp.click(function () {
            hideKeyPoint();
            //track call of next video in playlist
            trackCallPlaylist(options, 'Cancel/Close', options.playList[index].Item1, 'Up next - Popup');
        });
        closeKp.keydown(function () {
            if (event.which === 13) {
                hideKeyPoint();
                //track call of next video in playlist
                trackCallPlaylist(options, 'Cancel/Close', options.playList[index].Item1, 'Up next - Popup');
            }
        })
        var kptext = $('<div class="staytuned"><div id ="playlistendtext" tabindex="0" aria-label="Up next">' + 'Up next: ' + '</div>'
            + '<div class="staytunetile" tabindex="0" aria-label=' + title + '>' + title + '</div></div>');
        $("#NextVideoTop-Right").append(closeKp);
        $("#NextVideoTop-Right").append(kptext);

        //track call of next video in playlist
        trackCallPlaylist(options, 'Popup shown', options.playList[index].Item1, 'Up next - Popup');
    }
    $("#NextVideoTop-Right").show();
    setTimeout(hideKeyPoint, 8000);
}

function hideKeyPoint() {
    nextVideoFlag = true;
    $("#NextVideoTop-Right").html("");
    $("#NextVideoTop-Right").hide();
}

function hidePlaylist() {
    playlistFlag = false;
    endplaylistFlag = true;
    clearInterval(myTimer);
    $("#videoEndPlaylist").html("");
    $("#videoEndPlaylist").hide();
}

function closePlaylist() {
    playlistFlag = false;
    endplaylistFlag = true;
    $("#videoEndPlaylist").html("");
    $("#videoEndPlaylist").hide();
}

    function trackCallPlaylist(options, btnTitle, nextEventSessionId, categoryGroup) {
        var channelCode = options.playList[index].Item2.toUpperCase().split('-')[0];
        var sessionCode = options.playList[index].Item2;
        var props = {};
        props.mpsSourceId = "Medius";
        props.mpsChannel = channelCode;
        props.mpsEventId = sessionCode;
        props.aitl = btnTitle;     //"watch now/auto redirect/close/Cancel";
        props.tu = nextEventSessionId;
        props.cg = categoryGroup;
        props.ps = '0';
        props.isLive = 'vod';

    mpsAnalyticsCustomTrack(props);
    }
    mpsAnalyticsCustomTrack = function (props) {
        try {
            appInsights.trackEvent("lc", props, {});
            props.event = "lc";
            var overrideValues = {
                behavior: "OTHER",
                actionType: "CL",
                contentTags: props,
                pageTags: {}
            };
            
            mpsonedsanalytics.capturePageAction(null, overrideValues);
        }
        catch (ex) { }
    }
}

;
function shakaVideoStartNotification(options) {
    var player = document.querySelector('video');
    var notificationSent = false;
    var intervalSec = 5; 
    var videoPlayTime = 1;
    var scanPostingInterval = setInterval(function () {
        if (!player.paused && player.currentTime > 0) {
            videoPlayTime += intervalSec; // add 5 sec in videoplaytime if video keep playing
        }
        if (!notificationSent && videoPlayTime >= intervalSec*60) { // check if videoplaytime is more than 5 mins and notification not sent.
            clearInterval(scanPostingInterval); // clear the interval
            UpdateVideoStart(options.shortCode, options.channelList); // call UpdateVideoStart
        }
    }, intervalSec * 1000); // check in every 5 sec whether video is paused or playing

    var urls = {
        VideoStartUrl: "/VideoStartNotifications/UpdateVideoStart",
    };

    var getParameterByName = function (name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, '\\$&');
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)', 'i'),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, ' '));
    }

    var UpdateVideoStart = function (shortCode, channelList) {   
        notificationSent = true;   
        setTimeout(function () { 
                var registrantKey = getParameterByName("uid");
                var leadConsentKey = getParameterByName("sac");
                var regId = "";
                var channelKey = shortCode.toUpperCase().split('-')[0];
                if (registrantKey != null && registrantKey.length > 0
                    && shortCode != null && options.channelList.includes(channelKey)) {
                    regId = registrantKey;
                    registrantKey = "";
                    $.ajax({
                        url: urls.VideoStartUrl,
                        data: { 'ShortCode': shortCode, 'ChannelKey': channelKey, 'RegistrantKey': registrantKey, 'Scantype': options.scanType, 'RegId': regId, 'LeadConsentProvided': leadConsentKey },
                        dataType: "json",
                        type: "POST",
                        contentType: 'application/x-www-form-urlencoded',
                        success: function (data) {
                            console.log(data + " Video Start Informed");
                        },

                        failure: function (response) {
                            console.log(response + "Something went wrong");
                        }
                    });
            } 
        }, 500) // in 500 ms send request to /VideoStartNotifications/UpdateVideoStart
    };
};

//(function () {
var currentState;
var mpsaResolve = function (options) {
    var __indexOf = [].indexOf || function (item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };

    // amp.plugin('appInsights', function (options) {
    var player = oneStreamPlayer.video;

    var pluginVersion = 0.1;
    var parsedOptions;
    var playerStateonPageLoad;
    if (options == null) {
        options = {};
    }
    var st = parseInt(getQuerystring("l"));
    options.startTime = (isNaN(st) ? 0 : st);
    options.sessioncode = options.otherAIProps.mpsEventId;
    var dataSetupOptions = {};
    options.sessiontitles = [];
    options.fullscreen = false;
    //if (options["data-setup"]) {
    //    parsedOptions = JSON.parse(options["data-setup"]);
    //    if (parsedOptions.ga) {
    //        dataSetupOptions = parsedOptions.ga;
    //    }
    //}
    player.isLive = function () {
        return $(".shaka-current-time").text().indexOf(" / ") != -1
    }
    player.currentSrc1 = function () {
        return "";
    }
    player.videoBufferData = function () {
        return "";
    }
    player.currentTechName = function () {
        return "";
    }
    player.audioBufferData = function () {
        return "";
    }
    player.currentTime1 = function () {
        return player.currentTime;
    }
    player.currentType = function () {
        return "";
    }
    player.getAmpVersion = function () {
        return shaka.Player.version;
    }
    player.currentMediaTime = function () {
        return player.currentTime;
    }
    player.isFullscreen = function () {
        return options.fullscreen;
    }
    player.currentDownloadBitrate = function () {
        return 0;
    }
    player.buffered1 = function () {
        return false;
    }
    player.volume1 = function () {
        player.volume;
    }
    viewedSessionList = {};
    var prevSessionCode = '';
    //dynamic session logic
    var dynamicsession = {
        domain: "https://mediastream.microsoft.com",// 
        path: "/events/{yyyy}/{yymm}/{channel}/player/sessions/{sessionid}.json",
        json: {},
        frequency: 120,
        enable: false,
        titleDisplay: true,
        titleDisplayDuration: 5,
        sessioncodeDisplay: false
    }

    try {
        if (options.enableDynamicSession) {
            dynamicsession.enable = true;
        }
        if (options.enableTitleDisplay) {
            dynamicsession.titleDisplay = true;
            $(options.playerId).append('<div id="dynamictitle" style="display:none;"><span title="On now">On now: </span><span class="dt-sessiontitle"></span></div>');
        }
        if (getQuerystring("dsd")) {
            dynamicsession.sessioncodeDisplay = true;
            $(options.playerId).append('<div id="dynamicsessioncode""></div>');
            dynamicsession.sessioncodeEl = $("#dynamicsessioncode");
        }
        if (options.titleDisplayDuration) {
            dynamicsession.titleDisplayDuration = options.titleDisplayDuration;
        }
        if (options.domain) {
            dynamicsession.domain = options.domain;
        }
        if (options.path) {
            dynamicsession.path = options.path;
        }
        if (dynamicsession.enable && options.eventDate) {
            var eventDate = new Date(options.eventDate);
            var year = eventDate.getUTCFullYear().toString();
            var year2digit = year.substring(2);
            var month = eventDate.getUTCMonth() + 1;
            month = ("0" + month).slice(-2);
            dynamicsession.jsonPath = dynamicsession.path.replace("{yyyy}", year)
                .replace("{yymm}", year2digit + month)
                .replace("{channel}", options.otherAIProps.mpsChannel)
                .replace("{sessionid}", options.otherAIProps.mpsEventId);

            var refreshEventIds = function (callback) {
                try {
                    if (typeof mpsEventId !== "undefined") {
                        $.ajax({
                            url: dynamicsession.domain + dynamicsession.jsonPath,
                            type: "GET",
                            cache: false,
                            contentType: "application/javascript",
                            dataType: "json",
                            success: function (data) {
                                result = JSON.parse(JSON.stringify(data).replace(/'/g, ''));
                                callback(result);
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                            },
                        });
                    }
                }
                catch (ex) { }
            }

            var updateEventIds = function (jsonResult) {
                try {
                    if (jsonResult.config.streamstart) {
                        jsonResult.config.streamstart = new Date(jsonResult.config.streamstart);
                    }
                    if (jsonResult.config.streamend) {
                        jsonResult.config.streamend = new Date(jsonResult.config.streamend);
                    }
                    if (jsonResult.config.refresh) {
                        dynamicsession.frequency = jsonResult.config.refresh;
                    }
                    $.each(jsonResult, function (key, value) {
                        if (key !== "config") {
                            value.st = Math.abs(new Date(value.start) - jsonResult.config.streamstart) / 1000;
                            value.et = Math.abs(new Date(value.end) - jsonResult.config.streamstart) / 1000;
                        }
                    });
                    $.extend(true, dynamicsession.json, jsonResult);
                }
                catch (ex) { }
            }

            try {
                refreshEventIds(updateEventIds);
                setInterval(function () {
                    refreshEventIds(updateEventIds);
                }, parseInt(dynamicsession.frequency) * 1000) //2 minutes
            }
            catch (ex) { }
        }
    }
    catch (ex) { }

    //App Insights Config
    appInsights.config.maxBatchInterval = sendInterval = options.sendInterval || dataSetupOptions.sendInterval || 15;
    appInsights.config.disableFlushOnBeforeUnload = true;
    appInsights.maxAjaxCallsPerView = -1;

    //Setting plugin options

    /* All implemented metrics include: ['loaded', 'viewed', 'ended', 'playTime', 'percentsPlayed', 'play', 'pause', 'seek', 'fullscreen', 'error', 'buffering', 'bitrateQuality', 'playbackSummary', 'downloadInfo']; */
    var defaultMetricsToTrack = ['debug', 'playbackSummary', 'loaded', 'viewed', 'ended', 'playTime', 'timeUpdateInterval', 'play', 'pause', 'seek', 'fullscreen', 'error', 'buffering', 'bitrateQuality', 'trackSdn', 'downloadFailed', 'percentsPlayed', 'captions', 'volumechange', 'mutetoggle', 'captionsearch', 'audiotracks', 'downloadResource', 'share'];
    var listMetricsToTrack = options.metricsToTrack || dataSetupOptions.metricsToTrack || defaultMetricsToTrack;
    var metricsToTrack = {};
    listMetricsToTrack.forEach(function (value, index, array) {
        metricsToTrack[value] = true;
    });


    //var percentsPlayedInterval = options.percentsPlayedInterval || dataSetupOptions.percentsPlayedInterval || 5;
    //var timeUpdateInterval = options.timeUpdateInterval || dataSetupOptions.timeUpdateInterval || 15;
    options.debug = options.debug || false;

    var percentsPlayedInterval = 25;
    var timeUpdateInterval = 25;

    //TrackEvent Properties
    if (options.userId || dataSetupOptions.userId) {
        //setting authenticated user context
        var userId = options.userId || dataSetupOptions.userId;
        var accountId = options.accountId || dataSetupOptions.accountId || null;
        appInsights.setAuthenticatedUserContext(userId, accountId);
        if (options.debug) {
            console.log("Authenticated User Context set as userId: " + userId + " and accountId: " + accountId);
        }
    }
    var streamId = options.streamId || dataSetupOptions.streamId || null;

    //enable if you hav SDN or eCDN intentration with AMP
    var trackSdn = options.trackSdn || dataSetupOptions.trackSdn || false;

    //Initializing tracking variables
    var percentsAlreadyTracked = [];
    var lastPercentTracked = -1;
    var percentPlayed = 0;

    var timeAlreadyTracked = [];
    var lastTimeTracked = -1;
    var lastPosition = 0;
    var lastMediaTime = 0;

    if (options.otherAIProps && options.otherAIProps.mpsChannel && options.otherAIProps.mpsEventId) {
        var TrackedInterval = ReadTrackedInterval(options.otherAIProps.mpsChannel + options.otherAIProps.mpsEventId);
        percentsAlreadyTracked = TrackedInterval.playPercentage;
        timeAlreadyTracked = TrackedInterval.playTime;
    }
    var seeking = false;
    var currentProtectionInfo = null;

    //Trim the manifest url to get a streamId
    function mapManifestUrlToId(manifest) {
        var sourceManifest = "unknown";
        if (manifest) {
            sourceManifest = manifest.split("//")[1];
            if (sourceManifest.match(/.ism\/manifest/i)) {
                sourceManifest = sourceManifest.split(/.ism\/manifest/i)[0] + ".ism/manifest";
            }
        }
        return sourceManifest;
    }

    function mapProtectionInfo(protectionType) {
        var protectionInfo = "unknown";
        if (protectionType) {
            switch (protectionType.toLowerCase()) {
                case "aes":
                    protectionInfo = "aes";
                    break;
                case "playready":
                    protectionInfo = "drm";
                    break;
                case "widevine":
                    protectionInfo = "drm";
                    break;
                case "fairplay":
                    protectionInfo = "drm";
                    break;
                default:
                    protectionInfo = "none";
            }
        }
        return protectionInfo;
    }

    //Calculating bufferedAhead *Does not work in SilverlightSS
    function calculateBufferAhead() {
        var buffered = player.buffered1();
        var currentTime = player.currentTime1();

        if (!buffered) {
            return undefined;
        }

        return Math.max(0, buffered.end(buffered.length - 1) - currentTime);
    }


    //Loading information for tracking start, load times, unload events
    //loadTime is in milliseconds
    var load = {
        loadTime: 0,
        //incase loadedmetadata doesn't fire set start time
        loadTimeStart: new Date().getTime(),
        firstPlay: false,
        endedReached: false,
        videoElementUsed: false,
        unloaddatasent: false,
        updateLoadTime: function () {
            this.loadTime = Math.abs(new Date().getTime() - this.loadTimeStart);
            if (options.debug) {
                console.log("Player Load Time determined: " + this.loadTime + "ms");
            }
            this.send();
        },
        send: function () {
            //removing outliers @100s for load
            if (metricsToTrack.loaded) {
                if (this.loadTime < 100000) {
                    //trackEvent("loadTime", { "time": this.loadTime });
                }
            }
        },
        reset: function () {
            this.loadTime = 0;
            this.loadTimeStart = new Date().getTime();
            this.firstPlay = false;
            this.endedReached = false;
            var streamId = options.streamId || dataSetupOptions.streamId || null;
        }
    }

    //Buffering information for tracking waiting events
    //bufferingTime is in milliseconds
    var buffering = {
        state: false,
        bufferingTime: 0,
        bufferingTimeStart: 0,
        bufferingTimeTotal: 0,
        count: 0,
        enterBuffering: function () {
            if (load.firstPlay) {
                this.bufferingTimeStart = new Date().getTime();
                this.state = true;
                this.count++;
                if (options.debug) {
                    console.log("Entering buffering state...");
                }
            }
        },
        send: function (returnValue) {
            var props = {};
            if (this.state) {
                this.bufferingTime = Math.abs(new Date().getTime() - this.bufferingTimeStart);
                var currentTime = Math.round(player.currentTime1());
                if (currentTime !== 0) {
                    if (metricsToTrack.buffering) {
                        bufferingMetrics = {
                            'currentTime': currentTime,
                            'bufferingTime': this.bufferingTime,
                        };
                        if (download.videoBuffer) {
                            bufferingMetrics.perceivedBandwidth = download.videoBuffer.perceivedBandwidth;
                        }
                        if (calculateBufferAhead) {
                            bufferingMetrics.buffered = calculateBufferAhead();
                        }
                        props = bufferingMetrics;
                        if (typeof returnValue == "undefined" || (typeof returnValue != "undefined" && !returnValue)) {
                            trackEvent('buffering', props)
                        }
                    }
                }
                this.bufferingTimeTotal += this.bufferingTime;
                this.state = false;
                if (options.debug) {
                    console.log("Exiting buffering state.  Time spent rebuffering was " + this.bufferingTime + "ms");
                }
            }
            if (typeof returnValue != "undefined" && returnValue) {
                return props;
            }
        },
        reset: function () {
            this.bufferingTime = 0;
            this.state = false;
        },
        fullReset: function () {
            this.bufferingTime = 0;
            this.bufferingTimeStart = 0;
            this.bufferingTimeTotal = 0;
            this.count = 0;
            this.state = false;
        }
    }

    var download = {
        videoBuffer: null,
        audioBuffer: null,
        sumBitrate: 0,
        sumPerceivedBandwidth: 0,
        sumMeasuredBandwidth: 0,
        downloadedChunks: 0,
        failedChunks: 0,
        completed: function () {
            if (player.currentDownloadBitrate()) {
                this.downloadedChunks += 1;
                this.sumBitrate += player.currentDownloadBitrate();

                if (this.videoBuffer) {
                    if (metricsToTrack.downloadInfo) {
                        trackEvent("downloadCompleted", { "bitrate": player.currentDownloadBitrate(), "measuredBandwidth": this.videoBuffer.downloadCompleted.measuredBandwidth, "perceivedBandwidth": this.videoBuffer.perceivedBandwidth })
                    }

                    this.sumPerceivedBandwidth += this.videoBuffer.perceivedBandwidth;
                    this.sumMeasuredBandwidth += this.videoBuffer.downloadCompleted.measuredBandwidth;
                }
            }
        },
        failed: function (type) {
            if (metricsToTrack.downloadInfo || metricsToTrack.downloadFailed) {

                if (type.toLowerCase() == "audio") {
                    var isVideo = 0;
                    var code = this.audioBuffer.downloadFailed.code.toString(8);
                } else {
                    var isVideo = 1;
                    var code = this.videoBuffer.downloadFailed.code.toString(8);
                }

                trackEvent("downloadFailed", { "isVideo": isVideo, "errorCode": code });
            }
            this.failedChunks++;
        },
        send: function (returnValue) {
            var props = {};
            if (metricsToTrack.bitrateQuality) {
                if (this.downloadedChunks > 0) {
                    bitrateQualityMetrics = {
                        "avgBitrate": this.sumBitrate / this.downloadedChunks
                    }

                    if (this.videoBuffer) {

                        var AverageMeasuredBandwidth = Math.round(this.sumMeasuredBandwidth / this.downloadedChunks);
                        var AveragePerceivedBandwidth = Math.round(this.sumPerceivedBandwidth / this.downloadedChunks);

                        bitrateQualityMetrics.avgMeasuredBandwidth = AverageMeasuredBandwidth;
                        bitrateQualityMetrics.avgPerceivedBandwidth = AveragePerceivedBandwidth;

                    }
                    props = bitrateQualityMetrics;
                    if (typeof returnValue == "undefined" || (typeof returnValue != "undefined" && !returnValue)) {
                        trackEvent("bitrateQuality", props);
                    }
                }
            }

            if (typeof returnValue != "undefined" && returnValue) {
                return props;
            }
        },
        reset: function () {
            this.videoBuffer = null;
            this.audioBuffer = null;
            this.sumBitrate = 0;
            this.sumPerceivedBandwidth = 0;
            this.sumMeasuredBandwidth = 0;
            this.downloadedChunks = 0;
            this.failedChunks = 0;
        }
    }

    //playIntervals tracks the intervals of time in which the viewer watched on
    var playIntervals = {
        startTime: options.startTime,
        endTime: 0,
        added: false,
        lastCheckedTime: 0,
        arrayOfTimes: [],
        overlappingArrayOfTimes: [],
        sorted: false,
        totalSecondsFullscreen: 0,
        previouslyReportedTotalFullscreenTime: 0,
        previouslyReportedTotalPlayTime: options.startTime,
        sortAlgorithm: function (a, b) {

            if (a[0] < b[0]) return -1;
            if (a[0] > b[0]) return 1;
            return 0;

        },
        update: function (time) {
            if (time == this.lastCheckedTime + 1) {
                if (player.isFullscreen()) {
                    this.totalSecondsFullscreen += 1;
                }
            }

            if ((!(time == this.lastCheckedTime || time == this.lastCheckedTime + 1)) || (metricsToTrack.timeUpdateInterval && time == lastTimeTracked)) {
                this.endTime = this.lastCheckedTime;
                this.push();
                this.startTime = time;
                this.added = false;
            }
            this.lastCheckedTime = time;

        },
        push: function () {
            this.arrayOfTimes.push([this.startTime, this.endTime]);
            this.added = true;
        },
        getOverlappingArrayOfTimes: function () {
            if (!this.added) {
                this.endTime = Math.round(player.currentTime1());
                this.push();
            }
            this.arrayOfTimes = this.arrayOfTimes.sort(this.sortAlgorithm);


            if (this.arrayOfTimes.length > 1) {
                this.overlappingArrayOfTimes.push(this.arrayOfTimes[0]);
                for (var i = 1; i < this.arrayOfTimes.length; i++) {
                    if (this.arrayOfTimes[i][0] <= this.overlappingArrayOfTimes[this.overlappingArrayOfTimes.length - 1][1]) {
                        if (this.arrayOfTimes[i][1] > this.overlappingArrayOfTimes[this.overlappingArrayOfTimes.length - 1][1]) {
                            var t0 = this.overlappingArrayOfTimes[this.overlappingArrayOfTimes.length - 1][0];
                            var t1 = this.arrayOfTimes[i][1];
                            this.overlappingArrayOfTimes.pop();
                            //overlappingArrayOfTimes
                            this.overlappingArrayOfTimes.push([t0, t1]);
                        }
                    } else {
                        this.overlappingArrayOfTimes.push(this.arrayOfTimes[i]);
                    }
                }
            } else {
                this.overlappingArrayOfTimes = this.arrayOfTimes;
            }

            this.sorted = true;
        },
        getTotalPlayTime: function () {
            if (!this.sorted) {
                this.getOverlappingArrayOfTimes();
            }
            var TotalPlayTime = 0;
            for (var i = 0; i < this.arrayOfTimes.length; i++) {
                TotalPlayTime += this.arrayOfTimes[i][1] - this.arrayOfTimes[i][0];
            }
            return Math.round(TotalPlayTime);
        },
        getTotalUniquePlayTime: function () {
            if (!this.sorted) {
                this.getOverlappingArrayOfTimes();
            }
            var TotalUniquePlayTime = 0;
            for (var i = 0; i < this.overlappingArrayOfTimes.length; i++) {
                TotalUniquePlayTime += this.overlappingArrayOfTimes[i][1] - this.overlappingArrayOfTimes[i][0];
            }
            return Math.round(TotalUniquePlayTime);
        },
        reset: function () {

            this.startTime = 0;
            this.endTime = 0;
            this.totalSecondsFullscreen = 0;
            this.added = false;
            this.sorted = false;
            this.arrayOfTimes = [];
            this.overlappingArrayOfTimes = [];
        }
    };

    //Timer for playTime tracking for Live playback
    //Tracking totalSeconds in seconds
    var playTimeLive = {
        totalSeconds: 0,
        totalSecondsFullscreen: 0,
        previouslyReportedTotalPlayTime: 0,
        previouslyReportedTotalFullscreenTime: 0,
        start: function () {
            var self = this;
            this.interval = setInterval(function () {
                self.totalSeconds += 1;
                if (player.isFullscreen()) {
                    self.totalSecondsFullscreen += 1;
                }
            }, 1000);
        },
        pause: function () {
            clearInterval(this.interval);
            delete this.interval;
        },
        resume: function () {
            if (!this.interval) this.start();
        },
        send: function (returnValue) {
            var props = { "time": this.totalSeconds };
            if (typeof returnValue != "undefined" && returnValue) {
                return props;
            }
            else {
                trackEvent('playTime', props);
            }
        },
        reset: function () {
            this.totalSeconds = 0;
            this.totalSecondsFullscreen = 0;
        }
    };

    var sourceset = function () {

        if (load.videoElementUsed) {
            unloadData();
        }

        //resetting state for source change scenario
        load.reset()
        buffering.fullReset();
        playTimeLive.reset();
        playIntervals.reset();
        download.reset();
        percentPlayed = 0;
        lastPercentTracked = null;
        currentProtectionInfo = null;
        streamId = null;
        if (options.debug) {
            console.log("Resetting App Insight Plugin Config");
        }
    }

    var loaded = function () {
        playerStateonPageLoad = player.isLive();

        streamId = options.streamId || dataSetupOptions.streamId || null;
        if (!streamId) {
            streamId = mapManifestUrlToId(player.currentSrc1());
        }
        if (options.debug) {
            console.log("streamId set as: " + streamId);
        }

        if (player.currentProtectionInfo && player.currentProtectionInfo()) {
            currentProtectionInfo = mapProtectionInfo(player.currentProtectionInfo()[0].type);
        } else {
            currentProtectionInfo = "none";
        }

        if (options.debug) {
            console.log("protectionInfo set as: " + currentProtectionInfo);
        }


        //sending loadedmetadata event
        if (metricsToTrack.loaded) {
            trackEvent('loadedmetadata', { "time": load.loadTime });
        }

        //used to track if the video element is reused to appropriately send unload data
        load.videoElementUsed = true;

    };

    var canplaythrough = function () {
        load.updateLoadTime();
    }

    var timeupdate = function () {
        if (load.firstPlay && streamId) {
            var currentTime = Math.round(player.currentTime1());

            if (metricsToTrack.playbackSummary || metricsToTrack.playTime) {
                playIntervals.update(currentTime);
            }

            if (metricsToTrack.percentsPlayed) {
                //Currently not tracking percentage watched information for Live
                if (!this.isLive()) {
                    var duration = Math.round(player.duration);

                    var currentTimePercent = Math.round(currentTime / duration * 100);
                    if (currentTimePercent != lastPercentTracked) {

                        if (currentTimePercent % percentsPlayedInterval == 0 && currentTimePercent <= 100) {
                            if (__indexOf.call(percentsAlreadyTracked, currentTimePercent) < 0) {
                                if (currentTimePercent !== 0) {
                                    percentPlayed += percentsPlayedInterval;
                                }
                                percentsAlreadyTracked.push(currentTimePercent);
                            }
                            trackEvent("percentReached", { "percent": currentTimePercent });
                        }
                    }
                    lastPercentTracked = currentTimePercent;
                }

            }

            if (metricsToTrack.timeUpdateInterval) {
                if (!this.isLive()) {

                    //console.log("current time " + currentTime + " last position " + lastPosition)
                    if (currentTime != lastPosition) {
                        if (currentTime % timeUpdateInterval == 0) {
                            //console.log('time to report' + currentTime);
                            if (__indexOf.call(timeAlreadyTracked, currentTime) < 0) {
                                //console.log('push to array');
                                timeAlreadyTracked.push(currentTime);
                                lastTimeTracked = currentTime;
                                sendPlaybackSummary(false);
                                //console.log('sent summary')
                            }
                            else {
                                lastTimeTracked = currentTime;
                                playIntervals.previouslyReportedTotalPlayTime = playIntervals.getTotalPlayTime();
                                //console.log('time to report but not reporting' + currentTime + ", totalPlayTime: " + playIntervals.previouslyReportedTotalPlayTime);                                    
                            }
                        }
                        lastPosition = currentTime;
                    }
                }
                else {
                    var currentMediaTime = Math.round(player.currentMediaTime());

                    //console.log("currentMediaTime" + currentTime + " last position " + lastMediaTime)
                    if (currentMediaTime != lastMediaTime) {
                        if (currentMediaTime % timeUpdateInterval == 0) {
                            //console.log('time to report' + currentMediaTime);
                            if (__indexOf.call(timeAlreadyTracked, currentMediaTime) < 0) {
                                // console.log('push to array');
                                timeAlreadyTracked.push(currentMediaTime);
                                lastTimeTracked = currentTime;
                                sendPlaybackSummary(false);
                                //console.log('sent summary')
                            }
                            else {
                                lastTimeTracked = currentTime;
                                playIntervals.previouslyReportedTotalPlayTime = playTimeLive.totalSeconds;
                                //console.log('time to report but not reporting' + currentMediaTime);

                            }
                        }
                        lastMediaTime = currentMediaTime;
                    }
                }
            }

            if (metricsToTrack.bitrateQuality || metricsToTrack.playbackSummary) {
                if (!download.videoBuffer && player.currentDownloadBitrate()) {
                    download.completed();
                }
            }
        }
    };

    var play = function () {
        if (metricsToTrack.play) {
            var currentTime;
            currentTime = Math.round(player.currentTime1());
            trackEvent('play', { 'currentTime': currentTime });
        }
        addUsageData(customUserConfig.getCustomUserId(), options.otherAIProps["videoId"], "play");
    };

    var playing = function () {
        seeking = false;
        if (!load.firstPlay) {
            load.firstPlay = true;
            if (metricsToTrack.viewed) {
                trackEvent("viewed");
                sendPlaybackSummary(false);
            }
        }
        if (metricsToTrack.buffering || metricsToTrack.playbackSummary) {
            buffering.send();
        }

        if (metricsToTrack.playTime || metricsToTrack.playbackSummary) {
            if (player.isLive()) {
                if (playTimeLive.totalSeconds == 0) {
                    if (!playTimeLive.interval) {
                        playTimeLive.start();
                    }
                } else {
                    playTimeLive.resume();
                }
            }
        }
    }


    var pause = function () {


        if (metricsToTrack.playTime || metricsToTrack.playbackSummary) {
            if (player.isLive()) {
                playTimeLive.pause();
            }
        }

        if (metricsToTrack.pause) {
            var currentTime = Math.round(player.currentTime1());
            var duration = Math.round(player.duration);

            if (currentTime !== duration && !seeking) {
                if (metricsToTrack.pause) {
                    trackEvent('pause', { 'currentTime': currentTime });
                }
            }
        }
    }

    var seek = function () {
        seeking = true;

        if (metricsToTrack.seek) {
            //add seekingTime
            var currentTime = Math.round(player.currentTime1());
            trackEvent('seek', { 'currentTime': currentTime });
            var generatedProps = {
                tu: "",
                rg: "Player",
                aitl: currentTime,
                cg: 'Seek'
            }
            var objecttoSend = {};
            objecttoSend.properties = generatedProps;
            mediusAnalytics.sendTrackingdata(objecttoSend);
        }
    }

    var end = function () {
        if (metricsToTrack.playTime || metricsToTrack.playbackSummary) {
            if (player.isLive()) {
                playTimeLive.pause();
            }
        }
        if (metricsToTrack.ended) {
            if (!load.endedReached) {
                trackEvent('ended');
                sendPlaybackSummary(false);
                load.endedReached = true;
            }
        }
    };

    var waiting = function () {
        buffering.enterBuffering();
    }

    var downloadcompleted = function () {
        download.completed();
    }

    var downloadfailed = function () {

    }

    var fullscreen = function () {
        var currentTime = Math.round(player.currentTime);
        if (player.isFullscreen()) {
            //enter fullscreen
            trackEvent('fullscreen', { 'enter': 1, 'currentTime': currentTime });
        } else {
            //exit fullscreen
            trackEvent('fullscreen', { 'enter': 0, 'currentTime': currentTime });
        }
    };
    oneStreamPlayer.onFullscreenChange((event, isFullScreen) => {
        options.fullscreen = isFullScreen;
        fullscreen();
    });
    var triggervc = true;
    var volume;
    var volumechange = function () {
        volume = player.volume;
        if (triggervc) {
            triggervc = false;
            setTimeout(function () {
                triggervc = true;
                trackEvent('Volumn change', { 'volume': volume });
                //if (player.muted)
                //    trackEvent('mute', { 'muted': 1 });

            }, 1000);
        }
    }
    var muteToggle = function (e) {
        trackEvent('mute', { 'muted': (player.muted() == true) ? 1 : 0 })
    }

    var captionSearch = function () {
        $("body").on('autocompleteopen', '#captionsearchinput', function (event, ui) {
            var csKeyword = $(this).val();
            if (csKeyword.length > 0) {
                trackEvent('cs', {}, { 'csKeyword': csKeyword });
                var generatedProps = {
                    tu: "",
                    rg: "Player",
                    aitl: csKeyword,
                    cg: 'CaptionSearch'
                }
                var objecttoSend = {};
                objecttoSend.properties = generatedProps;
                mediusAnalytics.sendTrackingdata(objecttoSend);
            }
            $('.amp-captionsearch-control .vjs-menu-item').click(function () {
                var generatedProps = {
                    tu: "",
                    rg: "Player",
                    aitl: $(this).find('span').attr('title'),
                    cg: 'Caption Search link'
                }
                var objecttoSend = {};
                objecttoSend.properties = generatedProps;
                mediusAnalytics.sendTrackingdata(objecttoSend);
                trackEvent('csrc', {}, { 'csKeyword': $('#captionsearchinput').val(), 'csResult': $(this).find('span').attr('title') });
            });
        });
    }

    var addtocalendar = function () {
        $('body').on('click', '.addtocalendar', function () {
            trackEvent('adc', {});
        });
    }
    var downloadResource = function () {
        $('body').on('click', '.amp-donwload-control a', function () {
            trackEvent('downloadResource', {}, { 'rUrl': $(this).attr("href") });
        });
    }
    var share = function () {
        $('body').on('click', '.vjs-shareoptions-social a', function () {
            if ($(this).attr("href").indexOf("facebook") > -1) {

                trackEvent('share', { 'facebook': true });
            }
            if ($(this).attr("href").indexOf("twitter") > -1) {

                trackEvent('share', { 'twitter': true });
            }
            if ($(this).attr("href").indexOf("linkedin") > -1) {

                trackEvent('share', { 'linkedin': true });
            }
            if ($(this).attr("href").indexOf("mailto") > -1) {

                trackEvent('share', { 'mailto': true });
            }
        });
        $('body').on('click', '.vjs-sharePanel-CopyConfirmPopupContainer button', function () {
            if ($(this).text().indexOf("Location") > -1) {
                trackEvent('share', { 'CopywithLocation': true }, { 'lUrl': $("#txtVideoLocation").val() });
            }
            else {
                trackEvent('share', { 'CopyVideoUrl': true }, { 'vUrl': $(this).parent().find("textarea").first().val() });
            }
        });
    }
    var error = function () {
        if (load.loadTime == 0) {
            load.updateLoadTime();
        }

        if (metricsToTrack.playTime || metricsToTrack.playbackSummary) {
            if (player.isLive()) {
                playTimeLive.pause();
            }
        }
        if (metricsToTrack.error) {
            var currentTime = Math.round(player.currentTime1());
            var errorHexCode = player.error().code.toString(16);
            trackEvent("error", { "errorCode": errorHexCode, 'currentTime': currentTime });
        }
    };

    function exit() {
        //Check that you haven't already sent this data
        //iOS fires event twice
        if (!load.unloaddatasent) {
            load.unloaddatasent = true;
            unloadData();
        }
    };

    function sendPlaybackSummary(sendOtherEvents) {

        var totalPlayTime = playTimeLive.totalSeconds;
        var previouslyReportedTotalPlayTime = playTimeLive.previouslyReportedTotalPlayTime;
        playTimeLive.previouslyReportedTotalPlayTime = totalPlayTime;


        var totalFullscreenTime = playTimeLive.totalSecondsFullscreen;
        var previouslyReportedTotalFullscreenTime = playTimeLive.previouslyReportedTotalFullscreenTime;
        playTimeLive.previouslyReportedTotalFullscreenTime = totalFullscreenTime;

        var totalPercentViewed = Math.min(percentPlayed, 100);
        //var totalUniquePlayTime = totalPlayTime;

        if (!player.isLive()) {
            totalPlayTime = playIntervals.getTotalPlayTime();
            previouslyReportedTotalPlayTime = playIntervals.previouslyReportedTotalPlayTime;
            playIntervals.previouslyReportedTotalPlayTime = totalPlayTime;

            totalFullscreenTime = playIntervals.totalSecondsFullscreen;
            previouslyReportedTotalFullscreenTime = playIntervals.previouslyReportedTotalFullscreenTime;
            playIntervals.previouslyReportedTotalFullscreenTime = totalFullscreenTime;

            totalPercentViewed = Math.min(Math.round((playIntervals.getTotalUniquePlayTime() / player.duration) * 100), 100);

            //totalUniquePlayTime = playIntervals.getTotalUniquePlayTime();

        }

        if (load.loadTime == 0) {
            load.updateLoadTime();
        }


        //send events
        if (sendOtherEvents) {
            var unloadMetrics = {
                "percentPlayed": percentPlayed,
                'rebufferCount': buffering.count,
                "totalRebufferTime": buffering.bufferingTimeTotal
            }
            $.extend(unloadMetrics, buffering.send(true));
            $.extend(unloadMetrics, playTimeLive.send(true));
            $.extend(unloadMetrics, download.send(true));

            trackEvent("unload", unloadMetrics);

        }
        else if (load.firstPlay && metricsToTrack.playbackSummary) {
            var playbackSummaryMetric = {
                "playTime": totalPlayTime,
                "currentPlayTime": totalPlayTime - previouslyReportedTotalPlayTime,
                "fullscreenTime": totalFullscreenTime,
                "currentFullScreenTime": totalFullscreenTime - previouslyReportedTotalFullscreenTime,
                "rebufferCount": buffering.count,
                "rebufferTime": buffering.bufferingTimeTotal
            }

            if (load.loadTime <= 100000) {
                //removing outliers when loadTime cannot be properly calculated because browser doesn't accurately call events
                playbackSummaryMetric.loadTime = load.loadTime;
            }
            if (!player.isLive()) {
                playbackSummaryMetric.percentPlayed = totalPercentViewed;
            }

            if (download.downloadedChunks > 0) {
                var avgBitrate = Math.round(download.sumBitrate / download.downloadedChunks);
                var avgMeasuredBandwidth = Math.round(download.sumMeasuredBandwidth / download.downloadedChunks);
                var avgPerceivedBandwidth = Math.round(download.sumPerceivedBandwidth / download.downloadedChunks);

                playbackSummaryMetric.avgBitrate = avgBitrate;
                playbackSummaryMetric.avgMeasuredBandwidth = avgMeasuredBandwidth;
                playbackSummaryMetric.avgPerceivedBandwidth = avgPerceivedBandwidth;

            }

            if (download.videoBuffer) {
                playbackSummaryMetric.failedDownloads = download.failedChunks;
            }
            //if (player.error()) {
            //    playbackSummaryMetric.errorCode = player.error().code.toString(16);
            //}


            trackEvent("pbs", playbackSummaryMetric);
        }
    }


    function unloadData() {
        // trackEvent("playbackSummary", {});
        //appInsights.trackEvent("userLeft", {}, {});
        if (options.otherAIProps && options.otherAIProps.mpsChannel && options.otherAIProps.mpsEventId) {
            updateTrackedInterval(options.otherAIProps.mpsChannel + options.otherAIProps.mpsEventId, timeAlreadyTracked, percentsAlreadyTracked);
        }
        sendPlaybackSummary(true);
        if (appInsights && appInsights.flush)
            appInsights.flush();
    }
    function getQuerystring(key, default_) {
        if (default_ == null) default_ = "";
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href.toLowerCase());
        if (qs == null)
            return default_;
        else
            return qs[1];
    }
    var getPlayerState = function () {
        var playerMode;
        //0 - vod, 1 - live, 2 - dvr
        if (!playerStateonPageLoad && !currentState) { //live
            var liveflag = true;
            var scode = getQuerystring('scode', '');
            if (scode.length == 0 && typeof dynamicsession.json !== 'undefined' && dynamicsession.json[options.sessioncode]) {
                var now = new Date();
                var utcNow = new Date(now.getUTCFullYear() + '/' + (now.getUTCMonth() + 1) + '/' + now.getUTCDate() + ' ' + now.getUTCHours() + ':' + now.getUTCMinutes());
                if (!(utcNow <= dynamicsession.json[options.sessioncode].end)) {
                    liveflag = false;
                }
            }
            if (document.getElementById('hdnIsSemilive').value.toLowerCase() == "true") {
                playerMode = 1;
            }
            else {
                playerMode = 0;
            }
        }
        else if (playerStateonPageLoad && player.isLive()) { //dvr
            var liveflag = false;
            var scode = getQuerystring('scode', '');
            if (scode.length == 0 && typeof dynamicsession.json !== 'undefined' && dynamicsession.json[options.sessioncode]) {
                var now = new Date();
                var utcNow = new Date(now.getUTCFullYear() + '/' + (now.getUTCMonth() + 1) + '/' + now.getUTCDate() + ' ' + now.getUTCHours() + ':' + now.getUTCMinutes());
                if (utcNow <= dynamicsession.json[options.sessioncode].end) {
                    liveflag = true;
                }
            }
            if (document.getElementById('hdnIsSemilive').value.toLowerCase() == "true") {
                playerMode = 1;
            }
            else {
                playerMode = 0;
            }
        }
        else
            playerMode = 0;
        return playerMode;
    }
    var getPlayerAbsoluteTime = function (opt) {
        var pt = 0;
        if (!opt.playeroffset) {
            opt.playeroffset = 0;
        }
        if (typeof player.currentAbsoluteTime() !== "undefined") {
            pt = player.currentAbsoluteTime();
        }
        else if (opt.streamstart) {
            var dt;
            if (opt.streamend && !player.isLive()) {
                dt = new Date(opt.streamend);
            }
            else {
                var d1 = new Date();
                dt = new Date(d1.getUTCFullYear(), (d1.getUTCMonth()), d1.getUTCDate(), d1.getUTCHours(), d1.getUTCMinutes(), d1.getUTCSeconds());
            }
            var absoulteTime = (dt.getTime() - opt.streamstart.getTime()) / 1000;
            pt = absoulteTime - (player.duration - player.currentTime1() - opt.playeroffset);
        }
        else {
            pt = player.currentTime1();
        }
        return pt;
    }
    var GetDynamicMpsEventId = function (staticMpsEventId) {
        var sessionMetadata = { mpsEventId: staticMpsEventId };
        try {
            if (typeof dynamicsession.json !== "undefined") {
                var scode = getQuerystring('scode', '').toUpperCase();
                if (playmaker.options.currentSessioncode && playmaker.options.currentSessioncode.length > 0 && playmaker.options.currentSessioncode !== options.otherAIProps.mpsEventId) {
                    sessionMetadata.mpsEventId = playmaker.options.currentSessioncode;
                    sessionMetadata.stype = dynamicsession.json[sessionCode.mpsEventId].stype;
                    sessionMetadata.sproduct = dynamicsession.json[sessionCode.mpsEventId].sproduct;
                    sessionMetadata.strack = dynamicsession.json[sessionCode.mpsEventId].strack;
                    sessionMetadata.stitle = dynamicsession.json[sessionCode.mpsEventId].stitle;
                }
                else if (scode.length > 0) {
                    sessionMetadata.mpsEventId = scode;
                    sessionMetadata.stype = dynamicsession.json[scode].stype;
                    sessionMetadata.sproduct = dynamicsession.json[scode].sproduct;
                    sessionMetadata.strack = dynamicsession.json[scode].strack;
                    sessionMetadata.stitle = dynamicsession.json[scode].stitle;
                }
                else {
                    var pt = getPlayerAbsoluteTime(dynamicsession.json.config);

                    $.each(dynamicsession.json, function (key, val) {
                        if (pt > val.st && pt <= val.et) {
                            if (val.scode) {
                                sessionMetadata.mpsEventId = val.scode;
                            }
                            else {
                                sessionMetadata.mpsEventId = key;
                            }
                            sessionMetadata.stype = val.stype;
                            sessionMetadata.sproduct = val.sproduct;
                            sessionMetadata.strack = val.strack;
                            sessionMetadata.stitle = val.stitle;
                        }
                    });
                }
            }
            options.sessioncode = sessionMetadata.mpsEventId;
            return sessionMetadata;
        }
        catch (ex) {
            return sessionMetadata;
        }
    }
    var addUsageData = function (userAlias, videoGuid, action) {
        //var request = {
        //    url: "/Video/AddUsage",
        //    type: "POST",
        //    dataType: "json",
        //    data: { UserAlias: userAlias, Podcast: videoGuid, Action: action }
        //};
        //$.ajax(request).done(onAjaxSuccess).fail(onAjaxError);
        //function onAjaxSuccess(videoAssetSas, textStatus, jqXHR) {
        //    console.log("Added Usage Data");
        //}

        //function onAjaxError(jqXHR, textStatus, errorThrown) {
        //    console.log("Error Logging Usage Data");
        //}
    }

    var checkThirdPartyAdsOptOutCookieValue = function () {
        try {
            var ThirdPartyAdsOptOutCookieName = '3PAdsOptOut';
            var cookieValue = getCookieValue(ThirdPartyAdsOptOutCookieName);
            return cookieValue != 1;
        }
        catch (error) {
            return true;
        }
};
var getCookieValue = function (cookieName) {
    var cookieValue = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
    return (cookieValue) ? cookieValue[2] : '';
    }

    function checkPostSuccess(url, callback) {
        $.ajax({
            url: url,
            type: 'POST',
            data: null,
            success: function (response) {
               // console.log("POST success");
                callback(true);
            },
            error: function (xhr, status, error) {
              //  console.log("POST failed");
                callback(false);
            }
        });
    }

    var ADappinsightcall = function (addlProps) {
        $.ajax({
            url: "/VideoStartNotifications/AdBlockerTrackCall",
            type: "POST",
            contentType: "application/json",
            data: JSON.stringify(addlProps),
            success: function (response) {
                //if (response.success === 0) {
                //   // console.log("Call tracked successfully.");
                //} else {
                //    //console.log("Unexpected response:", response);
                //}
            },
            error: function (xhr, status, error) {
                console.error("Error occurred:", error);
            }
        });  
    }


    var trackEvent = function (event, metricsObj, addlProps) {
    if (currentState == null || currentState == undefined) {
        currentState = player.isLive();
        }
        var isInIFrame = false;
    if (window.appInsights) {
        var properties = {
            StreamId: streamId || "unknown",
            PluginVersion: pluginVersion,
            PlayerVersion: player.getAmpVersion() || "unknown",
            PlaybackTech: player.currentTechName() || "unknown",
            MimeType: player.currentType() || "unknown",
            ProtectionType: currentProtectionInfo || "unkown",
            isLive: document.getElementById('hdnIsSemilive').value.toLowerCase() == "true" ? "live" : "vod" || "unknown",
            cid: getQuerystring('wt.mc_id', '') || getQuerystring('cid', '') || getQuerystring('ocid', '') || getQuerystring('icid', '') || '',
            ru: decodeURIComponent(getQuerystring('ru', '')).substring(0, 1024) || getQuerystring('referrer', '').substring(0, 1024) || document.referrer.substring(0, 1024) || '',
            ps: getPlayerState(),
            event: event,
            cdn: streamId || "unknown",
        };
        var mhid = getQuerystring('mhid', '');
        if (mhid.length > 0) {
            properties.mhid = mhid;
        }
        var uid = getQuerystring('uid', '');
        if (uid.length > 0) {
            properties.uid = uid;
        }
        if (properties.cid.length === 0) {
            properties.cid = decodeURIComponent(getQuerystring('wt.mc_id', '', properties.ru) || getQuerystring('cid', '', properties.ru) || getQuerystring('ocid', '', properties.ru) || getQuerystring('icid', '', properties.ru) || '');
        }
        // add user consent details
        try {
            if (window.parent && window.parent.window && window.parent.window.length > 0 ) {
                var consent = siteConsent.getConsent();
                if (consent) {
                    isInIFrame = true;
                    var gpc_DataSharingOptIn_Value = checkThirdPartyAdsOptOutCookieValue();
                    consent.GPC_DataSharingOptIn = gpc_DataSharingOptIn_Value;
                    consent.isManual = true;
                    consent.userConsent = gpc_DataSharingOptIn_Value;
                    if (gpc_DataSharingOptIn_Value === false) {
                        properties.trigger = "GPCDataSharing";
                    }
                    properties.consentDetails = JSON.stringify(consent);
                }
            }
        }
        catch (ex) {
        }
        if (options.otherAIProps) {
            for (var key in options.otherAIProps) {
                if (options.otherAIProps.hasOwnProperty(key)) {
                    properties[key] = options.otherAIProps[key];
                }
            }
        }
        if (typeof addlProps == 'undefined') {
            addlProps = {};
        }

        var sessionMetadata = GetDynamicMpsEventId(properties.mpsEventId);

        if (prevSessionCode.length === 0) {
            prevSessionCode = sessionMetadata.mpsEventId;
        }
        else if (prevSessionCode.length > 0 && sessionMetadata.mpsEventId !== prevSessionCode) {
            try {
                var scode = getQuerystring('scode1', '').toUpperCase();
                if (scode === prevSessionCode.toUpperCase()) {
                    window.parent.postMessage({ type: "sessionend", data: { sessionCode: prevSessionCode } }, "*");
                    console.log(prevSessionCode);
                }
                prevSessionCode = sessionMetadata.mpsEventId;
                if (dynamicsession.titleDisplay && sessionMetadata.stitle && sessionMetadata.stitle.length > 0) {
                    options.sessiontitles.push(sessionMetadata.stitle);
                    setTimeout(function () {
                        if (options.sessiontitles.length === 1) {
                            var $dt = $("#dynamictitle");
                            $dt.find(".dt-sessiontitle").html(options.sessiontitles[0]);
                            var currentTime = new Date().getTime();
                            $dt.data("expires", currentTime + (dynamicsession.titleDisplayDuration * 1000));
                            $dt.show();
                            options.sessiontitles.splice(0, 1);
                        }
                        else if (options.sessiontitles.length > 1) {
                            options.sessiontitles.splice(0, 1);
                        }

                    }, 5000)
                }
            }
            catch (ex) { }
        }
        if (dynamicsession.sessioncodeDisplay) {
            dynamicsession.sessioncodeEl.html(sessionMetadata.mpsEventId);
        }
        $.extend(properties, sessionMetadata);

        properties.ps = getPlayerState();

        properties = $.extend(properties, properties, addlProps);
        //additional logic incase loadedmetadata event hasn't fired to set streamId
        //if (!streamId) {
        //    var sourceManifest = "unknown";
        //    if (player.options_.sourceList[0]) {
        //        sourceManifest = player.options_.sourceList[0].src.split("//")[1];
        //        if (sourceManifest.match(/.ism\/manifest/i)) {
        //            sourceManifest = sourceManifest.split(/.ism\/manifest/i)[0] + ".ism/manifest"
        //        }
        //    }
        //    properties.StreamId = sourceManifest;
        //}
        properties.StreamId = oneStreamPlayer.getManifestURL() || "unknown";

        const manifestURL = oneStreamPlayer.getManifestURL();
        if (manifestURL != "undefined" && manifestURL != null) {
            if (manifestURL.includes('amsmedius.event.microsoft.com'))
                properties.cdn = 'amsmedius';
            else if (manifestURL.includes('amsmediusw-ak.studios.ms'))
                properties.cdn = 'amsmediusw';
        }

        if (typeof currentDistro != "undefined") {
            properties.cdn = currentDistro;
        }

        //additional logic incase loadedmetadata event hasn't fired to set protetction info
        //if (!currentProtectionInfo) {
        //    var protectionInfo = "unknown";
        //    if (player.options_.sourceList[0]) {
        //        if (player.options_.sourceList[0].protectionInfo) {
        //            protectionInfo = mapProtectionInfo(player.options_.sourceList[0].protectionInfo[0].type);
        //        } else {
        //            protectionInfo = "none";
        //        }
        //    }
        //    properties.ProtectionType = protectionInfo;
        //}

        if (trackSdn) {
            properties.Sdn = player.options_.sdn.name || "none";
        }

        var metrics = metricsObj || {};
        $.each(metrics, function (key, val) {
            if (isNaN(val)) {
                metrics[key] = -99;
            }
        });
        properties.cookie = navigator.cookieEnabled ? 1 : 0;
        try {
            properties.ampct = player.currentTime1().toFixed();
            if (typeof player.currentAbsoluteTime() !== "undefined") {
                properties.ampcat = player.currentAbsoluteTime().toFixed();
            }
            if (typeof player.currentMediaTime() !== "undefined") {
                properties.ampcmt = player.currentMediaTime().toFixed();
            }
        }
        catch (ex) { }
        try {
            //appInsights.trackEvent({ name: event, properties: properties, measurements: metrics });
            appInsights.trackEvent(event, properties, metrics);
            if (isInIFrame) {
                checkPostSuccess('https://dc.services.visualstudio.com/v2/track', function (result) {
                    if (result) {
                        // console.log("Post was successful");
                    } else {
                        if (event !== "buffering" && event !== "seek" && event !== "downloadfailed" && event !== "downloadcompleted") {
                            var commonProperties = Object.assign({}, properties, metrics);
                            var customId = customUserConfig.getCustomUserId();
                            if (customId.length > 0) {
                                commonProperties.UserId = customId;
                            }
                            commonProperties.URL = window && window.location && window.location.href.substring(0, 1024);
                            commonProperties.apiCall = "VOD";
                            ADappinsightcall(commonProperties);
                        }
                    }
                });
            }
        }
        catch (ex) {
            if (options.debug) {
                console.log("Error in AI's track event.");
            }
        }
        trackJSLLEvent(event, properties, metrics);
        if (options.debug) {
            console.log("sent to Application Insights...'event': " + event + "\n'properties': " + JSON.stringify(properties) + "\n'metrics': " + JSON.stringify(metrics));
        }

        if (event == "error") {
            properties.errorMessage = player.error().message;

            appInsights.trackTrace(event, properties, metrics);
            if (options.debug) {
                console.log("sent to Application Insights Error Trace...'message': " + event + "\n'properties': " + JSON.stringify(properties) + "\n'metrics': " + JSON.stringify(metrics));
            }

        }
    } else if (options.debug) {
        console.log("App Insights not detected");
    }
}

var trackJSLLEvent = function (event, properties, metrics) {
    //if (window.appInsights)
    try {
        var behaviour;
        switch (event) {
            case "loadedmetadata":
                behaviour = "VIDEPLAYERLOAD";
                break;
            case "viewed":
                behaviour = "VIDEOSTART";
                break;
            case "pause":
                behaviour = "VIDEOPAUSE";
                break;
            case "play":
                behaviour = "VIDEOCONTINUE";
                break;
            case "ended":
                behaviour = "VIDEOCOMPLETE";
                break;
            case "fullscreen":
                if (metrics.enter && metrics.enter == 1) {
                    behaviour = "VIDEOFULLSCREEN";
                }
                else if (metrics.enter && metrics.enter == 0) {
                    behaviour = "VIDEOUNFULLSCREEN";
                }
                break;
            case "buffering":
                behaviour = "VIDEOBUFFERING";
                break;
            case "captions":
                behaviour = "OTHER";
                break;
            case "mutetoggle":
                if (metrics.muted && metrics.muted == 1) {
                    behaviour = "VIDEOMUTE";
                }
                else if (metrics.muted && metrics.muted == 0) {
                    behaviour = "VIDEOUNMUTE";
                }
                break;
            case "captionsearch":
                behaviour = "OTHER";
                break;
            case "audiotracks":
                behaviour = "OTHER";
                break;
            case "downloadFailed":
                behaviour = "VIDEOERROR";
                break;
            case "error":
                behaviour = "VIDEOERROR";
                break;
            default:
                behaviour = "OTHER";
                break;
        }

        for (var key in metrics) {
            if (metrics.hasOwnProperty(key)) {
                properties[key] = metrics[key];
            }
        }
        //properties =  $.extend(properties, metrics);
        if (properties.hasOwnProperty("mpsEventId")) {
            properties.vidnm = properties.mpsEventId;
        }
        if (properties.hasOwnProperty("percentPlayed")) {
            properties.vidpct = properties.percentPlayed;
        }
        if (properties.hasOwnProperty("playTime")) {
            properties.vidwt = properties.playTime
        }
        if (properties.hasOwnProperty("ps") && properties.ps == 0) {
            properties.viddur = player.duration;
        }
        if (properties.hasOwnProperty("cid")) {
            properties.campaignid = properties.cid;
        }
        //Added to compare metrics between AI and JSLL
        try {
            properties.aiuser = appInsights.context.user.id;
            properties.aisession = appInsights.context._sessionManager.automaticSession.id;
        }
        catch (ex) { }

        contentFields = {
            field1: properties.mhid, // host id
            field2: properties.mpsSourceId,  // Source Id (Medius/MPSLExt/YouTube)                 
            field3: properties.mpsEventId, //Session ShortCode
            field4: properties.event, //action name (viewed/pbs)
            field5: properties.ps,  // Session Mode (Live(1)/OnDemand(0))
            field6: ($("meta[name='awa-pageType']").attr('content') ? $("meta[name='awa-pageType']").attr('content') : ''),
            field7: ($("meta[name='awa-track']").attr('content') ? $("meta[name='awa-track']").attr('content') : ''),
            field8: ($("meta[name='awa-product']").attr('content') ? $("meta[name='awa-product']").attr('content') : '')
        }
        $.extend(properties, contentFields);
        properties.is1ds = 1;
        properties.id = customUserConfig.newId();
        
        var overrideValues = {
            behavior: behaviour,
            actionType: "CL",
            // Can be used for custom logging
            contentTags: properties,
            pageTags: {}
        };
        var gpc_DataSharingOptIn_Value = checkThirdPartyAdsOptOutCookieValue();
        overrideValues.contentTags.apiCall = 'VOD';
        if (gpc_DataSharingOptIn_Value === false) {
            overrideValues.contentTags.trigger = "GPCDataSharing";
          }
        mpsonedsanalytics.capturePageAction(null, overrideValues);
        //Post events to Parent Page
        try {
            window.parent.postMessage({ type: "jsll", data: overrideValues }, "*");
        }
        catch (ex) { }
    }
    catch (ex) {
        //appInsights.trackEvent({ name: 'jsllerror', properties: properties, measurements: {} });
        appInsights.trackEvent("jsllerror", properties);
        if (options.debug) {
            console.log("Error in logging JSLL events");
        }
    }
}

//add event listeners for tracking
player.addEventListener("sourceset", sourceset);
player.addEventListener("loadedmetadata", loaded);
player.addEventListener("canplaythrough", canplaythrough);
player.addEventListener("mute", function () { muteToggle(); });
player.addEventListener("unmute", function () { muteToggle(); });
if (metricsToTrack.bitrateQuality || metricsToTrack.downloadInfo || metricsToTrack.playbackSummary) {
    //does this double send on a change source?
    player.addEventListener("loadedmetadata", function () {
        download.videoBuffer = player.videoBufferData();
        if (download.videoBuffer) {
            download.videoBuffer.addEventListener("downloadcompleted", function () { download.completed() });
            download.videoBuffer.addEventListener("downloadfailed", function () { download.failed("video") });

        }
        download.audioBuffer = player.audioBufferData();
        if (download.audioBuffer) {
            download.audioBuffer.addEventListener("downloadfailed", function () { download.failed("audio") });
        }
    });
}

if (metricsToTrack.percentsPlayed || metricsToTrack.bitrateQuality || metricsToTrack.playbackSummary || metricsToTrack.playTime) {
    player.addEventListener("timeupdate", timeupdate);
}

player.addEventListener("playing", playing);
if (metricsToTrack.playTime || metricsToTrack.bitrateQuality || metricsToTrack.playbackSummary) {
    window.addEventListener("beforeunload", exit, false);
    window.addEventListener("pagehide", exit, false);
    //check dispose to send data
    player.tempDispose = player.dispose;
    player.dispose = function () {
        unloadData();
        player.tempDispose();
    }
}
if (metricsToTrack.error || metricsToTrack.playTime || metricsToTrack.playbackSummary) {
    player.addEventListener("error", error);
}
if (metricsToTrack.end || metricsToTrack.playTime || metricsToTrack.playbackSummary) {
    player.addEventListener("ended", end);
}
if (metricsToTrack.play) {
    player.addEventListener("play", play);
}
if (metricsToTrack.pause || metricsToTrack.playTime || metricsToTrack.buffering || metricsToTrack.playbackSummary) {
    player.addEventListener("pause", pause);
}
if (metricsToTrack.buffering || metricsToTrack.playbackSummary) {
    player.addEventListener("waiting", waiting);
}
if (metricsToTrack.buffering || metricsToTrack.seek || metricsToTrack.playbackSummary) {
    player.addEventListener("seeked", seek);
}
if (metricsToTrack.fullscreen) {
    player.addEventListener("fullscreenchange", fullscreen);
}
if (metricsToTrack.volumechange) {
    player.addEventListener("volumechange", volumechange);
}
if (metricsToTrack.mutetoggle) {
    $(".shaka-mute-button").mousedown(function () { muteToggle(); });
}
if (metricsToTrack.captionsearch) {
    captionSearch();
}

$('body').on('click', '.mps_track', function () {
    var linkName = ($(this).attr('title') ? $(this).attr('title') : $(this).text());
    if (linkName.length == 0 && $(this).find("img").length > 0) {
        linkName = ($(this).find("img").attr('alt') ? $(this).find("img").attr('alt') : "");
    }
    var linkUrl = ($(this).attr('href') ? $(this).attr('href') : '');
    var props = {};
    props.linkName = linkName;
    props.linkUrl = linkUrl;
    props.pageUrl = window.location.href;
    props.aitl = linkName;
    props.tu = linkUrl
    props.cg = ($(this).attr('data-category') ? $(this).attr('data-category') : '');
    trackEvent('lc', {}, props);
});

if (metricsToTrack.downloadResource) {
    downloadResource();
}
if (metricsToTrack.share) {
    share();
}
if (metricsToTrack.audiotracks) {
    var audiotracksCheckCount = 0
    audiotracksInterval = setInterval(function () {
        var audiotracksLinks = document.querySelectorAll(".amp-audiotracks-control .vjs-menu-item");
        if (audiotracksLinks.length > 0) {
            for (var i = 0; i < audiotracksLinks.length; i++) {
                clearInterval(audiotracksInterval);
                audiotracksLinks[i].addEventListener("mousedown", function () {
                    trackEvent('at', {}, { language: $(this).text() });
                });
            }
        }
        else if (audiotracksCheckCount < 120) //Check for ten minutes
        {
            audiotracksCheckCount++;
        }
        else {
            clearInterval(audiotracksInterval);
        }
    }, 5000);
}
//$('body').on("mousedown", ".asl_button .shaka-menu-item", function () {
//    var $this = $(this);
//    var text = $this.text().trim();
//    var controltext = $this.find(".vjs-control-text").text();
//    text = text.replace(controltext, '')
//    var props = {};
//    props.linkName = text;
//    props.aitl = text;
//    props.cg = "ASL";
//    trackEvent('lc', {}, props);
//    linkClick(trackEvent);

//});
if (metricsToTrack.captions) {
    var captionclickevent = function ($this) {
        var language = $this.text().trim();
        var controltext = $this.find(".vjs-control-text").text();
        language = language.replace(controltext, '');
        if (language.toLowerCase().indexOf("settings") === -1) {
            trackEvent('cc', {}, { language: language, aitl: language, cg: "Caption" });
        }
    }
    $('body').on("mousedown", ".amp-closedcaption-control .vjs-menu-item", function () {
        captionclickevent($(this));
    });
    $('body').on("touchstart", ".amp-closedcaption-control .vjs-menu-item", function () {
        captionclickevent($(this));
    });

    $('body').on("mousedown", ".amp-subtitles-control .vjs-menu-item", function () {
        captionclickevent($(this));
    });

    $('body').on("touchstart", ".amp-subtitles-control .vjs-menu-item", function () {
        captionclickevent($(this));
    });
}
linkClick(trackEvent);
}
//});

//}).call(this);
var clearAnalyticsInterval = setInterval(function () {
    try {
        if (typeof oneStreamPlayer != "undefined") {
            clearInterval(clearAnalyticsInterval);
            //if (config.captions && config.captions.captionStream) {           
            let hdnMpsChannel = document.getElementById('hdnMpsChannel').value;
            let hdnVideoId = document.getElementById('hdnVideoId').value;
            let hdnMpsEventId = document.getElementById('hdnMpsEventId').value;
            var opt = {
                percentsPlayedInterval: 10,
                timeUpdateInterval: 25,
                otherAIProps: {
                    mpsChannel: hdnMpsChannel,
                    videoId: hdnVideoId,
                    mpsEventId: hdnMpsEventId,
                    mpsSourceId: "Medius"
                }
            }
            mpsaResolve(opt);
            //}
        }
    }
    catch (ex) {
        console.log(ex);
    }

}, 1000);

function ReadTrackedInterval(name) {
    var pbsTrackedInterval = {
        playTime: [],
        playPercentage: []
    }
    try {
        if (typeof (localStorage) !== "undefined") {
            var pbsInterval = localStorage.getItem(customUserConfig.pbs.pbsInterval);
            if (pbsInterval != null) {
                pbsInterval = JSON.parse(pbsInterval);
                if (pbsInterval[name]) {
                    var alreadyTracked = pbsInterval[name];
                    if (alreadyTracked.playTime) {
                        pbsTrackedInterval.playTime = alreadyTracked.playTime;
                    }
                    if (alreadyTracked.playPercentage) {
                        pbsTrackedInterval.playPercentage = alreadyTracked.playPercentage;
                    }
                }
            }
        }
    }
    catch (ex) { }
    return pbsTrackedInterval;
}

function updateTrackedInterval(name, playTime, playPercentage) {
    try {
        if (typeof (localStorage) !== "undefined") {
            var pbsInterval = localStorage.getItem(customUserConfig.pbs.pbsInterval);
            if (pbsInterval == null) {
                pbsInterval = {}
            }
            else {
                pbsInterval = JSON.parse(pbsInterval);
            }
            pbsInterval[name] = {
                playTime: playTime,
                playPercentage: playPercentage,
                expires: customUserConfig.addDays(customUserConfig.pbs.duration)
            }
            updateLocalStorageForTrackedInterval(pbsInterval, 0);
        }
    }
    catch (ex) { }
}
var retryCountLS = 0
function updateLocalStorageForTrackedInterval(pbsInterval, noOfDays) {
    try {
        $.each(pbsInterval, function (key, item) {
            if (item.expires && new Date(item.expires) < customUserConfig.addDays(noOfDays)) {
                delete pbsInterval[key];
            }
        });
        window.localStorage.setItem(customUserConfig.pbs.pbsInterval, JSON.stringify(pbsInterval));
    }
    catch (ex) {
        if (ex.message == "QuotaExceededError" && retryCountLS < customUserConfig.pbs.duration) {
            retryCountLS++;
            updateLocalStorageForTrackedInterval(pbsInterval, retryCountLS)
        }
    }
}

//$(function () {
//    //added for Build  2018 event
//    var sendPageChangeMessage = function () {
//        console.log("player height:", $('body').outerHeight(true));
//        parent.postMessage({ type: "height", data: $('body').outerHeight(true) }, '*');
//        setTimeout(function () {
//            console.log("player height after 500:", $('body').outerHeight(true));
//            parent.postMessage({ type: "height", data: $('body').outerHeight(true) }, '*');
//        }, 500);
//        setTimeout(function () {
//            console.log("player height after 1000:", $('body').outerHeight(true));
//            parent.postMessage({ type: "height", data: $('body').outerHeight(true) }, '*');
//        }, 1000);                                //this one is really just a cleanup for ie8
//        setTimeout(function () {
//            console.log("player height after 3000:", $('body').outerHeight(true));
//            parent.postMessage({ type: "height", data: $('body').outerHeight(true) }, '*');
//        }, 30000);                             //cleanup again, just to make sure
//    };
//    $(window).resize(function () {
//        sendPageChangeMessage();
//    });
//    sendPageChangeMessage();
//});

var customClickControls = [
    {
        cat: "Audio Track",
        el: ".language_custom_scrub_menu",
        child: ".shaka-menu-item"
    },
    {
        cat: "Sign Languages",
        el: ".asl_button",
        child: ".shaka-menu-item"
    },
    {
        cat: "Sign Languages",
        el: ".asl_button",
        child: ""
    },
    {
        cat: "Rewind",
        el: ".custom_rewind",
        child: ""
    },
    {
        cat: "Forward",
        el: ".forward",
        child: ""
    },
    {
        cat: "Searchable transcripts",
        el: ".searchable_captions",
        child: ""
    },
    {
        cat: "Searchable transcripts",
        el: ".search-menu-content",
        child: ".shaka-menu-item"
    },
    {
        cat: "Play Button",
        el: ".shaka-small-play-button",
        child: ""
    },
    // Bug 130092: Medius - Shaka player - Track call Issue - captions
    {
        cat: "Captions Button",
        el: ".ios-caption-btn",
        child: ""
    },
    {
        cat: "Captions Button",
        el: ".custom-caption-overflow",
        child: ""
    },
    {
        cat: "Captions Submenu item",
        el: ".caption_submenu",
        child: "li"
    },
    // Bug 130092: Medius - Shaka player - Track call Issue - captions
    {
        cat: "Captions",
        el: ".shaka-caption-button",
        child: "button"
    },
    {
        cat: "Captions",
        el: ".close-container",
        child: ""
    },
    {
        cat: "Captions",
        el: ".shaka-caption-button",
        child: ""
    },
    {
        cat: "Full screen",
        el: ".shaka-fullscreen-button",
        child: ""
    },
    {
        cat: "Social Share",
        el: ".social-container",
        child: ".copy-icon"
    },
    {
        cat: "Social Share",
        el: ".checkbox-container",
        child: ""
    },
    {
        cat: "Social Share",
        el: ".shaka-share-submenu",
        child: ".close-btn"
    },
    {
        cat: "Social Share",
        el: ".share",
        child: ""
    },
    {
        cat: "playback speed",
        el: ".shaka-playbackrate-button",
        child: ""
    },
    {
        cat: "playback speed Rates",
        el: ".shaka-playback-rates",
        child: "button"

    },
    {
        cat: "Picture in Picture",
        el: ".shaka-pip-button",
        child: ""
    },
    {
        cat: "Resolution",
        el: ".shaka-resolution-button",
        child: ""
    },
    {
        cat: "Resolution selected",
        el: ".shaka-resolutions",
        child: ".explicit-resolution"
    },
    {
        cat: "Resolution Backbutton",
        el: ".shaka-resolutions",
        child: ".shaka-back-to-overflow-button"
    },
    {
        cat: "Captions Settings button",
        el: ".button-container",
        child: ".controls-btn"
    },
    {
        cat: "More Settings",
        el: ".shaka-overflow-menu-button",
        child: ""
    },
    {
        cat: "Chapters",
        el: ".chapters_menu",
        child: ".shaka-menu-item"

    },
    {
        cat: "Chapters",
        el: ".chapters_menu",
        child: ""

    },
    {
        cat: "Mute",
        el: ".shaka-mute-button",
        child: ""

    },
    {
        cat: "Settings",
        el: ".shaka-caption-settings-submenu",
        child: "button"
    },

    //MVP Controls:18-Jun-2025
       {
        cat: "Audio Track",
        el: ".mvp-audio-menu .mvp-sub-menu-items-div",
        child: "button"
    },
    {
        cat: "Sign Languages",
        el: ".mvp-sign-menu .mvp-sub-menu-items-div",
        child: "button"
    },
    {
        cat: "Captions Button",
        el: ".shaka-captionaudiosign-button",
        child: ""
    },
    {
        cat: "Captions Submenu item",
        el: ".mvp-captions-menu .mvp-sub-menu-items-div",
        child: "button"
    },
    {
        cat: "Captions",
        el: ".mvp-close-menu",
        child: ""
    },
    {
        cat: "Resolution",
        el: ".span-videoQuality-control",
        child: ""
    },
    {
        cat: "keyboardshortcuts",
        el: ".span-keyboardshortcuts-control",
        child: ""
    },
    {
        cat: "Caption Settings",
        el: ".span-captionsettings-control",
        child: ""
    },
    {
        cat: "keyboardshortcuts",
        el: ".shaka-keyboardShortcut-button.overflow",
        child: ""
    },
    {
        cat: "Resolution selected",
        el: ".shaka-resolutions .mvp-sub-menu-items-div",
        child: "button"
    },
    {
        cat: "playback speed Rates",
        el: ".shaka-playback.mvp-ctrl-overflow-sub-menu .mvp-sub-menu-items-div",
        child: "button"

    },
    {
        cat: "More Settings",
        el: ".shaka-overflow-menu .mvp-sub-menu-items-div",
        child: "button.captionSettings.overflow, button.chapters.overflow, button.resources.overflow"
    },
    {
        cat: "More Settings Close",
        el: ".shaka-overflow-menu .mvp-menu-header-div",
        child: "button"
    },
    {
        cat: "Adjust Settings",
        el: ".shaka-adjustSettings-button",
        child: ""
    },
    {
        cat: "Back button",
        el: ".mvp-ctrl-back-close-icon-span",
        child: ""
    },
    {
        cat: "Close button",
        el: ".button.mvp-ctrl-back-close-icon-span.mvp-cls-btn",
        child: ""
    },
    {
        cat: "Chapters",
        el: ".chapters-custom-menu-mobile .mvp-sub-menu-items-div",
        child: "button"

    }
];

var linkClick = function (trackEvent) {
    var elClass;
    for (var i = 0; i < customClickControls.length; i++) {
        var item = customClickControls[i];
        $(item.el).attr("aria-category", item.cat);
        elClass = item.el;

        if (item.child) {
            elClass += ' ' + item.child;
        }
        $(document).on('mousedown', elClass, function (e) {
            e.preventDefault();
            e.stopPropagation();
            linkClickTrack($(this), trackEvent);


        });
        $(document).on('touchstart', elClass, function (e) {
            e.preventDefault();
            e.stopPropagation();
            linkClickTrack($(this), trackEvent);
        });
    }
}

function linkClickTrack($this, trackEvent) {
    var linkName = ($this.attr('aria-label') ? $this.attr('aria-label') : $this.attr('title'));
    if (typeof linkName == "undefined" || linkName.length == 0) {
        //Bug 106138: Getting incorrect aitl values for Audio Track in SHAKA player
        var linkName = $this.context.innerText;
    }
    if (linkName.length == 0 && $this.find("img").length > 0) {
        linkName = ($this.find("img").attr('alt') ? $this.find("img").attr('alt') : "");
    }
    if (linkName == 'Include URL location') {
        if ($this.find(":checkbox").is(":checked"))
            linkName = 'Uncheck ' + linkName;
        else
            linkName = 'Check ' + linkName;
    }
    let newlinkName = linkName;
    if ($this.closest(".mvp-close-menu").length > 0) {
        const ariaLabel = $this.closest(".mvp-close-menu").find(".mvp-cls-btn").attr("aria-label");
        if (ariaLabel) {
            newlinkName = ariaLabel;
        }
    }
    if ($this.hasClass("mvp-ctrl-back-close-icon-span") && $this.hasClass("mvp-cls-btn")) {
        const dataAction = $this.attr('data-action');
        if (dataAction) {
            newlinkName = dataAction;
        } else if ($this.closest('button').length > 0) {
            const closestDataAction = $this.closest('button').attr('data-action');
            if (closestDataAction) {
                newlinkName = closestDataAction;
            }
        }
    } else if ($this.hasClass("mvp-ctrl-back-close-icon-span")) {
        const dataAction = $this.attr('data-action');
        if (dataAction) {
            newlinkName = dataAction;
        }
    }
    linkName = newlinkName;

    var linkUrl = ($this.attr('href') ? $this.attr('href') : '');
    var props = {};
    props.pageUrl = window.location.href;
    props.aitl = linkName;
    props.tu = linkUrl;
    props.cg = '';

    let $menuHeader;
    if ($this.is("span.mvp-ctrl-label")) {
        $menuHeader = $this;
    }
    else if ($this.closest(".mvp-menu-header-l2-div").length > 0) {
        $menuHeader = $this.closest(".mvp-menu-header-l2-div").find("span.mvp-ctrl-label");
    }
    else if ($this.closest(".mvp-sub-menu-items-div").length > 0) {
        $menuHeader = $this.closest(".mvp-sub-menu-items-div")
            .parent()
            .find(".mvp-menu-header-l2-div span.mvp-ctrl-label");
    }
    if ($this.attr('aria-category'))
        props.cg = $this.attr('aria-category')
    else if ($this.closest(".ios-caption-btn").length > 0)
        props.cg = $this.closest(".ios-caption-btn").attr('title');
    else if ($this.closest(".custom-caption-overflow").length > 0)
        props.cg = $this.find("span").first().text();
    else if ($this.closest(".caption_submenu").length > 0)
        props.cg = $this.closest(".caption_submenu ul").children().first().attr('aria-label');
    else if ($this.closest(".span-keyboardshortcuts-control").length > 0 || $this.closest(".span-captionsettings-control").length > 0 || $this.closest(".span-videoQuality-control").length > 0)
        props.cg = $this.attr('aria-label');
    else if ($this.hasClass("mvp-cls-btn") && $this.closest(".mvp-menu-header-div").length > 0 && $this.closest(".mvp-menu-header-div").closest(".shaka-overflow-menu").length > 0) {
        const $menuHeaderDiv = $this.closest(".mvp-menu-header-div");
        if ($menuHeaderDiv.closest(".shaka-overflow-menu").length > 0) {
            const ariaLabel = $menuHeaderDiv.find("span.mvp-ctrl-label").attr("aria-label");
            if (ariaLabel) {
                props.cg = ariaLabel.trim();
            }
        }
    }
    else if ($menuHeader && (($menuHeader.length && $menuHeader.text().trim() !== "") || $this.hasClass("mvp-ctrl-back-close-icon-span"))) {
            if ($this.hasClass("mvp-ctrl-back-close-icon-span") && !$this.hasClass("mvp-cls-btn"))
                props.cg = $menuHeader.text().trim() + " " + linkName;
            else props.cg = $menuHeader.text().trim();
    }
    else if ($this.closest(".mvp-captions-menu").length > 0) {
        props.cg = $this.closest(".mvp-captions-menu").find(".mvp-menu-header-div span.mvp-ctrl-label").attr('aria-label');
    }
    else if ($this.closest(".mvp-audio-menu").length > 0)
        props.cg = $this.closest(".mvp-audio-menu").find(".mvp-menu-header-div span.mvp-ctrl-label").attr('aria-label');
    else if ($this.closest(".mvp-sign-menu").length > 0) {
        props.cg = $this.closest(".mvp-sign-menu").find(".mvp-menu-header-div span.mvp-ctrl-label").attr('data-action');
    }
    else if ($this.closest(".control-button").length > 0)
        props.cg = $this.closest(".control-button").attr('aria-label');
    else if ($this.closest(".shaka-settings-menu").length > 0)
        props.cg = $this.closest(".shaka-settings-menu").find('button').eq(0).find('span').text();
    else if ($this.closest(".shaka-caption-settings-submenu").length > 0)
        props.cg = $this.closest(".shaka-caption-settings-submenu").attr('aria-describedby');
    if (props.cg == '')
        props.cg = linkName
    trackEvent('lc', {}, props);
};
function ShakaAudioLanguages(config) {

    if (!config.audioTracks) {
        config.audioTracks = {
            "default": "en",
            "orderby": "asc",
            "customLanguages": {
                "aud": "Audio Description"
            }
        };
    }

    let adValue = getAdValue();
    if (adValue) {
        window.localStorage.setItem('osp_audioTrack', adValue);
        config.audioTracks.default = adValue;
        console.log(config.audioTracks.default);
    }

    //function to map user defined audio language to the keys
    function getUserCultureAudioLanguage(adLang) {
        try {
            var userAudioLang = [
                { langKey: "en", langValue: "English" },
                { langKey: "fr", langValue: "French" },
                { langKey: "de", langValue: "German" },
                { langKey: "es", langValue: "Spanish" },
                { langKey: "ja", langValue: "Japanese" },
                { langKey: "pl", langValue: "Polish" },
                { langKey: "it", langValue: "Italian" },
                { langKey: "gr", langValue: "Greek" },
                { langKey: "zh-hans", langValue: "Chinese simplified" },
                { langKey: "cmn", langValue: "Mandarin" },
                { langKey: "cm", langValue: "Mandarin" },
                { langKey: "yue", langValue: "Cantonese" },
                { langKey: "yu", langValue: "Cantonese" }
               
            ];

            var lang = userAudioLang.find(x => x.langValue.toLowerCase() === adLang.toLowerCase());
            return lang ? lang.langKey : null;
        } catch (ex) {
            console.error("Error in getUserCultureAudioLanguage:", ex);
            return null;
        }
    }

    //function to get audio language value from query string
    function getAdValue() {
        try {
            var ad = getQuerystring("ad");
            if (ad) {
                return getUserCultureAudioLanguage(ad);
            }
            else {
                return null;
            }
        } catch (ex) {
            console.error("Error in getAdValue:", ex);
            return null;
        }
    }

    //function to extract query string parameters from url
    function getQuerystring(key, default_) {
        if (default_ == null) default_ = "";
        key = key.replace(/[\\[]/g, "\\\[").replace(/[\]]/g, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href.toLowerCase());
        if (qs == null)
            return default_;
        else
            return qs[1];
    }
}
;
