/* Minification failed. Returning unminified contents.
(133,29-30): run-time error JS1195: Expected expression: )
(133,32-33): run-time error JS1195: Expected expression: >
(135,18-19): run-time error JS1195: Expected expression: ,
(138,9-10): run-time error JS1006: Expected ')': }
(141,35-36): run-time error JS1004: Expected ';': {
(201,5-6): run-time error JS1002: Syntax error: }
(205,12-13): run-time error JS1195: Expected expression: )
(205,14-15): run-time error JS1004: Expected ';': {
(423,2-3): run-time error JS1195: Expected expression: )
(424,12-13): run-time error JS1195: Expected expression: )
(424,14-15): run-time error JS1004: Expected ';': {
(480,2-3): run-time error JS1195: Expected expression: )
(481,12-13): run-time error JS1195: Expected expression: )
(481,14-15): run-time error JS1004: Expected ';': {
(1120,2-3): run-time error JS1195: Expected expression: )
(1121,12-13): run-time error JS1195: Expected expression: )
(1121,14-15): run-time error JS1004: Expected ';': {
(1322,2-3): run-time error JS1195: Expected expression: )
(1323,2-10): run-time error JS1197: Too many errors. The file might not be a JavaScript file: function
 */
(function () {
    amp.plugin('apsKeyPoints', function (options) {
        // remember the video player instance
        var vidPlayer = this;
        var userGUIDKey = '';
        var hasCTALimit = false;

        // the key points array is passed in the options
        var keyPointsArray = options.options.kp;

        // dynamically create the kep point containers
        var vidContainer = $("#" + this.id());
        var keyPointHtml = "<div id='videoTop-Left' class='apsKeyPointRegion'/><div id='videoTop-Right' class='apsKeyPointRegion'/><div id='videoTop-Mid' class='apsKeyPointRegion'/><div id='videoBottom-Left' class='apsKeyPointRegion'/><div id='videoBottom-Right' class='apsKeyPointRegion'/><div id='videoBottom-Mid' class='apsKeyPointRegion'/><div id='videoMid-Left' class='apsKeyPointRegion'/><div id='videoMid-Right' class='apsKeyPointRegion'/><div id='videoMid-Mid' class='apsKeyPointRegion'/><div id='videoFull' class='apsKeyPointRegion'/>";
        vidContainer.append(keyPointHtml);

        // loadstart is the earliest event we can hook, use it to initialize our plugin
        vidPlayer.addEventListener(amp.eventName.loadstart, function () {
            console.log("player is ready!");
        });

        // hook the timeupdate to get the current playback time
        vidPlayer.addEventListener(amp.eventName.timeupdate, function () {
            // get the current time
            var videoPosition = vidPlayer.currentTime();
            // loop through the list of keypoints to see what keypoints should be shown at this time
            for (var i = 0; i < keyPointsArray.length; i++) {
                // see if this keypoint should be shown at this time
                if (videoPosition >= keyPointsArray[i].timeStart && videoPosition <= keyPointsArray[i].timeEnd) {
                    // it should, see if it is already showing
                    if (!keyPointsArray[i].isDisplayed) {
                        // Availability of CTA Discount Coupon
                        userGUIDKey = keyPointsArray[i].UserKeyGUID;
                        hasCTALimit = keyPointsArray[i].CTALimit;
                        if (validateCTALimit(keyPointsArray[i])) {
                            // it is not, mark it as showing
                            keyPointsArray[i].isDisplayed = true;
                            // show it
                            showKeyPoint(keyPointsArray[i]);
                        }
                    }
                } else {
                    // this keypoint should not be shown at this time, see if it is showing
                    if (keyPointsArray[i].isDisplayed) {
                        // it is showing, hide it and rememeber we hid it
                        hideKeyPoint(keyPointsArray[i]);
                        keyPointsArray[i].isDisplayed = false;
                    }
                }
            }
        });
        // show a keypoint item in the required container
        function showKeyPoint(kp) {
            if (kp.type == "Text") {
                var span = document.createElement('span');
                span.innerHTML = String(kp.text);
                var LinkText = span.textContent || span.innerText;
                var LinkHref = "";
                if (span.innerHTML.match(/href="([^"]*)/) != null) {
                    LinkHref = span.innerHTML.match(/href="([^"]*)/)[1];
                }
                // it is text, show the text in the corresponding location
                var closeKp = $('<dt style="position: absolute;right: 0;top: 0;font-size: 10px;padding-right: 3px;cursor: pointer;" tabIndex="0">☓</dt>')
                closeKp.click(function () {
                    var generatedProps = {
                        tu: LinkHref,
                        rg: "Player",
                        aitl: LinkText,
                        cg: 'CTA closed'
                    }
                    var objecttoSend = {};
                    objecttoSend.properties = generatedProps;
                    mediusAnalytics.sendTrackingdata(objecttoSend);
                    hideKeyPoint(kp);             
                  
                                });
                closeKp.keydown(function () {
                    if (event.which === 13) {
                        var generatedProps = {
                            tu: LinkHref,
                            rg: "Player",
                            aitl: LinkText,
                            cg: 'CTA closed'
                        }
                        var objecttoSend = {};
                        objecttoSend.properties = generatedProps;
                        mediusAnalytics.sendTrackingdata(objecttoSend);
                        hideKeyPoint(kp);
                    }
                })
                var kptext = $('<div style="opacity:1;padding: 0 16px;margin: 0px;font-size: 16px;text-shadow: 2px 2px #000000;font-family: Segoe UI;font-size: 14px;font-style: normal;font-variant: normal;font-weight: 400;line-height: 19.99px;">' + kp.text + '</div>');
                $("#video" + kp.position).append(closeKp);
                $("#video" + kp.position).append(kptext);
                kptext.click(function () {
                    var generatedProps = {
                        tu: LinkHref,
                        rg: "Player",
                        aitl: LinkText,
                        cg: 'CTA clicked'
                    }
                    var objecttoSend = {};
                    objecttoSend.properties = generatedProps;
                    mediusAnalytics.sendTrackingdata(objecttoSend);
                });
                kptext.keydown(function () {
                    if (event.which === 13) {
                        var generatedProps = {
                            tu: LinkHref,
                            rg: "Player",
                            aitl: LinkText,
                            cg: 'CTA clicked'
                        }
                        var objecttoSend = {};
                        objecttoSend.properties = generatedProps;
                        mediusAnalytics.sendTrackingdata(objecttoSend);
                    }
                });
                var generatedProps = {
                    tu: LinkHref,
                    rg: "Player",
                    aitl: LinkText,
                    cg: 'CTA Viewed'
                }
                var objecttoSend = {};
                objecttoSend.properties = generatedProps;
                mediusAnalytics.sendTrackingdata(objecttoSend);
                $("#video" + kp.position).show();
            }
            else if (kp.type == "Iframe") {
                $("#video" + kp.position).html('<iframe src="' + kp.link + '" style="width:100%; height: 100%;"></iframe>');
                $("#video" + kp.position).show();
            }
            else if (kp.type == "Parent Redirect") {
                setTimeout(() => {
                    window.top.location.href = kp.link;
                }, 50);

            }
        }

        // hide a keypoint item in the required container
        function hideKeyPoint(kp) {
            // remove the contents
            $("#video" + kp.position).html("");
            // hide the div
            $("#video" + kp.position).hide();
        }

        // Validate CTA discount coupon limit
        function validateCTALimit(kp) {
            var isShowKypoint = false;
            var ctaLimit = kp.CTALimit;
            
            if (!ctaLimit) {
                isShowKypoint = true;
            }
            else {
                var ctaLimitCount = parseInt(kp.CTACount);
                var currentCtaCount = parseInt(kp.CurrentCTACount);
                var isUserRestricted = kp.UserRestricted;
                var userKey = kp.UserKeyGUID;
                if (currentCtaCount < ctaLimitCount) {
                    if (isUserRestricted) {
                        isShowKypoint = localStorage.getItem(userKey) == undefined ? true : false;
                    }
                    else {
                        isShowKypoint = true;
                    }
                }
                else {
                    localStorage.removeItem(userGUIDKey);
                }
            }
            return isShowKypoint;
        }

        // Discount coupon link click event
        $(document).on('click', 'a.discount', function (e) {
            e.preventDefault();
            if (hasCTALimit) {
                $(".apsKeyPointRegion:visible").hide();
                var vid = $("#hdnVideoId").val();
                var token = $('input[name="__RequestVerificationToken"]').val();
                mediusCommon.executeXHR({
                    url: "/Video/UpdateCTACountKeypoint",
                    contentType: 'application/x-www-form-urlencoded',
                    asyncCall: true,
                    method: "POST",
                    data: { __RequestVerificationToken: token, videoId: vid }
                }).promise().then(function (data) {
                    if (data.Success) {
                        console.log('Updated CTA Count');
                        if (userGUIDKey != '' || userGUIDKey != undefined) {
                            localStorage.setItem(userGUIDKey, Math.random().toString(36).slice(2));
                        }
                    }
                }, function (err) {
                    console.log(err);
                });
            }
        });
    });
}).call(this);

;
(function () {

    amp.plugin('postRoll', function (options) {
        var player = this;
        var rollHtml = null;
        var linksnRecommend = null;

        player.addEventListener(amp.eventName.loadeddata, loadPostRoll.bind(this));
        player.addEventListener(amp.eventName.ended, unHideRoll.bind(this));
        player.addEventListener(amp.eventName.ended, attachLinks);

        function loadPostRoll() {
            var vidContainer = $("#" + this.id());
            getPostroll();
            if (options.options.pr.type === "Recommendations &amp; Links") {
                vidContainer.append(linksnRecommend);
                $("#basicsRecommendRow").append(rollHtml);
                $("#recommendRow").addClass("links-and-roll");
            }
            else {
                vidContainer.append(rollHtml);
            }
        }

        function getPostroll() {
            switch (options.options.pr.type) {
                case "Basic Links Only": getBasicLinks()
                    break;
                case "Recommendations": getRecommendation();
                    break;
                case "Recommendations &amp; Links": getRecommendationAndLink();
                    break;
                default:
                    break;
            }
        }

        function loadRecommendation(divToAppend) {
            rollHtml = $(divToAppend);
            id = $("#videoid").val();
            rollHtml.load("/Embed/PostRoll/" + id);
        }

        function getRecommendation() {
            rollHtml = $("<div id='recommendDiv' class='preroll-overlay displayNone'></div>");
            loadRecommendation(rollHtml);
        }

        function getBasicLinks() {
            var body = '<div id="basicsDiv" class="container preroll-overlay displayNone container-custom-postroll"><div class="row" id="basicsRow"><div class="ctaheaderInLink"><h3 class="postRollHeaderCTA">Call To Action Title</h3></div>';
            for (var item in options.options.pr.actions) {
                var href = "";
                if (String(options.options.pr.actions[item]).match(/href="([^"]*)/) != null) {
                    href = String(options.options.pr.actions[item]).match(/href="([^"]*)/)[1];
                }
                body += "<div class='col-xs-3 basic-links-section'>";
                body += "<p data-ai='true' class='recommLinkOnCTAoverlay' data-eleregion='Player' data-catagory='CTA Link clicked' data-tu='' title='" + href + "'>" + options.options.pr.actions[item] + "</p></div>";
            }
            body += "</div></div>";
            rollHtml = body;
        }

        function getRecommendationAndLink() {
            var href = "";
            if (String(options.options.pr.actions).match(/href="([^"]*)/) != null) {
                href = String(options.options.pr.actions).match(/href="([^"]*)/)[1];
            }
            loadRecommendation("<div class='col-xs-7'></div>");
            var body = '<div id="basicsRecommendDiv" class="container preroll-overlay displayNone container-custom-postroll"><div class="row" id="basicsRecommendRow"><div class="ctaheaderInLink"><h3 class="postRollHeaderCTA">Call To Action Title</h3></div>';
            body += "<div class='col-xs-3 basic-links-section'>";
            body += "<p data-ai='true' class='recommLinkOnCTAoverlay' data-eleregion='Player' data-catagory='CTA Link clicked' data-tu='' title='" + href + "'>" + options.options.pr.actions + "</p></div>";
            body += "</div></div>";

            linksnRecommend = body;
        }

        function unHideRoll() {
            $("#recommendDiv").removeClass("displayNone");
            $("#basicsDiv").removeClass("displayNone");
            $("#basicsRecommendDiv").removeClass("displayNone");
        }

        function attachLinks() {
            $('#recommendRow').focus();
            $(document).on('click', '.playPrePost', function () {
                var id = $(this).attr('id');
                var url_patch = window.location.pathname.split('/');
                window.location = "/" + url_patch[1] + "/" + url_patch[2] + "/" + id;
            });
            $(document).on('keydown', '.playPrePost', function () {
                if (event.which === 13) {
                    var id = $(this).attr('id');
                    var url_patch = window.location.pathname.split('/');
                    window.location = "/" + url_patch[1] + "/" + url_patch[2] + "/" + id;
                }
            });
            $(document).on('click', '.recommLinkOnCTAoverlay', function () {
                var generatedProps = {
                    tu: $(".recommLinkOnCTAoverlay").attr("title"),
                    rg: "Player",
                    aitl: $(".recommLinkOnCTAoverlay").text(),
                    cg: 'CTA clicked'
                }
                var objecttoSend = {};
                objecttoSend.properties = generatedProps;
                mediusAnalytics.sendTrackingdata(objecttoSend);
            });
            $(document).on('keydown', '.recommLinkOnCTAoverlay', function () {
                if (event.which === 13) {
                    var generatedProps = {
                        tu: $(".recommLinkOnCTAoverlay").attr("title"),
                        rg: "Player",
                        aitl: $(".recommLinkOnCTAoverlay").text(),
                        cg: 'CTA clicked'
                    }
                    var objecttoSend = {};
                    objecttoSend.properties = generatedProps;
                    mediusAnalytics.sendTrackingdata(objecttoSend);
                }
            });
            var AllTexts = "";
            var AllHrefs = "";
            for (var item in options.options.pr.actions) {

                var span = document.createElement('span');
                span.innerHTML = String(options.options.pr.actions[item]);
                var LinkText = span.textContent || span.innerText;
                var LinkHref = "";
                if (span.innerHTML.match(/href="([^"]*)/) != null) {
                    LinkHref = span.innerHTML.match(/href="([^"]*)/)[1];
                }
                AllTexts = AllTexts + LinkText;
                AllHrefs = AllHrefs + LinkHref;
                if (item != options.options.pr.actions.length - 1) {
                    AllTexts = AllTexts + ",";
                    AllHrefs = AllHrefs + ",";
                }
            }
            var generatedProps = {
                tu: AllHrefs,
                rg: "Player",
                aitl: AllTexts,
                cg: 'CTA viewed'
            }

            var objecttoSend = {};
            objecttoSend.properties = generatedProps;
            mediusAnalytics.sendTrackingdata(objecttoSend);
            updateCurrentCTA();
        }

        function validateCTALimit(pr) {
            var isShowPostroll = false;
            var ctaLimit = pr.CTALimit;

            if (!ctaLimit) {
                isShowPostroll = true;
            }
            else {
                var ctaLimitCount = parseInt(pr.CTACount);
                var currentCtaCount = parseInt(pr.CurrentCTACount);
                var isUserRestricted = pr.UserRestricted;
                var userKey = pr.UserKeyGUID;
                if (currentCtaCount < ctaLimitCount) {
                    if (isUserRestricted) {
                        isShowPostroll = localStorage.getItem(userKey) == undefined ? true : false;
                    }
                    else {
                        isShowPostroll = true;
                    }
                }
                else {
                    localStorage.removeItem(options.options.pr.UserKeyGUID);
                }
            }
            return isShowPostroll;
        }

        function updateCurrentCTA() {
            var updateFlag = true;
            if (options.options.pr.UserRestricted) {
                if (options.options.pr.UserKeyGUID != '' && localStorage.getItem(options.options.pr.UserKeyGUID) != undefined) {
                    updateFlag = false;
                }
            }
            if (options.options.pr.type !== 'URL Hyperlink') {
                updateFlag = false;
            }

            if (updateFlag) {
                $(".container-custom-postroll:visible").hide();
                var vid = $("#hdnVideoId").val();
                var token = $('input[name="__RequestVerificationToken"]').val();
                mediusCommon.executeXHR({
                    url: "/Video/UpdateCTACountPostroll",
                    contentType: 'application/x-www-form-urlencoded',
                    asyncCall: false,
                    method: "GET",
                    data: {videoId: vid }
                }).promise().then(function (data) {
                    if (data.Success) {
                        console.log('Updated CTA Count');
                        if (options.options.pr.UserKeyGUID != '' && options.options.pr.UserKeyGUID != undefined) {
                            localStorage.setItem(options.options.pr.UserKeyGUID, Math.random().toString(36).slice(2));
                        }
                    }
                    if (options.options.pr.actions[0].indexOf("?") > 0)
                        window.location.href = options.options.pr.actions + "&at=" + data.t;
                    else
                        window.location.href = options.options.pr.actions + "?at=" + data.t;
                        
                }, function (err) {
                    console.log(err);
                });
            }
        }

    });
}).call(this);;
(function () {

    amp.plugin('preRoll', function (options) {
        var vidPlayer = this;
        var count = 0;
        var prerollArray = options.options.pre;

        var vidContainer = $("#" + this.id());
        var vidControlBar = $('.vjs-control-bar');
        var keyPointHtml = "<div id='imageFull' class='preroll-overlay-player displayNone'/>";
        vidContainer.append(keyPointHtml);
        loadAdImage();
        vidPlayer.addEventListener(amp.eventName.loadeddata, function () {
            vidPlayer.muted(true);
        });
        vidPlayer.addEventListener(amp.eventName.play, function () {
            if (count == 0) {
                count = 1;
                vidPlayer.pause();
                vidControlBar.addClass('displayNone');
                showAdImage();
                setTimeout(hideAdImage, parseInt(prerollArray[0].prerollDuration) * 1000);
            }
        });

        function showAdImage() {
            //$("#imageFull").html('<div id="secondscounter"></div><img src="' + prerollArray[0].prerollImage + '" class="adImage"></img>');
            $("#imageFull").removeClass("displayNone").addClass("displayBlock");
            countdown();
        }

        function loadAdImage() {
            $("#imageFull").html('<div id="secondscounter"></div><img src="' + prerollArray[0].prerollImage + '" class="img-responsive" style="position:fixed;top:0;left:0;right:0;bottom:0;cursor:pointer;background:black;margin:auto;max-height:100%;"></img>');
        }

        function hideAdImage() {
            $("#imageFull").removeClass("displayBlock").addClass("displayNone");
            vidControlBar.removeClass('displayNone');
            vidPlayer.muted(false);
            vidPlayer.play();
        }

        var timeoutHandle;
        function countdown() {
            var seconds = prerollArray[0].prerollDuration;
            function tick() {
                var counter = document.getElementById("secondscounter");
                counter.innerHTML = "Video will start in " + seconds + " seconds";
                seconds--;
                if (seconds > 0) {
                    timeoutHandle = setTimeout(tick, 1000);
                }
            }
            tick();
        }
    });
}).call(this);;
(function () {
    amp.plugin('semuLive', function (options) {        
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = '/Content/js/AMPPlugins/amp-semuLive.css';
        document.getElementsByTagName('HEAD')[0].appendChild(link);
        console.log(options);
        var player = this;
        var test = document.getElementsByClassName('vjs-progress-control')[0];
        test.setAttribute("id", "player");
        var oldtime;
        player.addEventListener(amp.eventName.loadeddata, function () {
            var rightControlsContainer = document.getElementsByClassName("amp-controlbaricons-right")[0];
            if ($(rightControlsContainer).find('.amp-playbackspeed-control-normal').length > 0) {
                $(".amp-playbackspeed-control-normal").hide();
            }
            if ($(rightControlsContainer).find('.amp-closedcaption-control').length > 0) {
                var ele = document.getElementsByClassName('amp-closedcaption-control');
                ele[0].classList.remove("amp-control-disabled");
                ele[0].classList.remove("vjs-hidden");
            }
            if ($(".livediv").length <= 0) {
                $(".amp-controlbaricons-left").append("<div class='livediv' tabindex='-1' role='button' aria-live='off' aria-label='LIVE' title='Go to live'><div class='livecheckdiv'><button title='Live' class='button livecheck' style='background-color:#3c454f'></button></div><div id='livebutton' role='button' aria-label='LIVE' class='live-control' title='Go to live'>LIVE</div></div>");
            }
            if ($(".video-progress").length <= 0) {
                $(".amp-controlbaricons-middle").append("<div class='video-progress' style='position:absolute;right:0;bottom:100%;left:0;height:4px;width:100%;overflow:visible;-webkit-transition:height .15s;transition: height .15s;'><progress id = 'progress-bar' style='width:100%; position:absolute;bottom:0px;height:11px;' value = '0' min = '0'></progress><input title='progress bar' class='seek' tabindex='-1' id='seek' style='width:100%; position:absolute; bottom:-4px' value='0' min='0' type='range' step='1'>");
            }
            $('.vjs-progress-control').css({
                'display': 'none'
            });

        });

        var progressBar;
        var seek;
        var vid;
        var sessionEndDate;
        var postLive;
        var flag = "live";
         
        player.addEventListener("loadeddata", function () {
            $(document).ready(function () {                              
                setTimeout(function () {
                    $('.button').css({
                        'background-color': '#b5e2f5',
                        'border-color': '#b5e2f5'
                    });
                    $('.livediv').css({
                        'color': '#b5e2f5'
                    });
                    var currentTime = document.getElementsByClassName("vjs-current-time-display");
                    if (currentTime.length > 0) {
                        currentTime[0].classList.add("currenttime");
                    }
                    var liveTime = document.getElementsByClassName("amp-livetimeindicator");
                    if (liveTime.length > 0) {
                        liveTime[0].classList.add("livetime");
                    }
                }, 100);
                if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
                    var fullscreen = document.getElementsByClassName("vjs-fullscreen-control");
                    if (fullscreen.length > 0) {
                        fullscreen[0].classList.add("amp-control-disabled");
                    }
                }
                progressBar = document.getElementById('progress-bar');
                seek = document.getElementById('seek');
                const videoDuration = Math.round(player.duration());
                if (seek != null && progressBar != null) {
                    seek.setAttribute('max', videoDuration);
                    progressBar.setAttribute('max', videoDuration);
                    var currentDateTime = new Date();
                    var liveTiming = (Math.abs(currentDateTime - sessionStartDate)) / 1000;
                    console.log(liveTiming);
                    player.currentTime(liveTiming);
                    progressBar.value = liveTiming;
                    seek.value = liveTiming;
                    player.play();
                    setInterval(function () {
                        var ele = document.getElementsByClassName('vjs-captionsearch-button');
                        if (ele.length > 0) {
                            ele[0].classList.add("amp-control-disabled");
                            ele[0].classList.add("vjs-hidden");
                        }

                        var element = document.getElementsByClassName('more-caption-search');
                        if (element.length > 0) {
                            element[0].classList.add("amp-control-disabled");
                            element[0].classList.add("vjs-hidden");
                        }
                        //var currentTime = document.getElementsByClassName("vjs-current-time-display");
                        //if (currentTime.length > 0) {
                        //    var currTime = $(".vjs-current-time-display").contents()[1].data;
                        //    currTime = currTime.split(':');
                        //    if (currTime.length == 3 && currTime[0] != 0) {
                        //        document.getElementsByClassName("vjs-current-time-display")[0].innerText = currTime[0] + ':' + currTime[1] + ':' + currTime[2];
                        //    }
                        //    else if (currTime.length == 3 && currTime[0] == 0) {
                        //        document.getElementsByClassName("vjs-current-time-display")[0].innerText = currTime[1] + ':' + currTime[2];
                        //    }

                        //}

                        if (document.getElementById('videoDuration').value == "" && document.getElementsByClassName('vjs-duration-display').length > 0) {
                            var hourInSec = 0;
                            var minInSec = 0;
                            var sec = 0;
                            document.getElementById('videoDuration').value = $(".vjs-duration-display").contents()[1].data;
                            var videoTime = document.getElementById('videoDuration').value;
                            if (videoTime != "" && videoTime != undefined && videoTime != null) {
                                var DatewithTime = videoTime.split(':');
                                if (DatewithTime.length == 3) {
                                    hourInSec = parseInt(DatewithTime[0]) * 60 * 60;
                                    minInSec = parseInt(DatewithTime[1]) * 60;
                                    sec = parseInt(DatewithTime[2]);
                                }
                                else if (DatewithTime.length == 2) {
                                    minInSec = parseInt(DatewithTime[0]) * 60;
                                    sec = parseInt(DatewithTime[1]);
                                }
                                var totalseconds = hourInSec + minInSec + sec;
                                sessionEndDate = moment(sessionStartDate).add(totalseconds, 's').toDate();
                                postLive = moment(sessionEndDate).add(1, 'd').toDate();
                                handleSaveLiveConfiguration(videoTime);

                            }

                        }
                        //Only update if time is less than video duration
                        var distance = new Date().getTime() - sessionStartDate.getTime();
                        if (parseInt(distance / 1000) <= player.duration()) {
                            seek.max = Math.floor(moment().diff(sessionStartDate) / 1000);
                            progressBar.max = Math.floor(moment().diff(sessionStartDate) / 1000);
                        }
                        if (flag == "live") {
                            var currentDateTime = new Date();
                            var liveTiming = (Math.abs(currentDateTime - sessionStartDate)) / 1000;
                            if (Math.abs(player.currentTime() - liveTiming) > 1) {
                                player.currentTime(liveTiming);
                            }
                            progressBar.value = liveTiming;
                            seek.value = liveTiming;
                            var value = (seek.value - seek.min) / (seek.max - seek.min) * 100;
                        }
                        if (flag == "seeked") {
                            seek.value = Math.floor(player.currentTime());
                            progressBar.value = Math.floor(player.currentTime());
                            var value = (seek.value - seek.min) / (seek.max - seek.min) * 100;
                            //If on rewind video loaded again while switching asl live div should be empty, If condition is necessary as when we click big play button and video plays first time it seeks
                            if (value < 99.5) {
                                $('.button').css({
                                    'background-color': '#3c454f',
                                    'border-color': 'white'
                                });
                                $('.livediv').css({
                                    'color': '#fff'
                                });
                                var currentTime = document.getElementsByClassName("vjs-current-time-display");
                                if (currentTime.length > 0) {
                                    currentTime[0].classList.remove("currenttime");
                                }
                                var liveTime = document.getElementsByClassName("amp-livetimeindicator");
                                if (liveTime.length > 0) {
                                    liveTime[0].classList.remove("livetime");
                                }
                            }
                            else {
                                $('.button').css({
                                    'background-color': '#b5e2f5',
                                    'border-color': '#b5e2f5'
                                });
                                $('.livediv').css({
                                    'color': '#b5e2f5'
                                });
                                var currentTime = document.getElementsByClassName("vjs-current-time-display");
                                if (currentTime.length > 0) {
                                    currentTime[0].classList.add("currenttime");
                                }
                                var liveTime = document.getElementsByClassName("amp-livetimeindicator");
                                if (liveTime.length > 0) {
                                    liveTime[0].classList.add("livetime");
                                }
                            }
                        }
                        seek.style.background = 'linear-gradient(to right, #71b1d1 0%, #71b1d1 ' + value + '%, #bbc2ca ' + value + '%, #bbc2ca 100%)';
                        var hours = 0;
                        var minutes = 0;
                        var seconds = 0;
                        hours = Math.floor((distance % (1000 * 60 * 60 * 60)) / (1000 * 60 * 60));
                        minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
                        seconds = Math.floor((distance % (1000 * 60)) / 1000);
                        if (seconds < 10) {
                            seconds = '0' + seconds;
                        }
                        if (minutes < 10) {
                            minutes = '0' + minutes;
                        }
                        //if (hours < 10) {
                        //    hours = '0' + hours;
                        //}
                        //Only Update if time is less than video duration
                        if (parseInt(distance / 1000) <= player.duration()) {
                            if (hours > 0) {
                                document.getElementsByClassName('vjs-duration-display')[0].innerText = hours + ':' + minutes + ':' + seconds;
                            }
                            else {
                                document.getElementsByClassName('vjs-duration-display')[0].innerText = minutes + ':' + seconds;
                            }
                        }
                        //console.log('value', value, 'seek max', seek.max, 'seek value', seek.value);
                    }, 1000);

                }
            });
        });

        var handleSaveLiveConfiguration = function (videoTime, vid) {
            vid = $('#hdnVideoId').val();
            mediusCommon.executeXHR({
                url: "/Video/UpdateSessionEndTime",
                contentType: 'application/x-www-form-urlencoded',
                asyncCall: false,
                method: "POST",
                data: { VideoEndTime: videoTime.toString(), VideoId: vid }
            }).promise().then(function (data) {
                var result = [];
                if (data.modelerrorlist !== undefined) {
                    for (var i in data.modelerrorlist)
                        result.push([i, data.modelerrorlist[i]]);
                    if (result.length !== 0) {
                        for (var i = 0; i < result.length; i++) {
                            if (document.getElementById(result[i][0]) !== null) {
                                var errorelem = document.getElementById(result[i][0]);
                                errorelem.innerHTML = "<span style='color: red;'>" + result[i][1][0] + "</span > ";
                            }
                        }
                    }
                }
                if (data.Success > 0) {
                    //mediusCommon.createAlert("Session End Time Updated successfully", mediusCommon.alertTypes.success, "#collapsePubbleInfo");
                    // mediusCommon.createAutoClosingAlert(".alert-success", 2000);
                }
                else {
                    // mediusCommon.createAlert(data.err, mediusCommon.alertTypes.error, "#collapsePubbleInfo");
                    // mediusCommon.createAutoClosingAlert(".alert-danger", 2000);
                }
            }, function (err) {
                //alert(err);
            });
        };
        var ajaxCallForATToken = function (rt, guid, issuer, str, callbackfunction) {
            if (issuer != "") {
            $.ajax({
                type: "Get",
                cache: false,
                url: "/Embed/GetATTokenByGuid/" + options.MainVideoGuid,
                data: {
                    rt: rt,
                    guid: guid,
                    issuer: issuer
                },
                success: function (data) {
                    if (data !== null) {
                        console.log('got token after video end');
                        callbackfunction(str, data);
                    }
                }
            });
        } else {
            console.log('issuer is not present for ' + guid);
        }

    }
        player.addEventListener('pause', function () {
            flag = "seeked";
            $('.button').css({
                'background-color': '#3c454f',
                'border-color': 'white'
            });
            $('.livediv').css({
                'color': '#fff'
            });
            var currentTime = document.getElementsByClassName("vjs-current-time-display");
            if (currentTime.length > 0) {               
                currentTime[0].classList.remove("currenttime");
            }
            var liveTime = document.getElementsByClassName("amp-livetimeindicator");
            if (liveTime.length > 0) {
                liveTime[0].classList.remove("livetime");
            }
        });

        player.addEventListener('ended', function () {           
            var postAsset = options.postAsset;
            phase = "postLive";
            var rt = options.refreshToken;
            var postvideochannel = options.postViedoeChannel;
            var str = postAsset;
            if (options.postAsset != undefined && options.postAsset != null && options.postAsset != 'null' && options.postAsset != "") {
                phase = "postLive";               
                    var ele = document.getElementById("postvideo");
                if (ele == undefined || ele == null || ele == "") {
                    if (str.includes("jpg")) {
                        displayImage(postAsset, phase);
                    }
                    else {
                        if (str.includes("video-aes")) {
                            var arr = str.split('/')
                            var guid = "";
                            if (arr && arr.length > 5) {
                                if (arr[5].includes("?")) {
                                    var guidArr = arr[5].split('?');
                                    guid = guidArr[0];
                                }
                                else {
                                    guid = arr[5];
                                }
                            }
                           
                            ajaxCallForATToken(rt, guid, postvideochannel, str, function (str, data) {
                                
                                if (data.ATToken !="") {
                                    if (str.includes("?")) {
                                        options.postAsset = options.postAsset + "&" + "at=" + data.ATToken;
                                    }
                                    else {
                                        options.postAsset = options.postAsset + "?" + "at=" + data.ATToken;
                                    }
                                    if (options.Querystring != undefined) {
                                        var mainQuerystrings = options.Querystring;
                                        if (options.Querystring.includes('at=')) {
                                            mainQuerystrings = removeURLParameter(options.Querystring, 'at');
                                        }
                                        if (options.Querystring.includes('r=')) {
                                            mainQuerystrings = removeURLParameter(options.Querystring, 'r');
                                        }
                                        if (mainQuerystrings != "") {
                                            if (options.postAsset.includes("?")) {
                                                options.postAsset = options.postAsset + "&" + mainQuerystrings;
                                            }
                                            else {
                                                options.postAsset = options.postAsset + "?" + mainQuerystrings;
                                            }
                                        }
                                    }
                                    var iframe = document.createElement('iframe');
                                    iframe.setAttribute("class", "embed-responsive-item");
                                    iframe.setAttribute("id", "postvideo");
                                    /*iframe.setAttribute("style", "height:39.4rem !important; width:71rem !important");*/
                                    iframe.setAttribute("title", "Embeded video");
                                    iframe.setAttribute("allowfullscreen", "true");
                                    iframe.src = options.postAsset;
                                    document.body.appendChild(iframe);
                                }
                                else {
                                    console.log("Error while generating AT Token for post video" + options.postAsset);
                                }
                            });
                          
                        }
                        else {
                            if (options.Querystring != undefined) {
                                var mainQuerystrings = options.Querystring;
                                if (options.Querystring.includes('at=')) {
                                    mainQuerystrings = removeURLParameter(options.Querystring, 'at');
                                }
                                if (options.Querystring.includes('r=')) {
                                    mainQuerystrings = removeURLParameter(options.Querystring, 'r');
                                }
                                if (mainQuerystrings != "") {
                                    if (options.postAsset.includes("?")) {
                                        options.postAsset = options.postAsset + "&" + mainQuerystrings;
                                    }
                                    else {
                                        options.postAsset = options.postAsset + "?" + mainQuerystrings;
                                    }
                                }
                            }
                            var iframe = document.createElement('iframe');
                            iframe.setAttribute("class", "embed-responsive-item");
                            iframe.setAttribute("id", "postvideo");
                            /*iframe.setAttribute("style", "height:39.4rem !important; width:71rem !important");*/
                            iframe.setAttribute("title", "Embeded video");
                            iframe.setAttribute("allowfullscreen", "true");
                            iframe.src = options.postAsset;
                            document.body.appendChild(iframe);
                        }
                    }
                }
            }
            else {
                    displayImage(mediusCommon.GetImageForVideo('ImgVideoComingSoon', ''));
                } 
                $('#playerDiv').html('');
                var ele = document.getElementById("player_section");
                if (ele != undefined && ele != null && ele != "") {
                    ele.remove();
                }                
                $('#azuremediaplayer').css({
                    'display': 'none'
                });
            
            console.log('post live video coming soon');
        });

        function removeURLParameter(url, parameter) {

            var prefix = encodeURIComponent(parameter) + '=';
            var pars = url.split(/[&;]/g);
            for (var i = pars.length; i-- > 0;) {
                //idiom for string.startsWith
                if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                    pars.splice(i, 1);
                }
                if (pars[i] != undefined) {
                    if (pars[i].lastIndexOf('amp', 0) !== -1) {
                        pars.splice(i, 1);
                    }
                }
            }

            url = pars.join('&');
            return url;

        }

        $(document).on('input', '.seek', function (event) {
            //debugger;     
            flag = "seeked";
            progressBar = document.getElementById('progress-bar');
            seek = document.getElementById('seek');
            var skipTo = event.target.dataset.seek ? event.target.dataset.seek : event.target.value;
            oldtime = document.getElementsByClassName('vjs-play-progress')[0].getAttribute('data-current-time');
            oldtimeinsecs = hmsToSecondsOnly(oldtime);
            //if (parseInt(skipTo) < oldtimeinsecs) {
            var value = (this.value - this.min) / (this.max - this.min) * 100
            this.style.background = 'linear-gradient(to right, #71b1d1 0%, #71b1d1 ' + value + '%, #bbc2ca ' + value + '%, #bbc2ca 100%)'
            player.currentTime(parseInt(skipTo));
            progressBar.value = skipTo;
            seek.value = skipTo;
            $('.button').css({
                'background-color': '#3c454f',
                'border-color': 'white'
            });
            $('.livediv').css({
                'color': '#fff'
            });
            var currentTime = document.getElementsByClassName("vjs-current-time-display");
            if (currentTime.length > 0) {
                currentTime[0].classList.remove("currenttime");
            }
            var liveTime = document.getElementsByClassName("amp-livetimeindicator");
            if (liveTime.length > 0) {
                liveTime[0].classList.remove("livetime");
            }
            //}
        });

        function hmsToSecondsOnly(time) {
            var p = time.split(':'),
                s = 0, m = 1;
            while (p.length > 0) {
                s += m * parseInt(p.pop(), 10);
                m += 60;
            }
            return s;
        }

        $(document).on('click', '.livediv', function () {             
            var currdate = moment();
            if (!(currdate.diff(sessionEndDate) >= 0 && currdate.diff(postLive) <= 0)) {
                flag = "live";
                progressBar = document.getElementById('progress-bar');
                seek = document.getElementById('seek');
                var currentDateTime = new Date();
                console.log("oldstart  " + sessionStartDate);
                console.log("current " + currentDateTime);
                var liveTiming = (Math.abs(currentDateTime - sessionStartDate)) / 1000;
                console.log(liveTiming);
                player.currentTime(liveTiming);
                progressBar.value = liveTiming;
                seek.value = liveTiming;
                if (player.paused()) {
                    player.play()
                }
                setTimeout(function () {
                    $('.button').css({
                        'background-color': '#b5e2f5',
                        'border-color': '#b5e2f5'
                    });
                    $('.livediv').css({
                        'color': '#b5e2f5'
                    });
                    var currentTime = document.getElementsByClassName("vjs-current-time-display");
                    if (currentTime.length > 0) {
                        currentTime[0].classList.add("currenttime");
                    }
                    var liveTime = document.getElementsByClassName("amp-livetimeindicator");
                    if (liveTime.length > 0) {
                        liveTime[0].classList.add("livetime");
                    }
                }, 100);
            }
            else {
                player.pause();
                var postAsset = options.postAsset;
                phase = "postLive";
                var str = postAsset;
                if (options.postAsset != undefined && options.postAsset != null && options.postAsset != 'null' && options.postAsset != "") {
                    phase = "postLive";
                    var ele = document.getElementById("postvideo");
                    if (ele == undefined || ele == null || ele == "") {
                        if (str.includes("jpg")) {
                            displayImage(postAsset, phase);
                        }
                        else {
                            if (str.includes("video-aes")) {
                                var arr = str.split('/')
                                var guid = "";
                                if (arr && arr.length > 5) {
                                    if (arr[5].includes("?")) {
                                        var guidArr = arr[5].split('?');
                                        guid = guidArr[0];
                                    }
                                    else {
                                        guid = arr[5];
                                    }
                                }
                                var things = JSON.stringify({
                                    guid: guid
                                });
                                mediusCommon.executeXHR({
                                    url: '/Video/GetATTokenByGuid',
                                    method: "POST",
                                    data: things
                                }).promise().then(function (data) {
                                    var result = [];
                                    if (data.modelerrorlist !== undefined) {
                                        for (var i in data.modelerrorlist)
                                            result.push([i, data.modelerrorlist[i]]);
                                        if (result.length !== 0) {
                                            for (var i = 0; i < result.length; i++) {
                                                if (document.getElementById(result[i][0]) !== null) {
                                                    var errorelem = document.getElementById(result[i][0]);
                                                    errorelem.innerHTML = "<span style='color: red;'>" + result[i][1][0] + "</span > ";
                                                }
                                            }
                                        }
                                    }

                                    if (data.Success > 0) {
                                        if (str.includes("?") && data.Token != "") {
                                            options.postAsset = options.postAsset + "&" + "at=" + data.Token;
                                        }
                                        else {
                                            options.postAsset = options.postAsset + "?" + "at=" + data.Token;
                                        }
                                        if (options.Querystring != undefined) {
                                            var mainQuerystrings = options.Querystring;
                                            if (options.Querystring.includes('at=')) {
                                                mainQuerystrings = removeURLParameter(options.Querystring, 'at');
                                            }
                                            if (options.Querystring.includes('r=')) {
                                                mainQuerystrings = removeURLParameter(options.Querystring, 'r');
                                            }
                                            if (mainQuerystrings != "") {
                                                if (options.postAsset.includes("?")) {
                                                    options.postAsset = options.postAsset + "&" + mainQuerystrings;
                                                }
                                                else {
                                                    options.postAsset = options.postAsset + "?" + mainQuerystrings;
                                                }
                                            }
                                        }
                                        var iframe = document.createElement('iframe');
                                        iframe.setAttribute("class", "embed-responsive-item");
                                        iframe.setAttribute("id", "postvideo");
                                        /*iframe.setAttribute("style", "height:39.4rem !important; width:71rem !important");*/
                                        iframe.setAttribute("title", "Embeded video");
                                        iframe.setAttribute("allowfullscreen", "true");
                                        iframe.src = options.postAsset;
                                        document.body.appendChild(iframe);
                                    }
                                    else {
                                        mediusCommon.createAlert("Error while generating AT Token", mediusCommon.alertTypes.error, "#collapseLiveTab");
                                        mediusCommon.createAutoClosingAlert(".alert-danger", 2000);
                                    }
                                }, function (err) {
                                    console.log(err);
                                });
                            }
                            else {
                                if (options.Querystring != undefined) {
                                    var mainQuerystrings = options.Querystring;
                                    if (options.Querystring.includes('at=')) {
                                        mainQuerystrings = removeURLParameter(options.Querystring, 'at');
                                    }
                                    if (options.Querystring.includes('r=')) {
                                        mainQuerystrings = removeURLParameter(options.Querystring, 'r');
                                    }
                                    if (mainQuerystrings != "") {
                                        if (options.postAsset.includes("?")) {
                                            options.postAsset = options.postAsset + "&" + mainQuerystrings;
                                        }
                                        else {
                                            options.postAsset = options.postAsset + "?" + mainQuerystrings;
                                        }
                                    }
                                }
                                var iframe = document.createElement('iframe');
                                iframe.setAttribute("class", "embed-responsive-item");
                                iframe.setAttribute("id", "postvideo");
                                /*iframe.setAttribute("style", "height:39.4rem !important; width:71rem !important");*/
                                iframe.setAttribute("title", "Embeded video");
                                iframe.setAttribute("allowfullscreen", "true");
                                iframe.src = options.postAsset;
                                document.body.appendChild(iframe);
                            }
                        }
                    }
                }
                    else {
                        displayImage(mediusCommon.GetImageForVideo('ImgVideoComingSoon', ''));
                    }
                    $('#playerDiv').html('');
                    var ele = document.getElementById("player_section");
                    if (ele != undefined && ele != null && ele != "") {
                        ele.remove();
                    }
                    $('#azuremediaplayer').css({
                        'display': 'none'
                    });
                   
                console.log('post live video coming soon');
            }
        });

    });
}).call(this);;
(function () {
    amp.plugin('crossDomainMessaging', function (opt) {
        var ampPlayer = this;
        ampPlayer.addEventListener('ended', function () {
            try {
                window.parent.postMessage(
                    {
                        type: "info",
                        data: {
                            videoId: opt.videoGuId,
                            action: "ended",
                            location: ampPlayer.currentTime(),
                            playerUrl: document.location.href
                        }
                    }, "*");
                // console.log({ type: "info", data: { videoId: opt.videoGuId, action: "ended", location: ampPlayer.currentTime(), playerUrl: document.location.href } });
            }
            catch (ex) { }
        });

        $(document).ready(function () {
            $("video").click(function () {
                if (ampPlayer.paused()) {
                    try {
                        window.parent.postMessage(
                            {
                                type: "info",
                                data: {
                                    videoId: opt.videoGuId,
                                    action: "pause",
                                    location: ampPlayer.currentTime(),
                                    playerUrl: document.location.href
                                }
                            }, "*");
                        //console.log({ type: "info", data: { videoId: opt.videoGuId, action: "pause", location: ampPlayer.currentTime(), playerUrl: document.location.href } });
                    }
                    catch (ex) { }
                }
                else {
                    try {
                        window.parent.postMessage(
                            {
                                type: "info",
                                data: {
                                    videoId: opt.videoGuId,
                                    action: "play",
                                    location: ampPlayer.currentTime(),
                                    playerUrl: document.location.href
                                }
                            }, "*");
                        //console.log({ type: "info", data: { videoId: opt.videoGuId, action: "play", location: ampPlayer.currentTime(), playerUrl: document.location.href } });
                    }

                    catch (ex) { }
                }
            });
        });

        $(document).on("click", ".vjs-play-control.vjs-paused", function () {
            try {
                window.parent.postMessage(
                    {
                        type: "info",
                        data: {
                            videoId: opt.videoGuId,
                            action: "play",
                            location: ampPlayer.currentTime(),
                            playerUrl: document.location.href
                        }
                    }, "*");
                // console.log({ type: "info", data: { videoId: opt.videoGuId, action: "play", location: ampPlayer.currentTime(), playerUrl: document.location.href } });
            }

            catch (ex) { }
        });
        $(document).on("click", ".vjs-play-control.vjs-playing", function () {
            try {
                window.parent.postMessage(
                    {
                        type: "info",
                        data: {
                            videoId: opt.videoGuId,
                            action: "pause",
                            location: ampPlayer.currentTime(),
                            playerUrl: document.location.href
                        }
                    }, "*");
                //console.log({ type: "info", data: { videoId: opt.videoGuId, action: "pause", location: ampPlayer.currentTime(), playerUrl: document.location.href } });
            }
            catch (ex) { }
        });
        $(document).keydown(function (e) {
            if (e.keyCode === 27) {
                window.parent.postMessage(
                    {
                        type: "info",
                        data: {
                            videoId: opt.videoGuId,
                            action: "Escape button pressed",
                            playerUrl: document.location.href,
                            location: ampPlayer.currentTime()
                        }
                    }, "*");
                // console.log({ type: "info", data: { videoId: opt.videoGuId, action: "Escape button pressed", playerUrl: document.location.href, location: ampPlayer.currentTime()} });
            }
        });
        ampPlayer.addEventListener('loadedmetadata', function () {
            //if ($(".amp-controlbaricons-right").find(".vjs-popout-button").length == 0) {
            //    $(".amp-controlbaricons-right").append('<div class="vjs-menu-button vjs-menu-button-popup vjs-control vjs-button outline-enabled-control vjs-popout-button amp-popout-control" tabindex="0" role="region" aria-live="off" aria-expanded="false" aria-haspopup="true"></div>')
            //    var $divAlshtml = $('<img alt="Pop Out Player" src= "/Content/images/popout.png" style="margin-top: 2px;margin-left: 4px;height: 19px;"><span class="vjs-control-text">"Pop Out Player"</span>');
            //    $('.vjs-popout-button').html($divAlshtml);
            //    $(".vjs-popout-button").removeClass("vjs-hidden");
            //    $('.vjs-popout-button').attr("aria-label", "Pop Out Player");
            //    $('.vjs-popout-button').attr("title", "Pop Out Player");
            //}
            //$(document).on("click", ".amp-popout-control", function () {
            //    ampPlayer.pause();
            //    window.parent.postMessage({ type: "info", data: { videoId: opt.videoGuId, sentAction: "pop-out", location: ampPlayer.currentTime(), playerUrl: document.location.href } }, "*");
            //    console.log({ type: "info", data: { videoId: opt.videoGuId, sentAction: "pop-out", location: ampPlayer.currentTime(), playerUrl: document.location.href } });
            //});
            window.addEventListener('message', function (e) {
                var domainFlag;
                var origin = e.origin;
                var channelDomainList = opt.channelDomainList.split(";");
                if (channelDomainList.length > 0)
                    opt.domainList = opt.domainList + ';' + channelDomainList;
                var domainNameList = opt.domainList.split(";");
                for (var i = 0; i < domainNameList.length; i++) {
                    if (domainNameList[i] == e.origin.split('//')[1]) {
                        domainFlag = true;
                        // console.log('Received message:  ' + e.data, e);
                        switch (e.data.data.action) {
                            case "play":
                                ampPlayer.play();
                                try {
                                    window.parent.postMessage(
                                        {
                                            type: "info",
                                            data: {
                                                videoId: e.data.data.videoId,
                                                sentAction: "play",
                                                location: ampPlayer.currentTime(),
                                                playerUrl: document.location.href
                                            }
                                        }, "*");
                                    // console.log({ type: "info", data: { videoId: e.data.data.videoId, sentAction: "play", location: ampPlayer.currentTime(), playerUrl: document.location.href } });
                                }
                                catch (ex) { }
                                break;
                            case "pause":
                                ampPlayer.pause();
                                try {
                                    window.parent.postMessage(
                                        {
                                            type: "info",
                                            data: {
                                                videoId: e.data.data.videoId,
                                                sentAction: "pause",
                                                location: ampPlayer.currentTime(),
                                                playerUrl: document.location.href
                                            }
                                        }, "*");
                               // console.log({ type: "info", data: { videoId: e.data.data.videoId, sentAction: "pause", location: ampPlayer.currentTime(), playerUrl: document.location.href } });
                                }
                                catch (ex) { }
                                break;
                            case "resume":
                                ampPlayer.pause();
                                ampPlayer.currentTime(parseInt(e.data.data.location));
                                ampPlayer.play();
                                try {
                                    window.parent.postMessage(
                                        {
                                            type: "info",
                                            data: {
                                                videoId: e.data.data.videoId,
                                                sentAction: "resume",
                                                location: ampPlayer.currentTime(),
                                                playerUrl: document.location.href
                                            }
                                        }, "*");
                                    //console.log({ type: "info", data: { videoId: e.data.data.videoId, sentAction: "resume", location: ampPlayer.currentTime(), playerUrl: document.location.href } });
                                }
                                catch (ex) { }
                                break;
                        }
                    }
                }
                if (domainFlag != true) {
                    window.parent.postMessage(
                        {
                            type: "Failed",
                            data: {
                                sentAction: origin + "Not whitelisted domain"
                            }
                        }, "*");
                }
            }, false);
        });

    });
}).call(this);;
(function () {
    amp.plugin('saveUserPreference', function (options) {
        var player = this;       
        player.addEventListener('play', function () {
            var ele = $('#hdnloggedinuseremail1')[0];
            var userId = "";
            if (ele != null && ele.value != null && ele.value != undefined) {
                userId = ele.value;
            }
            var caption;
            var audioDescription;
            try {
                if (window.localStorage.getItem(userId + '_caption') != null) {
                    caption = window.localStorage.getItem(userId + '_caption');
                }
                else {
                    caption = 'undefined';
                }
                if (window.localStorage.getItem(userId + '_audio') != null) {
                    audioDescription = window.localStorage.getItem(userId + '_audio');
                }
                else {
                    audioDescription = 'undefined';
                }
            }
            catch(ex) {
            }
            try {               
                if (caption != 'undefined') {
                    if (player.textTracks_.length > 0) {
                        for (var i = 0; i < player.textTracks_.length; i++) {                            
                            if (player.textTracks_.tracks_[i].label == caption) {                                
                                player.setActiveTextTrack(player.textTracks_.tracks_[i]);
                            }
                        }
                    }
                }
                if (audioDescription != 'undefined') {
                    if (player.currentAudioStreamList()) {                        
                        for (var i = 0; i < player.currentAudioStreamList().streams.length; i++) {                           
                            if (player.currentAudioStreamList().streams[i].title == audioDescription) {                                
                                player.currentAudioStreamList().switchIndex(i);
                            }
                        }                        
                    }
                }
            }
            catch (ex) {
                logError("can't select language : " + ex.message);
            }
            });
      });
}).call(this);
;
(function () {
    amp.plugin('removePlayTooltip', function (option) {
        var link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = '/Content/js/AMPPlugins/amp-removePlayTooltip.css';
        document.getElementsByTagName('HEAD')[0].appendChild(link);
        var player = this;
        //player.addEventListener("loadeddata", function () {
        //    debugger;
        //    $(document).ready(function () {   
        //        setTimeout(function () {                    
        //            if (document.getElementsByClassName("amp-audiotracks-control").length > 0) {
        //                (document.getElementsByClassName("amp-audiotracks-control")[0]).setAttribute('role', 'button');
        //            }   
        //        }, 100);
        //    });
        //});

        player.addEventListener('play', function () {
            $(document).ready(function () {
                setTimeout(function () {
                    //if (document.getElementsByClassName("vjs-play-control").length > 0) {
                    //    (document.getElementsByClassName("vjs-play-control")[0]).setAttribute("title","Play");
                    //    (document.getElementsByClassName("vjs-play-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-play-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-play-control")[0]).removeAttribute("data-original-title");
                    //    (document.getElementsByClassName("vjs-play-control")[0]).removeAttribute("aria-label");
                    //}
                    if (document.getElementsByClassName("vjs-fullscreen-control").length > 0) {
                    //    (document.getElementsByClassName("vjs-fullscreen-control")[0]).setAttribute("title","Fullscreen");
                    //    (document.getElementsByClassName("vjs-fullscreen-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-fullscreen-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-fullscreen-control")[0]).removeAttribute("data-original-title");
                     // (document.getElementsByClassName("vjs-fullscreen-control")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("vjs-captionsearch-button").length > 0) {
                        //(document.getElementsByClassName("vjs-captionsearch-button")[0]).setAttribute("title");
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).removeAttribute("aria-live");
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).setAttribute('role', 'menubar');
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).removeAttribute("data-toggle");
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).removeAttribute("data-original-title");
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("amp-playbackspeed-control-normal").length > 0) {
                    //    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).setAttribute("title","Playback Speed");
                    //    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).removeAttribute("aria-live");
                          (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).setAttribute('role', 'menubar');
                    //    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("amp-audiotracks-control").length > 0) {
                    //    (document.getElementsByClassName("amp-audiotracks-control")[0]).setAttribute("title","Audio Tracks");
                    //    (document.getElementsByClassName("amp-audiotracks-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("amp-audiotracks-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-audiotracks-control")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("amp-audiotracks-control")[0]).removeAttribute("aria-label");
                          (document.getElementsByClassName("amp-audiotracks-control")[0]).setAttribute('role', 'menubar');
                    }
                    if (document.getElementsByClassName("amp-asl-control").length > 0) {
                    //    (document.getElementsByClassName("amp-asl-control")[0]).setAttribute("title","Asl");
                    //    (document.getElementsByClassName("amp-asl-control")[0]).removeAttribute("aria-live");
                          (document.getElementsByClassName("amp-asl-control")[0]).setAttribute('role', 'menubar');
                    //    (document.getElementsByClassName("amp-asl-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-asl-control")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("amp-asl-control")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("vjs-subtitles-button").length > 0) {
                    //    (document.getElementsByClassName("vjs-subtitles-button")[0]).setAttribute("title","Subtitles");
                    //    (document.getElementsByClassName("vjs-subtitles-button")[0]).removeAttribute("aria-live");
                          (document.getElementsByClassName("vjs-subtitles-button")[1]).setAttribute("role", "menuitem");
                    //    (document.getElementsByClassName("vjs-subtitles-button")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-subtitles-button")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("vjs-subtitles-button")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("vjs-captions-button").length > 0) {
                    //    (document.getElementsByClassName("vjs-captions-button")[0]).setAttribute("title","Captions Manu");
                    //    (document.getElementsByClassName("vjs-captions-button")[0]).removeAttribute("aria-live");
                          (document.getElementsByClassName("vjs-captions-button")[0]).setAttribute('role', 'menubar');
                    //    (document.getElementsByClassName("vjs-captions-button")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-captions-button")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("vjs-captions-button")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("amp-quality-control").length > 0) {
                    //    (document.getElementsByClassName("amp-quality-control")[0]).setAttribute("title","Video Quality");
                    //    (document.getElementsByClassName("amp-quality-control")[0]).removeAttribute("aria-live");
                          (document.getElementsByClassName("amp-quality-control")[0]).setAttribute('role', 'menubar');
                    //    (document.getElementsByClassName("amp-quality-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-quality-control")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("amp-quality-control")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("vjs-volume-control").length > 0) {
                        var volume = player.volume();
                        var volumeLevel = parseFloat(volume * 100).toFixed(2);
                        (document.getElementsByClassName("vjs-volume-control")[0]).setAttribute("title", volumeLevel + "%");                       

                      //    (document.getElementsByClassName("vjs-volume-control")[0]).setAttribute("title","Volume");
                      //    (document.getElementsByClassName("vjs-volume-control")[0]).removeAttribute("aria-live");
                      //    $(".vjs-volume-control").find('.vjs-control-text').attr("aria-hidden", "true");
                      //    (document.getElementsByClassName("vjs-volume-control")[0]).removeAttribute("data-toggle");
                      //    (document.getElementsByClassName("vjs-volume-control")[0]).removeAttribute("data-original-title");
                      //    (document.getElementsByClassName("vjs-volume-control")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("amp-moreoptions-control").length > 0) {
                    //    (document.getElementsByClassName("amp-moreoptions-control")[0]).setAttribute("title","More Options");
                    //    (document.getElementsByClassName("amp-moreoptions-control")[0]).removeAttribute("aria-live");
                          (document.getElementsByClassName("amp-moreoptions-control")[0]).setAttribute('role', 'menubar');
                    //    $('.amp-moreoptions-control').find('.vjs-menu-content').addClass('moreoptions-menu');
                    //    (document.getElementsByClassName("amp-moreoptions-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-moreoptions-control")[0]).removeAttribute("data-original-title");
                        (document.getElementsByClassName("amp-moreoptions-control")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("vjs-mute-control")[0].length > 0) {
                    //    (document.getElementsByClassName("vjs-mute-control")[0]).removeAttribute("data-original-title");
                    //    (document.getElementsByClassName("vjs-mute-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-mute-control")[0]).setAttribute('title', 'volume');
                        (document.getElementsByClassName("vjs-mute-control")[0]).removeAttribute("aria-label");
                    }
                   if (document.getElementsByClassName("amp-download-control").length > 0) {
                    //    (document.getElementsByClassName("amp-download-control")[0]).setAttribute("title","Download");
                    //    (document.getElementsByClassName("amp-download-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("amp-download-control")[0]).setAttribute('role', 'button');
                    //    (document.getElementsByClassName("amp-download-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-download-control")[0]).removeAttribute("data-original-title");
                      (document.getElementsByClassName("amp-download-control")[0]).removeAttribute("aria-label");
                    }
                   if (document.getElementsByClassName("vjs-text-track-display").length > 0) {
                    //    (document.getElementsByClassName("vjs-text-track-display")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-text-track-display")[0]).setAttribute('aria-hidden', 'true');
                    //    (document.getElementsByClassName("vjs-text-track-display")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-text-track-display")[0]).removeAttribute("data-original-title");
                     (document.getElementsByClassName("vjs-text-track-display")[0]).removeAttribute("aria-label");
                   }
                    $('#captionsearchinput').closest('div.vjs-menu').find('ul.vjs-menu-content').attr('role', 'list');
                    $('.vjs-menu-button').find('div.vjs-menu').attr('role', 'menuitem');
                    (document.getElementsByClassName("vjs-text-track-display")[0]).removeAttribute("aria-label");
                }, 2000);
            });
        });
        player.addEventListener('pause', function () {
            $(document).ready(function () {
                setTimeout(function () {
                    //if (document.getElementsByClassName("vjs-play-control").length > 0) {
                    //    (document.getElementsByClassName("vjs-play-control")[0]).setAttribute("title","Pause");
                    //    (document.getElementsByClassName("vjs-play-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-play-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-play-control")[0]).removeAttribute("data-original-title");
                    //    (document.getElementsByClassName("vjs-play-control")[0]).removeAttribute("aria-label");
                    //}
                   if (document.getElementsByClassName("vjs-fullscreen-control").length > 0) {
                    //    (document.getElementsByClassName("vjs-fullscreen-control")[0]).setAttribute("title","Fullscreen");
                    //    (document.getElementsByClassName("vjs-fullscreen-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-fullscreen-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-fullscreen-control")[0]).removeAttribute("data-original-title");
                       // (document.getElementsByClassName("vjs-fullscreen-control")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("vjs-captionsearch-button").length > 0) {
                        //(document.getElementsByClassName("vjs-captionsearch-button")[0]).setAttribute("title");
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).removeAttribute("aria-live");
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).removeAttribute("data-toggle");
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).removeAttribute("data-original-title");
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).removeAttribute("aria-label");
                        (document.getElementsByClassName("vjs-captionsearch-button")[0]).setAttribute('role', 'menubar');
                    }
                    if (document.getElementsByClassName("amp-playbackspeed-control-normal").length > 0) {
                    //    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).setAttribute("title","Playback Speed");
                    //    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).removeAttribute("aria-label");
                          (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).setAttribute('role', 'menubar');
                    }
                    if (document.getElementsByClassName("amp-audiotracks-control").length > 0) {
                    //    (document.getElementsByClassName("amp-audiotracks-control")[0]).seteAttribute("title", "Audio Tracks");
                    //    (document.getElementsByClassName("amp-audiotracks-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("amp-audiotracks-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-audiotracks-control")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("amp-audiotracks-control")[0]).removeAttribute("aria-label");
                          (document.getElementsByClassName("amp-audiotracks-control")[0]).setAttribute('role', 'menubar');
                    }
                    if (document.getElementsByClassName("vjs-subtitles-button").length > 0) {
                    //    (document.getElementsByClassName("vjs-subtitles-button")[0]).setAttribute("title","Subtitles");
                    //    (document.getElementsByClassName("vjs-subtitles-button")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-subtitles-button")[1]).setAttribute("role", "menuitem");
                    //    (document.getElementsByClassName("vjs-subtitles-button")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-subtitles-button")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("vjs-subtitles-button")[0]).removeAttribute("aria-label");
                          (document.getElementsByClassName("vjs-subtitles-button")[1]).setAttribute("role", "menuitem");
                    }
                    if (document.getElementsByClassName("vjs-captions-button").length > 0) {
                    //    (document.getElementsByClassName("vjs-captions-button")[0]).setAttribute("title","Captions");
                    //    (document.getElementsByClassName("vjs-captions-button")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-captions-button")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-captions-button")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("vjs-captions-button")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("amp-quality-control").length > 0) {
                    //    (document.getElementsByClassName("amp-quality-control")[0]).setAttribute("title","Quality");
                    //    (document.getElementsByClassName("amp-quality-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("amp-quality-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-quality-control")[0]).removeAttribute("data-original-title");
                          (document.getElementsByClassName("amp-quality-control")[0]).removeAttribute("aria-label");
                          (document.getElementsByClassName("amp-quality-control")[0]).setAttribute('role', 'menubar');
                    }
                    if (document.getElementsByClassName("vjs-volume-control").length > 0) {
                        var volume = player.volume();
                        var volumeLevel = parseFloat(volume * 100).toFixed(2);
                        (document.getElementsByClassName("vjs-volume-control")[0]).setAttribute("title", volumeLevel + "%");                       

                    //    (document.getElementsByClassName("vjs-volume-control")[0]).setAttribute("title","Volume");
                    //    (document.getElementsByClassName("vjs-volume-control")[0]).removeAttribute("aria-live");
                    //    $(".vjs-volume-control").find('.vjs-control-text').attr("aria-hidden", "true");
                    //    (document.getElementsByClassName("vjs-volume-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-volume-control")[0]).removeAttribute("data-original-title");
                      //    (document.getElementsByClassName("vjs-volume-control")[0]).removeAttribute("aria-label");
                   }
                    //if (document.getElementsByClassName("vjs-mute-control")[0].length > 0) {
                    //    (document.getElementsByClassName("vjs-mute-control")[0]).removeAttribute("data-original-title");
                    //    (document.getElementsByClassName("vjs-mute-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-mute-control")[0]).setAttribute('title', 'volume');
                     //}
                    if (document.getElementsByClassName("amp-moreoptions-control").length > 0) {
                    //    (document.getElementsByClassName("amp-moreoptions-control")[0]).setAttribute("title","More Options");
                    //    (document.getElementsByClassName("amp-moreoptions-control")[0]).removeAttribute("aria-live");
                    //    $('.amp-moreoptions-control').find('.vjs-menu-content').addClass('moreoptions-menu');
                    //    (document.getElementsByClassName("amp - moreoptions - control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-moreoptions-control")[0]).removeAttribute("data-original-title");
                        (document.getElementsByClassName("amp-moreoptions-control")[0]).removeAttribute("aria-label");
                        (document.getElementsByClassName("amp-moreoptions-control")[0]).setAttribute('role', 'menubar');
                    }
                   if (document.getElementsByClassName("amp-download-control").length > 0) {
                    //    (document.getElementsByClassName("amp-download-control")[0]).setAttribute("title","Download");
                    //    (document.getElementsByClassName("amp-download-control")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("amp-download-control")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("amp-download-control")[0]).removeAttribute("data-original-title");
                       (document.getElementsByClassName("amp-download-control")[0]).removeAttribute("aria-label");
                    }
                    if (document.getElementsByClassName("vjs-text-track-display").length > 0) {
                    //    (document.getElementsByClassName("vjs-text-track-display")[0]).removeAttribute("aria-live");
                    //    (document.getElementsByClassName("vjs-text-track-display")[0]).setAttribute('aria-hidden', 'true');
                    //    (document.getElementsByClassName("vjs-text-track-display")[0]).removeAttribute("data-toggle");
                    //    (document.getElementsByClassName("vjs-text-track-display")[0]).removeAttribute("data-original-title");
                        (document.getElementsByClassName("vjs-text-track-display")[0]).removeAttribute("aria-label");
                   }
                    $('#captionsearchinput').closest('div.vjs-menu').find('ul.vjs-menu-content').attr('role', 'list');
                    $('.vjs-menu-button').find('div.vjs-menu').attr('role', 'menuitem');
                }, 2000);
            });
        });
        player.addEventListener('volumechange', function () {
            var volume = player.volume();
            var volumeLevel = parseFloat(volume * 100).toFixed(2);
            (document.getElementsByClassName("vjs-volume-control")[0]).setAttribute("title", volumeLevel + "%");
        });
        $(document).on('keydown', '.vjs-volume-bar', function (event) {
            if (event.which === 27) {
                document.getElementsByClassName('vjs-volume-control')[0].setAttribute("aria-expanded", "false");
                $('.vjs-volume-control').find('.vjs-menu').removeClass('vjs-lock-showing');
                $(".vjs-mute-control").focus();
            }
        });

        $(document).on('keypress', '.vjs-volume-control', function (e) {
            var key = e.which || e.keyCode;
            if (key == '109' || key == '77') {
                if (!player.muted()) {
                    player.muted(true);
                }
                else {
                    player.muted(false);
                }
            }
        });
        
        $(document).on('keydown', '.moreoptions-menu', function (event) {
            if (event.which === 9) {
                document.getElementsByClassName('amp-moreoptions-control')[0].setAttribute("aria-expanded", "false");
                $('.amp-moreoptions-control').find('.vjs-menu').removeClass('vjs-lock-showing');
            }
        });

        $(document).on('keydown', '.vjs-menu>.vjs-menu-content>.vjs-menu-item', function (e) {
            if (e.keyCode === 40) {
                var visibleContent = $(this).closest('.vjs-control').find('.vjs-menu>.vjs-menu-content>.vjs-menu-item').filter(function () {
                    return $(this).css('display') !== 'none'
                });
                var idx = visibleContent.toArray().indexOf(this);
                $(visibleContent[idx + 1]).focus();
            } else if (e.keyCode === 38) {
                var visibleContent = $(this).closest('.vjs-control').find('.vjs-menu>.vjs-menu-content>.vjs-menu-item').filter(function () {
                    return $(this).css('display') !== 'none'
                });
                var idx = visibleContent.toArray().indexOf(this);
                $(visibleContent[idx - 1]).focus();
            }
        });
         
    });
}).call(this);;
(function () {
    amp.plugin('languagelocalization', function (language) {
        var player = this;
        var dictionary;
        var localizationLangList;
        var lang = language;
        localizationLangList = {
            "ar": "ar",
            "bg": "bg",
            "zh": "zh",
            "es-MX": "es",
            "de-DE": "de",
            "fr-FR": "fr",
            "ja-JP": "ja",
            "zh-hans": "zh",
            "zh-hant": "zh",
            "cs": "cs",
            "da": "da",
            "nl": "nl",
            "en-US": "en",
            "en": "en",
            "fi": "fi",
            "fr": "fr",
            "de": "de",
            "el": "el",
            "hi": "hi",
            "hu": "hu",
            "id": "id",
            "it": "it",
            "ja": "ja",
            "ko": "ko",
            "nb": "nb",
            "pl": "pl",
            "pt-br": "pt",
            "pt-pt": "pt",
            "ro": "ro",
            "ru": "ru",
            "sk": "sk",
            "sl": "sl",
            "es": "es",
            "sv": "sv",
            "th": "th",
            "tr": "tr",
            "vi": "vi"
        }
        if (lang == null) {
            lang = "en";
        }
        else if (localizationLangList.hasOwnProperty(lang) == false) {
            lang = "en";
        }
        dictionary = {
            "FullScreen": {
                "ar": "شاشة كاملة",
                "bg": "Цял екран",
                "zh": "全屏",
                "zh-hans": "全屏",
                "zh-hant": "全屏",
                "cs": "Celá obrazovka",
                "da": "Fuld skærm",
                "nl": "Volledig scherm",
                "en-US": "Fullscreen",
                "en": "Fullscreen",
                "fi": "Koko näyttö",
                "fr": "Plein écran",
                "de": "Vollbild",
                "el": "ΠΛΗΡΗΣ ΟΘΟΝΗ",
                "hi": "पूर्ण स्क्रीन",
                "hu": "Teljes képernyő",
                "id": "Layar penuh",
                "it": "A schermo intero",
                "ja": "全画面",
                "ko": "전체 화면",
                "nb": "Full skjerm",
                "pl": "Pełny ekran",
                "pt-br": "Tela cheia",
                "pt-pt": "Tela cheia",
                "ro": "Ecran complet",
                "ru": "Полноэкранный",
                "sk": "Celá obrazovka",
                "sl": "Celozaslonski način",
                "es": "Pantalla completa",
                "sv": "Fullskärm",
                "th": "เต็มจอ",
                "tr": "Tam ekran",
                "vi": "Toàn màn hình"
            },
            "Volume": {
                "ar": "الصوت",
                "bg": "Сила на звука",
                "zh": "音量 (除'M'键视频静音/静音)",
                "zh-hans": "音量 (除'M'键视频静音/静音)",
                "zh-hant": "音量 (除'M'键视频静音/静音)",
                "cs": "Hlasitost",
                "da": "Bind",
                "nl": "Volume",
                "en-US": "Volume (Press 'M' key to mute/unmute the video)",
                "en": "Volume (Press 'M' key to mute/unmute the video)",
                "fi": "Äänenvoimakkuus",
                "fr": "Volume (Appuyez sur la touche 'M' pour désactiver/réactiver le son de la vidéo)",
                "de": "Lautstärke (Drücken Sie die Taste 'M', um das Video stummzuschalten/die Stummschaltung aufzuheben)",
                "el": "Ενταση ΗΧΟΥ",
                "hi": "आयतन",
                "hu": "Hangerő",
                "id": "Volume",
                "it": "Volume",
                "ja": "音量 (ビデオをミュート/ミュート解除するには、「M」キーを押します)",
                "ko": "음량",
                "nb": "Volum",
                "pl": "Tom",
                "pt-br": "Volume",
                "pt-pt": "Volume",
                "ro": "Volum",
                "ru": "Объем",
                "sk": "Objem",
                "sl": "Glasnost",
                "es": "Volumen (Presione la tecla 'M' para silenciar / reactivar el video)",
                "sv": "Volym",
                "th": "ปริมาณ",
                "tr": "Ses",
                "vi": "Âm lượng"
            },
            "Play": {
                "ar": "لعب",
                "bg": "Възпроизвеждане",
                "zh": "播放 (如空格键播放/止视频)",
                "zh-hans": "播放 (如空格键播放/止视频)",
                "zh-hant": "播放 (如空格键播放/止视频)",
                "cs": "Hrát si",
                "da": "Spil",
                "nl": "Speel",
                "en-US": "Play (Press space key to play/pause the video)",
                "en": "Play (Press space key to play/pause the video)",
                "fi": "pelata",
                "fr": "Lecture (Appuyez sur la touche Espace pour lire/mettre en pause la vidéo)",
                "de": "Wiedergeben (Drücken Sie die Tastentaste, um das Video abzuspielen / anzuhalten)",
                "el": "Παίζω",
                "hi": "खेल",
                "hu": "Játék",
                "id": "Bermain",
                "it": "Giocare",
                "ja": "再生 (スペースキーを押してビデオを再生/一時停止)",
                "ko": "플레이",
                "nb": "Spille",
                "pl": "Grać",
                "pt-br": "Toque",
                "pt-pt": "Toque",
                "ro": "Joaca",
                "ru": "Играть в",
                "sk": "hrať",
                "sl": "Igraj",
                "es": "Reproducir (presione la tecla de espacio para reproducir / pausar el video)",
                "sv": "Spela",
                "th": "เล่น",
                "tr": "Oyna",
                "vi": "Chơi"
            },
            "Pause": {
                "ar": "وقفة",
                "bg": "Пауза",
                "zh": "暂停 (如空格键播放/止视频)",
                "zh-hans": "暂停 (如空格键播放/止视频)",
                "zh-hant": "暂停 (如空格键播放/止视频)",
                "cs": "Pauza",
                "da": "Pause",
                "nl": "Pauze",
                "en-US": "Pause (Press space key to play/pause the video)",
                "en": "Pause (Press space key to play/pause the video)",
                "fi": "Tauko",
                "fr": "Pause (Appuyez sur la touche Espace pour lire/mettre en pause la vidéo)",
                "de": "Anhalten (Drücken Sie die Tastentaste, um das Video abzuspielen / anzuhalten)",
                "el": "Παύση",
                "hi": "ठहराव",
                "hu": "Szünet",
                "id": "Berhenti sebentar",
                "it": "Pausa",
                "ja": "一時停止 (スペースキーを押してビデオを再生/一時停止)",
                "ko": "중지",
                "nb": "Pause",
                "pl": "Pauza",
                "pt-br": "Pausa",
                "pt-pt": "Pausa",
                "ro": "Pauză",
                "ru": "Пауза",
                "sk": "Pauza",
                "sl": "Pavza",
                "es": "Pausa (presione la tecla de espacio para reproducir / pausar el video)",
                "sv": "Paus",
                "th": "หยุด",
                "tr": "Duraklat",
                "vi": "Tạm ngừng"
            },
            "Live": {
                "ar": "حي",
                "bg": "На живо",
                "zh": "生活",
                "zh-hans": "生活",
                "zh-hant": "生活",
                "cs": "Žít",
                "da": "Direkte",
                "nl": "Leven",
                "en-US": "Live",
                "en": "Live",
                "fi": "Elää",
                "fr": "Vivre",
                "de": "Leben",
                "el": "Ζω",
                "hi": "लाइव",
                "hu": "Élő",
                "id": "Hidup",
                "it": "Vivere",
                "ja": "住む",
                "ko": "라이브",
                "nb": "Bo",
                "pl": "Relacja na żywo",
                "pt-br": "Viver",
                "pt-pt": "Viver",
                "ro": "Trăi",
                "ru": "Прямой эфир",
                "sk": "Naživo",
                "sl": "V živo",
                "es": "En Vivo",
                "sv": "leva",
                "th": "มีชีวิต",
                "tr": "Canlı",
                "vi": "Trực tiếp"
            },
            "CaptionSearch": {
                "ar": "بحث التسمية التوضيحية",
                "bg": "Търсене на надписи",
                "zh": "字幕搜索",
                "zh-hans": "字幕搜索",
                "zh-hant": "字幕搜索",
                "cs": "Hledání titulků",
                "da": "Tekstsøgning",
                "nl": "Bijschrift zoeken",
                "en-US": "Caption Search",
                "en": "Caption Search",
                "fi": "Tekstityshaku",
                "fr": "Recherche de sous-titres",
                "de": "Untertitelsuche",
                "el": "Αναζήτηση υπότιτλων",
                "hi": "कैप्शन खोज",
                "hu": "Feliratok keresése",
                "id": "Pencarian Teks",
                "it": "Ricerca sottotitoli",
                "ja": "キャプション検索",
                "ko": "캡션 검색",
                "nb": "Tekstsøk",
                "pl": "Wyszukiwanie napisów",
                "pt-br": "Pesquisa de legenda",
                "pt-pt": "Pesquisa de legenda",
                "ro": "Căutare subtitrare",
                "ru": "Поиск по субтитрам",
                "sk": "Vyhľadávanie titulkov",
                "sl": "Iskanje napisov",
                "es": "Búsqueda de subtítulos",
                "sv": "Bildtext Sök",
                "th": "ค้นหาคำบรรยาย",
                "tr": "Altyazı Arama",
                "vi": "Tìm kiếm phụ đề"
            },
            "Popout": {
                "ar": "بوب أوت بلاير",
                "bg": "Изскачащ плейър",
                "zh": "弹出播放器",
                "zh-hans": "弹出播放器",
                "zh-hant": "彈出播放器",
                "cs": "Vyskakovací přehrávač",
                "da": "Pop Out-afspiller",
                "nl": "Pop-out speler",
                "en-US": "Pop Out Player",
                "en": "Pop Out Player",
                "fi": "Pop Out Player",
                "fr": "Lecteur Pop Out",
                "de": "Pop-Out-Player",
                "el": "Αναδυόμενο πρόγραμμα αναπαραγωγής",
                "hi": "पॉप आउट प्लेयर",
                "hu": "Pop Out Player",
                "id": "Pemain Keluar",
                "it": "Giocatore a comparsa",
                "ja": "ポップアウトプレーヤー",
                "ko": "팝아웃 플레이어",
                "nb": "Pop Out-spiller",
                "pl": "Wyskakuj gracz",
                "pt-br": "Leitor de saída",
                "pt-pt": "Leitor de saída",
                "ro": "Pop Out Player",
                "ru": "Всплывающий плеер",
                "sk": "Vyskakovací prehrávač",
                "sl": "Pop Out Player",
                "es": "Reproductor emergente",
                "sv": "Pop Out-spelare",
                "th": "เครื่องเล่น Pop Out",
                "tr": "Pop Out Player",
                "vi": "Trình phát Pop Out"
            },
            "Sl": {
                "ar": "لغة الإشارة",
                "bg": "жестомимичен език",
                "zh": "手语",
                "zh-hans": "手语",
                "zh-hant": "手语",
                "cs": "Znaková řeč",
                "da": "Tegnsprog",
                "nl": "Gebarentaal",
                "en-US": "Sign Language",
                "en": "Sign Language",
                "fi": "Viittomakieli",
                "fr": "Langue des signes",
                "de": "Gebärdensprache",
                "el": "Νοηματική γλώσσα",
                "hi": "सांकेतिक भाषा",
                "hu": "Jelnyelvi",
                "id": "Bahasa isyarat",
                "it": "Linguaggio dei segni",
                "ja": "手話",
                "ko": "수화",
                "nb": "Tegnspråk",
                "pl": "Język migowy",
                "pt-br": "Linguagem de sinais",
                "pt-pt": "Linguagem de sinais",
                "ro": "Limbajul semnelor",
                "ru": "Язык знаков",
                "sk": "Posunková reč",
                "sl": "Znakovni jezik",
                "es": "Lengua de señas",
                "sv": "Teckenspråk",
                "th": "ภาษามือ",
                "tr": "İşaret dili",
                "vi": "Ngôn ngữ cử chỉ"
            },
            "Asl": {
                "ar": "لغة الإشارة الأمريكية",
                "bg": "Американски жестомимичен език",
                "zh": "美国手语",
                "zh-hans": "美国手语",
                "zh-hant": "美国手语",
                "cs": "Americký znakový jazyk",
                "da": "Amerikansk tegnsprog",
                "nl": "Amerikaanse gebaren taal",
                "en-US": "American Sign Language",
                "en": "American Sign Language",
                "fi": "Amerikkalainen viittomakieli",
                "fr": "Langue des signes américaine",
                "de": "Amerikanische Gebärdensprache",
                "el": "Αμερικανική νοηματική γλώσσα",
                "hi": "अमेरिकी सांकेतिक भाषा",
                "hu": "amerikai jelnyelv",
                "id": "bahasa isyarat Amerika",
                "it": "Linguaggio dei segni americano",
                "ja": "米国手話",
                "ko": "미국식 수화",
                "nb": "amerikansk tegnspråk",
                "pl": "amerykański język migowy",
                "pt-br": "linguagem gestual americana",
                "pt-pt": "linguagem gestual americana",
                "ro": "Limbajul semnelor americane",
                "ru": "Американский язык жестов",
                "sk": "Americký posunkový jazyk",
                "sl": "Ameriški znakovni jezik",
                "es": "Lengua de señas de Estados Unidos",
                "sv": "amerikanskt teckenspråk",
                "th": "ภาษามืออเมริกัน",
                "tr": "Amerikan İşaret Dili",
                "vi": "Ngôn ngữ ký hiệu của Mỹ"
            },
            "Bsl": {
                "ar": "لغة الإشارة البريطانية",
                "bg": "Британски жестомимичен език",
                "zh": "英国手语",
                "zh-hans": "英国手语",
                "zh-hant": "英国手语",
                "cs": "Britský znakový jazyk",
                "da": "Britisk tegnsprog",
                "nl": "Britse Gebarentaal",
                "en-US": "British Sign Language",
                "en": "British Sign Language",
                "fi": "brittiläinen viittomakieli",
                "fr": "Langue des signes britannique",
                "de": "Britische Gebärdensprache",
                "el": "Βρετανική Νοηματική Γλώσσα",
                "hi": "ब्रिटिश सांकेतिक भाषा",
                "hu": "brit jelnyelv",
                "id": "Bahasa Isyarat Inggris",
                "it": "Lingua dei segni britannica",
                "ja": "英国手話",
                "ko": "영국 수화",
                "nb": "Britisk tegnspråk",
                "pl": "Brytyjski język migowy",
                "pt-br": "Língua de sinais britânica",
                "pt-pt": "Língua de sinais britânica",
                "ro": "Limba semnelor britanică",
                "ru": "Limba semnelor britanică",
                "sk": "Britský posunkový jazyk",
                "sl": "Britanski znakovni jezik",
                "es": "Lengua de señas británica",
                "sv": "Brittiskt teckenspråk",
                "th": "ภาษามืออังกฤษ",
                "tr": "İngiliz İşaret Dili",
                "vi": "Ngôn ngữ ký hiệu của Anh"
            },
            "Isl": {
                "ar": "لغة الإشارة الدولية",
                "bg": "Международен жестомимичен език",
                "zh": "国际手语",
                "zh-hans": "国际手语",
                "zh-hant": "国际手语",
                "cs": "Mezinárodní znakový jazyk",
                "da": "Internationalt tegnsprog",
                "nl": "Internationale gebarentaal",
                "en-US": "International Sign Language",
                "en": "International Sign Language",
                "fi": "Kansainvälinen viittomakieli",
                "fr": "Langue des signes internationale",
                "de": "Internationale Gebärdensprache",
                "el": "Διεθνής Νοηματική Γλώσσα",
                "hi": "अंतर्राष्ट्रीय सांकेतिक भाषा",
                "hu": "Nemzetközi jelnyelv",
                "id": "Bahasa Isyarat Internasional",
                "it": "Lingua dei segni internazionale",
                "ja": "国際手話",
                "ko": "국제 수화",
                "nb": "Internasjonalt tegnspråk",
                "pl": "Międzynarodowy język migowy",
                "pt-br": "Língua Internacional de Sinais",
                "pt-pt": "Língua Internacional de Sinais",
                "ro": "Limbajul semnelor internațional",
                "ru": "Международный язык жестов",
                "sk": "Medzinárodný posunkový jazyk",
                "sl": "mednarodni znakovni jezik",
                "es": "Lengua de señas internacional",
                "sv": "Internationellt teckenspråk",
                "th": "ภาษามือสากล",
                "tr": "Uluslararası İşaret Dili",
                "vi": "Ngôn ngữ ký hiệu quốc tế"
            },
            "AudioTracks": {
                "ar": "المسارات الصوتية",
                "bg": "Аудио записи",
                "zh": "音频曲目",
                "zh-hans": "音频曲目",
                "zh-hant": "音频曲目",
                "cs": "Zvukové stopy",
                "da": "Lydspor",
                "nl": "Audiotracks",
                "en-US": "Audio Tracks",
                "en": "Audio Tracks",
                "fi": "Ääniraidat",
                "fr": "Pistes audio",
                "de": "Audiotitel",
                "el": "Κομμάτια ήχου",
                "hi": "ऑडियो ट्रैक्स",
                "hu": "Hangsávok",
                "id": "Trek Audio",
                "it": "Tracce audio",
                "ja": "音声トラック",
                "ko": "오디오 트랙",
                "nb": "Lydspor",
                "pl": "Ścieżki audio",
                "pt-br": "Faixas de Áudio",
                "pt-pt": "Faixas de Áudio",
                "ro": "Piste audio",
                "ru": "Аудио дорожки",
                "sk": "Zvukové stopy",
                "sl": "Avdio posnetki",
                "es": "Pistas de audio",
                "sv": "Ljudspår",
                "th": "แทร็กเสียง",
                "tr": "Ses Parçaları",
                "vi": "Bản nhạc âm thanh"
            },
            "DownloadResource": {
                "ar": "تنزيل المورد",
                "bg": "Изтеглете ресурс",
                "zh": "下载资源",
                "zh-hans": "下载资源",
                "zh-hant": "下載資源",
                "cs": "Stáhnout zdroj",
                "da": "Download ressource",
                "nl": "Download de bron",
                "en-US": "Download Resource",
                "en": "Download Resource",
                "fi": "Lataa resurssi",
                "fr": "Télécharger la ressource",
                "de": "Ressource herunterladen",
                "el": "Λήψη πόρου",
                "hi": "संसाधन डाउनलोड करें",
                "hu": "Töltse le az erőforrást",
                "id": "Unduh Sumber Daya",
                "it": "Scarica risorsa",
                "ja": "リソースのダウンロード",
                "ko": "리소스 다운로드",
                "nb": "Last ned ressurs",
                "pl": "Pobierz zasób",
                "pt-br": "Baixar recurso",
                "pt-pt": "Baixar recurso",
                "ro": "Descărcați resursa",
                "ru": "Скачать ресурс",
                "sk": "Stiahnite si zdroj",
                "sl": "Prenesite vir",
                "es": "Descargar recurso",
                "sv": "Ladda ner resurs",
                "th": "ดาวน์โหลดทรัพยากร",
                "tr": "Kaynağı İndir",
                "vi": "Tải xuống tài nguyên"
            },
            "ShowInsights": {
                "ar": "إظهار الرؤى",
                "bg": "Показване на статистика",
                "zh": "显示见解",
                "zh-hans": "显示见解",
                "zh-hant": "顯示見解",
                "cs": "Zobrazit statistiky",
                "da": "Vis indsigt",
                "nl": "Inzichten tonen",
                "en-US": "Show Insights",
                "en": "Show Insights",
                "fi": "Näytä oivallukset",
                "fr": "Afficher les statistiques",
                "de": "Einblicke zeigen",
                "el": "Εμφάνιση πληροφοριών",
                "hi": "अंतर्दृष्टि दिखाएं",
                "hu": "Statisztikák megjelenítése",
                "id": "Tunjukkan Wawasan",
                "it": "Mostra approfondimenti",
                "ja": "インサイトを表示",
                "ko": "통찰력 표시",
                "nb": "Vis innsikt",
                "pl": "Pokaż statystyki",
                "pt-br": "Mostrar insights",
                "pt-pt": "Mostrar insights",
                "ro": "Afișați informații",
                "ru": "Показать статистику",
                "sk": "Zobraziť štatistiky",
                "sl": "Pokaži vpoglede",
                "es": "Mostrar estadísticas",
                "sv": "Visa insikter",
                "th": "แสดงข้อมูลเชิงลึก",
                "tr": "Analizleri Göster",
                "vi": "Hiển thị thông tin chi tiết"
            },
            "VideoQuality": {
                "ar": "جودة الفيديو",
                "bg": "Видео качество",
                "zh": "视频质量",
                "zh-hans": "视频质量",
                "zh-hant": "视频质量",
                "cs": "Kvalita videa",
                "da": "Videokvalitet",
                "nl": "Video kwaliteit",
                "en-US": "Video Quality",
                "en": "Video Quality",
                "fi": "Videon laatu",
                "fr": "Qualité vidéo",
                "de": "Videoqualität",
                "el": "Ποιότητα βίντεο",
                "hi": "वीडियो की गुणवत्ता",
                "hu": "Videó minőség",
                "id": "Kualitas video",
                "it": "Qualità video",
                "ja": "動画の画質",
                "ko": "비디오 품질",
                "nb": "Video kvalitet",
                "pl": "Jakość wideo",
                "pt-br": "Qualidade de vídeo",
                "pt-pt": "Qualidade de vídeo",
                "ro": "Calitate video",
                "ru": "Качество видео",
                "sk": "Kvalita videa",
                "sl": "Kakovost videa",
                "es": "Calidad de video",
                "sv": "Videokvalitét",
                "th": "คุณภาพวีดีโอ",
                "tr": "Video kalitesi",
                "vi": "Chất lượng video"
            },
            "PlaybackSpeed": {
                "ar": "سرعة التشغيل",
                "bg": "Скорост на възпроизвеждане",
                "zh": "播放速度",
                "zh-hans": "播放速度",
                "zh-hant": "播放速度",
                "cs": "Rychlost přehrávání",
                "da": "Afspilningshastighed",
                "nl": "Afspeelsnelheid",
                "en-US": "Playback Speed",
                "en": "Playback Speed",
                "fi": "Toistonopeus",
                "fr": "Vitesse de lecture",
                "de": "Wiedergabegeschwindigkeit",
                "el": "Ταχύτητα αναπαραγωγής",
                "hi": "प्लेबैक गति",
                "hu": "Lejátszási sebesség",
                "id": "Kecepatan Putar",
                "it": "Velocità di riproduzione",
                "ja": "再生速度",
                "ko": "재생 속도",
                "nb": "Avspillingshastighet",
                "pl": "Szybkość odtwarzania",
                "pt-br": "Velocidade de reprodução",
                "pt-pt": "Velocidade de reprodução",
                "ro": "Viteza de redare",
                "ru": "Скорость воспроизведения",
                "sk": "Rýchlosť prehrávania",
                "sl": "Hitrost predvajanja",
                "es": "Velocidad de reproducción",
                "sv": "Uppspelningshastighet",
                "th": "ความเร็วในการเล่น",
                "tr": "Oynatma Hızı",
                "vi": "Tốc độ phát lại"
            },
            "MoreOptions": {
                "ar": "المزيد من الخيارات",
                "bg": "Повече опций",
                "zh": "更多的选择",
                "zh-hans": "更多的选择",
                "zh-hant": "更多的選擇",
                "cs": "Více možností",
                "da": "Flere muligheder",
                "nl": "Meer opties",
                "en-US": "More Options",
                "en": "More Options",
                "fi": "Lisää vaihtoehtoja",
                "fr": "Plus d'options",
                "de": "Mehr Optionen",
                "el": "Περισσότερες επιλογές",
                "hi": "अधिक विकल्प",
                "hu": "Több lehetőség",
                "id": "Opsi lanjutan",
                "it": "Più opzioni",
                "ja": "より多くのオプション",
                "ko": "더 많은 옵션",
                "nb": "Flere valg",
                "pl": "Więcej możliwości",
                "pt-br": "Mais opções",
                "pt-pt": "Mais opções",
                "ro": "Mai multe opțiuni",
                "ru": "Больше вариантов",
                "sk": "Viac možností",
                "sl": "Več možnosti",
                "es": "Mas opciones",
                "sv": "Fler alternativ",
                "th": "ตัวเลือกเพิ่มเติม",
                "tr": "Daha fazla seçenek",
                "vi": "Lựa chọn khác"
            },
            "language": {
                "ar": "عربى",
                "bg": "български",
                "zh": "中文 (Zhōngwén), 汉语, 漢語",
                "zh-hans": "中文 (Zhōngwén), 汉语, 漢語",
                "zh-hant": "中文 (Zhōngwén), 汉语, 漢語",
                "cs": "čeština",
                "da": "dansk",
                "nl": "Nederlands",
                "en-US": "English-US",
                "en": "English",
                "fi": "Suomalainen",
                "fr": "français",
                "de": "Deutsche",
                "el": "Ελληνικά",
                "hi": "हिंदी",
                "hu": "Magyar",
                "id": "bahasa Indonesia",
                "it": "Italiana",
                "ja": "日本人",
                "ko": "한국어",
                "nb": "norsk",
                "pl": "Polskie",
                "pt-br": "Português",
                "pt-pt": "Português",
                "ro": "Română",
                "ru": "русский",
                "sk": "Slovák",
                "sl": "Slovenščina",
                "es": "Español",
                "sv": "svenska",
                "th": "ไทย",
                "tr": "Türk",
                "vi": "Tiếng Việt"
            },
            "PlayingIn": {
                "ar": "اللعب في",
                "bg": "Игра в",
                "zh": "参加比赛",
                "zh-hans": "参加比赛",
                "zh-hant": "參加比賽",
                "cs": "Hraní v",
                "da": "Spiller i",
                "nl": "Inspelen",
                "en-US": "Playing in",
                "en": "Playing in",
                "fi": "Pelaamassa",
                "fr": "Jouer dans",
                "de": "Einspielen",
                "es": "jugando en",
                "ja": "で遊ぶ"
            },
            "Seconds": {
                "zh": "秒：",
                "zh-hans": "秒：",
                "zh-hant": "秒：",
                "en-US": "seconds:",
                "en": "seconds:",
                "fr": "seconds:",
                "de": "Sekunden:",
                "es": "segundos:",
                "ja": "秒："
            },
            "WatchNow": {
                "zh": "立即观看",
                "zh-hans": "立即观看",
                "zh-hant": "立即觀看",
                "en-US": "Watch now",
                "en": "Watch now",
                "fr": "Regarde maintenant",
                "de": "Schau jetzt",
                "es": "Ver ahora",
                "ja": "今見る"
            },
            "Cancel": {
                "zh": "取消",
                "zh-hans": "取消",
                "zh-hant": "取消",
                "en-US": "Cancel",
                "en": "Cancel",
                "fr": "Annuler",
                "de": "Abbrechen",
                "es": "Cancelar",
                "ja": "キャンセル"
            },
            "StayTunedUpNext": {
                "ar": "التالي:",
                "bg": "Нагоре следваща:",
                "zh": "下一個：",
                "zh-hans": "下一个：",
                "zh-hant": "下一個：",
                "cs": "Nahoru další:",
                "da": "Næste trin:",
                "nl": "Volgende:",
                "en-US": "Up next: ",
                "en": "Up next: ",
                "fi": "Seuraavaksi:",
                "fr": "Suivant:",
                "de": "Als nächstes:",
                "el": "Επόμενος:",
                "hi": "ऊपर अगले:",
                "hu": "Felfelé a következő:",
                "id": "Selanjutnya:",
                "it": "Avanti:",
                "ja": "次へ：",
                "ko": "다음 위로:",
                "nb": "Opp neste:",
                "pl": "Następna:",
                "pt-br": "Até o próximo:",
                "pt-pt": "Até o próximo:",
                "ro": "În continuare:",
                "ru": "Наверх далее:",
                "sk": "Ďalej:",
                "sl": "Naprej naprej:",
                "es": "A continuación:",
                "sv": "Nästa steg:",
                "th": "ถัดไป:",
                "tr": "Sıradaki:",
                "vi": "Tiếp theo:"
            },
            "ExitFullScreen": {
                "zh": "非全屏 (如'Esc'按钮出全屏)",
                "zh-hans": "退出全屏 (如'Esc'按钮出全屏)",
                "zh-hant": "退出全屏 (如'Esc'按钮出全屏)",
                "en-US": "Exit Fullscreen (Press 'Esc' button to exit fullscreen)",
                "en": "Exit Fullscreen (Press 'Esc' button to exit fullscreen)",
                "fr": "Plein écran désactivé (Appuyez sur le bouton 'Esc' pour quitter le plein écran)",
                "de": "Vollbildmodus beenden (Drücken Sie die Taste 'Esc', um den Vollbildmodus zu verlassen)",
                "ja": "非全画面表示 (「Esc」ボタンを押してフルスクリーンを終了します)",
                "es": "Tamaño normal (Presione el botón 'Esc' para salir de la pantalla completa)"
            }
        };

        this.addEventListener(amp.eventName.pause, function () {
            if (dictionary.Play[lang] != undefined) {
                (document.getElementsByClassName("vjs-play-control")[0]).setAttribute("title", dictionary.Play[lang]);
                (document.getElementsByClassName("vjs-play-control")[0]).setAttribute("data-original-title", dictionary.Play[lang]);
            }
        });

        this.addEventListener(amp.eventName.timeupdate, function () {
            if (player.duration() > 0) {
                var percentagePlayed = Math.abs(player.duration() - (5 * 60));
                if (Math.ceil(player.currentTime()) == percentagePlayed) {
                    const div = document.getElementById("playlistendtext");
                    if (div != null && div != undefined && dictionary.StayTunedUpNext[lang] != undefined) {
                        div.textContent = dictionary.StayTunedUpNext[lang];
                    }
                }
                var endPercentagePlayed = Math.abs(player.duration() - (1 * 60));
                if (Math.abs(player.currentTime()) >= endPercentagePlayed) {
                    const div1 = document.getElementById("playingInText");
                    if (div1 != null && div1 != undefined && dictionary.PlayingIn[lang] != undefined) {
                        div1.textContent = dictionary.PlayingIn[lang];
                    }
                    const div2 = document.getElementById("secondText");
                    if (div2 != null && div2 != undefined && dictionary.Seconds[lang] != undefined) {
                        div2.textContent = dictionary.Seconds[lang];
                    }
                    const div3 = document.getElementById("watchNowlink");
                    if (div3 != null && div3 != undefined && dictionary.WatchNow[lang] != undefined) {
                        div3.textContent = dictionary.WatchNow[lang];
                        div3.setAttribute("title", dictionary.WatchNow[lang]);
                    }
                    const div4 = document.getElementById("closelink");
                    if (div4 != null && div4 != undefined && dictionary.Cancel[lang] != undefined) {
                        div4.textContent = dictionary.Cancel[lang];
                        div4.setAttribute("title", dictionary.Cancel[lang]);
                    }
                }
            }
        });
       
        var count = 0;
        this.addEventListener(amp.eventName.loadedmetadata, function () {

            var id = setInterval(function () {
                $("video").attr('disablePictureInPicture', 'true');
                $("div.vjs-menu >ul.vjs-menu-content>li.amp-menu-header").attr("role", "menuitem");
                $("div.vjs-menu >ul.vjs-menu-content>li.mps_track").attr("role", "menuitemcheckbox");
                $('.vjs-text-track-display').addClass('caption-font');
                if (document.getElementsByClassName("vjs-captionsearch-button").length > 0 && dictionary.CaptionSearch[lang] != undefined) {
                    (document.getElementsByClassName("vjs-captionsearch-button")[0]).setAttribute("title", dictionary.CaptionSearch[lang]);
                    (document.getElementsByClassName("vjs-captionsearch-button")[0]).setAttribute("data-original-title", dictionary.CaptionSearch[lang]);
                }
                if ($("li.more-caption-search").length > 0 && dictionary.CaptionSearch[lang] != undefined) {
                    (document.getElementsByClassName("more-caption-search")[0]).setAttribute("title", dictionary.CaptionSearch[lang]);
                    (document.getElementsByClassName("more-caption-search")[0]).setAttribute("data-original-title", dictionary.CaptionSearch[lang]);
                    $("li.more-caption-search").text(dictionary.CaptionSearch[lang]);
                }
                // if ($("li.amp-asl-control").length > 0 && dictionary.Asl[lang] != undefined) {
                // debugger;
                //$("li.amp-asl-control").text(dictionary.Asl[lang]);
                // }
                if (document.querySelectorAll('[data-category="BSL"]').length > 0 && dictionary.Bsl[lang] != undefined) {
                    document.querySelectorAll('[data-category="BSL"]')[0].setAttribute("title", dictionary.Bsl[lang]);
                    document.querySelectorAll('[data-category="BSL"]')[0].setAttribute("data-original-title", dictionary.Bsl[lang]);
                }
                if (document.querySelectorAll('[data-category="ASL"]').length > 0 && dictionary.Asl[lang] != undefined) {
                    document.querySelectorAll('[data-category="ASL"]')[0].setAttribute("title", dictionary.Asl[lang]);
                    document.querySelectorAll('[data-category="ASL"]')[0].setAttribute("data-original-title", dictionary.Asl[lang]);
                }
                if (document.querySelectorAll('[data-category="ISL"]').length > 0 && dictionary.Isl[lang] != undefined) {
                    document.querySelectorAll('[data-category="ISL"]')[0].setAttribute("title", dictionary.Isl[lang]);
                    document.querySelectorAll('[data-category="ISL"]')[0].setAttribute("data-original-title", dictionary.Isl[lang]);
                }
                if ($('.vjs-asl-button').length > 0 && dictionary.Sl[lang] != undefined) {
                    $('.vjs-asl-button').attr("title", dictionary.Sl[lang]);
                }
                if (document.getElementsByClassName("vjs-play-control").length > 0 && dictionary.Pause[lang] != undefined) {
                   //(document.getElementsByClassName("vjs-play-control")[0]).setAttribute("title", dictionary.Pause[lang]);
                    (document.getElementsByClassName("vjs-play-control")[0]).setAttribute("data-original-title", dictionary.Pause[lang]);
                }
                if (document.getElementsByClassName("download-button").length > 0 && dictionary.DownloadResource[lang] != undefined) {
                    (document.getElementsByClassName("download-button")[0]).setAttribute("title", dictionary.DownloadResource[lang]);
                    (document.getElementsByClassName("download-button")[0]).setAttribute("data-original-title", dictionary.DownloadResource[lang]);
                }
                if (document.getElementsByClassName("amp-playbackspeed-control-normal").length > 0 && dictionary.PlaybackSpeed[lang] != undefined) {
                    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).setAttribute("title", dictionary.PlaybackSpeed[lang]);
                    (document.getElementsByClassName("amp-playbackspeed-control-normal")[0]).setAttribute("data-original-title", dictionary.PlaybackSpeed[lang]);
                }
                if (document.getElementsByClassName("amp-quality-control").length > 0 && dictionary.VideoQuality[lang] != undefined) {
                    (document.getElementsByClassName("amp-quality-control")[0]).setAttribute("title", dictionary.VideoQuality[lang]);
                    (document.getElementsByClassName("amp-quality-control")[0]).setAttribute("data-original-title", dictionary.VideoQuality[lang]);
                }
                if (document.getElementsByClassName("amp-moreoptions-control").length > 0 && dictionary.MoreOptions[lang] != undefined) {
                    (document.getElementsByClassName("amp-moreoptions-control")[0]).setAttribute("title", dictionary.MoreOptions[lang]);
                    (document.getElementsByClassName("amp-moreoptions-control")[0]).setAttribute("data-original-title", dictionary.MoreOptions[lang]);
                }
                if ($('.vjs-vii-button').find('span.vjs-control-text') != null && dictionary.ShowInsights[lang] != undefined) {
                    $('.vjs-vii-button').find('span.vjs-control-text').text(dictionary.ShowInsights[lang]);
                }
                if ($('.amp-vii-control') > 0 && dictionary.ShowInsights[lang] != undefined) {
                    var ele = $('.amp-vii-control')[1];
                    ele.childNodes[1].innerHTML = dictionary.ShowInsights[lang];
                }
                if ($('.download-button') > 0 && dictionary.DownloadResource[lang] != undefined) {
                    var ele = $('.download-button')[1];
                    ele.childNodes[1].innerHTML = dictionary.DownloadResource[lang];
                }
                if (document.getElementsByClassName("vjs-vii-button").length > 0 && dictionary.ShowInsights[lang] != undefined) {
                    (document.getElementsByClassName("vjs-vii-button")[0]).setAttribute("title", dictionary.ShowInsights[lang]);
                    (document.getElementsByClassName("vjs-vii-button")[0]).setAttribute("data-original-title", dictionary.ShowInsights[lang]);
                }
                if (document.getElementsByClassName("amp-asl-control").length > 0 && dictionary.Sl[lang] != undefined) {
                    // (document.getElementsByClassName("amp-asl-control")[0]).setAttribute("title", dictionary.Sl[lang]);
                    (document.getElementsByClassName("amp-asl-control")[0]).setAttribute("data-original-title", dictionary.Sl[lang]);
                }
                if (document.getElementsByClassName("amp-popout-control").length > 0 && dictionary.Popout[lang] != undefined) {
                    (document.getElementsByClassName("amp-popout-control")[0]).setAttribute("data-original-title", dictionary.Popout[lang]);
                }
                if (document.getElementsByClassName("amp-audiotracks-control").length > 0 && dictionary.AudioTracks[lang] != undefined) {
                    (document.getElementsByClassName("amp-audiotracks-control")[0]).setAttribute("title", dictionary.AudioTracks[lang]);
                    (document.getElementsByClassName("amp-audiotracks-control")[0]).setAttribute("data-original-title", dictionary.AudioTracks[lang]);

                    // v-shych Commented as this part of code is breaking while there is switch from ASL to Normal :BUG 27771

                    //if (player.currentAudioStreamList()) {
                    //    for (var i = 0; i < player.currentAudioStreamList().streams.length; i++) {
                    //        if (player.currentAudioStreamList().streams[i].language == lang) {
                    //            player.currentAudioStreamList().switchIndex(i);
                    //            break;
                    //        }
                    //    }
                    //}
                }
                if (document.getElementsByClassName("vjs-mute-control").length > 0 && dictionary.Volume[lang] != undefined) {
                    (document.getElementsByClassName("vjs-mute-control")[0]).setAttribute("title", dictionary.Volume[lang]); 
                    (document.getElementsByClassName("vjs-mute-control")[0]).setAttribute("data-original-title", dictionary.Volume[lang]);
                }
                if (document.getElementsByClassName("vjs-fullscreen-control").length > 0 && dictionary.FullScreen[lang] != undefined) {
                    if (player.isFullscreen() && dictionary.ExitFullScreen[lang] != undefined) {
                        (document.getElementsByClassName("vjs-fullscreen-control")[0]).setAttribute("title", dictionary.ExitFullScreen[lang]);
                    }
                    else {
                        (document.getElementsByClassName("vjs-fullscreen-control")[0]).setAttribute("title", dictionary.FullScreen[lang]);
                        (document.getElementsByClassName("vjs-fullscreen-control")[0]).setAttribute("data-original-title", dictionary.FullScreen[lang]);
                        (document.getElementsByClassName("vjs-fullscreen-control")[0]).setAttribute("aria-label", dictionary.FullScreen[lang]);
                    }
                }
                if (document.getElementsByClassName("ui-autocomplete-input").length > 0 && dictionary.CaptionSearch[lang] != undefined) {
                    (document.getElementsByClassName("ui-autocomplete-input")[0]).setAttribute("placeholder", dictionary.CaptionSearch[lang]);
                }
                count++;
                if (count == 5) {
                    clearInterval(id);
                }
            }, 200);

        });
        this.addEventListener(amp.eventName.play, function () {
            if (dictionary.Pause[lang] != undefined) {
                (document.getElementsByClassName("vjs-play-control")[0]).setAttribute("title", dictionary.Pause[lang]);
                (document.getElementsByClassName("vjs-play-control")[0]).setAttribute("data-original-title", dictionary.Pause[lang]);
            }

        });
        this.addEventListener(amp.eventName.fullscreenchange, function () {
            if (this.isFullscreen_) {
                //trapFocus();
                if (dictionary.ExitFullScreen[lang] != undefined) {
                    (document.getElementsByClassName("vjs-fullscreen-control")[0]).setAttribute("title", dictionary.ExitFullScreen[lang]);
                }
            }
            else {
                //lastAnchor.removeEventListener("keydown", keydownHandler);
                if (dictionary.FullScreen[lang] != undefined) {
                    (document.getElementsByClassName("vjs-fullscreen-control")[0]).setAttribute("title", dictionary.FullScreen[lang]);
                }
            }
        });
    });

}).call(this);;
(function () {

    amp.plugin('statsForNerds', function (options) {
        var player = this;
        var graphsDrawn = false;
        var bwGraphData = [];
        var bufferGraphData = [];
        var p = player.mediaPlayer;
        var res = p.videoWidth + " x " + p.videoHeight;
        var widthHeight = player.options_.width + " x " + player.options_.height;
        var contextMenuHtml = "<div id='custom-menu' class='show-context-menu'><ol><li class='show-stats' data-ai='true'  data-eleregion='Player' data-catagory='stats for nerds' title='Playback Statistics'>Playback Statistics</li></ol></div>";
        var statsOverlayHtml = "<div id='overlay' class='hide-stat-item'><button type='button' class='close closeStats close-icon-button' aria-label='Close'><span aria-hidden='true'>&times;</span></button><p id='overlayText'>No data to show.</p></div>";
        var chartOverHtml = '<div id="chartOverlay" class="graphsRow" style="font-size:0.75em;"><div id="BWGraphs" class="graphsDiv"><div class="graphLegendDiv"><div id="BWGraphsLegendDiv"></div> </div><div id="BWGraphsDiv" style="height:150px"></div></div><br /> <div id="BufferGraphs" class="graphsDiv"><div class="graphLegendDiv"><div id="BufferGraphsLegendDiv"></div></div><div id="BufferGraphsDiv" style="height: 150px"></div></div></div>';
        player.addEventListener(amp.eventName.loadedmetadata, bindContextMenu.bind(this));

        function bindContextMenu() {
            $("#" + this.id()).append(contextMenuHtml);          
            $("#"+this.id()).bind("contextmenu", function (e) {
                e.preventDefault();
                $("#custom-menu").css({ top: e.offsetY, left: e.offsetX }).show(100);
            });

            $("#" + this.id()).mouseup(function (e) {
                var container = $("#custom-menu");
                if (container.has(e.target).length === 0) {
                    container.hide();
                }
            });

            $(".show-stats").click(function () {
                $(".show-context-menu").toggle();
                //  $("#overlay").removeClass("hide-stat-item");
                $("#overlay").show();
                $("#chartOverlay").attr("style","visibility:visible");
                $("#BWGraphs").attr("style", "visibility:visible");
                $("#BWGraphsLegendDiv").attr("style", "visibility:visible");
                $("#BWGraphsDiv").attr("style", "visibility:visible");
                $("#BufferGraphs").attr("style", "visibility:visible");
                $("#BufferGraphsLegendDiv").attr("style", "visibility:visible");
                $("#BufferGraphsDiv").attr("style", "visibility:visible");
            });

            $(".closeStats").click(function () {
                //  $("#overlay").addClass("hide-stat-item");
                $("#overlay").hide();
                $("#chartOverlay").hide();
                $("#BWGraphs").hide();
                $("#BWGraphsLegendDiv").hide();
                $("#BWGraphsDiv").hide();
                $("#BufferGraphs").hide();
                $("#BufferGraphsLegendDiv").hide();
                $("#BufferGraphsDiv").hide();
            });
        }

        /**
         * Takes player source URL and determines if it is using http || https.
         * @return {string} - "http" or "https" 
         */
        function getHttpStatus() {
            var endpoint = p.src;

            // Head returns 'http' or 'https'
            // ^  Start of Line
            // .  Match zero or more
            // *  Match previous char
            // \  Literal next char
            var re = /^.*:\/\//;
            var head = re.exec(endpoint);

            if (head[0] === "https://") {
                return "https";
            } else {
                return "http";
            }

        }
   
        /**
         * Data object used to store misc values of AMS player.
         */
        var data = {
            "curPlaybackBitrate": "",
            "mimeType": p.type ,
            "src": $(".azuremediaplayer").attr("data-id"),
            "curTime": "",
            "res": "",
            "dimensions": "",
            "avgBandwidthKbps": "",
            "curDlBitrate": "",
            "streamType": "",
            "techName": player.currentTechName(),
            "duration": "",
            "ended": "",
            "paused": "",
            "seeking" :"",
            "isLive": p.isLive,
            "autoPlay": p.autoplay,
            "error": "",
            "curAbsoluteTime": "",
            "volume": "",
            "GUID": options.videoGUID,
            "VideoBufferLevel": "",
            "AudioBufferLevel": "",
            "UserAgent": navigator.userAgent
        }


        /**
         * Instantiates a formatted block of text based on info returnes from data object.
         * @param {object} stats - Accepts data object, which is automatically updated every (x) seconds. 
         * @return {string} - Formatted string which will be set as the innerText of the overlay
         */
        function createTextBlock(stats) {
            var sData =
              "User ID: " + stats.UserID + '\n' +
                "Video Guid: " + stats.GUID + '\n' +
                "Video Title: " + options.VideoTitle + '\n' +
              //"VideoCDN: " + stats.src + '\n' +
              "Mime Type: " + stats.mimeType + '\n' +
              "Stream Type: " + stats.streamType + '\n' +
              "Tech Name: " + stats.techName + '\n' +
              "Dimensions: " + stats.dimensions + '\n' +
              "Resolution: " + stats.res + '\n' +
              "Dl Bitrate: " + stats.curDlBitrate + '\n' +
              "Avg Bandwidth: " + stats.avgBandwidthKbps + '\n' +
              "Current Bitrate: " + stats.curPlaybackBitrate + '\n' +
              "Video Buffer Level: " + stats.VideoBufferLevel + '\n' +
              "Audio Buffer Level: " + stats.AudioBufferLevel + '\n' +
              "Is Live: " + stats.isLive + '\n' +
              "Autoplay: " + stats.autoPlay + '\n' +
              "Volume: " + stats.volume + '\n' +
              "Duration: " + stats.duration + '\n' +
              "Current Time: " + stats.curTime + '\n' +
              "Absolute Time: " + stats.curAbsoluteTime + '\n' +
              "Ended: " + stats.ended + '\n' +
              "Paused: " + stats.paused + '\n' +
              "Seeking: " + stats.seeking + '\n' +
              "Error: " + stats.error + '\n'+
              "User Agent: " + stats.UserAgent + '\n';


            return sData;
        }

      
        /**
         * Sets the text value of the overlay with updated stats from data object.
         */
        function updateOverlayText() {
            document.getElementById('overlayText').innerText = createTextBlock(data);
        }


        /**
        * Conver size to bytes
        * @param {number} bytes - downlaod value
        * @param {string} decimals - Where should the placeholder be?
        * @return {number} parseFloat - size changes, depending on initial size of bytes passed in
        */
        function formatBytes(bytes, decimals) {
            if (bytes === 0) return '0 Byte';
            var k = 1000;
            var dm = decimals + 1 || 3;
            var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            var i = Math.floor(Math.log(bytes) / Math.log(k));

            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        }


        /**
         * Updates data object every (x) seconds, which the stats overlay text object then reads 
         */
        function setValuesForStatsOverlay() {          
            setInterval(function () { data.curTime = p.currentTime }, 1000);
            setInterval(function () { data.curAbsoluteTime = p.currentAbsoluteTime }, 1000);
            setInterval(function () { data.duration = p.duration }, 1000);
            setInterval(function () { data.ended = p.ended }, 1000);
            setInterval(function () { data.paused = p.paused }, 1000);
            setInterval(function () { data.seeking = p.seeking }, 1000);
            setInterval(function () { data.error = p.error }, 1000);
            setInterval(function () { data.volume = p.volume }, 1000);
            setInterval(function () { data.curDlBitrate = formatBytes(p.currentDownloadBitrate) }, 1000);
            setInterval(function () { data.VideoBufferLevel = formatBytes(p.videoBufferData.bufferLevel) }, 1000);
            setInterval(function () { data.AudioBufferLevel = formatBytes(p.audioBufferData.bufferLevel) }, 1000);
            setInterval(function () { data.avgBandwidthKbps = formatBytes(p.videoBufferData._bandwidthTracker.averageBandwidthInKbps) }, 1000);
            setInterval(function () { data.dimensions = player.options_.width + " x " + player.options_.height }, 1000);
            setInterval(function () { data.curPlaybackBitrate = formatBytes(p.currentPlaybackBitrate) }, 1000);
            setInterval(function () { data.res = p.videoWidth + " x " + p.videoHeight }, 1000);
            setTimeout(function () { data.streamType = getHttpStatus() }, 1000);
            setInterval(function () { updateOverlayText() }, 1000);
            setTimeout(function () { data.UserID = customUserConfig.getCustomUserId() }, 1000);
        }


        var chartControl = function () {

            var graphs = [];
            var graphData = [];
            var startTime = Date.now();

            function setupCharts(ifBufferDataAvailable) {
                var bwGraphOptions = {
                    labels: ['time', 'DownloadBR', 'PlaybackBR'],
                    strokeWidth: 2,
                    drawPoints: true,
                    pointSize: 3,
                    axisLabelFontSize: 10,
                    digitsAfterDecimal: 1,
                    labelsKMB: true,
                    labelsDiv: 'BWGraphsLegendDiv',
                    legend: 'always',
                    ylabel: 'Bitrate (bps)',
                    series: {
                        DownloadBR: { axis: 'y' },
                        PlaybackBR: { axis: 'y' }
                    },
                    axes: {
                        x: {},
                        y: {},
                        y2: {}
                    }
                };

                if (ifBufferDataAvailable) {
                    bwGraphOptions.labels = ['time', 'DownloadBR', 'PlaybackBR', 'MeasuredBW', 'AverageBW'];
                    bwGraphOptions.y2label = 'Bandwidth (bps)';
                    bwGraphOptions.y2labelWidth = 20;
                    bwGraphOptions.series = {
                        DownloadBR: { axis: 'y' },
                        PlaybackBR: { axis: 'y' },
                        MeasuredBW: { axis: 'y2' },
                        AverageBW: { axis: 'y2' }
                    };
                    bwGraphOptions.axes = {
                        x: {},
                        y: {},
                        y2: {}
                    };
                }
                bwGraph = new Dygraph(document.getElementById("BWGraphsDiv"), bwGraphData, bwGraphOptions);
                graphs.push(bwGraph);

                var bufferGraphOptions = {
                    labels: ['time', 'bufferSize'],
                    strokeWidth: 2,
                    drawPoints: true,
                    pointSize: 2,
                    axisLabelFontSize: 10,
                    digitsAfterDecimal: 1,
                    ylabel: 'Buffer Size (s)',
                    labelsKMB: true,
                    labelsDiv: 'BufferGraphsLegendDiv',
                    legend: 'always',
                    series: {
                        bufferSize: { axis: 'y' },
                    },
                    axes: {
                        x: {},
                        y: {},
                    }
                }

                if (ifBufferDataAvailable) {
                    bufferGraphOptions.labels = ['time', 'videoBuffer', 'audioBuffer', 'videoDLTime'];
                    bufferGraphOptions.y2label = 'Download Time (ms)';
                    bufferGraphOptions.y2LabelWidth = 0;
                    bufferGraphOptions.series = {
                        videoBuffer: { axis: 'y' },
                        audioBuffer: { axis: 'y' },
                        videoDLTime: { axis: 'y2' }
                    };
                    bufferGraphOptions.axes = {
                        x: {},
                        y: {},
                        y2: {}
                    }
                }

                bufferGraph = new Dygraph(document.getElementById("BufferGraphsDiv"), bufferGraphData, bufferGraphOptions);
                graphs.push(bufferGraph);

                var sync = Dygraph.synchronize(graphs, {
                    zoom: false,
                    selection: true
                });

            }

            function registerBufferDataEvents() {
                if (!graphsDrawn) {
                    var bufferData = player.videoBufferData();
                    if (bufferData) {
                        bufferData.addEventListener("downloadcompleted", addGraphData);
                    } else {
                        player.addEventListener("timeupdate", function () {
                            if (player.paused()) {
                                if (player.currentTechName() === "Html5") {
                                    addGraphData();
                                } else if (player.currentTechName() !== "SilverlightSS") {
                                    if (calculateBufferAhead() < 29) {
                                        addGraphData();
                                    }
                                }
                            } else {
                                addGraphData();
                            }
                        });
                    }
                }
            }

            function addGraphData() {
              
                var bufferData = player.videoBufferData();
                var completed = bufferData ? bufferData.downloadCompleted : null;
                var download = bufferData ? completed.mediaDownload : null;

                var measuredBandwidth = completed ? completed.measuredBandwidth : null;
                var perceivedBandwidth = bufferData ? bufferData.perceivedBandwidth : null
                var downloadBitrate = download ? download.bitrate : player.currentDownloadBitrate();
                var currentPlaybackBitrate = player.currentPlaybackBitrate();
                var videoBufferLevel = bufferData ? bufferData.bufferLevel : calculateBufferAhead();
                var audioBufferLevel = player.audioBufferData() ? player.audioBufferData().bufferLevel : null;
                var downloadTimeInMs = completed ? completed.totalDownloadMs : null;

                if (bwGraphData.length > 30) {
                    bwGraphData.shift();
                }

                if (bufferGraphData.length > 30) {
                    bufferGraphData.shift();
                }

                if (bufferData) {
                    bwGraphData.push([(Date.now() - startTime) / 1000, downloadBitrate, currentPlaybackBitrate, measuredBandwidth, perceivedBandwidth]);
                    bufferGraphData.push([(Date.now() - startTime) / 1000, videoBufferLevel, audioBufferLevel, downloadTimeInMs]);
                } else {
                    bwGraphData.push([(Date.now() - startTime) / 1000, downloadBitrate, currentPlaybackBitrate]);
                    bufferGraphData.push([(Date.now() - startTime) / 1000, videoBufferLevel]);
                }

                if (!graphsDrawn) {
                    setupCharts(bufferData);
                    graphsDrawn = true;
                    if (player.currentTechName() === "SilverlightSS") {
                        $("#BufferGraphs").hide();
                    } else if (player.currentTechName() === "Html5") {
                        $("#BWGraphs").hide();
                    }
                }
                updateGraphs();
            }

            function init() {
                player.addEventListener("loadedmetadata", registerBufferDataEvents);
                player.addEventListener("playbackbitratechanged", addGraphData);
            }

            return {
                init: init,
                addGraphData:addGraphData
            }
        }

        var updateGraphs = function () {
                if (document.getElementById('BWGraphs').style.display !== "none") {
                    bwGraph.updateOptions({ file: bwGraphData });
                }
                if (document.getElementById('BufferGraphs').style.display !== "none") {
                    bufferGraph.updateOptions({ file: bufferGraphData });
                }           
        }

        /**
         * Main function -- Entry point of this application
         */
        player.ready(function () {
            $("#" + this.id()).append(statsOverlayHtml);
            $("#" + this.id()).append(chartOverHtml);
            player.on('play', setValuesForStatsOverlay);
            chartControl().init();
        });
    });
}).call(this);;
(function () {
    amp.plugin('downloadresource', function (options) {
        // remember the video player instance
        var vidPlayer = this;

        //wait till player gets load
        vidPlayer.addEventListener(amp.eventName.loadeddata, function () {
            var downloadIcon = document.createElement('div');
            downloadIcon.setAttribute("class", "download-button vjs-menu-button vjs-control outline-enabled-control");
            downloadIcon.setAttribute("tabindex", "0");
            downloadIcon.setAttribute("role", "button");
            downloadIcon.setAttribute("aria-expanded", "false");
            downloadIcon.setAttribute("aria-haspopup", "true");
            downloadIcon.setAttribute("aria-live", "polite");
            downloadIcon.setAttribute("title", "Download Resource");
            var outerDiv = ' '
            //Create Menu
            var menu = '<div class="vjs-control-content"><a style="line-height: 1.9; font-size: 15px;color:white; font-weight:600" class="amp-cust-download-control amp-control-display-xs-hidden-sm"></a><span class="vjs-control-text">Resources</span><div class="vjs-menu" style="display: none;"><ul class="vjs-menu-content"><li class="amp-menu-header" style="position: relative; padding: 5px !important; text-transform: capitalize;">Resources</li></ul></div></div>';
            var menuitem = '';
            for (var v in options.links) {
                menuitem += '<li class="vjs-menu-item amp-menu-item outline-enabled-control" role="button" aria-selected="false" aria-live="polite"><a href="' + options.links[v].link + '" target="_blank" class="amp-embed-share" data-ai="true"   data-eleregion="Player" data-catagory="DownloadResource" title="' + options.links[v].title + '">' + options.links[v].title + '<span class="vjs-control-text"> </span></a></li>'
            }
            //Add menu
            downloadIcon.insertAdjacentHTML('afterbegin', menu);
            var list = downloadIcon.getElementsByTagName("ul")[0].insertAdjacentHTML('beforeend', menuitem);

            //Add downloadIcon
            var rightControlsContainer = document.getElementsByClassName("amp-controlbaricons-right")[0];
            
            if ($(rightControlsContainer).find('.download-button').length == 0) {
                rightControlsContainer.insertBefore(downloadIcon, rightControlsContainer.childNodes[1]);
            }
            //bind mouse events
            downloadIcon.addEventListener("mouseover", function () {
                downloadIcon.setAttribute("aria-expanded", "true");
                addClass(downloadIcon.getElementsByClassName("vjs-menu")[0], "vjs-lock-showing");
                //setTimeout(function () {
                //    removeClass(downloadIcon.getElementsByClassName("vjs-menu")[0], "vjs-lock-showing");
                //}, 2000);
            });
            //downloadIcon.addEventListener("mouseout", function () {
            //    downloadIcon.setAttribute("aria-expanded", "false");
            //    removeClass(downloadIcon.getElementsByClassName("vjs-menu")[0], "vjs-lock-showing");
            //});
            downloadIcon.addEventListener('keydown', function () {
                if (event.which === 13 || event.which === 32) {
                    downloadIcon.setAttribute("aria-expanded", "true");
                    addClass(downloadIcon.getElementsByClassName("vjs-menu")[0], "vjs-lock-showing");
                    //setTimeout(function () {
                    //    removeClass(downloadIcon.getElementsByClassName("vjs-menu")[0], "vjs-lock-showing");
                    //}, 2000);
                }
            });

            renderDownloadForMoreOptions();

            addDownloadMoreEvents();
        });

        function addDownloadMoreEvents() {
            $('.download-button').click(function () {
                $('.download-button').attr('aria-expanded', 'true');
                $(".amp-moreoptions-control").attr('aria-expanded', 'false');
                removeClass($(".amp-moreoptions-control").find(".vjs-menu")[0], "vjs-lock-showing");
                addClass($('.download-button').find(".vjs-menu")[0], "vjs-lock-showing");
                //setTimeout(function () {
                //    removeClass($('.download-button').find(".vjs-menu")[0], "vjs-lock-showing");
                //}, 2000);
            });

            $('.download-button').keydown(function () {
                if (event.which === 13 || event.which === 32) {
                    $('.download-button').attr('aria-expanded', 'true');
                    $(".amp-moreoptions-control").attr('aria-expanded', 'false');
                    removeClass($(".amp-moreoptions-control").find(".vjs-menu")[0], "vjs-lock-showing");
                    addClass($('.download-button').find(".vjs-menu")[0], "vjs-lock-showing");
                    //setTimeout(function () {
                    //    removeClass($('.download-button').find(".vjs-menu")[0], "vjs-lock-showing");
                    //}, 2000);
                }
            });

            $('.vjs-menu').mouseout(function () {
                removeClass($('.download-button').find(".vjs-menu")[0], "vjs-lock-showing");
                $('.download-button').attr('aria-expanded', 'false');
            });
        }

        function hasClass(el, className) {
            if (el.classList)
                return el.classList.contains(className)
            else
                return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
        }

        function addClass(el, className) {
            if (el.classList)
                el.classList.add(className)
            else if (!hasClass(el, className)) el.className += " " + className
        }

        function removeClass(el, className) {
            if (el.classList)
                el.classList.remove(className)
            else if (hasClass(el, className)) {
                var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
                el.className = el.className.replace(reg, ' ')
            }
        }

        var renderDownloadForMoreOptions = function () {
            var DownloadMIcons = document.createElement('li');
            DownloadMIcons.setAttribute("class", "display-sm-hidden-xs download-button margin-top-halfpx vjs-menu-item amp-menu-item vjs-menu-button vjs-menu-button-popup vjs-control vjs-button outline-enabled-control");
            DownloadMIcons.setAttribute("tabindex", "-1");
            DownloadMIcons.setAttribute("role", "menuitem");
            DownloadMIcons.setAttribute("aria-live", "off");
            DownloadMIcons.setAttribute("title", "Download Resource");
            DownloadMIcons.setAttribute("aria-label", "Download Resource");
            DownloadMIcons.insertAdjacentHTML('afterbegin', "<span class='amp-cust-download-control' style='font-size:18px; float:left;'></span><span style='margin-left:-15px!important;font-size:11px'>Download</span>");
            $(".amp-moreoptions-control ul").append(DownloadMIcons);
        };
    });
}).call(this);;
(function () {
    amp.plugin('castvideo', function (options) {
        // remember the video player instance
        var vidPlayer = this;

        vidPlayer.addEventListener(amp.eventName.loadeddata, function () {
            var castIcon = document.createElement('button');
            castIcon.setAttribute("class", "cast-button amp-control-display-xs-hidden-sm vjs-menu-button vjs-control outline-enabled-control");
            castIcon.setAttribute("tabindex", "0");
            castIcon.setAttribute("role", "button");
            castIcon.setAttribute("aria-live", "polite");
            castIcon.setAttribute("title", "Cast Video");
            castIcon.setAttribute("id", "castbutton");
            castIcon.innerHTML = "<div class='amp-control-display-xs-hidden-sm cast-button-inner' style='margin:7px'></div>";
            
            var rightControlsContainer = document.getElementsByClassName("amp-controlbaricons-right")[0];
            rightControlsContainer.insertBefore(castIcon, rightControlsContainer.childNodes[1]);
            
            castIcon.addEventListener('keydown', function () {
                if (event.which === 13) {
                    castIcon.click();
                }
            });
            
            $('#castbutton').css("display", "block !important");

            addCastMoreEvents();
            renderLikeForMoreOptions();
        });

        function addCastMoreEvents() {
            $(document).on('click touchstart', ".cast-button", castBtnClick);
        }

        var loadNow = function () {
            
            console.log('LoadNow, session:', cast.session)
            var streamType = "video/mp4";
            if (options.streamUrl.lastIndexOf('.m3u8') >= 0) {
                // HTTP Live Streaming
                streamType = "application/vnd.apple.mpegurl";
            } else if (options.streamUrl.lastIndexOf('.mpd') >= 0) {
                // MPEG-DASH
                streamType = "application/dash+xml";
            } else if (options.streamUrl.indexOf('.ism/') >= 0) {
                // Smooth Streaming
                streamType = "application/vnd.ms-sstr+xml";
            }
            var mediaInfo = new chrome.cast.media.MediaInfo(options.streamUrl, streamType);

            if (options.captionUrl !== undefined && options.captionUrl !== null && options.captionUrl.trim() !== "") {
                var englishSubtitle = new chrome.cast.media.Track(1, // track ID
                    chrome.cast.media.TrackType.TEXT);
                englishSubtitle.trackContentId = options.captionUrl;
                englishSubtitle.trackContentType = 'text/vtt';
                englishSubtitle.subtype = chrome.cast.media.TextTrackType.SUBTITLES;
                englishSubtitle.name = 'English Subtitles';
                englishSubtitle.language = 'en-US';
                englishSubtitle.customData = null;

                mediaInfo.tracks = [englishSubtitle]
                mediaInfo.activeTrackIds = [1]
            }

            mediaInfo.metadata = new chrome.cast.media.GenericMediaMetadata();
            mediaInfo.metadata.title = options.title;
            
            request = new chrome.cast.media.LoadRequest(mediaInfo);
            cast.session.loadMedia(request,
                onMediaDiscovered.bind(this, 'loadMedia'),
                function (er) {
                    console.log('onMediaError', er)
                });

            function onMediaDiscovered(how, media) {
                console.log('got media!', media)
                cast.currentMedia = media;
                var activeTrackIds = [1];
                var tracksInfoRequest = new chrome.cast.media.EditTracksInfoRequest(activeTrackIds);
                media.editTracksInfo(tracksInfoRequest, function succCB() {
                    console.log('success changing trackIDs!')
                }, function errorCallback() {
                    console.log('Error CB!')
                });
            }
        }

        var castNow = function () {
            console.log('casting!')
            var sessionRequest = new chrome.cast.SessionRequest(chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID);
            chrome.cast.requestSession(function onRequestSessionSuccess(session) {
                console.log('Session success', session)
                cast.session = session
                loadNow();
            }, function onLaunchError(er) {
                console.log('onLaunchError', er)
            }, sessionRequest);

            setTimeout(function () {
                var sessionRequest = new chrome.cast.SessionRequest(chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID);
                chrome.cast.requestSession(function onRequestSessionSuccess(session) {
                    console.log('Session success', session)
                    cast.session = session
                    loadNow();
                }, function onLaunchError(er) {
                    console.log('onLaunchError', er)
                }, sessionRequest);

            }, 1000)

        }

        var castAirplayNow = function () {
            var video = document.querySelector("video");
            video.webkitShowPlaybackTargetPicker();
        }

        var castBtnClick = function (e) {
            e.stopPropagation();
            if (window.WebKitPlaybackTargetAvailabilityEvent) {
                castAirplayNow();
            }
            else if (isChromeCastApiAvailable === true) {
                castNow();
            } else {
                mediusCommon.createAlert("Cast not available for browser", mediusCommon.alertTypes.info, ".row");
                mediusCommon.createAutoClosingAlert(".alert-info", 1500);
            }
        };

        var renderLikeForMoreOptions = function () {
            var castIcons = document.createElement('li');
            castIcons.setAttribute("class", "cast-button display-sm-hidden-xs margin-top-halfpx amp-latest-like-control vjs-menu-item amp-menu-item vjs-menu-button vjs-menu-button-popup vjs-control vjs-button  outline-enabled-control");
            castIcons.setAttribute("tabindex", "-1");
            castIcons.setAttribute("role", "menuitem");
            castIcons.setAttribute("aria-live", "off");
            castIcons.setAttribute("title", "Cast");
            castIcons.setAttribute("aria-label", "Cast Video");
            castIcons.onclick = castBtnClick;
            castIcons.insertAdjacentHTML('afterbegin', "<span class='cast-button-inner'></span><span class='' style='font-size:11px;position:absolute;margin-left:8px !important;'>Cast</span>");
            $(".amp-moreoptions-control ul").append(castIcons);
        };

        function hasClass(el, className) {
            if (el.classList)
                return el.classList.contains(className)
            else
                return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
        }

        function addClass(el, className) {
            if (el.classList)
                el.classList.add(className)
            else if (!hasClass(el, className)) el.className += " " + className
        }

        function removeClass(el, className) {
            if (el.classList)
                el.classList.remove(className)
            else if (hasClass(el, className)) {
                var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
                el.className = el.className.replace(reg, ' ')
            }
        }
    });
}).call(this);;
(function () {
    amp.plugin('seekToPosition', function (options) {
        var player = this;
        player.addEventListener(amp.eventName.loadeddata, function () {
            seekToPosition(options.timeInterval);
        });

        function seekToPosition(timeInSecs) {
            if (timeInSecs) {
                var time = timeInSecs;
                if (!isNaN(time))
                    player.currentTime(parseInt(time, 10));
            }
        }
    });
}).call(this);;

(function () {
    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 = this;

        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;
        options.sessiontitles = [];
        var dataSetupOptions = {};
        if (this.options()["data-setup"]) {
            parsedOptions = JSON.parse(this.options()["data-setup"]);
            if (parsedOptions.ga) {
                dataSetupOptions = parsedOptions.ga;
            }
        }

        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.buffered();
            var currentTime = player.currentTime();

            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.currentTime());
                    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.currentTime());
                    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.currentSrc());
            }
            if (options.debug) {
                console.log("streamId set as: " + streamId);
            }

            if (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.currentTime());

                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.currentTime());
                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) {
                        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.currentTime());
                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.currentTime());
                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 ((typeof player.isFullscreen === "function" ? player.isFullscreen() : void 0) || (typeof player.isFullScreen === "function" ? player.isFullScreen() : void 0)) {
                //enter fullscreen
                trackEvent('fullscreen', { 'enter': 1, 'currentTime': currentTime });
            } else {
                //exit fullscreen
                trackEvent('fullscreen', { 'enter': 0, 'currentTime': currentTime });
            }
        };
        var triggervc = true;
        var volume;
        var volumechange = function () {
            volume = player.volume();
            if (triggervc) {
                triggervc = false;
                setTimeout(function () {
                    triggervc = true;
                    trackEvent('vc', { 'volume': volume });
                    if (volume < 0.02)
                        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.currentTime());
                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(/[\\[]/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];
        }
        var getPlayerState = function () {
            var playerMode;
            //0 - vod, 1 - live, 2 - dvr
            if (playerStateonPageLoad && player.isLive()) { //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 (liveflag) {
                    playerMode = 1;
                }
                else {
                    playerMode = 0;
                }
            }
            else if (playerStateonPageLoad && !player.isLive()) { //dvr
                var liveflag = false;
                var scode = getQuerystring('scode', '');
                if (scode.length > 0) {
                    liveflag = true;
                }
                else {
                    if (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 (liveflag) {
                    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.currentTime() - opt.playeroffset);
            }
            else {
                pt = player.currentTime();
            }
            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 trackEvent = function (event, metricsObj, addlProps) {
            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: player.isLive() ? "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
                };
                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) || '');
                }
                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();
                if (window.isLive === true) {
                    properties.isLive = "live";
                    properties.ps = 1;
                }
                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;

                }
                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.currentTime().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);
                }
                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: {}
                };
                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) {
        //    $(".vjs-volume-menu-button").click(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("click", ".vjs-asl-button .vjs-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);

        });
        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));
            });
        }

    });

}).call(this);


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();
//});;
(function () {

    amp.plugin('supportFeedback', function (options) {

        var player = this;
        var mediaPlay = player.mediaPlayer;
        player.addEventListener(amp.eventName.loadeddata, function () {
            //var feedbackIcon = document.createElement('div');
            //feedbackIcon.setAttribute("class", "amp-feedback-control quality-4 vjs-menu-button vjs-control outline-enabled-control");
            //feedbackIcon.setAttribute("tabindex", "0");
            //feedbackIcon.setAttribute("role", "button");
            //feedbackIcon.setAttribute("aria-expanded", "false");
            //feedbackIcon.setAttribute("aria-live", "polite");

            ////Create Menu
            //var menu = '<div class="vjs-control-content"><dt class="feedback-button" style="line-height: 1.4; font-size: 16px;"></dt><div class="vjs-menu" style="display: none;"><ul class="vjs-menu-content"><li class="amp-menu-header">Feedback</li></ul></div></div>';

            ////Add menu
            //feedbackIcon.insertAdjacentHTML('afterbegin', menu);

            ////Add feedbackIcon
            //var rightControlsContainer = document.getElementsByClassName("amp-controlbaricons-right")[0];
            //rightControlsContainer.insertBefore(feedbackIcon, rightControlsContainer.childNodes[0]);

            ////bind mouse events
            //feedbackIcon.addEventListener("mouseover", function () {
            //    feedbackIcon.setAttribute("aria-expanded", "true");
            //    addClass(feedbackIcon.getElementsByClassName("vjs-menu")[0], "vjs-lock-showing");
            //});
            //feedbackIcon.addEventListener("mouseout", function () {
            //    feedbackIcon.setAttribute("aria-expanded", "false");
            //    removeClass(feedbackIcon.getElementsByClassName("vjs-menu")[0], "vjs-lock-showing");
            //});

            var manuheader = document.getElementsByClassName("amp-feedback-control")[0];
            manuheader.addEventListener("keydown", function () {
                if (event.which === 13 || event.which === 32) {
                    saveStats(data);
                }
            });
            manuheader.addEventListener("click", function () {
                saveStats(data);
            });
        });
        /**
         * Takes player source URL and determines if it is using http || https.
         * @return {string} - "http" or "https" 
         */
        function getHttpStatus() {
            var endpoint = mediaPlay.src;

            // Head returns 'http' or 'https'
            // ^  Start of Line
            // .  Match zero or more
            // *  Match previous char
            // \  Literal next char
            var re = /^.*:\/\//;
            var head = re.exec(endpoint);

            if (head[0] === "https://") {
                return "https";
            } else {
                return "http";
            }

        }

        /**
         * Data object used to store misc values of AMS player.
         */
        var data = {
            "streamType": "",
            "mimeType": mediaPlay.type,
            "source": $(".azuremediaplayer").attr("data-id"),
            "techName": player.currentTechName(),
            "Video GUID": options.videoGUID,
            "resolution": "",
            "dimensions": "",
            "duration": "",
            "currentTime": "",
            "currentAbsoluteTime": "",
            "currentDownloadBitrate": "",
            "currentPlaybackBitrate": "",
            "avgBandwidthKbps": "",
            "ended": "",
            "paused": "",
            "seeking": "",
            "volume": "",
            "isLive": mediaPlay.isLive,
            "autoPlay": mediaPlay.autoplay,
            "error": "",
            "VideoBufferLevel": "",
            "AudioBufferLevel": "",
            "UserAgent": navigator.userAgent
        }

        /**
       * Conver size to bytes
       * @param {number} bytes - downlaod value
       * @param {string} decimals - Where should the placeholder be?
       * @return {number} parseFloat - size changes, depending on initial size of bytes passed in
       */
        function formatBytes(bytes, decimals) {
            if (bytes === 0) return '0 Byte';
            var k = 1000;
            var dm = decimals + 1 || 3;
            var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
            var i = Math.floor(Math.log(bytes) / Math.log(k));

            return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
        }

        /**
         * Updates data object every (x) seconds, which the stats overlay text object then reads 
         */
        function setValuesForStatsOverlay() {
            setInterval(function () { data.currentTime = mediaPlay.currentTime }, 1000);
            setInterval(function () { data.currentAbsoluteTime = mediaPlay.currentAbsoluteTime }, 1000);
            setInterval(function () { data.duration = mediaPlay.duration }, 1000);
            setInterval(function () { data.ended = mediaPlay.ended }, 1000);
            setInterval(function () { data.paused = mediaPlay.paused }, 1000);
            setInterval(function () { data.seeking = mediaPlay.seeking }, 1000);
            setInterval(function () { data.error = mediaPlay.error }, 1000);
            setInterval(function () { data.volume = mediaPlay.volume }, 1000);
            setInterval(function () { data.currentDownloadBitrate = formatBytes(mediaPlay.currentDownloadBitrate) }, 1000);
            setInterval(function () { data.VideoBufferLevel = formatBytes(mediaPlay.videoBufferData.bufferLevel) }, 1000);
            setInterval(function () { data.AudioBufferLevel = formatBytes(mediaPlay.audioBufferData.bufferLevel) }, 1000);
            setInterval(function () { data.avgBandwidthKbps = formatBytes(mediaPlay.videoBufferData._bandwidthTracker.averageBandwidthInKbps) }, 1000);
            setInterval(function () { data.dimensions = player.options_.width + " x " + player.options_.height }, 1000);
            setInterval(function () { data.currentPlaybackBitrate = formatBytes(mediaPlay.currentPlaybackBitrate) }, 1000);
            setInterval(function () { data.resolution = mediaPlay.videoWidth + " x " + mediaPlay.videoHeight }, 1000);
            setTimeout(function () { data.streamType = getHttpStatus() }, 1000);
        }


        var saveStats = function (curdata) {
            curdata["User ID"] = customUserConfig.getCustomUserId();
            var vid = $("#videoid").val();
            var statObj = { VideoGuid: vid, StatType: "ForNerds", JsonValue: encodeURI(JSON.stringify(curdata)), CreatedBy: customUserConfig.getCustomUserId() };
            var token = $('input[name="__RequestVerificationToken"]').val();
            mediusCommon.executeXHR({
                url: "/video/saveStatsForNerds",
                contentType: 'application/x-www-form-urlencoded',
                method: "POST",
                asyncCall: false,
                data: { __RequestVerificationToken: token, statsDetails: statObj }
            }).promise().then(function (data) {
                var protocol = location.protocol;
                var slashes = protocol.concat("//");
                var host = slashes.concat(window.location.host);
                window.location.href = "mailto:mediusadmins@microsoft.com?subject=Medius Dev Support&body=Please do not remove this link from the mail body: " + host + "/video/GetStatsForNerds/" + data.guid;
            }, function (err) {
                console.log(err);
            });
        }

        function hasClass(el, className) {
            if (el.classList)
                return el.classList.contains(className)
            else
                return !!el.className.match(new RegExp('(\\s|^)' + className + '(\\s|$)'))
        }

        function addClass(el, className) {
            if (el.classList)
                el.classList.add(className)
            else if (!hasClass(el, className)) el.className += " " + className
        }

        function removeClass(el, className) {
            if (el.classList)
                el.classList.remove(className)
            else if (hasClass(el, className)) {
                var reg = new RegExp('(\\s|^)' + className + '(\\s|$)')
                el.className = el.className.replace(reg, ' ')
            }
        }

        /**
         * Main function -- Entry point of this application
         */
        player.ready(function () {
            player.on('play', setValuesForStatsOverlay);
        });

    });
}).call(this);


;
(function () {

    amp.plugin('likeUnlikeVideo', function (options) {        
        var player = this;
        var mediaPlay = player.mediaPlayer;        
        player.addEventListener(amp.eventName.loadeddata, function () {            
            if ($('.amp-like-control').length === 0) {
                var likeIcon = document.createElement('div');
                likeIcon.setAttribute("class", "display-xs-hidden-sm like-button amp-like-control quality-4 vjs-menu-button vjs-control outline-enabled-control");
                likeIcon.setAttribute("tabindex", "0");
                likeIcon.setAttribute("role", "button");
                likeIcon.setAttribute("aria-live", "polite");
                likeIcon.setAttribute("title", "Like Video");
                //Create Menu
                var menu = '<div class="vjs-control-content"><a data-ai="true" aria-label="Like this video"  data-eleregion="Player" data-catagory="Like" title="Like Video" style="line-height: 1.67; color:white; font-size: 18px;">&#x2661;</a></div>';

            //Add menu
            likeIcon.insertAdjacentHTML('afterbegin', menu);
            //Add likeIcon
            var rightControlsContainer = document.getElementsByClassName("amp-controlbaricons-right")[0];
            if ($(rightControlsContainer).find('.amp-like-control').length == 0) {
                rightControlsContainer.insertBefore(likeIcon, rightControlsContainer.childNodes[0]);
            }

                // var likeClick = likeIcon.getElementsByClassName("like-button")[0];



                //likeClick.addEventListener("click", function () {             
                //    handleClick(this);
                //});
                //likeIcon.addEventListener("keydown", function () {
                //    if (event.which === 13 || event.which === 32) {
                //        handleClick(this);
                //    }
                //});
                renderLikeForMoreOptions();

                addEvents();
            }
        });


        var addEvents = function (obj) {

            $('.like-button').click(function () {
                handleClick(this);
            });

            $('.like-button').keydown(function (event) {
                if (event.which === 13 || event.which === 32) {
                    handleClick(this);
                }
            });
            getVideoLikeStatus($('.like-button'));
        };
        var handleClick = function (obj) {
            var likeFlag = false;
            var el = $('.like-button');
            if (obj.classList.contains('liked-video')) {
                el.addClass('unliked-video');
                el.removeClass('liked-video');
            }
            else {
                el.addClass('liked-video');
                el.removeClass('unliked-video');
                likeFlag = true;
            }
            saveLikes(likeFlag);
        }

        var getVideoLikeStatus = function (el) {
            var vid = $("#videoid").val();
            if (vid.length > 0) {
                mediusCommon.executeXHR({
                    url: "/video/GetVideoLikeFlag",
                    method: "GET",
                    data: { id: vid, user: customUserConfig.getCustomUserId() }
                }).promise().then(function (data) {
                    if (data.flag) {
                        el.addClass('liked-video');
                        el.removeClass('unliked-video');
                    }
                    else {
                        el.addClass('unliked-video');
                        el.removeClass('liked-video');
                    }
                }, function (err) {
                    console.log(err);
                });
            }
        };

        var saveLikes = function (likeFlag) {
            var vid = $("#videoid").val();
            var token = $('input[name="__RequestVerificationToken"]').val();
            var likeObj = { VideoGuid: vid, Liked: likeFlag, UserName: customUserConfig.getCustomUserId(), CreatedBy: customUserConfig.getCustomUserId() };
            mediusCommon.executeXHR({
                url: "/video/AddEditVideoLike",
                contentType: 'application/x-www-form-urlencoded',
                method: "POST",
                data: { __RequestVerificationToken: token, curObj: likeObj }
            }).promise().then(function (data) {

            }, function (err) {
                console.log(err);
            });
        };

        var renderLikeForMoreOptions = function () {
            var LikeMIcons = document.createElement('li');
            LikeMIcons.setAttribute("class", "display-sm-hidden-xs margin-top-halfpx like-button amp-latest-like-control vjs-menu-item amp-menu-item vjs-menu-button vjs-menu-button-popup vjs-control vjs-button  outline-enabled-control");
            LikeMIcons.setAttribute("tabindex", "-1");
            LikeMIcons.setAttribute("role", "menuitem");
            LikeMIcons.setAttribute("aria-live", "off");
            LikeMIcons.setAttribute("title", "Like");
            LikeMIcons.setAttribute("aria-label", "Like");
            LikeMIcons.insertAdjacentHTML('afterbegin', "<span style='font-size:18px; margin-left: 2px !important; float: left;'>&#x2661;</span><span class='moreoptionliketext' style='font-size:11px'>Like</span>");
            $(".amp-moreoptions-control ul").append(LikeMIcons);
        };

    });
}).call(this);;
(function () {
    amp.plugin('UpdateVideoDuration', function (options) {
        var player = this;

        player.addEventListener(amp.eventName.play, updatedata.bind(this));
        function updatedata() {
            if ((!options.VideoDuration.length > 0) || options.VideoDuration.trim() == '00:00:00') {
                var DurationToUpdate = secondsToHms(Math.round(player.duration()));
                var UpdateResponse = UpdateDetails(options.videoGUID, DurationToUpdate);
            }

        }

        var urls = {
            UpdateDurationUrl: "/Video/UpdateDuration",
        };

        var secondsToHms = function (totalSeconds) {
            var hours = Math.floor(totalSeconds / 3600);
            var minutes = Math.floor((totalSeconds - (hours * 3600)) / 60);
            var seconds = totalSeconds - (hours * 3600) - (minutes * 60);

            // round seconds
            seconds = Math.round(seconds * 100) / 100

            var result = (hours < 10 ? "0" + hours : hours);
            result += ":" + (minutes < 10 ? "0" + minutes : minutes);
            result += ":" + (seconds < 10 ? "0" + seconds : seconds);
            return result;
        }

        var UpdateDetails = function (videoId, videoDuration) {
            var token = $('input[name="__RequestVerificationToken"]').val();
            $.ajax({
                url: window.location.origin + urls.UpdateDurationUrl,
                data: { __RequestVerificationToken: token, 'VideoGuid': videoId, 'VideoDurations': videoDuration },
                type: "POST",
                contentType: 'application/x-www-form-urlencoded',
                success: function (data) {
                    console.log(data + "Duration Updated");
                },

                error: function (response) {
                    console.log(response + "Something went wrong");
                }
            });
        };
    });
}).call(this);





;
(function () {
    amp.plugin('VideoStartNotification', function (options) {
        var player = this;
        player.addEventListener(amp.eventName.start, videoStartNotification.bind(this));
        function videoStartNotification() {
            UpdateVideoStart(options.shortCode, options.channelList);
        }

        var urls = {
            VideoStartUrl: window.location.origin + "/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) {
            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)
                    && (channelKey != "IR19")
                    && (channelKey != "IG19")
                    && (channelKey != "MSRFY20")) {
                    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");
                        }
                    });
                }
            }, 5 * 60 * 1000) // Trigger every 5 minutes
        };
    });
}).call(this);;
(function () {
    amp.plugin('VideoStartNotification_old', function (options) {
        var player = this;

        player.addEventListener(amp.eventName.play, videoStartNotification.bind(this));
        function videoStartNotification() {
            if (player.currentTime().toString().slice(0, 3) == "0.0") {
                UpdateVideoStart(options.shortCode);
            }
        }

        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) {
            var registrantKey = getParameterByName("uid");
            if (registrantKey != null && registrantKey.length > 0 && shortCode != null && shortCode.toUpperCase().startsWith("IR19")) {
                var token = $('input[name="__RequestVerificationToken"]').val();
                $.ajax({
                    url: urls.VideoStartUrl,
                    data: {  __RequestVerificationToken: token, 'ShortCode': shortCode, 'ChannelKey': 'IR19', 'RegistrantKey': registrantKey, 'Scantype': 'OnDemand' },
                    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");
                    }
                });
            }
        };
    });
}).call(this);;


(function () {
    amp.plugin('mediusplaylist', function (options) {
        // remember the video player instance
        var vidPlayer = this;

        // the key points array is passed in the options
        var showPlaylist = options.options.showplaylist;
        var htmlTemplate = {
            playlistIconDiv: '<div id="playlistIcon" class="vjs-control outline-enabled-control" role="button" aria-live="polite" tabindex="1" data-ai="true"  data-eleregion="Player" data-catagory="ShowPlaylist" title="Show playlist"><div class="vjs-control-content"><span class="glyphicon glyphicon-th-list" aria-hidden="true" style="padding:3px;" title="show playlist"></span></div></div>',
            replayandautoplay: '<div class="vjs-big-play-buttons" id="autoplaynreplayoverlay" role="button" aria-live="polite" tabindex="0" aria-label="play video" style="content: &quot;e630 &quot;;left: 0.0em;top: 0;font-size: 3em;display: block;z-index: 100;position: absolute;width: 100%;height: 100%;/text-align: center;cursor: pointer;opacity: 1;background-color: rgba(60, 69, 79, 1);opacity:0.95;border: .1em solid #3b4249;-moz-box-shadow: 0 0 1em rgba(255,255,255,.25);box-shadow: 0 0 1em rgba(255,255,255,.25);-moz-transition: all .4s;-o-transition: all .4s;transition: all .4s;"><span aria-hidden="true" style="position: relative;top: 42%;left: 42%;" id="replayvideoFromplaylist" data-ai="true"  data-eleregion="Player" data-catagory="Replay" title="Replay"><span class="glyphicon glyphicon-repeat" aria-hidden="true"></span> REPLAY</span><span aria-hidden="true" style="position: absolute;top: 49%;left: 42%; clear:both"><input style="height:20px;width:22px;" type="checkbox" id="chkmarkautoPlayfornextVideo" name="chkmarkautoPlayfornextVideo" data-ai="true"  data-eleregion="Player" data-catagory="Autoplay" title="Autoplay"><label for="chkmarkautoPlayfornextVideo" style="font-size: 25px; text-align: center;color:#fff;padding: 16px;"> Auto play</label></span></div>',
            onlyreplay: '<div class="vjs-big-play-buttons" id="autoplaynreplayoverlay" role="button" aria-live="polite" tabindex="0" aria-label="play video" style="content: &quot;e630 &quot;left: 0.0em;top: 0;font-size: 3em;display: block;z-index: 100;position: absolute;width: 100%;height: 100%;/text-align: center;cursor: pointer;opacity: 1;background-color: rgba(60, 69, 79, 1);opacity:0.95;border: .1em solid #3b4249;-moz-box-shadow: 0 0 1em rgba(255,255,255,.25);box-shadow: 0 0 1em rgba(255,255,255,.25);-moz-transition: all .4s;-o-transition: all .4s;transition: all .4s;"><span aria-hidden="true" style="position: relative;top: 42%;left: 42%;" id="replayvideoFromplaylist" data-ai="true"  data-eleregion="Player" data-catagory="Reaply" title="Reaply"><span class="glyphicon glyphicon-repeat" aria-hidden="true"></span> REPLAY</span></div>'
        }
        vidPlayer.addEventListener(amp.eventName.pause, function () {
            // console.log('plyaer paused');
        });
        vidPlayer.addEventListener(amp.eventName.play, function () {
            var overlayautoplay = document.getElementById('autoplaynreplayoverlay');
            if (typeof overlayautoplay !== 'null')
                $(overlayautoplay).hide();
            //console.log('plyaer play');
        });
        // loadstart is the earliest event we can hook, use it to initialize our plugin
        vidPlayer.addEventListener(amp.eventName.loadstart, function () {
            $(".azuremediaplayer").attr('style', 'border:0px!important;');
           
    
            var playlistdiv = window.parent.document.getElementById('playerPlaylistDiv');
            if ($(playlistdiv).length > 0) {
                $(".vjs-control-bar").attr('style', 'padding-left:14px!important;padding-right:20px!important;');
                if ($(playlistdiv).parent('#playlistparent').hasClass('playlistAsidetoVideo')) {
                    
                    var playlistdivClose = window.parent.document.getElementById('closePlaylist');
                    $(playlistdivClose).hide();
                    $(playlistdiv).show();
                } else {
                    $(playlistdiv).hide();
                    var playerht = $(".azuremediaplayer").height();
                    playerht = parseInt(playerht) - 38;
                    playerht = playerht;
                    //chane left prop
                    if (!$(playlistdiv).is(":visible")) {
                        $(playlistdiv).parent('#playlistparent').attr('style', "left:0!important;height:"+playerht);
                    } else {
                        $(playlistdiv).parent('#playlistparent').attr('style', "left:58.7%!important;height:"+playerht);
                    }
                    if ($("#playlistIcon").length <= 0) {
                        $(".amp-controlbaricons-left").append($(htmlTemplate.playlistIconDiv));
                        $('#playlistIcon').click(function () {
                            $(playlistdiv).toggle();
                            //chane left prop
                            if (!$(playlistdiv).is(":visible")) {
                                $(playlistdiv).parent('#playlistparent').attr('style', "left:0!important;height:"+playerht);
                            } else {
                                $(playlistdiv).parent('#playlistparent').attr('style', "left:58.7%!important;height:"+playerht);
                            }

                        });
                    } else {
                        //nothing to show
                    }
                }

            }
        });
        vidPlayer.addEventListener(amp.eventName.ended, function () {
            //handle end and play next item;3

            var playlistdiv = window.parent.document.getElementById('playerPlaylistDiv');
            if ($(playlistdiv).length > 0) {
                var tilenumber = $(playlistdiv).find('.playlistItem').find('.boldHeader').attr('data-tileorder');

                if (parseInt(tilenumber) === 1) {
                    //show option to replay and auto play 
                    showandbindautoplayscreen();
                }
                else {
                    startautoplaying();
                }
            }
        });
        var startautoplaying = function () {
            var playlistdiv = window.parent.document.getElementById('playerPlaylistDiv');
            if ($(playlistdiv).length > 0) {
                var tilenumber = $(playlistdiv).find('.playlistItem').find('.boldHeader').attr('data-tileorder');
                var txtforautoplay = window.parent.document.getElementById('autoplaystatus');
                var currentAUtoplaystatus = $(txtforautoplay).val();
                if (currentAUtoplaystatus === "autoplay") {
                    tilenumber = parseInt(tilenumber) + 1;
                    var rr = window.parent.document.getElementsByClassName("headerNumber_" + tilenumber);
                    var nextVguid = $(rr).attr('data-vguid');
                    if (nextVguid !== "" && typeof nextVguid !== 'undefined' && nextVguid !== null) {
                        var hrefValue = window.location.host;
                        $(playlistdiv).find('.playlistItem').find(".playlist_heading").removeClass('boldHeader');
                        var rrr = window.parent.document.getElementsByClassName("headerNumber_" + tilenumber);
                        $(rrr).addClass('boldHeader');
                       
                        setIFrameSrc("ifrmamy", "https://" + hrefValue + "/Embed/Video?id=" + nextVguid + "&showPlaylist=" + true + "&Autoplay=" +"1");

                    } else {
                        showandbindraplayonly();
                    }
                }
                else {
                    showandbindautoplayscreen();
                }
            }

        };
        var showandbindraplayonly = function () {
            $(htmlTemplate.onlyreplay).insertAfter($(".vjs-big-play-button"));
            $("#replayvideoFromplaylist").bind('click', function () {
                checkandreplay();
            });
        };
        var showandbindautoplayscreen = function () {
            $(htmlTemplate.replayandautoplay).insertAfter($(".vjs-big-play-button"));
            $("#replayvideoFromplaylist").bind('click', function () {
                checkandreplay();
            });
            $('input[name=chkmarkautoPlayfornextVideo]').bind("change", function () {
                var txtforautoplay = window.parent.document.getElementById('autoplaystatus');
                if ($(this).is(":checked")) {
                    $(txtforautoplay).val("autoplay");
                    startautoplaying();
                    // console.log('setting autoplay');
                }
                else {
                    $(txtforautoplay).val("manualplay");
                    //   console.log('setting manualplay');
                }
            });
        };
        var checkandreplay = function () {
            var playlistdiv = window.parent.document.getElementById('playerPlaylistDiv');
            if ($(playlistdiv).length > 0) {
                var tilenumber = $(playlistdiv).find('.playlistItem').find('.boldHeader').attr('data-tileorder');

                var rr = window.parent.document.getElementsByClassName("headerNumber_" + tilenumber);
                var nextVguid = $(rr).attr('data-vguid');
                if (nextVguid !== "") {
                    var hrefValue = window.location.host;
                    setIFrameSrc("ifrmamy", "https://" + hrefValue + "/Embed/Video?id=" + nextVguid + "&showPlaylist=" + true);
                }
            }
        };
        var setIFrameSrc = function (idFrame, url) {
            var originalFrame = window.parent.document.getElementById(idFrame);
            var newFrame = window.parent.document.createElement("iframe");
            newFrame.id = originalFrame.getAttribute("id");
            newFrame.width = originalFrame.getAttribute("width");
            newFrame.height = originalFrame.getAttribute("height");
            newFrame.src = url;
            newFrame.setAttribute("style", "border:0px;");
            var parent = originalFrame.parentNode;
            parent.replaceChild(newFrame, originalFrame);
        }
    });
}).call(this);;
/*! @license Copyright 2014 Dan Vanderkam (danvdk@gmail.com) MIT-licensed (http://opensource.org/licenses/MIT) */
!function (t) { "use strict"; for (var e, a, i = {}, r = function () { }, n = "memory".split(","), o = "assert,clear,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn".split(",") ; e = n.pop() ;) t[e] = t[e] || i; for (; a = o.pop() ;) t[a] = t[a] || r }(this.console = this.console || {}), function () { "use strict"; CanvasRenderingContext2D.prototype.installPattern = function (t) { if ("undefined" != typeof this.isPatternInstalled) throw "Must un-install old line pattern before installing a new one."; this.isPatternInstalled = !0; var e = [0, 0], a = [], i = this.beginPath, r = this.lineTo, n = this.moveTo, o = this.stroke; this.uninstallPattern = function () { this.beginPath = i, this.lineTo = r, this.moveTo = n, this.stroke = o, this.uninstallPattern = void 0, this.isPatternInstalled = void 0 }, this.beginPath = function () { a = [], i.call(this) }, this.moveTo = function (t, e) { a.push([[t, e]]), n.call(this, t, e) }, this.lineTo = function (t, e) { var i = a[a.length - 1]; i.push([t, e]) }, this.stroke = function () { if (0 === a.length) return void o.call(this); for (var i = 0; i < a.length; i++) for (var s = a[i], l = s[0][0], h = s[0][1], p = 1; p < s.length; p++) { var g = s[p][0], d = s[p][1]; this.save(); var u = g - l, c = d - h, y = Math.sqrt(u * u + c * c), _ = Math.atan2(c, u); this.translate(l, h), n.call(this, 0, 0), this.rotate(_); for (var v = e[0], f = 0; y > f;) { var x = t[v]; f += e[1] ? e[1] : x, f > y ? (e = [v, f - y], f = y) : e = [(v + 1) % t.length, 0], v % 2 === 0 ? r.call(this, f, 0) : n.call(this, f, 0), v = (v + 1) % t.length } this.restore(), l = g, h = d } o.call(this), a = [] } }, CanvasRenderingContext2D.prototype.uninstallPattern = function () { throw "Must install a line pattern before uninstalling it." } }(); var DygraphOptions = function () { return function () { "use strict"; var t = function (t) { this.dygraph_ = t, this.yAxes_ = [], this.xAxis_ = {}, this.series_ = {}, this.global_ = this.dygraph_.attrs_, this.user_ = this.dygraph_.user_attrs_ || {}, this.labels_ = [], this.highlightSeries_ = this.get("highlightSeriesOpts") || {}, this.reparseSeries() }; t.AXIS_STRING_MAPPINGS_ = { y: 0, Y: 0, y1: 0, Y1: 0, y2: 1, Y2: 1 }, t.axisToIndex_ = function (e) { if ("string" == typeof e) { if (t.AXIS_STRING_MAPPINGS_.hasOwnProperty(e)) return t.AXIS_STRING_MAPPINGS_[e]; throw "Unknown axis : " + e } if ("number" == typeof e) { if (0 === e || 1 === e) return e; throw "Dygraphs only supports two y-axes, indexed from 0-1." } if (e) throw "Unknown axis : " + e; return 0 }, t.prototype.reparseSeries = function () { var e = this.get("labels"); if (e) { this.labels_ = e.slice(1), this.yAxes_ = [{ series: [], options: {} }], this.xAxis_ = { options: {} }, this.series_ = {}; var a = !this.user_.series; if (a) { for (var i = 0, r = 0; r < this.labels_.length; r++) { var n = this.labels_[r], o = this.user_[n] || {}, s = 0, l = o.axis; "object" == typeof l && (s = ++i, this.yAxes_[s] = { series: [n], options: l }), l || this.yAxes_[0].series.push(n), this.series_[n] = { idx: r, yAxis: s, options: o } } for (var r = 0; r < this.labels_.length; r++) { var n = this.labels_[r], o = this.series_[n].options, l = o.axis; if ("string" == typeof l) { if (!this.series_.hasOwnProperty(l)) return void console.error("Series " + n + " wants to share a y-axis with series " + l + ", which does not define its own axis."); var s = this.series_[l].yAxis; this.series_[n].yAxis = s, this.yAxes_[s].series.push(n) } } } else for (var r = 0; r < this.labels_.length; r++) { var n = this.labels_[r], o = this.user_.series[n] || {}, s = t.axisToIndex_(o.axis); this.series_[n] = { idx: r, yAxis: s, options: o }, this.yAxes_[s] ? this.yAxes_[s].series.push(n) : this.yAxes_[s] = { series: [n], options: {} } } var h = this.user_.axes || {}; Dygraph.update(this.yAxes_[0].options, h.y || {}), this.yAxes_.length > 1 && Dygraph.update(this.yAxes_[1].options, h.y2 || {}), Dygraph.update(this.xAxis_.options, h.x || {}) } }, t.prototype.get = function (t) { var e = this.getGlobalUser_(t); return null !== e ? e : this.getGlobalDefault_(t) }, t.prototype.getGlobalUser_ = function (t) { return this.user_.hasOwnProperty(t) ? this.user_[t] : null }, t.prototype.getGlobalDefault_ = function (t) { return this.global_.hasOwnProperty(t) ? this.global_[t] : Dygraph.DEFAULT_ATTRS.hasOwnProperty(t) ? Dygraph.DEFAULT_ATTRS[t] : null }, t.prototype.getForAxis = function (t, e) { var a, i; if ("number" == typeof e) a = e, i = 0 === a ? "y" : "y2"; else { if ("y1" == e && (e = "y"), "y" == e) a = 0; else if ("y2" == e) a = 1; else { if ("x" != e) throw "Unknown axis " + e; a = -1 } i = e } var r = -1 == a ? this.xAxis_ : this.yAxes_[a]; if (r) { var n = r.options; if (n.hasOwnProperty(t)) return n[t] } if ("x" !== e || "logscale" !== t) { var o = this.getGlobalUser_(t); if (null !== o) return o } var s = Dygraph.DEFAULT_ATTRS.axes[i]; return s.hasOwnProperty(t) ? s[t] : this.getGlobalDefault_(t) }, t.prototype.getForSeries = function (t, e) { if (e === this.dygraph_.getHighlightSeries() && this.highlightSeries_.hasOwnProperty(t)) return this.highlightSeries_[t]; if (!this.series_.hasOwnProperty(e)) throw "Unknown series: " + e; var a = this.series_[e], i = a.options; return i.hasOwnProperty(t) ? i[t] : this.getForAxis(t, a.yAxis) }, t.prototype.numAxes = function () { return this.yAxes_.length }, t.prototype.axisForSeries = function (t) { return this.series_[t].yAxis }, t.prototype.axisOptions = function (t) { return this.yAxes_[t].options }, t.prototype.seriesForAxis = function (t) { return this.yAxes_[t].series }, t.prototype.seriesNames = function () { return this.labels_ }; return t }() }(), DygraphLayout = function () { "use strict"; var t = function (t) { this.dygraph_ = t, this.points = [], this.setNames = [], this.annotations = [], this.yAxes_ = null, this.xTicks_ = null, this.yTicks_ = null }; return t.prototype.addDataset = function (t, e) { this.points.push(e), this.setNames.push(t) }, t.prototype.getPlotArea = function () { return this.area_ }, t.prototype.computePlotArea = function () { var t = { x: 0, y: 0 }; t.w = this.dygraph_.width_ - t.x - this.dygraph_.getOption("rightGap"), t.h = this.dygraph_.height_; var e = { chart_div: this.dygraph_.graphDiv, reserveSpaceLeft: function (e) { var a = { x: t.x, y: t.y, w: e, h: t.h }; return t.x += e, t.w -= e, a }, reserveSpaceRight: function (e) { var a = { x: t.x + t.w - e, y: t.y, w: e, h: t.h }; return t.w -= e, a }, reserveSpaceTop: function (e) { var a = { x: t.x, y: t.y, w: t.w, h: e }; return t.y += e, t.h -= e, a }, reserveSpaceBottom: function (e) { var a = { x: t.x, y: t.y + t.h - e, w: t.w, h: e }; return t.h -= e, a }, chartRect: function () { return { x: t.x, y: t.y, w: t.w, h: t.h } } }; this.dygraph_.cascadeEvents_("layout", e), this.area_ = t }, t.prototype.setAnnotations = function (t) { this.annotations = []; for (var e = this.dygraph_.getOption("xValueParser") || function (t) { return t }, a = 0; a < t.length; a++) { var i = {}; if (!t[a].xval && void 0 === t[a].x) return void console.error("Annotations must have an 'x' property"); if (t[a].icon && (!t[a].hasOwnProperty("width") || !t[a].hasOwnProperty("height"))) return void console.error("Must set width and height when setting annotation.icon property"); Dygraph.update(i, t[a]), i.xval || (i.xval = e(i.x)), this.annotations.push(i) } }, t.prototype.setXTicks = function (t) { this.xTicks_ = t }, t.prototype.setYAxes = function (t) { this.yAxes_ = t }, t.prototype.evaluate = function () { this._xAxis = {}, this._evaluateLimits(), this._evaluateLineCharts(), this._evaluateLineTicks(), this._evaluateAnnotations() }, t.prototype._evaluateLimits = function () { var t = this.dygraph_.xAxisRange(); this._xAxis.minval = t[0], this._xAxis.maxval = t[1]; var e = t[1] - t[0]; this._xAxis.scale = 0 !== e ? 1 / e : 1, this.dygraph_.getOptionForAxis("logscale", "x") && (this._xAxis.xlogrange = Dygraph.log10(this._xAxis.maxval) - Dygraph.log10(this._xAxis.minval), this._xAxis.xlogscale = 0 !== this._xAxis.xlogrange ? 1 / this._xAxis.xlogrange : 1); for (var a = 0; a < this.yAxes_.length; a++) { var i = this.yAxes_[a]; i.minyval = i.computedValueRange[0], i.maxyval = i.computedValueRange[1], i.yrange = i.maxyval - i.minyval, i.yscale = 0 !== i.yrange ? 1 / i.yrange : 1, this.dygraph_.getOption("logscale") && (i.ylogrange = Dygraph.log10(i.maxyval) - Dygraph.log10(i.minyval), i.ylogscale = 0 !== i.ylogrange ? 1 / i.ylogrange : 1, (!isFinite(i.ylogrange) || isNaN(i.ylogrange)) && console.error("axis " + a + " of graph at " + i.g + " can't be displayed in log scale for range [" + i.minyval + " - " + i.maxyval + "]")) } }, t.calcXNormal_ = function (t, e, a) { return a ? (Dygraph.log10(t) - Dygraph.log10(e.minval)) * e.xlogscale : (t - e.minval) * e.scale }, t.calcYNormal_ = function (t, e, a) { if (a) { var i = 1 - (Dygraph.log10(e) - Dygraph.log10(t.minyval)) * t.ylogscale; return isFinite(i) ? i : 0 / 0 } return 1 - (e - t.minyval) * t.yscale }, t.prototype._evaluateLineCharts = function () { for (var e = this.dygraph_.getOption("stackedGraph"), a = this.dygraph_.getOptionForAxis("logscale", "x"), i = 0; i < this.points.length; i++) { for (var r = this.points[i], n = this.setNames[i], o = this.dygraph_.getOption("connectSeparatedPoints", n), s = this.dygraph_.axisPropertiesForSeries(n), l = this.dygraph_.attributes_.getForSeries("logscale", n), h = 0; h < r.length; h++) { var p = r[h]; p.x = t.calcXNormal_(p.xval, this._xAxis, a); var g = p.yval; e && (p.y_stacked = t.calcYNormal_(s, p.yval_stacked, l), null === g || isNaN(g) || (g = p.yval_stacked)), null === g && (g = 0 / 0, o || (p.yval = 0 / 0)), p.y = t.calcYNormal_(s, g, l) } this.dygraph_.dataHandler_.onLineEvaluated(r, s, l) } }, t.prototype._evaluateLineTicks = function () { var t, e, a, i; for (this.xticks = [], t = 0; t < this.xTicks_.length; t++) e = this.xTicks_[t], a = e.label, i = this.dygraph_.toPercentXCoord(e.v), i >= 0 && 1 > i && this.xticks.push([i, a]); for (this.yticks = [], t = 0; t < this.yAxes_.length; t++) for (var r = this.yAxes_[t], n = 0; n < r.ticks.length; n++) e = r.ticks[n], a = e.label, i = this.dygraph_.toPercentYCoord(e.v, t), i > 0 && 1 >= i && this.yticks.push([t, i, a]) }, t.prototype._evaluateAnnotations = function () { var t, e = {}; for (t = 0; t < this.annotations.length; t++) { var a = this.annotations[t]; e[a.xval + "," + a.series] = a } if (this.annotated_points = [], this.annotations && this.annotations.length) for (var i = 0; i < this.points.length; i++) { var r = this.points[i]; for (t = 0; t < r.length; t++) { var n = r[t], o = n.xval + "," + n.name; o in e && (n.annotation = e[o], this.annotated_points.push(n)) } } }, t.prototype.removeAllDatasets = function () { delete this.points, delete this.setNames, delete this.setPointsLengths, delete this.setPointsOffsets, this.points = [], this.setNames = [], this.setPointsLengths = [], this.setPointsOffsets = [] }, t }(), DygraphCanvasRenderer = function () { "use strict"; var t = function (t, e, a, i) { if (this.dygraph_ = t, this.layout = i, this.element = e, this.elementContext = a, this.height = t.height_, this.width = t.width_, !this.isIE && !Dygraph.isCanvasSupported(this.element)) throw "Canvas is not supported."; if (this.area = i.getPlotArea(), this.dygraph_.isUsingExcanvas_) this._createIEClipArea(); else if (!Dygraph.isAndroid()) { var r = this.dygraph_.canvas_ctx_; r.beginPath(), r.rect(this.area.x, this.area.y, this.area.w, this.area.h), r.clip(), r = this.dygraph_.hidden_ctx_, r.beginPath(), r.rect(this.area.x, this.area.y, this.area.w, this.area.h), r.clip() } }; return t.prototype.clear = function () { var t; if (this.isIE) try { this.clearDelay && (this.clearDelay.cancel(), this.clearDelay = null), t = this.elementContext } catch (e) { return } t = this.elementContext, t.clearRect(0, 0, this.width, this.height) }, t.prototype.render = function () { this._updatePoints(), this._renderLineChart() }, t.prototype._createIEClipArea = function () { function t(t) { if (0 !== t.w && 0 !== t.h) { var i = document.createElement("div"); i.className = e, i.style.backgroundColor = r, i.style.position = "absolute", i.style.left = t.x + "px", i.style.top = t.y + "px", i.style.width = t.w + "px", i.style.height = t.h + "px", a.appendChild(i) } } for (var e = "dygraph-clip-div", a = this.dygraph_.graphDiv, i = a.childNodes.length - 1; i >= 0; i--) a.childNodes[i].className == e && a.removeChild(a.childNodes[i]); for (var r = document.bgColor, n = this.dygraph_.graphDiv; n != document;) { var o = n.currentStyle.backgroundColor; if (o && "transparent" != o) { r = o; break } n = n.parentNode } var s = this.area; t({ x: 0, y: 0, w: s.x, h: this.height }), t({ x: s.x, y: 0, w: this.width - s.x, h: s.y }), t({ x: s.x + s.w, y: 0, w: this.width - s.x - s.w, h: this.height }), t({ x: s.x, y: s.y + s.h, w: this.width - s.x, h: this.height - s.h - s.y }) }, t._getIteratorPredicate = function (e) { return e ? t._predicateThatSkipsEmptyPoints : null }, t._predicateThatSkipsEmptyPoints = function (t, e) { return null !== t[e].yval }, t._drawStyledLine = function (e, a, i, r, n, o, s) { var l = e.dygraph, h = l.getBooleanOption("stepPlot", e.setName); Dygraph.isArrayLike(r) || (r = null); var p = l.getBooleanOption("drawGapEdgePoints", e.setName), g = e.points, d = e.setName, u = Dygraph.createIterator(g, 0, g.length, t._getIteratorPredicate(l.getBooleanOption("connectSeparatedPoints", d))), c = r && r.length >= 2, y = e.drawingContext; y.save(), c && y.installPattern(r); var _ = t._drawSeries(e, u, i, s, n, p, h, a); t._drawPointsOnLine(e, _, o, a, s), c && y.uninstallPattern(), y.restore() }, t._drawSeries = function (t, e, a, i, r, n, o, s) { var l, h, p = null, g = null, d = null, u = [], c = !0, y = t.drawingContext; y.beginPath(), y.strokeStyle = s, y.lineWidth = a; for (var _ = e.array_, v = e.end_, f = e.predicate_, x = e.start_; v > x; x++) { if (h = _[x], f) { for (; v > x && !f(_, x) ;) x++; if (x == v) break; h = _[x] } if (null === h.canvasy || h.canvasy != h.canvasy) o && null !== p && (y.moveTo(p, g), y.lineTo(h.canvasx, g)), p = g = null; else { if (l = !1, n || !p) { e.nextIdx_ = x, e.next(), d = e.hasNext ? e.peek.canvasy : null; var m = null === d || d != d; l = !p && m, n && (!c && !p || e.hasNext && m) && (l = !0) } null !== p ? a && (o && (y.moveTo(p, g), y.lineTo(h.canvasx, g)), y.lineTo(h.canvasx, h.canvasy)) : y.moveTo(h.canvasx, h.canvasy), (r || l) && u.push([h.canvasx, h.canvasy, h.idx]), p = h.canvasx, g = h.canvasy } c = !1 } return y.stroke(), u }, t._drawPointsOnLine = function (t, e, a, i, r) { for (var n = t.drawingContext, o = 0; o < e.length; o++) { var s = e[o]; n.save(), a.call(t.dygraph, t.dygraph, t.setName, n, s[0], s[1], i, r, s[2]), n.restore() } }, t.prototype._updatePoints = function () { for (var t = this.layout.points, e = t.length; e--;) for (var a = t[e], i = a.length; i--;) { var r = a[i]; r.canvasx = this.area.w * r.x + this.area.x, r.canvasy = this.area.h * r.y + this.area.y } }, t.prototype._renderLineChart = function (t, e) { var a, i, r = e || this.elementContext, n = this.layout.points, o = this.layout.setNames; this.colors = this.dygraph_.colorsMap_; var s = this.dygraph_.getOption("plotter"), l = s; Dygraph.isArrayLike(l) || (l = [l]); var h = {}; for (a = 0; a < o.length; a++) { i = o[a]; var p = this.dygraph_.getOption("plotter", i); p != s && (h[i] = p) } for (a = 0; a < l.length; a++) for (var g = l[a], d = a == l.length - 1, u = 0; u < n.length; u++) if (i = o[u], !t || i == t) { var c = n[u], y = g; if (i in h) { if (!d) continue; y = h[i] } var _ = this.colors[i], v = this.dygraph_.getOption("strokeWidth", i); r.save(), r.strokeStyle = _, r.lineWidth = v, y({ points: c, setName: i, drawingContext: r, color: _, strokeWidth: v, dygraph: this.dygraph_, axis: this.dygraph_.axisPropertiesForSeries(i), plotArea: this.area, seriesIndex: u, seriesCount: n.length, singleSeriesName: t, allSeriesPoints: n }), r.restore() } }, t._Plotters = { linePlotter: function (e) { t._linePlotter(e) }, fillPlotter: function (e) { t._fillPlotter(e) }, errorPlotter: function (e) { t._errorPlotter(e) } }, t._linePlotter = function (e) { var a = e.dygraph, i = e.setName, r = e.strokeWidth, n = a.getNumericOption("strokeBorderWidth", i), o = a.getOption("drawPointCallback", i) || Dygraph.Circles.DEFAULT, s = a.getOption("strokePattern", i), l = a.getBooleanOption("drawPoints", i), h = a.getNumericOption("pointSize", i); n && r && t._drawStyledLine(e, a.getOption("strokeBorderColor", i), r + 2 * n, s, l, o, h), t._drawStyledLine(e, e.color, r, s, l, o, h) }, t._errorPlotter = function (e) { var a = e.dygraph, i = e.setName, r = a.getBooleanOption("errorBars") || a.getBooleanOption("customBars"); if (r) { var n = a.getBooleanOption("fillGraph", i); n && console.warn("Can't use fillGraph option with error bars"); var o, s = e.drawingContext, l = e.color, h = a.getNumericOption("fillAlpha", i), p = a.getBooleanOption("stepPlot", i), g = e.points, d = Dygraph.createIterator(g, 0, g.length, t._getIteratorPredicate(a.getBooleanOption("connectSeparatedPoints", i))), u = 0 / 0, c = 0 / 0, y = [-1, -1], _ = Dygraph.toRGB_(l), v = "rgba(" + _.r + "," + _.g + "," + _.b + "," + h + ")"; s.fillStyle = v, s.beginPath(); for (var f = function (t) { return null === t || void 0 === t || isNaN(t) }; d.hasNext;) { var x = d.next(); !p && f(x.y) || p && !isNaN(c) && f(c) ? u = 0 / 0 : (o = [x.y_bottom, x.y_top], p && (c = x.y), isNaN(o[0]) && (o[0] = x.y), isNaN(o[1]) && (o[1] = x.y), o[0] = e.plotArea.h * o[0] + e.plotArea.y, o[1] = e.plotArea.h * o[1] + e.plotArea.y, isNaN(u) || (p ? (s.moveTo(u, y[0]), s.lineTo(x.canvasx, y[0]), s.lineTo(x.canvasx, y[1])) : (s.moveTo(u, y[0]), s.lineTo(x.canvasx, o[0]), s.lineTo(x.canvasx, o[1])), s.lineTo(u, y[1]), s.closePath()), y = o, u = x.canvasx) } s.fill() } }, t._fastCanvasProxy = function (t) { var e = [], a = null, i = 1, r = 2, n = 0, o = function (t) { if (!(e.length <= 1)) { for (var a = e.length - 1; a > 0; a--) { var n = e[a]; if (n[0] == r) { var o = e[a - 1]; o[1] == n[1] && o[2] == n[2] && e.splice(a, 1) } } for (var a = 0; a < e.length - 1;) { var n = e[a]; n[0] == r && e[a + 1][0] == r ? e.splice(a, 1) : a++ } if (e.length > 2 && !t) { var s = 0; e[0][0] == r && s++; for (var l = null, h = null, a = s; a < e.length; a++) { var n = e[a]; if (n[0] == i) if (null === l && null === h) l = a, h = a; else { var p = n[2]; p < e[l][2] ? l = a : p > e[h][2] && (h = a) } } var g = e[l], d = e[h]; e.splice(s, e.length - s), h > l ? (e.push(g), e.push(d)) : l > h ? (e.push(d), e.push(g)) : e.push(g) } } }, s = function (a) { o(a); for (var s = 0, l = e.length; l > s; s++) { var h = e[s]; h[0] == i ? t.lineTo(h[1], h[2]) : h[0] == r && t.moveTo(h[1], h[2]) } n += e.length, e = [] }, l = function (t, i, r) { var n = Math.round(i); (null === a || n != a) && (s(), a = n), e.push([t, i, r]) }; return { moveTo: function (t, e) { l(r, t, e) }, lineTo: function (t, e) { l(i, t, e) }, stroke: function () { s(!0), t.stroke() }, fill: function () { s(!0), t.fill() }, beginPath: function () { s(!0), t.beginPath() }, closePath: function () { s(!0), t.closePath() }, _count: function () { return n } } }, t._fillPlotter = function (e) { if (!e.singleSeriesName && 0 === e.seriesIndex) { for (var a = e.dygraph, i = a.getLabels().slice(1), r = i.length; r >= 0; r--) a.visibility()[r] || i.splice(r, 1); var n = function () { for (var t = 0; t < i.length; t++) if (a.getBooleanOption("fillGraph", i[t])) return !0; return !1 }(); if (n) for (var o, s, l = e.plotArea, h = e.allSeriesPoints, p = h.length, g = a.getNumericOption("fillAlpha"), d = a.getBooleanOption("stackedGraph"), u = a.getColors(), c = {}, y = function (t, e, a, i) { if (t.lineTo(e, a), d) for (var r = i.length - 1; r >= 0; r--) { var n = i[r]; t.lineTo(n[0], n[1]) } }, _ = p - 1; _ >= 0; _--) { var v = e.drawingContext, f = i[_]; if (a.getBooleanOption("fillGraph", f)) { var x = a.getBooleanOption("stepPlot", f), m = u[_], D = a.axisPropertiesForSeries(f), A = 1 + D.minyval * D.yscale; 0 > A ? A = 0 : A > 1 && (A = 1), A = l.h * A + l.y; var w, b = h[_], T = Dygraph.createIterator(b, 0, b.length, t._getIteratorPredicate(a.getBooleanOption("connectSeparatedPoints", f))), E = 0 / 0, C = [-1, -1], L = Dygraph.toRGB_(m), P = "rgba(" + L.r + "," + L.g + "," + L.b + "," + g + ")"; v.fillStyle = P, v.beginPath(); var S, O = !0; b.length > 2 * a.width_ && (v = t._fastCanvasProxy(v)); for (var M, F = []; T.hasNext;) if (M = T.next(), Dygraph.isOK(M.y) || x) { if (d) { if (!O && S == M.xval) continue; O = !1, S = M.xval, o = c[M.canvasx]; var R; R = void 0 === o ? A : s ? o[0] : o, w = [M.canvasy, R], c[M.canvasx] = x ? -1 === C[0] ? [M.canvasy, A] : [M.canvasy, C[0]] : M.canvasy } else w = isNaN(M.canvasy) && x ? [l.y + l.h, A] : [M.canvasy, A]; isNaN(E) ? (v.moveTo(M.canvasx, w[1]), v.lineTo(M.canvasx, w[0])) : (x ? (v.lineTo(M.canvasx, C[0]), v.lineTo(M.canvasx, w[0])) : v.lineTo(M.canvasx, w[0]), d && (F.push([E, C[1]]), F.push(s && o ? [M.canvasx, o[1]] : [M.canvasx, w[1]]))), C = w, E = M.canvasx } else y(v, E, C[1], F), F = [], E = 0 / 0, null === M.y_stacked || isNaN(M.y_stacked) || (c[M.canvasx] = l.h * M.y_stacked + l.y); s = x, w && M && (y(v, M.canvasx, w[1], F), F = []), v.fill() } } } }, t }(), Dygraph = function () {
    "use strict"; var t = function (t, e, a, i) { this.is_initial_draw_ = !0, this.readyFns_ = [], void 0 !== i ? (console.warn("Using deprecated four-argument dygraph constructor"), this.__old_init__(t, e, a, i)) : this.__init__(t, e, a) }; return t.NAME = "Dygraph", t.VERSION = "1.1.0", t.__repr__ = function () { return "[" + t.NAME + " " + t.VERSION + "]" }, t.toString = function () { return t.__repr__() }, t.DEFAULT_ROLL_PERIOD = 1, t.DEFAULT_WIDTH = 480, t.DEFAULT_HEIGHT = 320, t.ANIMATION_STEPS = 12, t.ANIMATION_DURATION = 200, t.KMB_LABELS = ["K", "M", "B", "T", "Q"], t.KMG2_BIG_LABELS = ["k", "M", "G", "T", "P", "E", "Z", "Y"], t.KMG2_SMALL_LABELS = ["m", "u", "n", "p", "f", "a", "z", "y"], t.numberValueFormatter = function (e, a) { var i = a("sigFigs"); if (null !== i) return t.floatFormat(e, i); var r, n = a("digitsAfterDecimal"), o = a("maxNumberWidth"), s = a("labelsKMB"), l = a("labelsKMG2"); if (r = 0 !== e && (Math.abs(e) >= Math.pow(10, o) || Math.abs(e) < Math.pow(10, -n)) ? e.toExponential(n) : "" + t.round_(e, n), s || l) { var h, p = [], g = []; s && (h = 1e3, p = t.KMB_LABELS), l && (s && console.warn("Setting both labelsKMB and labelsKMG2. Pick one!"), h = 1024, p = t.KMG2_BIG_LABELS, g = t.KMG2_SMALL_LABELS); for (var d = Math.abs(e), u = t.pow(h, p.length), c = p.length - 1; c >= 0; c--, u /= h) if (d >= u) { r = t.round_(e / u, n) + p[c]; break } if (l) { var y = String(e.toExponential()).split("e-"); 2 === y.length && y[1] >= 3 && y[1] <= 24 && (r = y[1] % 3 > 0 ? t.round_(y[0] / t.pow(10, y[1] % 3), n) : Number(y[0]).toFixed(2), r += g[Math.floor(y[1] / 3) - 1]) } } return r }, t.numberAxisLabelFormatter = function (e, a, i) { return t.numberValueFormatter(e, i) }, t.SHORT_MONTH_NAMES_ = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], t.dateAxisLabelFormatter = function (e, a, i) { var r = i("labelsUTC"), n = r ? t.DateAccessorsUTC : t.DateAccessorsLocal, o = n.getFullYear(e), s = n.getMonth(e), l = n.getDate(e), h = n.getHours(e), p = n.getMinutes(e), g = n.getSeconds(e), d = n.getSeconds(e); if (a >= t.DECADAL) return "" + o; if (a >= t.MONTHLY) return t.SHORT_MONTH_NAMES_[s] + "&#160;" + o; var u = 3600 * h + 60 * p + g + .001 * d; return 0 === u || a >= t.DAILY ? t.zeropad(l) + "&#160;" + t.SHORT_MONTH_NAMES_[s] : t.hmsString_(h, p, g) }, t.dateAxisFormatter = t.dateAxisLabelFormatter, t.dateValueFormatter = function (e, a) { return t.dateString_(e, a("labelsUTC")) }, t.Plotters = DygraphCanvasRenderer._Plotters, t.DEFAULT_ATTRS = { highlightCircleSize: 3, highlightSeriesOpts: null, highlightSeriesBackgroundAlpha: .5, labelsDivWidth: 250, labelsDivStyles: {}, labelsSeparateLines: !1, labelsShowZeroValues: !0, labelsKMB: !1, labelsKMG2: !1, showLabelsOnHighlight: !0, digitsAfterDecimal: 2, maxNumberWidth: 6, sigFigs: null, strokeWidth: 1, strokeBorderWidth: 0, strokeBorderColor: "white", axisTickSize: 3, axisLabelFontSize: 14, rightGap: 5, showRoller: !1, xValueParser: t.dateParser, delimiter: ",", sigma: 2, errorBars: !1, fractions: !1, wilsonInterval: !0, customBars: !1, fillGraph: !1, fillAlpha: .15, connectSeparatedPoints: !1, stackedGraph: !1, stackedGraphNaNFill: "all", hideOverlayOnMouseOut: !0, legend: "onmouseover", stepPlot: !1, avoidMinZero: !1, xRangePad: 0, yRangePad: null, drawAxesAtZero: !1, titleHeight: 28, xLabelHeight: 18, yLabelWidth: 18, drawXAxis: !0, drawYAxis: !0, axisLineColor: "black", axisLineWidth: .3, gridLineWidth: .3, axisLabelColor: "black", axisLabelWidth: 50, drawYGrid: !0, drawXGrid: !0, gridLineColor: "rgb(128,128,128)", interactionModel: null, animatedZooms: !1, showRangeSelector: !1, rangeSelectorHeight: 40, rangeSelectorPlotStrokeColor: "#808FAB", rangeSelectorPlotFillColor: "#A7B1C4", showInRangeSelector: null, plotter: [t.Plotters.fillPlotter, t.Plotters.errorPlotter, t.Plotters.linePlotter], plugins: [], axes: { x: { pixelsPerLabel: 70, axisLabelWidth: 60, axisLabelFormatter: t.dateAxisLabelFormatter, valueFormatter: t.dateValueFormatter, drawGrid: !0, drawAxis: !0, independentTicks: !0, ticker: null }, y: { axisLabelWidth: 50, pixelsPerLabel: 30, valueFormatter: t.numberValueFormatter, axisLabelFormatter: t.numberAxisLabelFormatter, drawGrid: !0, drawAxis: !0, independentTicks: !0, ticker: null }, y2: { axisLabelWidth: 50, pixelsPerLabel: 30, valueFormatter: t.numberValueFormatter, axisLabelFormatter: t.numberAxisLabelFormatter, drawAxis: !0, drawGrid: !1, independentTicks: !1, ticker: null } } }, t.HORIZONTAL = 1, t.VERTICAL = 2, t.PLUGINS = [], t.addedAnnotationCSS = !1, t.prototype.__old_init__ = function (e, a, i, r) { if (null !== i) { for (var n = ["Date"], o = 0; o < i.length; o++) n.push(i[o]); t.update(r, { labels: n }) } this.__init__(e, a, r) }, t.prototype.__init__ = function (e, a, i) { if (/MSIE/.test(navigator.userAgent) && !window.opera && "undefined" != typeof G_vmlCanvasManager && "complete" != document.readyState) { var r = this; return void setTimeout(function () { r.__init__(e, a, i) }, 100) } if ((null === i || void 0 === i) && (i = {}), i = t.mapLegacyOptions_(i), "string" == typeof e && (e = document.getElementById(e)), !e) return void console.error("Constructing dygraph with a non-existent div!"); this.isUsingExcanvas_ = "undefined" != typeof G_vmlCanvasManager, this.maindiv_ = e, this.file_ = a, this.rollPeriod_ = i.rollPeriod || t.DEFAULT_ROLL_PERIOD, this.previousVerticalX_ = -1, this.fractions_ = i.fractions || !1, this.dateWindow_ = i.dateWindow || null, this.annotations_ = [], this.zoomed_x_ = !1, this.zoomed_y_ = !1, e.innerHTML = "", "" === e.style.width && i.width && (e.style.width = i.width + "px"), "" === e.style.height && i.height && (e.style.height = i.height + "px"), "" === e.style.height && 0 === e.clientHeight && (e.style.height = t.DEFAULT_HEIGHT + "px", "" === e.style.width && (e.style.width = t.DEFAULT_WIDTH + "px")), this.width_ = e.clientWidth || i.width || 0, this.height_ = e.clientHeight || i.height || 0, i.stackedGraph && (i.fillGraph = !0), this.user_attrs_ = {}, t.update(this.user_attrs_, i), this.attrs_ = {}, t.updateDeep(this.attrs_, t.DEFAULT_ATTRS), this.boundaryIds_ = [], this.setIndexByName_ = {}, this.datasetIndex_ = [], this.registeredEvents_ = [], this.eventListeners_ = {}, this.attributes_ = new DygraphOptions(this), this.createInterface_(), this.plugins_ = []; for (var n = t.PLUGINS.concat(this.getOption("plugins")), o = 0; o < n.length; o++) { var s, l = n[o]; s = "undefined" != typeof l.activate ? l : new l; var h = { plugin: s, events: {}, options: {}, pluginOptions: {} }, p = s.activate(this); for (var g in p) p.hasOwnProperty(g) && (h.events[g] = p[g]); this.plugins_.push(h) } for (var o = 0; o < this.plugins_.length; o++) { var d = this.plugins_[o]; for (var g in d.events) if (d.events.hasOwnProperty(g)) { var u = d.events[g], c = [d.plugin, u]; g in this.eventListeners_ ? this.eventListeners_[g].push(c) : this.eventListeners_[g] = [c] } } this.createDragInterface_(), this.start_() }, t.prototype.cascadeEvents_ = function (e, a) { if (!(e in this.eventListeners_)) return !1; var i = { dygraph: this, cancelable: !1, defaultPrevented: !1, preventDefault: function () { if (!i.cancelable) throw "Cannot call preventDefault on non-cancelable event."; i.defaultPrevented = !0 }, propagationStopped: !1, stopPropagation: function () { i.propagationStopped = !0 } }; t.update(i, a); var r = this.eventListeners_[e]; if (r) for (var n = r.length - 1; n >= 0; n--) { var o = r[n][0], s = r[n][1]; if (s.call(o, i), i.propagationStopped) break } return i.defaultPrevented }, t.prototype.getPluginInstance_ = function (t) { for (var e = 0; e < this.plugins_.length; e++) { var a = this.plugins_[e]; if (a.plugin instanceof t) return a.plugin } return null }, t.prototype.isZoomed = function (t) { if (null === t || void 0 === t) return this.zoomed_x_ || this.zoomed_y_; if ("x" === t) return this.zoomed_x_; if ("y" === t) return this.zoomed_y_; throw "axis parameter is [" + t + "] must be null, 'x' or 'y'." }, t.prototype.toString = function () { var t = this.maindiv_, e = t && t.id ? t.id : t; return "[Dygraph " + e + "]" }, t.prototype.attr_ = function (t, e) { return e ? this.attributes_.getForSeries(t, e) : this.attributes_.get(t) }, t.prototype.getOption = function (t, e) { return this.attr_(t, e) }, t.prototype.getNumericOption = function (t, e) { return this.getOption(t, e) }, t.prototype.getStringOption = function (t, e) { return this.getOption(t, e) }, t.prototype.getBooleanOption = function (t, e) { return this.getOption(t, e) }, t.prototype.getFunctionOption = function (t, e) { return this.getOption(t, e) }, t.prototype.getOptionForAxis = function (t, e) { return this.attributes_.getForAxis(t, e) }, t.prototype.optionsViewForAxis_ = function (t) { var e = this; return function (a) { var i = e.user_attrs_.axes; return i && i[t] && i[t].hasOwnProperty(a) ? i[t][a] : "x" === t && "logscale" === a ? !1 : "undefined" != typeof e.user_attrs_[a] ? e.user_attrs_[a] : (i = e.attrs_.axes, i && i[t] && i[t].hasOwnProperty(a) ? i[t][a] : "y" == t && e.axes_[0].hasOwnProperty(a) ? e.axes_[0][a] : "y2" == t && e.axes_[1].hasOwnProperty(a) ? e.axes_[1][a] : e.attr_(a)) } }, t.prototype.rollPeriod = function () { return this.rollPeriod_ }, t.prototype.xAxisRange = function () { return this.dateWindow_ ? this.dateWindow_ : this.xAxisExtremes() }, t.prototype.xAxisExtremes = function () { var t = this.getNumericOption("xRangePad") / this.plotter_.area.w; if (0 === this.numRows()) return [0 - t, 1 + t]; var e = this.rawData_[0][0], a = this.rawData_[this.rawData_.length - 1][0]; if (t) { var i = a - e; e -= i * t, a += i * t } return [e, a] }, t.prototype.yAxisRange = function (t) { if ("undefined" == typeof t && (t = 0), 0 > t || t >= this.axes_.length) return null; var e = this.axes_[t]; return [e.computedValueRange[0], e.computedValueRange[1]] }, t.prototype.yAxisRanges = function () { for (var t = [], e = 0; e < this.axes_.length; e++) t.push(this.yAxisRange(e)); return t }, t.prototype.toDomCoords = function (t, e, a) { return [this.toDomXCoord(t), this.toDomYCoord(e, a)] }, t.prototype.toDomXCoord = function (t) { if (null === t) return null; var e = this.plotter_.area, a = this.xAxisRange(); return e.x + (t - a[0]) / (a[1] - a[0]) * e.w }, t.prototype.toDomYCoord = function (t, e) { var a = this.toPercentYCoord(t, e); if (null === a) return null; var i = this.plotter_.area; return i.y + a * i.h }, t.prototype.toDataCoords = function (t, e, a) { return [this.toDataXCoord(t), this.toDataYCoord(e, a)] }, t.prototype.toDataXCoord = function (e) { if (null === e) return null; var a = this.plotter_.area, i = this.xAxisRange(); if (this.attributes_.getForAxis("logscale", "x")) { var r = (e - a.x) / a.w, n = t.log10(i[0]), o = t.log10(i[1]), s = n + r * (o - n), l = Math.pow(t.LOG_SCALE, s); return l } return i[0] + (e - a.x) / a.w * (i[1] - i[0]) }, t.prototype.toDataYCoord = function (e, a) { if (null === e) return null; var i = this.plotter_.area, r = this.yAxisRange(a); if ("undefined" == typeof a && (a = 0), this.attributes_.getForAxis("logscale", a)) { var n = (e - i.y) / i.h, o = t.log10(r[0]), s = t.log10(r[1]), l = s - n * (s - o), h = Math.pow(t.LOG_SCALE, l); return h } return r[0] + (i.y + i.h - e) / i.h * (r[1] - r[0]) }, t.prototype.toPercentYCoord = function (e, a) { if (null === e) return null; "undefined" == typeof a && (a = 0); var i, r = this.yAxisRange(a), n = this.attributes_.getForAxis("logscale", a); if (n) { var o = t.log10(r[0]), s = t.log10(r[1]); i = (s - t.log10(e)) / (s - o) } else i = (r[1] - e) / (r[1] - r[0]); return i }, t.prototype.toPercentXCoord = function (e) { if (null === e) return null; var a, i = this.xAxisRange(), r = this.attributes_.getForAxis("logscale", "x"); if (r === !0) { var n = t.log10(i[0]), o = t.log10(i[1]); a = (t.log10(e) - n) / (o - n) } else a = (e - i[0]) / (i[1] - i[0]); return a }, t.prototype.numColumns = function () { return this.rawData_ ? this.rawData_[0] ? this.rawData_[0].length : this.attr_("labels").length : 0 }, t.prototype.numRows = function () { return this.rawData_ ? this.rawData_.length : 0 }, t.prototype.getValue = function (t, e) { return 0 > t || t > this.rawData_.length ? null : 0 > e || e > this.rawData_[t].length ? null : this.rawData_[t][e] }, t.prototype.createInterface_ = function () { var e = this.maindiv_; this.graphDiv = document.createElement("div"), this.graphDiv.style.textAlign = "left", this.graphDiv.style.position = "relative", e.appendChild(this.graphDiv), this.canvas_ = t.createCanvas(), this.canvas_.style.position = "absolute", this.hidden_ = this.createPlotKitCanvas_(this.canvas_), this.canvas_ctx_ = t.getContext(this.canvas_), this.hidden_ctx_ = t.getContext(this.hidden_), this.resizeElements_(), this.graphDiv.appendChild(this.hidden_), this.graphDiv.appendChild(this.canvas_), this.mouseEventElement_ = this.createMouseEventElement_(), this.layout_ = new DygraphLayout(this); var a = this; this.mouseMoveHandler_ = function (t) { a.mouseMove_(t) }, this.mouseOutHandler_ = function (e) { var i = e.target || e.fromElement, r = e.relatedTarget || e.toElement; t.isNodeContainedBy(i, a.graphDiv) && !t.isNodeContainedBy(r, a.graphDiv) && a.mouseOut_(e) }, this.addAndTrackEvent(window, "mouseout", this.mouseOutHandler_), this.addAndTrackEvent(this.mouseEventElement_, "mousemove", this.mouseMoveHandler_), this.resizeHandler_ || (this.resizeHandler_ = function () { a.resize() }, this.addAndTrackEvent(window, "resize", this.resizeHandler_)) }, t.prototype.resizeElements_ = function () { this.graphDiv.style.width = this.width_ + "px", this.graphDiv.style.height = this.height_ + "px"; var e = t.getContextPixelRatio(this.canvas_ctx_); this.canvas_.width = this.width_ * e, this.canvas_.height = this.height_ * e, this.canvas_.style.width = this.width_ + "px", this.canvas_.style.height = this.height_ + "px", 1 !== e && this.canvas_ctx_.scale(e, e); var a = t.getContextPixelRatio(this.hidden_ctx_); this.hidden_.width = this.width_ * a, this.hidden_.height = this.height_ * a, this.hidden_.style.width = this.width_ + "px", this.hidden_.style.height = this.height_ + "px", 1 !== a && this.hidden_ctx_.scale(a, a) }, t.prototype.destroy = function () { this.canvas_ctx_.restore(), this.hidden_ctx_.restore(); for (var e = this.plugins_.length - 1; e >= 0; e--) { var a = this.plugins_.pop(); a.plugin.destroy && a.plugin.destroy() } var i = function (t) { for (; t.hasChildNodes() ;) i(t.firstChild), t.removeChild(t.firstChild) }; this.removeTrackedEvents_(), t.removeEvent(window, "mouseout", this.mouseOutHandler_), t.removeEvent(this.mouseEventElement_, "mousemove", this.mouseMoveHandler_), t.removeEvent(window, "resize", this.resizeHandler_), this.resizeHandler_ = null, i(this.maindiv_); var r = function (t) { for (var e in t) "object" == typeof t[e] && (t[e] = null) }; r(this.layout_), r(this.plotter_), r(this) }, t.prototype.createPlotKitCanvas_ = function (e) { var a = t.createCanvas(); return a.style.position = "absolute", a.style.top = e.style.top, a.style.left = e.style.left, a.width = this.width_, a.height = this.height_, a.style.width = this.width_ + "px", a.style.height = this.height_ + "px", a }, t.prototype.createMouseEventElement_ = function () { if (this.isUsingExcanvas_) { var t = document.createElement("div"); return t.style.position = "absolute", t.style.backgroundColor = "white", t.style.filter = "alpha(opacity=0)", t.style.width = this.width_ + "px", t.style.height = this.height_ + "px", this.graphDiv.appendChild(t), t } return this.canvas_ }, t.prototype.setColors_ = function () {
        var e = this.getLabels(), a = e.length - 1; this.colors_ = [], this.colorsMap_ = {}; for (var i = this.getNumericOption("colorSaturation") || 1, r = this.getNumericOption("colorValue") || .5, n = Math.ceil(a / 2), o = this.getOption("colors"), s = this.visibility(), l = 0; a > l; l++) if (s[l]) {
            var h = e[l + 1], p = this.attributes_.getForSeries("color", h);
            if (!p) if (o) p = o[l % o.length]; else { var g = l % 2 ? n + (l + 1) / 2 : Math.ceil((l + 1) / 2), d = 1 * g / (1 + a); p = t.hsvToRGB(d, i, r) } this.colors_.push(p), this.colorsMap_[h] = p
        }
    }, t.prototype.getColors = function () { return this.colors_ }, t.prototype.getPropertiesForSeries = function (t) { for (var e = -1, a = this.getLabels(), i = 1; i < a.length; i++) if (a[i] == t) { e = i; break } return -1 == e ? null : { name: t, column: e, visible: this.visibility()[e - 1], color: this.colorsMap_[t], axis: 1 + this.attributes_.axisForSeries(t) } }, t.prototype.createRollInterface_ = function () { this.roller_ || (this.roller_ = document.createElement("input"), this.roller_.type = "text", this.roller_.style.display = "none", this.graphDiv.appendChild(this.roller_)); var t = this.getBooleanOption("showRoller") ? "block" : "none", e = this.plotter_.area, a = { position: "absolute", zIndex: 10, top: e.y + e.h - 25 + "px", left: e.x + 1 + "px", display: t }; this.roller_.size = "2", this.roller_.value = this.rollPeriod_; for (var i in a) a.hasOwnProperty(i) && (this.roller_.style[i] = a[i]); var r = this; this.roller_.onchange = function () { r.adjustRoll(r.roller_.value) } }, t.prototype.createDragInterface_ = function () { var e = { isZooming: !1, isPanning: !1, is2DPan: !1, dragStartX: null, dragStartY: null, dragEndX: null, dragEndY: null, dragDirection: null, prevEndX: null, prevEndY: null, prevDragDirection: null, cancelNextDblclick: !1, initialLeftmostDate: null, xUnitsPerPixel: null, dateRange: null, px: 0, py: 0, boundedDates: null, boundedValues: null, tarp: new t.IFrameTarp, initializeMouseDown: function (e, a, i) { e.preventDefault ? e.preventDefault() : (e.returnValue = !1, e.cancelBubble = !0); var r = t.findPos(a.canvas_); i.px = r.x, i.py = r.y, i.dragStartX = t.dragGetX_(e, i), i.dragStartY = t.dragGetY_(e, i), i.cancelNextDblclick = !1, i.tarp.cover() }, destroy: function () { var t = this; if ((t.isZooming || t.isPanning) && (t.isZooming = !1, t.dragStartX = null, t.dragStartY = null), t.isPanning) { t.isPanning = !1, t.draggingDate = null, t.dateRange = null; for (var e = 0; e < i.axes_.length; e++) delete i.axes_[e].draggingValue, delete i.axes_[e].dragValueRange } t.tarp.uncover() } }, a = this.getOption("interactionModel"), i = this, r = function (t) { return function (a) { t(a, i, e) } }; for (var n in a) a.hasOwnProperty(n) && this.addAndTrackEvent(this.mouseEventElement_, n, r(a[n])); if (!a.willDestroyContextMyself) { var o = function () { e.destroy() }; this.addAndTrackEvent(document, "mouseup", o) } }, t.prototype.drawZoomRect_ = function (e, a, i, r, n, o, s, l) { var h = this.canvas_ctx_; o == t.HORIZONTAL ? h.clearRect(Math.min(a, s), this.layout_.getPlotArea().y, Math.abs(a - s), this.layout_.getPlotArea().h) : o == t.VERTICAL && h.clearRect(this.layout_.getPlotArea().x, Math.min(r, l), this.layout_.getPlotArea().w, Math.abs(r - l)), e == t.HORIZONTAL ? i && a && (h.fillStyle = "rgba(128,128,128,0.33)", h.fillRect(Math.min(a, i), this.layout_.getPlotArea().y, Math.abs(i - a), this.layout_.getPlotArea().h)) : e == t.VERTICAL && n && r && (h.fillStyle = "rgba(128,128,128,0.33)", h.fillRect(this.layout_.getPlotArea().x, Math.min(r, n), this.layout_.getPlotArea().w, Math.abs(n - r))), this.isUsingExcanvas_ && (this.currentZoomRectArgs_ = [e, a, i, r, n, 0, 0, 0]) }, t.prototype.clearZoomRect_ = function () { this.currentZoomRectArgs_ = null, this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_) }, t.prototype.doZoomX_ = function (t, e) { this.currentZoomRectArgs_ = null; var a = this.toDataXCoord(t), i = this.toDataXCoord(e); this.doZoomXDates_(a, i) }, t.prototype.doZoomXDates_ = function (t, e) { var a = this.xAxisRange(), i = [t, e]; this.zoomed_x_ = !0; var r = this; this.doAnimatedZoom(a, i, null, null, function () { r.getFunctionOption("zoomCallback") && r.getFunctionOption("zoomCallback").call(r, t, e, r.yAxisRanges()) }) }, t.prototype.doZoomY_ = function (t, e) { this.currentZoomRectArgs_ = null; for (var a = this.yAxisRanges(), i = [], r = 0; r < this.axes_.length; r++) { var n = this.toDataYCoord(t, r), o = this.toDataYCoord(e, r); i.push([o, n]) } this.zoomed_y_ = !0; var s = this; this.doAnimatedZoom(null, null, a, i, function () { if (s.getFunctionOption("zoomCallback")) { var t = s.xAxisRange(); s.getFunctionOption("zoomCallback").call(s, t[0], t[1], s.yAxisRanges()) } }) }, t.zoomAnimationFunction = function (t, e) { var a = 1.5; return (1 - Math.pow(a, -t)) / (1 - Math.pow(a, -e)) }, t.prototype.resetZoom = function () { var t = !1, e = !1, a = !1; null !== this.dateWindow_ && (t = !0, e = !0); for (var i = 0; i < this.axes_.length; i++) "undefined" != typeof this.axes_[i].valueWindow && null !== this.axes_[i].valueWindow && (t = !0, a = !0); if (this.clearSelection(), t) { this.zoomed_x_ = !1, this.zoomed_y_ = !1; var r = this.rawData_[0][0], n = this.rawData_[this.rawData_.length - 1][0]; if (!this.getBooleanOption("animatedZooms")) { for (this.dateWindow_ = null, i = 0; i < this.axes_.length; i++) null !== this.axes_[i].valueWindow && delete this.axes_[i].valueWindow; return this.drawGraph_(), void (this.getFunctionOption("zoomCallback") && this.getFunctionOption("zoomCallback").call(this, r, n, this.yAxisRanges())) } var o = null, s = null, l = null, h = null; if (e && (o = this.xAxisRange(), s = [r, n]), a) { l = this.yAxisRanges(); var p = this.gatherDatasets_(this.rolledSeries_, null), g = p.extremes; for (this.computeYAxisRanges_(g), h = [], i = 0; i < this.axes_.length; i++) { var d = this.axes_[i]; h.push(null !== d.valueRange && void 0 !== d.valueRange ? d.valueRange : d.extremeRange) } } var u = this; this.doAnimatedZoom(o, s, l, h, function () { u.dateWindow_ = null; for (var t = 0; t < u.axes_.length; t++) null !== u.axes_[t].valueWindow && delete u.axes_[t].valueWindow; u.getFunctionOption("zoomCallback") && u.getFunctionOption("zoomCallback").call(u, r, n, u.yAxisRanges()) }) } }, t.prototype.doAnimatedZoom = function (e, a, i, r, n) { var o, s, l = this.getBooleanOption("animatedZooms") ? t.ANIMATION_STEPS : 1, h = [], p = []; if (null !== e && null !== a) for (o = 1; l >= o; o++) s = t.zoomAnimationFunction(o, l), h[o - 1] = [e[0] * (1 - s) + s * a[0], e[1] * (1 - s) + s * a[1]]; if (null !== i && null !== r) for (o = 1; l >= o; o++) { s = t.zoomAnimationFunction(o, l); for (var g = [], d = 0; d < this.axes_.length; d++) g.push([i[d][0] * (1 - s) + s * r[d][0], i[d][1] * (1 - s) + s * r[d][1]]); p[o - 1] = g } var u = this; t.repeatAndCleanup(function (t) { if (p.length) for (var e = 0; e < u.axes_.length; e++) { var a = p[t][e]; u.axes_[e].valueWindow = [a[0], a[1]] } h.length && (u.dateWindow_ = h[t]), u.drawGraph_() }, l, t.ANIMATION_DURATION / l, n) }, t.prototype.getArea = function () { return this.plotter_.area }, t.prototype.eventToDomCoords = function (e) { if (e.offsetX && e.offsetY) return [e.offsetX, e.offsetY]; var a = t.findPos(this.mouseEventElement_), i = t.pageX(e) - a.x, r = t.pageY(e) - a.y; return [i, r] }, t.prototype.findClosestRow = function (e) { for (var a = 1 / 0, i = -1, r = this.layout_.points, n = 0; n < r.length; n++) for (var o = r[n], s = o.length, l = 0; s > l; l++) { var h = o[l]; if (t.isValidPoint(h, !0)) { var p = Math.abs(h.canvasx - e); a > p && (a = p, i = h.idx) } } return i }, t.prototype.findClosestPoint = function (e, a) { for (var i, r, n, o, s, l, h, p = 1 / 0, g = this.layout_.points.length - 1; g >= 0; --g) for (var d = this.layout_.points[g], u = 0; u < d.length; ++u) o = d[u], t.isValidPoint(o) && (r = o.canvasx - e, n = o.canvasy - a, i = r * r + n * n, p > i && (p = i, s = o, l = g, h = o.idx)); var c = this.layout_.setNames[l]; return { row: h, seriesName: c, point: s } }, t.prototype.findStackedPoint = function (e, a) { for (var i, r, n = this.findClosestRow(e), o = 0; o < this.layout_.points.length; ++o) { var s = this.getLeftBoundary_(o), l = n - s, h = this.layout_.points[o]; if (!(l >= h.length)) { var p = h[l]; if (t.isValidPoint(p)) { var g = p.canvasy; if (e > p.canvasx && l + 1 < h.length) { var d = h[l + 1]; if (t.isValidPoint(d)) { var u = d.canvasx - p.canvasx; if (u > 0) { var c = (e - p.canvasx) / u; g += c * (d.canvasy - p.canvasy) } } } else if (e < p.canvasx && l > 0) { var y = h[l - 1]; if (t.isValidPoint(y)) { var u = p.canvasx - y.canvasx; if (u > 0) { var c = (p.canvasx - e) / u; g += c * (y.canvasy - p.canvasy) } } } (0 === o || a > g) && (i = p, r = o) } } } var _ = this.layout_.setNames[r]; return { row: n, seriesName: _, point: i } }, t.prototype.mouseMove_ = function (t) { var e = this.layout_.points; if (void 0 !== e && null !== e) { var a = this.eventToDomCoords(t), i = a[0], r = a[1], n = this.getOption("highlightSeriesOpts"), o = !1; if (n && !this.isSeriesLocked()) { var s; s = this.getBooleanOption("stackedGraph") ? this.findStackedPoint(i, r) : this.findClosestPoint(i, r), o = this.setSelection(s.row, s.seriesName) } else { var l = this.findClosestRow(i); o = this.setSelection(l) } var h = this.getFunctionOption("highlightCallback"); h && o && h.call(this, t, this.lastx_, this.selPoints_, this.lastRow_, this.highlightSet_) } }, t.prototype.getLeftBoundary_ = function (t) { if (this.boundaryIds_[t]) return this.boundaryIds_[t][0]; for (var e = 0; e < this.boundaryIds_.length; e++) if (void 0 !== this.boundaryIds_[e]) return this.boundaryIds_[e][0]; return 0 }, t.prototype.animateSelection_ = function (e) { var a = 10, i = 30; void 0 === this.fadeLevel && (this.fadeLevel = 0), void 0 === this.animateId && (this.animateId = 0); var r = this.fadeLevel, n = 0 > e ? r : a - r; if (0 >= n) return void (this.fadeLevel && this.updateSelection_(1)); var o = ++this.animateId, s = this; t.repeatAndCleanup(function () { s.animateId == o && (s.fadeLevel += e, 0 === s.fadeLevel ? s.clearSelection() : s.updateSelection_(s.fadeLevel / a)) }, n, i, function () { }) }, t.prototype.updateSelection_ = function (e) { this.cascadeEvents_("select", { selectedX: this.lastx_, selectedPoints: this.selPoints_ }); var a, i = this.canvas_ctx_; if (this.getOption("highlightSeriesOpts")) { i.clearRect(0, 0, this.width_, this.height_); var r = 1 - this.getNumericOption("highlightSeriesBackgroundAlpha"); if (r) { var n = !0; if (n) { if (void 0 === e) return void this.animateSelection_(1); r *= e } i.fillStyle = "rgba(255,255,255," + r + ")", i.fillRect(0, 0, this.width_, this.height_) } this.plotter_._renderLineChart(this.highlightSet_, i) } else if (this.previousVerticalX_ >= 0) { var o = 0, s = this.attr_("labels"); for (a = 1; a < s.length; a++) { var l = this.getNumericOption("highlightCircleSize", s[a]); l > o && (o = l) } var h = this.previousVerticalX_; i.clearRect(h - o - 1, 0, 2 * o + 2, this.height_) } if (this.isUsingExcanvas_ && this.currentZoomRectArgs_ && t.prototype.drawZoomRect_.apply(this, this.currentZoomRectArgs_), this.selPoints_.length > 0) { var p = this.selPoints_[0].canvasx; for (i.save(), a = 0; a < this.selPoints_.length; a++) { var g = this.selPoints_[a]; if (t.isOK(g.canvasy)) { var d = this.getNumericOption("highlightCircleSize", g.name), u = this.getFunctionOption("drawHighlightPointCallback", g.name), c = this.plotter_.colors[g.name]; u || (u = t.Circles.DEFAULT), i.lineWidth = this.getNumericOption("strokeWidth", g.name), i.strokeStyle = c, i.fillStyle = c, u.call(this, this, g.name, i, p, g.canvasy, c, d, g.idx) } } i.restore(), this.previousVerticalX_ = p } }, t.prototype.setSelection = function (t, e, a) { this.selPoints_ = []; var i = !1; if (t !== !1 && t >= 0) { t != this.lastRow_ && (i = !0), this.lastRow_ = t; for (var r = 0; r < this.layout_.points.length; ++r) { var n = this.layout_.points[r], o = t - this.getLeftBoundary_(r); if (o < n.length && n[o].idx == t) { var s = n[o]; null !== s.yval && this.selPoints_.push(s) } else for (var l = 0; l < n.length; ++l) { var s = n[l]; if (s.idx == t) { null !== s.yval && this.selPoints_.push(s); break } } } } else this.lastRow_ >= 0 && (i = !0), this.lastRow_ = -1; return this.lastx_ = this.selPoints_.length ? this.selPoints_[0].xval : -1, void 0 !== e && (this.highlightSet_ !== e && (i = !0), this.highlightSet_ = e), void 0 !== a && (this.lockedSet_ = a), i && this.updateSelection_(void 0), i }, t.prototype.mouseOut_ = function (t) { this.getFunctionOption("unhighlightCallback") && this.getFunctionOption("unhighlightCallback").call(this, t), this.getBooleanOption("hideOverlayOnMouseOut") && !this.lockedSet_ && this.clearSelection() }, t.prototype.clearSelection = function () { return this.cascadeEvents_("deselect", {}), this.lockedSet_ = !1, this.fadeLevel ? void this.animateSelection_(-1) : (this.canvas_ctx_.clearRect(0, 0, this.width_, this.height_), this.fadeLevel = 0, this.selPoints_ = [], this.lastx_ = -1, this.lastRow_ = -1, void (this.highlightSet_ = null)) }, t.prototype.getSelection = function () { if (!this.selPoints_ || this.selPoints_.length < 1) return -1; for (var t = 0; t < this.layout_.points.length; t++) for (var e = this.layout_.points[t], a = 0; a < e.length; a++) if (e[a].x == this.selPoints_[0].x) return e[a].idx; return -1 }, t.prototype.getHighlightSeries = function () { return this.highlightSet_ }, t.prototype.isSeriesLocked = function () { return this.lockedSet_ }, t.prototype.loadedEvent_ = function (t) { this.rawData_ = this.parseCSV_(t), this.cascadeDataDidUpdateEvent_(), this.predraw_() }, t.prototype.addXTicks_ = function () { var t; t = this.dateWindow_ ? [this.dateWindow_[0], this.dateWindow_[1]] : this.xAxisExtremes(); var e = this.optionsViewForAxis_("x"), a = e("ticker")(t[0], t[1], this.plotter_.area.w, e, this); this.layout_.setXTicks(a) }, t.prototype.getHandlerClass_ = function () { var e; return e = this.attr_("dataHandler") ? this.attr_("dataHandler") : this.fractions_ ? this.getBooleanOption("errorBars") ? t.DataHandlers.FractionsBarsHandler : t.DataHandlers.DefaultFractionHandler : this.getBooleanOption("customBars") ? t.DataHandlers.CustomBarsHandler : this.getBooleanOption("errorBars") ? t.DataHandlers.ErrorBarsHandler : t.DataHandlers.DefaultHandler }, t.prototype.predraw_ = function () { var t = new Date; this.dataHandler_ = new (this.getHandlerClass_()), this.layout_.computePlotArea(), this.computeYAxes_(), this.is_initial_draw_ || (this.canvas_ctx_.restore(), this.hidden_ctx_.restore()), this.canvas_ctx_.save(), this.hidden_ctx_.save(), this.plotter_ = new DygraphCanvasRenderer(this, this.hidden_, this.hidden_ctx_, this.layout_), this.createRollInterface_(), this.cascadeEvents_("predraw"), this.rolledSeries_ = [null]; for (var e = 1; e < this.numColumns() ; e++) { var a = this.dataHandler_.extractSeries(this.rawData_, e, this.attributes_); this.rollPeriod_ > 1 && (a = this.dataHandler_.rollingAverage(a, this.rollPeriod_, this.attributes_)), this.rolledSeries_.push(a) } this.drawGraph_(); var i = new Date; this.drawingTimeMs_ = i - t }, t.PointType = void 0, t.stackPoints_ = function (t, e, a, i) { for (var r = null, n = null, o = null, s = -1, l = function (e) { if (!(s >= e)) for (var a = e; a < t.length; ++a) if (o = null, !isNaN(t[a].yval) && null !== t[a].yval) { s = a, o = t[a]; break } }, h = 0; h < t.length; ++h) { var p = t[h], g = p.xval; void 0 === e[g] && (e[g] = 0); var d = p.yval; isNaN(d) || null === d ? "none" == i ? d = 0 : (l(h), d = n && o && "none" != i ? n.yval + (o.yval - n.yval) * ((g - n.xval) / (o.xval - n.xval)) : n && "all" == i ? n.yval : o && "all" == i ? o.yval : 0) : n = p; var u = e[g]; r != g && (u += d, e[g] = u), r = g, p.yval_stacked = u, u > a[1] && (a[1] = u), u < a[0] && (a[0] = u) } }, t.prototype.gatherDatasets_ = function (e, a) { var i, r, n, o, s, l, h = [], p = [], g = [], d = {}, u = e.length - 1; for (i = u; i >= 1; i--) if (this.visibility()[i - 1]) { if (a) { l = e[i]; var c = a[0], y = a[1]; for (n = null, o = null, r = 0; r < l.length; r++) l[r][0] >= c && null === n && (n = r), l[r][0] <= y && (o = r); null === n && (n = 0); for (var _ = n, v = !0; v && _ > 0;) _--, v = null === l[_][1]; null === o && (o = l.length - 1); var f = o; for (v = !0; v && f < l.length - 1;) f++, v = null === l[f][1]; _ !== n && (n = _), f !== o && (o = f), h[i - 1] = [n, o], l = l.slice(n, o + 1) } else l = e[i], h[i - 1] = [0, l.length - 1]; var x = this.attr_("labels")[i], m = this.dataHandler_.getExtremeYValues(l, a, this.getBooleanOption("stepPlot", x)), D = this.dataHandler_.seriesToPoints(l, x, h[i - 1][0]); this.getBooleanOption("stackedGraph") && (s = this.attributes_.axisForSeries(x), void 0 === g[s] && (g[s] = []), t.stackPoints_(D, g[s], m, this.getBooleanOption("stackedGraphNaNFill"))), d[x] = m, p[i] = D } return { points: p, extremes: d, boundaryIds: h } }, t.prototype.drawGraph_ = function () { var t = new Date, e = this.is_initial_draw_; this.is_initial_draw_ = !1, this.layout_.removeAllDatasets(), this.setColors_(), this.attrs_.pointSize = .5 * this.getNumericOption("highlightCircleSize"); var a = this.gatherDatasets_(this.rolledSeries_, this.dateWindow_), i = a.points, r = a.extremes; this.boundaryIds_ = a.boundaryIds, this.setIndexByName_ = {}; var n = this.attr_("labels"); n.length > 0 && (this.setIndexByName_[n[0]] = 0); for (var o = 0, s = 1; s < i.length; s++) this.setIndexByName_[n[s]] = s, this.visibility()[s - 1] && (this.layout_.addDataset(n[s], i[s]), this.datasetIndex_[s] = o++); this.computeYAxisRanges_(r), this.layout_.setYAxes(this.axes_), this.addXTicks_(); var l = this.zoomed_x_; if (this.zoomed_x_ = l, this.layout_.evaluate(), this.renderGraph_(e), this.getStringOption("timingName")) { var h = new Date; console.log(this.getStringOption("timingName") + " - drawGraph: " + (h - t) + "ms") } }, t.prototype.renderGraph_ = function (t) { this.cascadeEvents_("clearChart"), this.plotter_.clear(), this.getFunctionOption("underlayCallback") && this.getFunctionOption("underlayCallback").call(this, this.hidden_ctx_, this.layout_.getPlotArea(), this, this); var e = { canvas: this.hidden_, drawingContext: this.hidden_ctx_ }; if (this.cascadeEvents_("willDrawChart", e), this.plotter_.render(), this.cascadeEvents_("didDrawChart", e), this.lastRow_ = -1, this.canvas_.getContext("2d").clearRect(0, 0, this.width_, this.height_), null !== this.getFunctionOption("drawCallback") && this.getFunctionOption("drawCallback")(this, t), t) for (this.readyFired_ = !0; this.readyFns_.length > 0;) { var a = this.readyFns_.pop(); a(this) } }, t.prototype.computeYAxes_ = function () { var e, a, i, r, n; if (void 0 !== this.axes_ && this.user_attrs_.hasOwnProperty("valueRange") === !1) for (e = [], i = 0; i < this.axes_.length; i++) e.push(this.axes_[i].valueWindow); for (this.axes_ = [], a = 0; a < this.attributes_.numAxes() ; a++) r = { g: this }, t.update(r, this.attributes_.axisOptions(a)), this.axes_[a] = r; if (n = this.attr_("valueRange"), n && (this.axes_[0].valueRange = n), void 0 !== e) { var o = Math.min(e.length, this.axes_.length); for (i = 0; o > i; i++) this.axes_[i].valueWindow = e[i] } for (a = 0; a < this.axes_.length; a++) if (0 === a) r = this.optionsViewForAxis_("y" + (a ? "2" : "")), n = r("valueRange"), n && (this.axes_[a].valueRange = n); else { var s = this.user_attrs_.axes; s && s.y2 && (n = s.y2.valueRange, n && (this.axes_[a].valueRange = n)) } }, t.prototype.numAxes = function () { return this.attributes_.numAxes() }, t.prototype.axisPropertiesForSeries = function (t) { return this.axes_[this.attributes_.axisForSeries(t)] }, t.prototype.computeYAxisRanges_ = function (t) { for (var e, a, i, r, n, o = function (t) { return isNaN(parseFloat(t)) }, s = this.attributes_.numAxes(), l = 0; s > l; l++) { var h = this.axes_[l], p = this.attributes_.getForAxis("logscale", l), g = this.attributes_.getForAxis("includeZero", l), d = this.attributes_.getForAxis("independentTicks", l); if (i = this.attributes_.seriesForAxis(l), e = !0, r = .1, null !== this.getNumericOption("yRangePad") && (e = !1, r = this.getNumericOption("yRangePad") / this.plotter_.area.h), 0 === i.length) h.extremeRange = [0, 1]; else { for (var u, c, y = 1 / 0, _ = -1 / 0, v = 0; v < i.length; v++) t.hasOwnProperty(i[v]) && (u = t[i[v]][0], null !== u && (y = Math.min(u, y)), c = t[i[v]][1], null !== c && (_ = Math.max(c, _))); g && !p && (y > 0 && (y = 0), 0 > _ && (_ = 0)), 1 / 0 == y && (y = 0), _ == -1 / 0 && (_ = 1), a = _ - y, 0 === a && (0 !== _ ? a = Math.abs(_) : (_ = 1, a = 1)); var f, x; if (p) if (e) f = _ + r * a, x = y; else { var m = Math.exp(Math.log(a) * r); f = _ * m, x = y / m } else f = _ + r * a, x = y - r * a, e && !this.getBooleanOption("avoidMinZero") && (0 > x && y >= 0 && (x = 0), f > 0 && 0 >= _ && (f = 0)); h.extremeRange = [x, f] } if (h.valueWindow) h.computedValueRange = [h.valueWindow[0], h.valueWindow[1]]; else if (h.valueRange) { var D = o(h.valueRange[0]) ? h.extremeRange[0] : h.valueRange[0], A = o(h.valueRange[1]) ? h.extremeRange[1] : h.valueRange[1]; if (!e) if (h.logscale) { var m = Math.exp(Math.log(a) * r); D *= m, A /= m } else a = A - D, D -= a * r, A += a * r; h.computedValueRange = [D, A] } else h.computedValueRange = h.extremeRange; if (d) { h.independentTicks = d; var w = this.optionsViewForAxis_("y" + (l ? "2" : "")), b = w("ticker"); h.ticks = b(h.computedValueRange[0], h.computedValueRange[1], this.plotter_.area.h, w, this), n || (n = h) } } if (void 0 === n) throw 'Configuration Error: At least one axis has to have the "independentTicks" option activated.'; for (var l = 0; s > l; l++) { var h = this.axes_[l]; if (!h.independentTicks) { for (var w = this.optionsViewForAxis_("y" + (l ? "2" : "")), b = w("ticker"), T = n.ticks, E = n.computedValueRange[1] - n.computedValueRange[0], C = h.computedValueRange[1] - h.computedValueRange[0], L = [], P = 0; P < T.length; P++) { var S = (T[P].v - n.computedValueRange[0]) / E, O = h.computedValueRange[0] + S * C; L.push(O) } h.ticks = b(h.computedValueRange[0], h.computedValueRange[1], this.plotter_.area.h, w, this, L) } } }, t.prototype.detectTypeFromString_ = function (t) { var e = !1, a = t.indexOf("-"); a > 0 && "e" != t[a - 1] && "E" != t[a - 1] || t.indexOf("/") >= 0 || isNaN(parseFloat(t)) ? e = !0 : 8 == t.length && t > "19700101" && "20371231" > t && (e = !0), this.setXAxisOptions_(e) }, t.prototype.setXAxisOptions_ = function (e) { e ? (this.attrs_.xValueParser = t.dateParser, this.attrs_.axes.x.valueFormatter = t.dateValueFormatter, this.attrs_.axes.x.ticker = t.dateTicker, this.attrs_.axes.x.axisLabelFormatter = t.dateAxisLabelFormatter) : (this.attrs_.xValueParser = function (t) { return parseFloat(t) }, this.attrs_.axes.x.valueFormatter = function (t) { return t }, this.attrs_.axes.x.ticker = t.numericTicks, this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter) }, t.prototype.parseCSV_ = function (e) { var a, i, r = [], n = t.detectLineDelimiter(e), o = e.split(n || "\n"), s = this.getStringOption("delimiter"); -1 == o[0].indexOf(s) && o[0].indexOf("	") >= 0 && (s = "	"); var l = 0; "labels" in this.user_attrs_ || (l = 1, this.attrs_.labels = o[0].split(s), this.attributes_.reparseSeries()); for (var h, p = 0, g = !1, d = this.attr_("labels").length, u = !1, c = l; c < o.length; c++) { var y = o[c]; if (p = c, 0 !== y.length && "#" != y[0]) { var _ = y.split(s); if (!(_.length < 2)) { var v = []; if (g || (this.detectTypeFromString_(_[0]), h = this.getFunctionOption("xValueParser"), g = !0), v[0] = h(_[0], this), this.fractions_) for (i = 1; i < _.length; i++) a = _[i].split("/"), 2 != a.length ? (console.error('Expected fractional "num/den" values in CSV data but found a value \'' + _[i] + "' on line " + (1 + c) + " ('" + y + "') which is not of this form."), v[i] = [0, 0]) : v[i] = [t.parseFloat_(a[0], c, y), t.parseFloat_(a[1], c, y)]; else if (this.getBooleanOption("errorBars")) for (_.length % 2 != 1 && console.error("Expected alternating (value, stdev.) pairs in CSV data but line " + (1 + c) + " has an odd number of values (" + (_.length - 1) + "): '" + y + "'"), i = 1; i < _.length; i += 2) v[(i + 1) / 2] = [t.parseFloat_(_[i], c, y), t.parseFloat_(_[i + 1], c, y)]; else if (this.getBooleanOption("customBars")) for (i = 1; i < _.length; i++) { var f = _[i]; /^ *$/.test(f) ? v[i] = [null, null, null] : (a = f.split(";"), 3 == a.length ? v[i] = [t.parseFloat_(a[0], c, y), t.parseFloat_(a[1], c, y), t.parseFloat_(a[2], c, y)] : console.warn('When using customBars, values must be either blank or "low;center;high" tuples (got "' + f + '" on line ' + (1 + c))) } else for (i = 1; i < _.length; i++) v[i] = t.parseFloat_(_[i], c, y); if (r.length > 0 && v[0] < r[r.length - 1][0] && (u = !0), v.length != d && console.error("Number of columns in line " + c + " (" + v.length + ") does not agree with number of labels (" + d + ") " + y), 0 === c && this.attr_("labels")) { var x = !0; for (i = 0; x && i < v.length; i++) v[i] && (x = !1); if (x) { console.warn("The dygraphs 'labels' option is set, but the first row of CSV data ('" + y + "') appears to also contain labels. Will drop the CSV labels and use the option labels."); continue } } r.push(v) } } } return u && (console.warn("CSV is out of order; order it correctly to speed loading."), r.sort(function (t, e) { return t[0] - e[0] })), r }, t.prototype.parseArray_ = function (e) { if (0 === e.length) return console.error("Can't plot empty data set"), null; if (0 === e[0].length) return console.error("Data set cannot contain an empty row"), null; var a; if (null === this.attr_("labels")) { for (console.warn("Using default labels. Set labels explicitly via 'labels' in the options parameter"), this.attrs_.labels = ["X"], a = 1; a < e[0].length; a++) this.attrs_.labels.push("Y" + a); this.attributes_.reparseSeries() } else { var i = this.attr_("labels"); if (i.length != e[0].length) return console.error("Mismatch between number of labels (" + i + ") and number of columns in array (" + e[0].length + ")"), null } if (t.isDateLike(e[0][0])) { this.attrs_.axes.x.valueFormatter = t.dateValueFormatter, this.attrs_.axes.x.ticker = t.dateTicker, this.attrs_.axes.x.axisLabelFormatter = t.dateAxisLabelFormatter; var r = t.clone(e); for (a = 0; a < e.length; a++) { if (0 === r[a].length) return console.error("Row " + (1 + a) + " of data is empty"), null; if (null === r[a][0] || "function" != typeof r[a][0].getTime || isNaN(r[a][0].getTime())) return console.error("x value in row " + (1 + a) + " is not a Date"), null; r[a][0] = r[a][0].getTime() } return r } return this.attrs_.axes.x.valueFormatter = function (t) { return t }, this.attrs_.axes.x.ticker = t.numericTicks, this.attrs_.axes.x.axisLabelFormatter = t.numberAxisLabelFormatter, e }, t.prototype.parseDataTable_ = function (e) { var a = function (t) { var e = String.fromCharCode(65 + t % 26); for (t = Math.floor(t / 26) ; t > 0;) e = String.fromCharCode(65 + (t - 1) % 26) + e.toLowerCase(), t = Math.floor((t - 1) / 26); return e }, i = e.getNumberOfColumns(), r = e.getNumberOfRows(), n = e.getColumnType(0); if ("date" == n || "datetime" == n) this.attrs_.xValueParser = t.dateParser, this.attrs_.axes.x.valueFormatter = t.dateValueFormatter, this.attrs_.axes.x.ticker = t.dateTicker, this.attrs_.axes.x.axisLabelFormatter = t.dateAxisLabelFormatter; else { if ("number" != n) return console.error("only 'date', 'datetime' and 'number' types are supported for column 1 of DataTable input (Got '" + n + "')"), null; this.attrs_.xValueParser = function (t) { return parseFloat(t) }, this.attrs_.axes.x.valueFormatter = function (t) { return t }, this.attrs_.axes.x.ticker = t.numericTicks, this.attrs_.axes.x.axisLabelFormatter = this.attrs_.axes.x.valueFormatter } var o, s, l = [], h = {}, p = !1; for (o = 1; i > o; o++) { var g = e.getColumnType(o); if ("number" == g) l.push(o); else if ("string" == g && this.getBooleanOption("displayAnnotations")) { var d = l[l.length - 1]; h.hasOwnProperty(d) ? h[d].push(o) : h[d] = [o], p = !0 } else console.error("Only 'number' is supported as a dependent type with Gviz. 'string' is only supported if displayAnnotations is true") } var u = [e.getColumnLabel(0)]; for (o = 0; o < l.length; o++) u.push(e.getColumnLabel(l[o])), this.getBooleanOption("errorBars") && (o += 1); this.attrs_.labels = u, i = u.length; var c = [], y = !1, _ = []; for (o = 0; r > o; o++) { var v = []; if ("undefined" != typeof e.getValue(o, 0) && null !== e.getValue(o, 0)) { if (v.push("date" == n || "datetime" == n ? e.getValue(o, 0).getTime() : e.getValue(o, 0)), this.getBooleanOption("errorBars")) for (s = 0; i - 1 > s; s++) v.push([e.getValue(o, 1 + 2 * s), e.getValue(o, 2 + 2 * s)]); else { for (s = 0; s < l.length; s++) { var f = l[s]; if (v.push(e.getValue(o, f)), p && h.hasOwnProperty(f) && null !== e.getValue(o, h[f][0])) { var x = {}; x.series = e.getColumnLabel(f), x.xval = v[0], x.shortText = a(_.length), x.text = ""; for (var m = 0; m < h[f].length; m++) m && (x.text += "\n"), x.text += e.getValue(o, h[f][m]); _.push(x) } } for (s = 0; s < v.length; s++) isFinite(v[s]) || (v[s] = null) } c.length > 0 && v[0] < c[c.length - 1][0] && (y = !0), c.push(v) } else console.warn("Ignoring row " + o + " of DataTable because of undefined or null first column.") } y && (console.warn("DataTable is out of order; order it correctly to speed loading."), c.sort(function (t, e) { return t[0] - e[0] })), this.rawData_ = c, _.length > 0 && this.setAnnotations(_, !0), this.attributes_.reparseSeries() }, t.prototype.cascadeDataDidUpdateEvent_ = function () { this.cascadeEvents_("dataDidUpdate", {}) }, t.prototype.start_ = function () { var e = this.file_; if ("function" == typeof e && (e = e()), t.isArrayLike(e)) this.rawData_ = this.parseArray_(e), this.cascadeDataDidUpdateEvent_(), this.predraw_(); else if ("object" == typeof e && "function" == typeof e.getColumnRange) this.parseDataTable_(e), this.cascadeDataDidUpdateEvent_(), this.predraw_(); else if ("string" == typeof e) { var a = t.detectLineDelimiter(e); if (a) this.loadedEvent_(e); else { var i; i = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP"); var r = this; i.onreadystatechange = function () { 4 == i.readyState && (200 === i.status || 0 === i.status) && r.loadedEvent_(i.responseText) }, i.open("GET", e, !0), i.send(null) } } else console.error("Unknown data format: " + typeof e) }, t.prototype.updateOptions = function (e, a) { "undefined" == typeof a && (a = !1); var i = e.file, r = t.mapLegacyOptions_(e); "rollPeriod" in r && (this.rollPeriod_ = r.rollPeriod), "dateWindow" in r && (this.dateWindow_ = r.dateWindow, "isZoomedIgnoreProgrammaticZoom" in r || (this.zoomed_x_ = null !== r.dateWindow)), "valueRange" in r && !("isZoomedIgnoreProgrammaticZoom" in r) && (this.zoomed_y_ = null !== r.valueRange); var n = t.isPixelChangingOptionList(this.attr_("labels"), r); t.updateDeep(this.user_attrs_, r), this.attributes_.reparseSeries(), i ? (this.cascadeEvents_("dataWillUpdate", {}), this.file_ = i, a || this.start_()) : a || (n ? this.predraw_() : this.renderGraph_(!1)) }, t.mapLegacyOptions_ = function (t) { var e = {}; for (var a in t) t.hasOwnProperty(a) && "file" != a && t.hasOwnProperty(a) && (e[a] = t[a]); var i = function (t, a, i) { e.axes || (e.axes = {}), e.axes[t] || (e.axes[t] = {}), e.axes[t][a] = i }, r = function (a, r, n) { "undefined" != typeof t[a] && (console.warn("Option " + a + " is deprecated. Use the " + n + " option for the " + r + " axis instead. (e.g. { axes : { " + r + " : { " + n + " : ... } } } (see http://dygraphs.com/per-axis.html for more information."), i(r, n, t[a]), delete e[a]) }; return r("xValueFormatter", "x", "valueFormatter"), r("pixelsPerXLabel", "x", "pixelsPerLabel"), r("xAxisLabelFormatter", "x", "axisLabelFormatter"), r("xTicker", "x", "ticker"), r("yValueFormatter", "y", "valueFormatter"), r("pixelsPerYLabel", "y", "pixelsPerLabel"), r("yAxisLabelFormatter", "y", "axisLabelFormatter"), r("yTicker", "y", "ticker"), r("drawXGrid", "x", "drawGrid"), r("drawXAxis", "x", "drawAxis"), r("drawYGrid", "y", "drawGrid"), r("drawYAxis", "y", "drawAxis"), r("xAxisLabelWidth", "x", "axisLabelWidth"), r("yAxisLabelWidth", "y", "axisLabelWidth"), e }, t.prototype.resize = function (t, e) { if (!this.resize_lock) { this.resize_lock = !0, null === t != (null === e) && (console.warn("Dygraph.resize() should be called with zero parameters or two non-NULL parameters. Pretending it was zero."), t = e = null); var a = this.width_, i = this.height_; t ? (this.maindiv_.style.width = t + "px", this.maindiv_.style.height = e + "px", this.width_ = t, this.height_ = e) : (this.width_ = this.maindiv_.clientWidth, this.height_ = this.maindiv_.clientHeight), (a != this.width_ || i != this.height_) && (this.resizeElements_(), this.predraw_()), this.resize_lock = !1 } }, t.prototype.adjustRoll = function (t) { this.rollPeriod_ = t, this.predraw_() }, t.prototype.visibility = function () { for (this.getOption("visibility") || (this.attrs_.visibility = []) ; this.getOption("visibility").length < this.numColumns() - 1;) this.attrs_.visibility.push(!0); return this.getOption("visibility") }, t.prototype.setVisibility = function (t, e) { var a = this.visibility(); 0 > t || t >= a.length ? console.warn("invalid series number in setVisibility: " + t) : (a[t] = e, this.predraw_()) }, t.prototype.size = function () { return { width: this.width_, height: this.height_ } }, t.prototype.setAnnotations = function (e, a) { return t.addAnnotationRule(), this.annotations_ = e, this.layout_ ? (this.layout_.setAnnotations(this.annotations_), void (a || this.predraw_())) : void console.warn("Tried to setAnnotations before dygraph was ready. Try setting them in a ready() block. See dygraphs.com/tests/annotation.html") }, t.prototype.annotations = function () { return this.annotations_ }, t.prototype.getLabels = function () { var t = this.attr_("labels"); return t ? t.slice() : null }, t.prototype.indexFromSetName = function (t) { return this.setIndexByName_[t] }, t.prototype.ready = function (t) { this.is_initial_draw_ ? this.readyFns_.push(t) : t.call(this, this) }, t.addAnnotationRule = function () { if (!t.addedAnnotationCSS) { var e = "border: 1px solid black; background-color: white; text-align: center;", a = document.createElement("style"); a.type = "text/css", document.getElementsByTagName("head")[0].appendChild(a); for (var i = 0; i < document.styleSheets.length; i++) if (!document.styleSheets[i].disabled) { var r = document.styleSheets[i]; try { if (r.insertRule) { var n = r.cssRules ? r.cssRules.length : 0; r.insertRule(".dygraphDefaultAnnotation { " + e + " }", n) } else r.addRule && r.addRule(".dygraphDefaultAnnotation", e); return void (t.addedAnnotationCSS = !0) } catch (o) { } } console.warn("Unable to add default annotation CSS rule; display may be off.") } }, t
}(); !function () {
    "use strict"; Dygraph.LOG_SCALE = 10, Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE), Dygraph.log10 = function (t) { return Math.log(t) / Dygraph.LN_TEN }, Dygraph.DOTTED_LINE = [2, 2], Dygraph.DASHED_LINE = [7, 3], Dygraph.DOT_DASH_LINE = [7, 2, 2, 2], Dygraph.getContext = function (t) { return t.getContext("2d") }, Dygraph.addEvent = function (t, e, a) { t.addEventListener ? t.addEventListener(e, a, !1) : (t[e + a] = function () { a(window.event) }, t.attachEvent("on" + e, t[e + a])) }, Dygraph.prototype.addAndTrackEvent = function (t, e, a) { Dygraph.addEvent(t, e, a), this.registeredEvents_.push({ elem: t, type: e, fn: a }) }, Dygraph.removeEvent = function (t, e, a) { if (t.removeEventListener) t.removeEventListener(e, a, !1); else { try { t.detachEvent("on" + e, t[e + a]) } catch (i) { } t[e + a] = null } }, Dygraph.prototype.removeTrackedEvents_ = function () { if (this.registeredEvents_) for (var t = 0; t < this.registeredEvents_.length; t++) { var e = this.registeredEvents_[t]; Dygraph.removeEvent(e.elem, e.type, e.fn) } this.registeredEvents_ = [] }, Dygraph.cancelEvent = function (t) { return t = t ? t : window.event, t.stopPropagation && t.stopPropagation(), t.preventDefault && t.preventDefault(), t.cancelBubble = !0, t.cancel = !0, t.returnValue = !1, !1 }, Dygraph.hsvToRGB = function (t, e, a) { var i, r, n; if (0 === e) i = a, r = a, n = a; else { var o = Math.floor(6 * t), s = 6 * t - o, l = a * (1 - e), h = a * (1 - e * s), p = a * (1 - e * (1 - s)); switch (o) { case 1: i = h, r = a, n = l; break; case 2: i = l, r = a, n = p; break; case 3: i = l, r = h, n = a; break; case 4: i = p, r = l, n = a; break; case 5: i = a, r = l, n = h; break; case 6: case 0: i = a, r = p, n = l } } return i = Math.floor(255 * i + .5), r = Math.floor(255 * r + .5), n = Math.floor(255 * n + .5), "rgb(" + i + "," + r + "," + n + ")" }, Dygraph.findPos = function (t) { var e = 0, a = 0; if (t.offsetParent) for (var i = t; ;) { var r = "0", n = "0"; if (window.getComputedStyle) { var o = window.getComputedStyle(i, null); r = o.borderLeft || "0", n = o.borderTop || "0" } if (e += parseInt(r, 10), a += parseInt(n, 10), e += i.offsetLeft, a += i.offsetTop, !i.offsetParent) break; i = i.offsetParent } else t.x && (e += t.x), t.y && (a += t.y); for (; t && t != document.body;) e -= t.scrollLeft, a -= t.scrollTop, t = t.parentNode; return { x: e, y: a } }, Dygraph.pageX = function (t) {
        if (t.pageX) return !t.pageX || t.pageX < 0 ? 0 : t.pageX;
        var e = document.documentElement, a = document.body; return t.clientX + (e.scrollLeft || a.scrollLeft) - (e.clientLeft || 0)
    }, Dygraph.pageY = function (t) { if (t.pageY) return !t.pageY || t.pageY < 0 ? 0 : t.pageY; var e = document.documentElement, a = document.body; return t.clientY + (e.scrollTop || a.scrollTop) - (e.clientTop || 0) }, Dygraph.dragGetX_ = function (t, e) { return Dygraph.pageX(t) - e.px }, Dygraph.dragGetY_ = function (t, e) { return Dygraph.pageY(t) - e.py }, Dygraph.isOK = function (t) { return !!t && !isNaN(t) }, Dygraph.isValidPoint = function (t, e) { return t ? null === t.yval ? !1 : null === t.x || void 0 === t.x ? !1 : null === t.y || void 0 === t.y ? !1 : isNaN(t.x) || !e && isNaN(t.y) ? !1 : !0 : !1 }, Dygraph.floatFormat = function (t, e) { var a = Math.min(Math.max(1, e || 2), 21); return Math.abs(t) < .001 && 0 !== t ? t.toExponential(a - 1) : t.toPrecision(a) }, Dygraph.zeropad = function (t) { return 10 > t ? "0" + t : "" + t }, Dygraph.DateAccessorsLocal = { getFullYear: function (t) { return t.getFullYear() }, getMonth: function (t) { return t.getMonth() }, getDate: function (t) { return t.getDate() }, getHours: function (t) { return t.getHours() }, getMinutes: function (t) { return t.getMinutes() }, getSeconds: function (t) { return t.getSeconds() }, getMilliseconds: function (t) { return t.getMilliseconds() }, getDay: function (t) { return t.getDay() }, makeDate: function (t, e, a, i, r, n, o) { return new Date(t, e, a, i, r, n, o) } }, Dygraph.DateAccessorsUTC = { getFullYear: function (t) { return t.getUTCFullYear() }, getMonth: function (t) { return t.getUTCMonth() }, getDate: function (t) { return t.getUTCDate() }, getHours: function (t) { return t.getUTCHours() }, getMinutes: function (t) { return t.getUTCMinutes() }, getSeconds: function (t) { return t.getUTCSeconds() }, getMilliseconds: function (t) { return t.getUTCMilliseconds() }, getDay: function (t) { return t.getUTCDay() }, makeDate: function (t, e, a, i, r, n, o) { return new Date(Date.UTC(t, e, a, i, r, n, o)) } }, Dygraph.hmsString_ = function (t, e, a) { var i = Dygraph.zeropad, r = i(t) + ":" + i(e); return a && (r += ":" + i(a)), r }, Dygraph.dateString_ = function (t, e) { var a = Dygraph.zeropad, i = e ? Dygraph.DateAccessorsUTC : Dygraph.DateAccessorsLocal, r = new Date(t), n = i.getFullYear(r), o = i.getMonth(r), s = i.getDate(r), l = i.getHours(r), h = i.getMinutes(r), p = i.getSeconds(r), g = "" + n, d = a(o + 1), u = a(s), c = 3600 * l + 60 * h + p, y = g + "/" + d + "/" + u; return c && (y += " " + Dygraph.hmsString_(l, h, p)), y }, Dygraph.round_ = function (t, e) { var a = Math.pow(10, e); return Math.round(t * a) / a }, Dygraph.binarySearch = function (t, e, a, i, r) { if ((null === i || void 0 === i || null === r || void 0 === r) && (i = 0, r = e.length - 1), i > r) return -1; (null === a || void 0 === a) && (a = 0); var n, o = function (t) { return t >= 0 && t < e.length }, s = parseInt((i + r) / 2, 10), l = e[s]; return l == t ? s : l > t ? a > 0 && (n = s - 1, o(n) && e[n] < t) ? s : Dygraph.binarySearch(t, e, a, i, s - 1) : t > l ? 0 > a && (n = s + 1, o(n) && e[n] > t) ? s : Dygraph.binarySearch(t, e, a, s + 1, r) : -1 }, Dygraph.dateParser = function (t) { var e, a; if ((-1 == t.search("-") || -1 != t.search("T") || -1 != t.search("Z")) && (a = Dygraph.dateStrToMillis(t), a && !isNaN(a))) return a; if (-1 != t.search("-")) { for (e = t.replace("-", "/", "g") ; -1 != e.search("-") ;) e = e.replace("-", "/"); a = Dygraph.dateStrToMillis(e) } else 8 == t.length ? (e = t.substr(0, 4) + "/" + t.substr(4, 2) + "/" + t.substr(6, 2), a = Dygraph.dateStrToMillis(e)) : a = Dygraph.dateStrToMillis(t); return (!a || isNaN(a)) && console.error("Couldn't parse " + t + " as a date"), a }, Dygraph.dateStrToMillis = function (t) { return new Date(t).getTime() }, Dygraph.update = function (t, e) { if ("undefined" != typeof e && null !== e) for (var a in e) e.hasOwnProperty(a) && (t[a] = e[a]); return t }, Dygraph.updateDeep = function (t, e) { function a(t) { return "object" == typeof Node ? t instanceof Node : "object" == typeof t && "number" == typeof t.nodeType && "string" == typeof t.nodeName } if ("undefined" != typeof e && null !== e) for (var i in e) e.hasOwnProperty(i) && (null === e[i] ? t[i] = null : Dygraph.isArrayLike(e[i]) ? t[i] = e[i].slice() : a(e[i]) ? t[i] = e[i] : "object" == typeof e[i] ? (("object" != typeof t[i] || null === t[i]) && (t[i] = {}), Dygraph.updateDeep(t[i], e[i])) : t[i] = e[i]); return t }, Dygraph.isArrayLike = function (t) { var e = typeof t; return "object" != e && ("function" != e || "function" != typeof t.item) || null === t || "number" != typeof t.length || 3 === t.nodeType ? !1 : !0 }, Dygraph.isDateLike = function (t) { return "object" != typeof t || null === t || "function" != typeof t.getTime ? !1 : !0 }, Dygraph.clone = function (t) { for (var e = [], a = 0; a < t.length; a++) e.push(Dygraph.isArrayLike(t[a]) ? Dygraph.clone(t[a]) : t[a]); return e }, Dygraph.createCanvas = function () { var t = document.createElement("canvas"), e = /MSIE/.test(navigator.userAgent) && !window.opera; return e && "undefined" != typeof G_vmlCanvasManager && (t = G_vmlCanvasManager.initElement(t)), t }, Dygraph.getContextPixelRatio = function (t) { try { var e = window.devicePixelRatio, a = t.webkitBackingStorePixelRatio || t.mozBackingStorePixelRatio || t.msBackingStorePixelRatio || t.oBackingStorePixelRatio || t.backingStorePixelRatio || 1; return void 0 !== e ? e / a : 1 } catch (i) { return 1 } }, Dygraph.isAndroid = function () { return /Android/.test(navigator.userAgent) }, Dygraph.Iterator = function (t, e, a, i) { e = e || 0, a = a || t.length, this.hasNext = !0, this.peek = null, this.start_ = e, this.array_ = t, this.predicate_ = i, this.end_ = Math.min(t.length, e + a), this.nextIdx_ = e - 1, this.next() }, Dygraph.Iterator.prototype.next = function () { if (!this.hasNext) return null; for (var t = this.peek, e = this.nextIdx_ + 1, a = !1; e < this.end_;) { if (!this.predicate_ || this.predicate_(this.array_, e)) { this.peek = this.array_[e], a = !0; break } e++ } return this.nextIdx_ = e, a || (this.hasNext = !1, this.peek = null), t }, Dygraph.createIterator = function (t, e, a, i) { return new Dygraph.Iterator(t, e, a, i) }, Dygraph.requestAnimFrame = function () { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (t) { window.setTimeout(t, 1e3 / 60) } }(), Dygraph.repeatAndCleanup = function (t, e, a, i) { var r, n = 0, o = (new Date).getTime(); if (t(n), 1 == e) return void i(); var s = e - 1; !function l() { n >= e || Dygraph.requestAnimFrame.call(window, function () { var e = (new Date).getTime(), h = e - o; r = n, n = Math.floor(h / a); var p = n - r, g = n + p > s; g || n >= s ? (t(s), i()) : (0 !== p && t(n), l()) }) }() }; var t = { annotationClickHandler: !0, annotationDblClickHandler: !0, annotationMouseOutHandler: !0, annotationMouseOverHandler: !0, axisLabelColor: !0, axisLineColor: !0, axisLineWidth: !0, clickCallback: !0, drawCallback: !0, drawHighlightPointCallback: !0, drawPoints: !0, drawPointCallback: !0, drawXGrid: !0, drawYGrid: !0, fillAlpha: !0, gridLineColor: !0, gridLineWidth: !0, hideOverlayOnMouseOut: !0, highlightCallback: !0, highlightCircleSize: !0, interactionModel: !0, isZoomedIgnoreProgrammaticZoom: !0, labelsDiv: !0, labelsDivStyles: !0, labelsDivWidth: !0, labelsKMB: !0, labelsKMG2: !0, labelsSeparateLines: !0, labelsShowZeroValues: !0, legend: !0, panEdgeFraction: !0, pixelsPerYLabel: !0, pointClickCallback: !0, pointSize: !0, rangeSelectorPlotFillColor: !0, rangeSelectorPlotStrokeColor: !0, showLabelsOnHighlight: !0, showRoller: !0, strokeWidth: !0, underlayCallback: !0, unhighlightCallback: !0, zoomCallback: !0 }; Dygraph.isPixelChangingOptionList = function (e, a) { var i = {}; if (e) for (var r = 1; r < e.length; r++) i[e[r]] = !0; var n = function (e) { for (var a in e) if (e.hasOwnProperty(a) && !t[a]) return !0; return !1 }; for (var o in a) if (a.hasOwnProperty(o)) if ("highlightSeriesOpts" == o || i[o] && !a.series) { if (n(a[o])) return !0 } else if ("series" == o || "axes" == o) { var s = a[o]; for (var l in s) if (s.hasOwnProperty(l) && n(s[l])) return !0 } else if (!t[o]) return !0; return !1 }, Dygraph.Circles = { DEFAULT: function (t, e, a, i, r, n, o) { a.beginPath(), a.fillStyle = n, a.arc(i, r, o, 0, 2 * Math.PI, !1), a.fill() } }, Dygraph.IFrameTarp = function () { this.tarps = [] }, Dygraph.IFrameTarp.prototype.cover = function () { for (var t = document.getElementsByTagName("iframe"), e = 0; e < t.length; e++) { var a = t[e], i = Dygraph.findPos(a), r = i.x, n = i.y, o = a.offsetWidth, s = a.offsetHeight, l = document.createElement("div"); l.style.position = "absolute", l.style.left = r + "px", l.style.top = n + "px", l.style.width = o + "px", l.style.height = s + "px", l.style.zIndex = 999, document.body.appendChild(l), this.tarps.push(l) } }, Dygraph.IFrameTarp.prototype.uncover = function () { for (var t = 0; t < this.tarps.length; t++) this.tarps[t].parentNode.removeChild(this.tarps[t]); this.tarps = [] }, Dygraph.detectLineDelimiter = function (t) { for (var e = 0; e < t.length; e++) { var a = t.charAt(e); if ("\r" === a) return e + 1 < t.length && "\n" === t.charAt(e + 1) ? "\r\n" : a; if ("\n" === a) return e + 1 < t.length && "\r" === t.charAt(e + 1) ? "\n\r" : a } return null }, Dygraph.isNodeContainedBy = function (t, e) { if (null === e || null === t) return !1; for (var a = t; a && a !== e;) a = a.parentNode; return a === e }, Dygraph.pow = function (t, e) { return 0 > e ? 1 / Math.pow(t, -e) : Math.pow(t, e) }, Dygraph.toRGB_ = function (t) { var e = document.createElement("div"); e.style.backgroundColor = t, e.style.visibility = "hidden", document.body.appendChild(e); var a; a = window.getComputedStyle ? window.getComputedStyle(e, null).backgroundColor : e.currentStyle.backgroundColor, document.body.removeChild(e); var i = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/.exec(a); return { r: parseInt(i[1], 10), g: parseInt(i[2], 10), b: parseInt(i[3], 10) } }, Dygraph.isCanvasSupported = function (t) { var e; try { e = t || document.createElement("canvas"), e.getContext("2d") } catch (a) { var i = navigator.appVersion.match(/MSIE (\d\.\d)/), r = -1 != navigator.userAgent.toLowerCase().indexOf("opera"); return !i || i[1] < 6 || r ? !1 : !0 } return !0 }, Dygraph.parseFloat_ = function (t, e, a) { var i = parseFloat(t); if (!isNaN(i)) return i; if (/^ *$/.test(t)) return null; if (/^ *nan *$/i.test(t)) return 0 / 0; var r = "Unable to parse '" + t + "' as a number"; return void 0 !== a && void 0 !== e && (r += " on line " + (1 + (e || 0)) + " ('" + a + "') of CSV."), console.error(r), null }
}(), function () { "use strict"; Dygraph.GVizChart = function (t) { this.container = t }, Dygraph.GVizChart.prototype.draw = function (t, e) { this.container.innerHTML = "", "undefined" != typeof this.date_graph && this.date_graph.destroy(), this.date_graph = new Dygraph(this.container, t, e) }, Dygraph.GVizChart.prototype.setSelection = function (t) { var e = !1; t.length && (e = t[0].row), this.date_graph.setSelection(e) }, Dygraph.GVizChart.prototype.getSelection = function () { var t = [], e = this.date_graph.getSelection(); if (0 > e) return t; for (var a = this.date_graph.layout_.points, i = 0; i < a.length; ++i) t.push({ row: e, column: i + 1 }); return t } }(), function () { "use strict"; var t = 100; Dygraph.Interaction = {}, Dygraph.Interaction.maybeTreatMouseOpAsClick = function (t, e, a) { a.dragEndX = Dygraph.dragGetX_(t, a), a.dragEndY = Dygraph.dragGetY_(t, a); var i = Math.abs(a.dragEndX - a.dragStartX), r = Math.abs(a.dragEndY - a.dragStartY); 2 > i && 2 > r && void 0 !== e.lastx_ && -1 != e.lastx_ && Dygraph.Interaction.treatMouseOpAsClick(e, t, a), a.regionWidth = i, a.regionHeight = r }, Dygraph.Interaction.startPan = function (t, e, a) { var i, r; a.isPanning = !0; var n = e.xAxisRange(); if (e.getOptionForAxis("logscale", "x") ? (a.initialLeftmostDate = Dygraph.log10(n[0]), a.dateRange = Dygraph.log10(n[1]) - Dygraph.log10(n[0])) : (a.initialLeftmostDate = n[0], a.dateRange = n[1] - n[0]), a.xUnitsPerPixel = a.dateRange / (e.plotter_.area.w - 1), e.getNumericOption("panEdgeFraction")) { var o = e.width_ * e.getNumericOption("panEdgeFraction"), s = e.xAxisExtremes(), l = e.toDomXCoord(s[0]) - o, h = e.toDomXCoord(s[1]) + o, p = e.toDataXCoord(l), g = e.toDataXCoord(h); a.boundedDates = [p, g]; var d = [], u = e.height_ * e.getNumericOption("panEdgeFraction"); for (i = 0; i < e.axes_.length; i++) { r = e.axes_[i]; var c = r.extremeRange, y = e.toDomYCoord(c[0], i) + u, _ = e.toDomYCoord(c[1], i) - u, v = e.toDataYCoord(y, i), f = e.toDataYCoord(_, i); d[i] = [v, f] } a.boundedValues = d } for (a.is2DPan = !1, a.axes = [], i = 0; i < e.axes_.length; i++) { r = e.axes_[i]; var x = {}, m = e.yAxisRange(i), D = e.attributes_.getForAxis("logscale", i); D ? (x.initialTopValue = Dygraph.log10(m[1]), x.dragValueRange = Dygraph.log10(m[1]) - Dygraph.log10(m[0])) : (x.initialTopValue = m[1], x.dragValueRange = m[1] - m[0]), x.unitsPerPixel = x.dragValueRange / (e.plotter_.area.h - 1), a.axes.push(x), (r.valueWindow || r.valueRange) && (a.is2DPan = !0) } }, Dygraph.Interaction.movePan = function (t, e, a) { a.dragEndX = Dygraph.dragGetX_(t, a), a.dragEndY = Dygraph.dragGetY_(t, a); var i = a.initialLeftmostDate - (a.dragEndX - a.dragStartX) * a.xUnitsPerPixel; a.boundedDates && (i = Math.max(i, a.boundedDates[0])); var r = i + a.dateRange; if (a.boundedDates && r > a.boundedDates[1] && (i -= r - a.boundedDates[1], r = i + a.dateRange), e.dateWindow_ = e.getOptionForAxis("logscale", "x") ? [Math.pow(Dygraph.LOG_SCALE, i), Math.pow(Dygraph.LOG_SCALE, r)] : [i, r], a.is2DPan) for (var n = a.dragEndY - a.dragStartY, o = 0; o < e.axes_.length; o++) { var s = e.axes_[o], l = a.axes[o], h = n * l.unitsPerPixel, p = a.boundedValues ? a.boundedValues[o] : null, g = l.initialTopValue + h; p && (g = Math.min(g, p[1])); var d = g - l.dragValueRange; p && d < p[0] && (g -= d - p[0], d = g - l.dragValueRange), s.valueWindow = e.attributes_.getForAxis("logscale", o) ? [Math.pow(Dygraph.LOG_SCALE, d), Math.pow(Dygraph.LOG_SCALE, g)] : [d, g] } e.drawGraph_(!1) }, Dygraph.Interaction.endPan = Dygraph.Interaction.maybeTreatMouseOpAsClick, Dygraph.Interaction.startZoom = function (t, e, a) { a.isZooming = !0, a.zoomMoved = !1 }, Dygraph.Interaction.moveZoom = function (t, e, a) { a.zoomMoved = !0, a.dragEndX = Dygraph.dragGetX_(t, a), a.dragEndY = Dygraph.dragGetY_(t, a); var i = Math.abs(a.dragStartX - a.dragEndX), r = Math.abs(a.dragStartY - a.dragEndY); a.dragDirection = r / 2 > i ? Dygraph.VERTICAL : Dygraph.HORIZONTAL, e.drawZoomRect_(a.dragDirection, a.dragStartX, a.dragEndX, a.dragStartY, a.dragEndY, a.prevDragDirection, a.prevEndX, a.prevEndY), a.prevEndX = a.dragEndX, a.prevEndY = a.dragEndY, a.prevDragDirection = a.dragDirection }, Dygraph.Interaction.treatMouseOpAsClick = function (t, e, a) { for (var i = t.getFunctionOption("clickCallback"), r = t.getFunctionOption("pointClickCallback"), n = null, o = -1, s = Number.MAX_VALUE, l = 0; l < t.selPoints_.length; l++) { var h = t.selPoints_[l], p = Math.pow(h.canvasx - a.dragEndX, 2) + Math.pow(h.canvasy - a.dragEndY, 2); !isNaN(p) && (-1 == o || s > p) && (s = p, o = l) } var g = t.getNumericOption("highlightCircleSize") + 2; if (g * g >= s && (n = t.selPoints_[o]), n) { var d = { cancelable: !0, point: n, canvasx: a.dragEndX, canvasy: a.dragEndY }, u = t.cascadeEvents_("pointClick", d); if (u) return; r && r.call(t, e, n) } var d = { cancelable: !0, xval: t.lastx_, pts: t.selPoints_, canvasx: a.dragEndX, canvasy: a.dragEndY }; t.cascadeEvents_("click", d) || i && i.call(t, e, t.lastx_, t.selPoints_) }, Dygraph.Interaction.endZoom = function (t, e, a) { e.clearZoomRect_(), a.isZooming = !1, Dygraph.Interaction.maybeTreatMouseOpAsClick(t, e, a); var i = e.getArea(); if (a.regionWidth >= 10 && a.dragDirection == Dygraph.HORIZONTAL) { var r = Math.min(a.dragStartX, a.dragEndX), n = Math.max(a.dragStartX, a.dragEndX); r = Math.max(r, i.x), n = Math.min(n, i.x + i.w), n > r && e.doZoomX_(r, n), a.cancelNextDblclick = !0 } else if (a.regionHeight >= 10 && a.dragDirection == Dygraph.VERTICAL) { var o = Math.min(a.dragStartY, a.dragEndY), s = Math.max(a.dragStartY, a.dragEndY); o = Math.max(o, i.y), s = Math.min(s, i.y + i.h), s > o && e.doZoomY_(o, s), a.cancelNextDblclick = !0 } a.dragStartX = null, a.dragStartY = null }, Dygraph.Interaction.startTouch = function (t, e, a) { t.preventDefault(), t.touches.length > 1 && (a.startTimeForDoubleTapMs = null); for (var i = [], r = 0; r < t.touches.length; r++) { var n = t.touches[r]; i.push({ pageX: n.pageX, pageY: n.pageY, dataX: e.toDataXCoord(n.pageX), dataY: e.toDataYCoord(n.pageY) }) } if (a.initialTouches = i, 1 == i.length) a.initialPinchCenter = i[0], a.touchDirections = { x: !0, y: !0 }; else if (i.length >= 2) { a.initialPinchCenter = { pageX: .5 * (i[0].pageX + i[1].pageX), pageY: .5 * (i[0].pageY + i[1].pageY), dataX: .5 * (i[0].dataX + i[1].dataX), dataY: .5 * (i[0].dataY + i[1].dataY) }; var o = 180 / Math.PI * Math.atan2(a.initialPinchCenter.pageY - i[0].pageY, i[0].pageX - a.initialPinchCenter.pageX); o = Math.abs(o), o > 90 && (o = 90 - o), a.touchDirections = { x: 67.5 > o, y: o > 22.5 } } a.initialRange = { x: e.xAxisRange(), y: e.yAxisRange() } }, Dygraph.Interaction.moveTouch = function (t, e, a) { a.startTimeForDoubleTapMs = null; var i, r = []; for (i = 0; i < t.touches.length; i++) { var n = t.touches[i]; r.push({ pageX: n.pageX, pageY: n.pageY }) } var o, s = a.initialTouches, l = a.initialPinchCenter; o = 1 == r.length ? r[0] : { pageX: .5 * (r[0].pageX + r[1].pageX), pageY: .5 * (r[0].pageY + r[1].pageY) }; var h = { pageX: o.pageX - l.pageX, pageY: o.pageY - l.pageY }, p = a.initialRange.x[1] - a.initialRange.x[0], g = a.initialRange.y[0] - a.initialRange.y[1]; h.dataX = h.pageX / e.plotter_.area.w * p, h.dataY = h.pageY / e.plotter_.area.h * g; var d, u; if (1 == r.length) d = 1, u = 1; else if (r.length >= 2) { var c = s[1].pageX - l.pageX; d = (r[1].pageX - o.pageX) / c; var y = s[1].pageY - l.pageY; u = (r[1].pageY - o.pageY) / y } d = Math.min(8, Math.max(.125, d)), u = Math.min(8, Math.max(.125, u)); var _ = !1; if (a.touchDirections.x && (e.dateWindow_ = [l.dataX - h.dataX + (a.initialRange.x[0] - l.dataX) / d, l.dataX - h.dataX + (a.initialRange.x[1] - l.dataX) / d], _ = !0), a.touchDirections.y) for (i = 0; 1 > i; i++) { var v = e.axes_[i], f = e.attributes_.getForAxis("logscale", i); f || (v.valueWindow = [l.dataY - h.dataY + (a.initialRange.y[0] - l.dataY) / u, l.dataY - h.dataY + (a.initialRange.y[1] - l.dataY) / u], _ = !0) } if (e.drawGraph_(!1), _ && r.length > 1 && e.getFunctionOption("zoomCallback")) { var x = e.xAxisRange(); e.getFunctionOption("zoomCallback").call(e, x[0], x[1], e.yAxisRanges()) } }, Dygraph.Interaction.endTouch = function (t, e, a) { if (0 !== t.touches.length) Dygraph.Interaction.startTouch(t, e, a); else if (1 == t.changedTouches.length) { var i = (new Date).getTime(), r = t.changedTouches[0]; a.startTimeForDoubleTapMs && i - a.startTimeForDoubleTapMs < 500 && a.doubleTapX && Math.abs(a.doubleTapX - r.screenX) < 50 && a.doubleTapY && Math.abs(a.doubleTapY - r.screenY) < 50 ? e.resetZoom() : (a.startTimeForDoubleTapMs = i, a.doubleTapX = r.screenX, a.doubleTapY = r.screenY) } }; var e = function (t, e, a) { return e > t ? e - t : t > a ? t - a : 0 }, a = function (t, a) { var i = Dygraph.findPos(a.canvas_), r = { left: i.x, right: i.x + a.canvas_.offsetWidth, top: i.y, bottom: i.y + a.canvas_.offsetHeight }, n = { x: Dygraph.pageX(t), y: Dygraph.pageY(t) }, o = e(n.x, r.left, r.right), s = e(n.y, r.top, r.bottom); return Math.max(o, s) }; Dygraph.Interaction.defaultModel = { mousedown: function (e, i, r) { if (!e.button || 2 != e.button) { r.initializeMouseDown(e, i, r), e.altKey || e.shiftKey ? Dygraph.startPan(e, i, r) : Dygraph.startZoom(e, i, r); var n = function (e) { if (r.isZooming) { var n = a(e, i); t > n ? Dygraph.moveZoom(e, i, r) : null !== r.dragEndX && (r.dragEndX = null, r.dragEndY = null, i.clearZoomRect_()) } else r.isPanning && Dygraph.movePan(e, i, r) }, o = function (t) { r.isZooming ? null !== r.dragEndX ? Dygraph.endZoom(t, i, r) : Dygraph.Interaction.maybeTreatMouseOpAsClick(t, i, r) : r.isPanning && Dygraph.endPan(t, i, r), Dygraph.removeEvent(document, "mousemove", n), Dygraph.removeEvent(document, "mouseup", o), r.destroy() }; i.addAndTrackEvent(document, "mousemove", n), i.addAndTrackEvent(document, "mouseup", o) } }, willDestroyContextMyself: !0, touchstart: function (t, e, a) { Dygraph.Interaction.startTouch(t, e, a) }, touchmove: function (t, e, a) { Dygraph.Interaction.moveTouch(t, e, a) }, touchend: function (t, e, a) { Dygraph.Interaction.endTouch(t, e, a) }, dblclick: function (t, e, a) { if (a.cancelNextDblclick) return void (a.cancelNextDblclick = !1); var i = { canvasx: a.dragEndX, canvasy: a.dragEndY }; e.cascadeEvents_("dblclick", i) || t.altKey || t.shiftKey || e.resetZoom() } }, Dygraph.DEFAULT_ATTRS.interactionModel = Dygraph.Interaction.defaultModel, Dygraph.defaultInteractionModel = Dygraph.Interaction.defaultModel, Dygraph.endZoom = Dygraph.Interaction.endZoom, Dygraph.moveZoom = Dygraph.Interaction.moveZoom, Dygraph.startZoom = Dygraph.Interaction.startZoom, Dygraph.endPan = Dygraph.Interaction.endPan, Dygraph.movePan = Dygraph.Interaction.movePan, Dygraph.startPan = Dygraph.Interaction.startPan, Dygraph.Interaction.nonInteractiveModel_ = { mousedown: function (t, e, a) { a.initializeMouseDown(t, e, a) }, mouseup: Dygraph.Interaction.maybeTreatMouseOpAsClick }, Dygraph.Interaction.dragIsPanInteractionModel = { mousedown: function (t, e, a) { a.initializeMouseDown(t, e, a), Dygraph.startPan(t, e, a) }, mousemove: function (t, e, a) { a.isPanning && Dygraph.movePan(t, e, a) }, mouseup: function (t, e, a) { a.isPanning && Dygraph.endPan(t, e, a) } } }(), function () { "use strict"; Dygraph.TickList = void 0, Dygraph.Ticker = void 0, Dygraph.numericLinearTicks = function (t, e, a, i, r, n) { var o = function (t) { return "logscale" === t ? !1 : i(t) }; return Dygraph.numericTicks(t, e, a, o, r, n) }, Dygraph.numericTicks = function (t, e, a, i, r, n) { var o, s, l, h, p = i("pixelsPerLabel"), g = []; if (n) for (o = 0; o < n.length; o++) g.push({ v: n[o] }); else { if (i("logscale")) { h = Math.floor(a / p); var d = Dygraph.binarySearch(t, Dygraph.PREFERRED_LOG_TICK_VALUES, 1), u = Dygraph.binarySearch(e, Dygraph.PREFERRED_LOG_TICK_VALUES, -1); -1 == d && (d = 0), -1 == u && (u = Dygraph.PREFERRED_LOG_TICK_VALUES.length - 1); var c = null; if (u - d >= h / 4) { for (var y = u; y >= d; y--) { var _ = Dygraph.PREFERRED_LOG_TICK_VALUES[y], v = Math.log(_ / t) / Math.log(e / t) * a, f = { v: _ }; null === c ? c = { tickValue: _, pixel_coord: v } : Math.abs(v - c.pixel_coord) >= p ? c = { tickValue: _, pixel_coord: v } : f.label = "", g.push(f) } g.reverse() } } if (0 === g.length) { var x, m, D = i("labelsKMG2"); D ? (x = [1, 2, 4, 8, 16, 32, 64, 128, 256], m = 16) : (x = [1, 2, 5, 10, 20, 50, 100], m = 10); var A, w, b, T, E = Math.ceil(a / p), C = Math.abs(e - t) / E, L = Math.floor(Math.log(C) / Math.log(m)), P = Math.pow(m, L); for (s = 0; s < x.length && (A = P * x[s], w = Math.floor(t / A) * A, b = Math.ceil(e / A) * A, h = Math.abs(b - w) / A, T = a / h, !(T > p)) ; s++); for (w > b && (A *= -1), o = 0; h >= o; o++) l = w + o * A, g.push({ v: l }) } } var S = i("axisLabelFormatter"); for (o = 0; o < g.length; o++) void 0 === g[o].label && (g[o].label = S(g[o].v, 0, i, r)); return g }, Dygraph.dateTicker = function (t, e, a, i, r) { var n = Dygraph.pickDateTickGranularity(t, e, a, i); return n >= 0 ? Dygraph.getDateAxis(t, e, n, i, r) : [] }, Dygraph.SECONDLY = 0, Dygraph.TWO_SECONDLY = 1, Dygraph.FIVE_SECONDLY = 2, Dygraph.TEN_SECONDLY = 3, Dygraph.THIRTY_SECONDLY = 4, Dygraph.MINUTELY = 5, Dygraph.TWO_MINUTELY = 6, Dygraph.FIVE_MINUTELY = 7, Dygraph.TEN_MINUTELY = 8, Dygraph.THIRTY_MINUTELY = 9, Dygraph.HOURLY = 10, Dygraph.TWO_HOURLY = 11, Dygraph.SIX_HOURLY = 12, Dygraph.DAILY = 13, Dygraph.TWO_DAILY = 14, Dygraph.WEEKLY = 15, Dygraph.MONTHLY = 16, Dygraph.QUARTERLY = 17, Dygraph.BIANNUAL = 18, Dygraph.ANNUAL = 19, Dygraph.DECADAL = 20, Dygraph.CENTENNIAL = 21, Dygraph.NUM_GRANULARITIES = 22, Dygraph.DATEFIELD_Y = 0, Dygraph.DATEFIELD_M = 1, Dygraph.DATEFIELD_D = 2, Dygraph.DATEFIELD_HH = 3, Dygraph.DATEFIELD_MM = 4, Dygraph.DATEFIELD_SS = 5, Dygraph.DATEFIELD_MS = 6, Dygraph.NUM_DATEFIELDS = 7, Dygraph.TICK_PLACEMENT = [], Dygraph.TICK_PLACEMENT[Dygraph.SECONDLY] = { datefield: Dygraph.DATEFIELD_SS, step: 1, spacing: 1e3 }, Dygraph.TICK_PLACEMENT[Dygraph.TWO_SECONDLY] = { datefield: Dygraph.DATEFIELD_SS, step: 2, spacing: 2e3 }, Dygraph.TICK_PLACEMENT[Dygraph.FIVE_SECONDLY] = { datefield: Dygraph.DATEFIELD_SS, step: 5, spacing: 5e3 }, Dygraph.TICK_PLACEMENT[Dygraph.TEN_SECONDLY] = { datefield: Dygraph.DATEFIELD_SS, step: 10, spacing: 1e4 }, Dygraph.TICK_PLACEMENT[Dygraph.THIRTY_SECONDLY] = { datefield: Dygraph.DATEFIELD_SS, step: 30, spacing: 3e4 }, Dygraph.TICK_PLACEMENT[Dygraph.MINUTELY] = { datefield: Dygraph.DATEFIELD_MM, step: 1, spacing: 6e4 }, Dygraph.TICK_PLACEMENT[Dygraph.TWO_MINUTELY] = { datefield: Dygraph.DATEFIELD_MM, step: 2, spacing: 12e4 }, Dygraph.TICK_PLACEMENT[Dygraph.FIVE_MINUTELY] = { datefield: Dygraph.DATEFIELD_MM, step: 5, spacing: 3e5 }, Dygraph.TICK_PLACEMENT[Dygraph.TEN_MINUTELY] = { datefield: Dygraph.DATEFIELD_MM, step: 10, spacing: 6e5 }, Dygraph.TICK_PLACEMENT[Dygraph.THIRTY_MINUTELY] = { datefield: Dygraph.DATEFIELD_MM, step: 30, spacing: 18e5 }, Dygraph.TICK_PLACEMENT[Dygraph.HOURLY] = { datefield: Dygraph.DATEFIELD_HH, step: 1, spacing: 36e5 }, Dygraph.TICK_PLACEMENT[Dygraph.TWO_HOURLY] = { datefield: Dygraph.DATEFIELD_HH, step: 2, spacing: 72e5 }, Dygraph.TICK_PLACEMENT[Dygraph.SIX_HOURLY] = { datefield: Dygraph.DATEFIELD_HH, step: 6, spacing: 216e5 }, Dygraph.TICK_PLACEMENT[Dygraph.DAILY] = { datefield: Dygraph.DATEFIELD_D, step: 1, spacing: 864e5 }, Dygraph.TICK_PLACEMENT[Dygraph.TWO_DAILY] = { datefield: Dygraph.DATEFIELD_D, step: 2, spacing: 1728e5 }, Dygraph.TICK_PLACEMENT[Dygraph.WEEKLY] = { datefield: Dygraph.DATEFIELD_D, step: 7, spacing: 6048e5 }, Dygraph.TICK_PLACEMENT[Dygraph.MONTHLY] = { datefield: Dygraph.DATEFIELD_M, step: 1, spacing: 2629817280 }, Dygraph.TICK_PLACEMENT[Dygraph.QUARTERLY] = { datefield: Dygraph.DATEFIELD_M, step: 3, spacing: 216e5 * 365.2524 }, Dygraph.TICK_PLACEMENT[Dygraph.BIANNUAL] = { datefield: Dygraph.DATEFIELD_M, step: 6, spacing: 432e5 * 365.2524 }, Dygraph.TICK_PLACEMENT[Dygraph.ANNUAL] = { datefield: Dygraph.DATEFIELD_Y, step: 1, spacing: 864e5 * 365.2524 }, Dygraph.TICK_PLACEMENT[Dygraph.DECADAL] = { datefield: Dygraph.DATEFIELD_Y, step: 10, spacing: 315578073600 }, Dygraph.TICK_PLACEMENT[Dygraph.CENTENNIAL] = { datefield: Dygraph.DATEFIELD_Y, step: 100, spacing: 3155780736e3 }, Dygraph.PREFERRED_LOG_TICK_VALUES = function () { for (var t = [], e = -39; 39 >= e; e++) for (var a = Math.pow(10, e), i = 1; 9 >= i; i++) { var r = a * i; t.push(r) } return t }(), Dygraph.pickDateTickGranularity = function (t, e, a, i) { for (var r = i("pixelsPerLabel"), n = 0; n < Dygraph.NUM_GRANULARITIES; n++) { var o = Dygraph.numDateTicks(t, e, n); if (a / o >= r) return n } return -1 }, Dygraph.numDateTicks = function (t, e, a) { var i = Dygraph.TICK_PLACEMENT[a].spacing; return Math.round(1 * (e - t) / i) }, Dygraph.getDateAxis = function (t, e, a, i, r) { var n = i("axisLabelFormatter"), o = i("labelsUTC"), s = o ? Dygraph.DateAccessorsUTC : Dygraph.DateAccessorsLocal, l = Dygraph.TICK_PLACEMENT[a].datefield, h = Dygraph.TICK_PLACEMENT[a].step, p = Dygraph.TICK_PLACEMENT[a].spacing, g = new Date(t), d = []; d[Dygraph.DATEFIELD_Y] = s.getFullYear(g), d[Dygraph.DATEFIELD_M] = s.getMonth(g), d[Dygraph.DATEFIELD_D] = s.getDate(g), d[Dygraph.DATEFIELD_HH] = s.getHours(g), d[Dygraph.DATEFIELD_MM] = s.getMinutes(g), d[Dygraph.DATEFIELD_SS] = s.getSeconds(g), d[Dygraph.DATEFIELD_MS] = s.getMilliseconds(g); var u = d[l] % h; a == Dygraph.WEEKLY && (u = s.getDay(g)), d[l] -= u; for (var c = l + 1; c < Dygraph.NUM_DATEFIELDS; c++) d[c] = c === Dygraph.DATEFIELD_D ? 1 : 0; var y = [], _ = s.makeDate.apply(null, d), v = _.getTime(); if (a <= Dygraph.HOURLY) for (t > v && (v += p, _ = new Date(v)) ; e >= v;) y.push({ v: v, label: n(_, a, i, r) }), v += p, _ = new Date(v); else for (t > v && (d[l] += h, _ = s.makeDate.apply(null, d), v = _.getTime()) ; e >= v;) (a >= Dygraph.DAILY || s.getHours(_) % h === 0) && y.push({ v: v, label: n(_, a, i, r) }), d[l] += h, _ = s.makeDate.apply(null, d), v = _.getTime(); return y }, Dygraph && Dygraph.DEFAULT_ATTRS && Dygraph.DEFAULT_ATTRS.axes && Dygraph.DEFAULT_ATTRS.axes.x && Dygraph.DEFAULT_ATTRS.axes.y && Dygraph.DEFAULT_ATTRS.axes.y2 && (Dygraph.DEFAULT_ATTRS.axes.x.ticker = Dygraph.dateTicker, Dygraph.DEFAULT_ATTRS.axes.y.ticker = Dygraph.numericTicks, Dygraph.DEFAULT_ATTRS.axes.y2.ticker = Dygraph.numericTicks) }(), Dygraph.Plugins = {}, Dygraph.Plugins.Annotations = function () { "use strict"; var t = function () { this.annotations_ = [] }; return t.prototype.toString = function () { return "Annotations Plugin" }, t.prototype.activate = function () { return { clearChart: this.clearChart, didDrawChart: this.didDrawChart } }, t.prototype.detachLabels = function () { for (var t = 0; t < this.annotations_.length; t++) { var e = this.annotations_[t]; e.parentNode && e.parentNode.removeChild(e), this.annotations_[t] = null } this.annotations_ = [] }, t.prototype.clearChart = function () { this.detachLabels() }, t.prototype.didDrawChart = function (t) { var e = t.dygraph, a = e.layout_.annotated_points; if (a && 0 !== a.length) for (var i = t.canvas.parentNode, r = { position: "absolute", fontSize: e.getOption("axisLabelFontSize") + "px", zIndex: 10, overflow: "hidden" }, n = function (t, a, i) { return function (r) { var n = i.annotation; n.hasOwnProperty(t) ? n[t](n, i, e, r) : e.getOption(a) && e.getOption(a)(n, i, e, r) } }, o = t.dygraph.plotter_.area, s = {}, l = 0; l < a.length; l++) { var h = a[l]; if (!(h.canvasx < o.x || h.canvasx > o.x + o.w || h.canvasy < o.y || h.canvasy > o.y + o.h)) { var p = h.annotation, g = 6; p.hasOwnProperty("tickHeight") && (g = p.tickHeight); var d = document.createElement("div"); for (var u in r) r.hasOwnProperty(u) && (d.style[u] = r[u]); p.hasOwnProperty("icon") || (d.className = "dygraphDefaultAnnotation"), p.hasOwnProperty("cssClass") && (d.className += " " + p.cssClass); var c = p.hasOwnProperty("width") ? p.width : 16, y = p.hasOwnProperty("height") ? p.height : 16; if (p.hasOwnProperty("icon")) { var _ = document.createElement("img"); _.src = p.icon, _.width = c, _.height = y, d.appendChild(_) } else h.annotation.hasOwnProperty("shortText") && d.appendChild(document.createTextNode(h.annotation.shortText)); var v = h.canvasx - c / 2; d.style.left = v + "px"; var f = 0; if (p.attachAtBottom) { var x = o.y + o.h - y - g; s[v] ? x -= s[v] : s[v] = 0, s[v] += g + y, f = x } else f = h.canvasy - y - g; d.style.top = f + "px", d.style.width = c + "px", d.style.height = y + "px", d.title = h.annotation.text, d.style.color = e.colorsMap_[h.name], d.style.borderColor = e.colorsMap_[h.name], p.div = d, e.addAndTrackEvent(d, "click", n("clickHandler", "annotationClickHandler", h, this)), e.addAndTrackEvent(d, "mouseover", n("mouseOverHandler", "annotationMouseOverHandler", h, this)), e.addAndTrackEvent(d, "mouseout", n("mouseOutHandler", "annotationMouseOutHandler", h, this)), e.addAndTrackEvent(d, "dblclick", n("dblClickHandler", "annotationDblClickHandler", h, this)), i.appendChild(d), this.annotations_.push(d); var m = t.drawingContext; if (m.save(), m.strokeStyle = e.colorsMap_[h.name], m.beginPath(), p.attachAtBottom) { var x = f + y; m.moveTo(h.canvasx, x), m.lineTo(h.canvasx, x + g) } else m.moveTo(h.canvasx, h.canvasy), m.lineTo(h.canvasx, h.canvasy - 2 - g); m.closePath(), m.stroke(), m.restore() } } }, t.prototype.destroy = function () { this.detachLabels() }, t }(), Dygraph.Plugins.Axes = function () { "use strict"; var t = function () { this.xlabels_ = [], this.ylabels_ = [] }; return t.prototype.toString = function () { return "Axes Plugin" }, t.prototype.activate = function () { return { layout: this.layout, clearChart: this.clearChart, willDrawChart: this.willDrawChart } }, t.prototype.layout = function (t) { var e = t.dygraph; if (e.getOptionForAxis("drawAxis", "y")) { var a = e.getOptionForAxis("axisLabelWidth", "y") + 2 * e.getOptionForAxis("axisTickSize", "y"); t.reserveSpaceLeft(a) } if (e.getOptionForAxis("drawAxis", "x")) { var i; i = e.getOption("xAxisHeight") ? e.getOption("xAxisHeight") : e.getOptionForAxis("axisLabelFontSize", "x") + 2 * e.getOptionForAxis("axisTickSize", "x"), t.reserveSpaceBottom(i) } if (2 == e.numAxes()) { if (e.getOptionForAxis("drawAxis", "y2")) { var a = e.getOptionForAxis("axisLabelWidth", "y2") + 2 * e.getOptionForAxis("axisTickSize", "y2"); t.reserveSpaceRight(a) } } else e.numAxes() > 2 && e.error("Only two y-axes are supported at this time. (Trying to use " + e.numAxes() + ")") }, t.prototype.detachLabels = function () { function t(t) { for (var e = 0; e < t.length; e++) { var a = t[e]; a.parentNode && a.parentNode.removeChild(a) } } t(this.xlabels_), t(this.ylabels_), this.xlabels_ = [], this.ylabels_ = [] }, t.prototype.clearChart = function () { this.detachLabels() }, t.prototype.willDrawChart = function (t) { function e(t) { return Math.round(t) + .5 } function a(t) { return Math.round(t) - .5 } var i = t.dygraph; if (i.getOptionForAxis("drawAxis", "x") || i.getOptionForAxis("drawAxis", "y") || i.getOptionForAxis("drawAxis", "y2")) { var r, n, o, s, l, h = t.drawingContext, p = t.canvas.parentNode, g = i.width_, d = i.height_, u = function (t) { return { position: "absolute", fontSize: i.getOptionForAxis("axisLabelFontSize", t) + "px", zIndex: 10, color: i.getOptionForAxis("axisLabelColor", t), width: i.getOptionForAxis("axisLabelWidth", t) + "px", lineHeight: "normal", overflow: "hidden" } }, c = { x: u("x"), y: u("y"), y2: u("y2") }, y = function (t, e, a) { var i = document.createElement("div"), r = c["y2" == a ? "y2" : e]; for (var n in r) r.hasOwnProperty(n) && (i.style[n] = r[n]); var o = document.createElement("div"); return o.className = "dygraph-axis-label dygraph-axis-label-" + e + (a ? " dygraph-axis-label-" + a : ""), o.innerHTML = t, i.appendChild(o), i }; h.save(); var _ = i.layout_, v = t.dygraph.plotter_.area, f = function (t) { return function (e) { return i.getOptionForAxis(e, t) } }; if (i.getOptionForAxis("drawAxis", "y")) { if (_.yticks && _.yticks.length > 0) { var x = i.numAxes(), m = [f("y"), f("y2")]; for (l = 0; l < _.yticks.length; l++) { if (s = _.yticks[l], "function" == typeof s) return; n = v.x; var D = 1, A = "y1", w = m[0]; 1 == s[0] && (n = v.x + v.w, D = -1, A = "y2", w = m[1]); var b = w("axisLabelFontSize"); o = v.y + s[1] * v.h, r = y(s[2], "y", 2 == x ? A : null); var T = o - b / 2; 0 > T && (T = 0), T + b + 3 > d ? r.style.bottom = "0" : r.style.top = T + "px", 0 === s[0] ? (r.style.left = v.x - w("axisLabelWidth") - w("axisTickSize") + "px", r.style.textAlign = "right") : 1 == s[0] && (r.style.left = v.x + v.w + w("axisTickSize") + "px", r.style.textAlign = "left"), r.style.width = w("axisLabelWidth") + "px", p.appendChild(r), this.ylabels_.push(r) } var E = this.ylabels_[0], b = i.getOptionForAxis("axisLabelFontSize", "y"), C = parseInt(E.style.top, 10) + b; C > d - b && (E.style.top = parseInt(E.style.top, 10) - b / 2 + "px") } var L; if (i.getOption("drawAxesAtZero")) { var P = i.toPercentXCoord(0); (P > 1 || 0 > P || isNaN(P)) && (P = 0), L = e(v.x + P * v.w) } else L = e(v.x); h.strokeStyle = i.getOptionForAxis("axisLineColor", "y"), h.lineWidth = i.getOptionForAxis("axisLineWidth", "y"), h.beginPath(), h.moveTo(L, a(v.y)), h.lineTo(L, a(v.y + v.h)), h.closePath(), h.stroke(), 2 == i.numAxes() && (h.strokeStyle = i.getOptionForAxis("axisLineColor", "y2"), h.lineWidth = i.getOptionForAxis("axisLineWidth", "y2"), h.beginPath(), h.moveTo(a(v.x + v.w), a(v.y)), h.lineTo(a(v.x + v.w), a(v.y + v.h)), h.closePath(), h.stroke()) } if (i.getOptionForAxis("drawAxis", "x")) { if (_.xticks) { var w = f("x"); for (l = 0; l < _.xticks.length; l++) { s = _.xticks[l], n = v.x + s[0] * v.w, o = v.y + v.h, r = y(s[1], "x"), r.style.textAlign = "center", r.style.top = o + w("axisTickSize") + "px"; var S = n - w("axisLabelWidth") / 2; S + w("axisLabelWidth") > g && (S = g - w("axisLabelWidth"), r.style.textAlign = "right"), 0 > S && (S = 0, r.style.textAlign = "left"), r.style.left = S + "px", r.style.width = w("axisLabelWidth") + "px", p.appendChild(r), this.xlabels_.push(r) } } h.strokeStyle = i.getOptionForAxis("axisLineColor", "x"), h.lineWidth = i.getOptionForAxis("axisLineWidth", "x"), h.beginPath(); var O; if (i.getOption("drawAxesAtZero")) { var P = i.toPercentYCoord(0, 0); (P > 1 || 0 > P) && (P = 1), O = a(v.y + P * v.h) } else O = a(v.y + v.h); h.moveTo(e(v.x), O), h.lineTo(e(v.x + v.w), O), h.closePath(), h.stroke() } h.restore() } }, t }(), Dygraph.Plugins.ChartLabels = function () {
    "use strict";
    var t = function () { this.title_div_ = null, this.xlabel_div_ = null, this.ylabel_div_ = null, this.y2label_div_ = null }; t.prototype.toString = function () { return "ChartLabels Plugin" }, t.prototype.activate = function () { return { layout: this.layout, didDrawChart: this.didDrawChart } }; var e = function (t) { var e = document.createElement("div"); return e.style.position = "absolute", e.style.left = t.x + "px", e.style.top = t.y + "px", e.style.width = t.w + "px", e.style.height = t.h + "px", e }; t.prototype.detachLabels_ = function () { for (var t = [this.title_div_, this.xlabel_div_, this.ylabel_div_, this.y2label_div_], e = 0; e < t.length; e++) { var a = t[e]; a && a.parentNode && a.parentNode.removeChild(a) } this.title_div_ = null, this.xlabel_div_ = null, this.ylabel_div_ = null, this.y2label_div_ = null }; var a = function (t, e, a, i, r) { var n = document.createElement("div"); n.style.position = "absolute", n.style.left = 1 == a ? "0px" : e.x + "px", n.style.top = e.y + "px", n.style.width = e.w + "px", n.style.height = e.h + "px", n.style.fontSize = t.getOption("yLabelWidth") - 2 + "px"; var o = document.createElement("div"); o.style.position = "absolute", o.style.width = e.h + "px", o.style.height = e.w + "px", o.style.top = e.h / 2 - e.w / 2 + "px", o.style.left = e.w / 2 - e.h / 2 + "px", o.style.textAlign = "center"; var s = "rotate(" + (1 == a ? "-" : "") + "90deg)"; o.style.transform = s, o.style.WebkitTransform = s, o.style.MozTransform = s, o.style.OTransform = s, o.style.msTransform = s, "undefined" != typeof document.documentMode && document.documentMode < 9 && (o.style.filter = "progid:DXImageTransform.Microsoft.BasicImage(rotation=" + (1 == a ? "3" : "1") + ")", o.style.left = "0px", o.style.top = "0px"); var l = document.createElement("div"); return l.className = i, l.innerHTML = r, o.appendChild(l), n.appendChild(o), n }; return t.prototype.layout = function (t) { this.detachLabels_(); var i = t.dygraph, r = t.chart_div; if (i.getOption("title")) { var n = t.reserveSpaceTop(i.getOption("titleHeight")); this.title_div_ = e(n), this.title_div_.style.textAlign = "center", this.title_div_.style.fontSize = i.getOption("titleHeight") - 8 + "px", this.title_div_.style.fontWeight = "bold", this.title_div_.style.zIndex = 10; var o = document.createElement("div"); o.className = "dygraph-label dygraph-title", o.innerHTML = i.getOption("title"), this.title_div_.appendChild(o), r.appendChild(this.title_div_) } if (i.getOption("xlabel")) { var s = t.reserveSpaceBottom(i.getOption("xLabelHeight")); this.xlabel_div_ = e(s), this.xlabel_div_.style.textAlign = "center", this.xlabel_div_.style.fontSize = i.getOption("xLabelHeight") - 2 + "px"; var o = document.createElement("div"); o.className = "dygraph-label dygraph-xlabel", o.innerHTML = i.getOption("xlabel"), this.xlabel_div_.appendChild(o), r.appendChild(this.xlabel_div_) } if (i.getOption("ylabel")) { var l = t.reserveSpaceLeft(0); this.ylabel_div_ = a(i, l, 1, "dygraph-label dygraph-ylabel", i.getOption("ylabel")), r.appendChild(this.ylabel_div_) } if (i.getOption("y2label") && 2 == i.numAxes()) { var h = t.reserveSpaceRight(0); this.y2label_div_ = a(i, h, 2, "dygraph-label dygraph-y2label", i.getOption("y2label")), r.appendChild(this.y2label_div_) } }, t.prototype.didDrawChart = function (t) { var e = t.dygraph; this.title_div_ && (this.title_div_.children[0].innerHTML = e.getOption("title")), this.xlabel_div_ && (this.xlabel_div_.children[0].innerHTML = e.getOption("xlabel")), this.ylabel_div_ && (this.ylabel_div_.children[0].children[0].innerHTML = e.getOption("ylabel")), this.y2label_div_ && (this.y2label_div_.children[0].children[0].innerHTML = e.getOption("y2label")) }, t.prototype.clearChart = function () { }, t.prototype.destroy = function () { this.detachLabels_() }, t
}(), Dygraph.Plugins.Grid = function () { "use strict"; var t = function () { }; return t.prototype.toString = function () { return "Gridline Plugin" }, t.prototype.activate = function () { return { willDrawChart: this.willDrawChart } }, t.prototype.willDrawChart = function (t) { function e(t) { return Math.round(t) + .5 } function a(t) { return Math.round(t) - .5 } var i, r, n, o, s = t.dygraph, l = t.drawingContext, h = s.layout_, p = t.dygraph.plotter_.area; if (s.getOptionForAxis("drawGrid", "y")) { for (var g = ["y", "y2"], d = [], u = [], c = [], y = [], _ = [], n = 0; n < g.length; n++) c[n] = s.getOptionForAxis("drawGrid", g[n]), c[n] && (d[n] = s.getOptionForAxis("gridLineColor", g[n]), u[n] = s.getOptionForAxis("gridLineWidth", g[n]), _[n] = s.getOptionForAxis("gridLinePattern", g[n]), y[n] = _[n] && _[n].length >= 2); for (o = h.yticks, l.save(), n = 0; n < o.length; n++) { var v = o[n][0]; c[v] && (y[v] && l.installPattern(_[v]), l.strokeStyle = d[v], l.lineWidth = u[v], i = e(p.x), r = a(p.y + o[n][1] * p.h), l.beginPath(), l.moveTo(i, r), l.lineTo(i + p.w, r), l.closePath(), l.stroke(), y[v] && l.uninstallPattern()) } l.restore() } if (s.getOptionForAxis("drawGrid", "x")) { o = h.xticks, l.save(); var _ = s.getOptionForAxis("gridLinePattern", "x"), y = _ && _.length >= 2; for (y && l.installPattern(_), l.strokeStyle = s.getOptionForAxis("gridLineColor", "x"), l.lineWidth = s.getOptionForAxis("gridLineWidth", "x"), n = 0; n < o.length; n++) i = e(p.x + o[n][0] * p.w), r = a(p.y + p.h), l.beginPath(), l.moveTo(i, r), l.lineTo(i, p.y), l.closePath(), l.stroke(); y && l.uninstallPattern(), l.restore() } }, t.prototype.destroy = function () { }, t }(), Dygraph.Plugins.Legend = function () { "use strict"; var t = function () { this.legend_div_ = null, this.is_generated_div_ = !1 }; t.prototype.toString = function () { return "Legend Plugin" }; var e; t.prototype.activate = function (t) { var e, a = t.getOption("labelsDivWidth"), i = t.getOption("labelsDiv"); if (i && null !== i) e = "string" == typeof i || i instanceof String ? document.getElementById(i) : i; else { var r = { position: "absolute", fontSize: "14px", zIndex: 10, width: a + "px", top: "0px", left: t.size().width - a - 2 + "px", background: "white", lineHeight: "normal", textAlign: "left", overflow: "hidden" }; Dygraph.update(r, t.getOption("labelsDivStyles")), e = document.createElement("div"), e.className = "dygraph-legend"; for (var n in r) if (r.hasOwnProperty(n)) try { e.style[n] = r[n] } catch (o) { console.warn("You are using unsupported css properties for your browser in labelsDivStyles") } t.graphDiv.appendChild(e), this.is_generated_div_ = !0 } return this.legend_div_ = e, this.one_em_width_ = 10, { select: this.select, deselect: this.deselect, predraw: this.predraw, didDrawChart: this.didDrawChart } }; var a = function (t) { var e = document.createElement("span"); e.setAttribute("style", "margin: 0; padding: 0 0 0 1em; border: 0;"), t.appendChild(e); var a = e.offsetWidth; return t.removeChild(e), a }, i = function (t) { return t.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;") }; return t.prototype.select = function (e) { var a = e.selectedX, i = e.selectedPoints, r = e.dygraph.getOption("legend"); if ("never" === r) return void (this.legend_div_.style.display = "none"); if ("follow" === r) { var n = e.dygraph.plotter_.area, o = e.dygraph.getOption("labelsDivWidth"), s = e.dygraph.getOptionForAxis("axisLabelWidth", "y"), l = i[0].x * n.w + 20, h = i[0].y * n.h - 20; l + o + 1 > window.scrollX + window.innerWidth && (l = l - 40 - o - (s - n.x)), e.dygraph.graphDiv.appendChild(this.legend_div_), this.legend_div_.style.left = s + l + "px", this.legend_div_.style.top = h + "px" } var p = t.generateLegendHTML(e.dygraph, a, i, this.one_em_width_); this.legend_div_.innerHTML = p, this.legend_div_.style.display = "" }, t.prototype.deselect = function (e) { var i = e.dygraph.getOption("legend"); "always" !== i && (this.legend_div_.style.display = "none"); var r = a(this.legend_div_); this.one_em_width_ = r; var n = t.generateLegendHTML(e.dygraph, void 0, void 0, r); this.legend_div_.innerHTML = n }, t.prototype.didDrawChart = function (t) { this.deselect(t) }, t.prototype.predraw = function (t) { if (this.is_generated_div_) { t.dygraph.graphDiv.appendChild(this.legend_div_); var e = t.dygraph.plotter_.area, a = t.dygraph.getOption("labelsDivWidth"); this.legend_div_.style.left = e.x + e.w - a - 1 + "px", this.legend_div_.style.top = e.y + "px", this.legend_div_.style.width = a + "px" } }, t.prototype.destroy = function () { this.legend_div_ = null }, t.generateLegendHTML = function (t, a, r, n) { if (t.getOption("showLabelsOnHighlight") !== !0) return ""; var o, s, l, h, p, g = t.getLabels(); if ("undefined" == typeof a) { if ("always" != t.getOption("legend")) return ""; for (s = t.getOption("labelsSeparateLines"), o = "", l = 1; l < g.length; l++) { var d = t.getPropertiesForSeries(g[l]); d.visible && ("" !== o && (o += s ? "<br/>" : " "), p = t.getOption("strokePattern", g[l]), h = e(p, d.color, n), o += "<span style='font-weight: bold; color: " + d.color + ";'>" + h + " " + i(g[l]) + "</span>") } return o } var u = t.optionsViewForAxis_("x"), c = u("valueFormatter"); o = c(a, u, g[0], t), "" !== o && (o += ":"); var y = [], _ = t.numAxes(); for (l = 0; _ > l; l++) y[l] = t.optionsViewForAxis_("y" + (l ? 1 + l : "")); var v = t.getOption("labelsShowZeroValues"); s = t.getOption("labelsSeparateLines"); var f = t.getHighlightSeries(); for (l = 0; l < r.length; l++) { var x = r[l]; if ((0 !== x.yval || v) && Dygraph.isOK(x.canvasy)) { s && (o += "<br/>"); var d = t.getPropertiesForSeries(x.name), m = y[d.axis - 1], D = m("valueFormatter"), A = D(x.yval, m, x.name, t), w = x.name == f ? " class='highlight'" : ""; o += "<span" + w + "> <b><span style='color: " + d.color + ";'>" + i(x.name) + "</span></b>:&#160;" + A + "</span>" } } return o }, e = function (t, e, a) { var i = /MSIE/.test(navigator.userAgent) && !window.opera; if (i) return "&mdash;"; if (!t || t.length <= 1) return '<div style="display: inline-block; position: relative; bottom: .5ex; padding-left: 1em; height: 1px; border-bottom: 2px solid ' + e + ';"></div>'; var r, n, o, s, l, h = 0, p = 0, g = []; for (r = 0; r <= t.length; r++) h += t[r % t.length]; if (l = Math.floor(a / (h - t[0])), l > 1) { for (r = 0; r < t.length; r++) g[r] = t[r] / a; p = g.length } else { for (l = 1, r = 0; r < t.length; r++) g[r] = t[r] / h; p = g.length + 1 } var d = ""; for (n = 0; l > n; n++) for (r = 0; p > r; r += 2) o = g[r % g.length], s = r < t.length ? g[(r + 1) % g.length] : 0, d += '<div style="display: inline-block; position: relative; bottom: .5ex; margin-right: ' + s + "em; padding-left: " + o + "em; height: 1px; border-bottom: 2px solid " + e + ';"></div>'; return d }, t }(), Dygraph.Plugins.RangeSelector = function () { "use strict"; var t = function () { this.isIE_ = /MSIE/.test(navigator.userAgent) && !window.opera, this.hasTouchInterface_ = "undefined" != typeof TouchEvent, this.isMobileDevice_ = /mobile|android/gi.test(navigator.appVersion), this.interfaceCreated_ = !1 }; return t.prototype.toString = function () { return "RangeSelector Plugin" }, t.prototype.activate = function (t) { return this.dygraph_ = t, this.isUsingExcanvas_ = t.isUsingExcanvas_, this.getOption_("showRangeSelector") && this.createInterface_(), { layout: this.reserveSpace_, predraw: this.renderStaticLayer_, didDrawChart: this.renderInteractiveLayer_ } }, t.prototype.destroy = function () { this.bgcanvas_ = null, this.fgcanvas_ = null, this.leftZoomHandle_ = null, this.rightZoomHandle_ = null, this.iePanOverlay_ = null }, t.prototype.getOption_ = function (t, e) { return this.dygraph_.getOption(t, e) }, t.prototype.setDefaultOption_ = function (t, e) { this.dygraph_.attrs_[t] = e }, t.prototype.createInterface_ = function () { this.createCanvases_(), this.isUsingExcanvas_ && this.createIEPanOverlay_(), this.createZoomHandles_(), this.initInteraction_(), this.getOption_("animatedZooms") && (console.warn("Animated zooms and range selector are not compatible; disabling animatedZooms."), this.dygraph_.updateOptions({ animatedZooms: !1 }, !0)), this.interfaceCreated_ = !0, this.addToGraph_() }, t.prototype.addToGraph_ = function () { var t = this.graphDiv_ = this.dygraph_.graphDiv; t.appendChild(this.bgcanvas_), t.appendChild(this.fgcanvas_), t.appendChild(this.leftZoomHandle_), t.appendChild(this.rightZoomHandle_) }, t.prototype.removeFromGraph_ = function () { var t = this.graphDiv_; t.removeChild(this.bgcanvas_), t.removeChild(this.fgcanvas_), t.removeChild(this.leftZoomHandle_), t.removeChild(this.rightZoomHandle_), this.graphDiv_ = null }, t.prototype.reserveSpace_ = function (t) { this.getOption_("showRangeSelector") && t.reserveSpaceBottom(this.getOption_("rangeSelectorHeight") + 4) }, t.prototype.renderStaticLayer_ = function () { this.updateVisibility_() && (this.resize_(), this.drawStaticLayer_()) }, t.prototype.renderInteractiveLayer_ = function () { this.updateVisibility_() && !this.isChangingRange_ && (this.placeZoomHandles_(), this.drawInteractiveLayer_()) }, t.prototype.updateVisibility_ = function () { var t = this.getOption_("showRangeSelector"); if (t) this.interfaceCreated_ ? this.graphDiv_ && this.graphDiv_.parentNode || this.addToGraph_() : this.createInterface_(); else if (this.graphDiv_) { this.removeFromGraph_(); var e = this.dygraph_; setTimeout(function () { e.width_ = 0, e.resize() }, 1) } return t }, t.prototype.resize_ = function () { function t(t, e, a) { var i = Dygraph.getContextPixelRatio(e); t.style.top = a.y + "px", t.style.left = a.x + "px", t.width = a.w * i, t.height = a.h * i, t.style.width = a.w + "px", t.style.height = a.h + "px", 1 != i && e.scale(i, i) } var e = this.dygraph_.layout_.getPlotArea(), a = 0; this.dygraph_.getOptionForAxis("drawAxis", "x") && (a = this.getOption_("xAxisHeight") || this.getOption_("axisLabelFontSize") + 2 * this.getOption_("axisTickSize")), this.canvasRect_ = { x: e.x, y: e.y + e.h + a + 4, w: e.w, h: this.getOption_("rangeSelectorHeight") }, t(this.bgcanvas_, this.bgcanvas_ctx_, this.canvasRect_), t(this.fgcanvas_, this.fgcanvas_ctx_, this.canvasRect_) }, t.prototype.createCanvases_ = function () { this.bgcanvas_ = Dygraph.createCanvas(), this.bgcanvas_.className = "dygraph-rangesel-bgcanvas", this.bgcanvas_.style.position = "absolute", this.bgcanvas_.style.zIndex = 9, this.bgcanvas_ctx_ = Dygraph.getContext(this.bgcanvas_), this.fgcanvas_ = Dygraph.createCanvas(), this.fgcanvas_.className = "dygraph-rangesel-fgcanvas", this.fgcanvas_.style.position = "absolute", this.fgcanvas_.style.zIndex = 9, this.fgcanvas_.style.cursor = "default", this.fgcanvas_ctx_ = Dygraph.getContext(this.fgcanvas_) }, t.prototype.createIEPanOverlay_ = function () { this.iePanOverlay_ = document.createElement("div"), this.iePanOverlay_.style.position = "absolute", this.iePanOverlay_.style.backgroundColor = "white", this.iePanOverlay_.style.filter = "alpha(opacity=0)", this.iePanOverlay_.style.display = "none", this.iePanOverlay_.style.cursor = "move", this.fgcanvas_.appendChild(this.iePanOverlay_) }, t.prototype.createZoomHandles_ = function () { var t = new Image; t.className = "dygraph-rangesel-zoomhandle", t.style.position = "absolute", t.style.zIndex = 10, t.style.visibility = "hidden", t.style.cursor = "col-resize", /MSIE 7/.test(navigator.userAgent) ? (t.width = 7, t.height = 14, t.style.backgroundColor = "white", t.style.border = "1px solid #333333") : (t.width = 9, t.height = 16, t.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAkAAAAQCAYAAADESFVDAAAAAXNSR0IArs4c6QAAAAZiS0dEANAAzwDP4Z7KegAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9sHGw0cMqdt1UwAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAAaElEQVQoz+3SsRFAQBCF4Z9WJM8KCDVwownl6YXsTmCUsyKGkZzcl7zkz3YLkypgAnreFmDEpHkIwVOMfpdi9CEEN2nGpFdwD03yEqDtOgCaun7sqSTDH32I1pQA2Pb9sZecAxc5r3IAb21d6878xsAAAAAASUVORK5CYII="), this.isMobileDevice_ && (t.width *= 2, t.height *= 2), this.leftZoomHandle_ = t, this.rightZoomHandle_ = t.cloneNode(!1) }, t.prototype.initInteraction_ = function () { var t, e, a, i, r, n, o, s, l, h, p, g, d, u, c = this, y = document, _ = 0, v = null, f = !1, x = !1, m = !this.isMobileDevice_ && !this.isUsingExcanvas_, D = new Dygraph.IFrameTarp; t = function (t) { var e = c.dygraph_.xAxisExtremes(), a = (e[1] - e[0]) / c.canvasRect_.w, i = e[0] + (t.leftHandlePos - c.canvasRect_.x) * a, r = e[0] + (t.rightHandlePos - c.canvasRect_.x) * a; return [i, r] }, e = function (t) { return Dygraph.cancelEvent(t), f = !0, _ = t.clientX, v = t.target ? t.target : t.srcElement, ("mousedown" === t.type || "dragstart" === t.type) && (Dygraph.addEvent(y, "mousemove", a), Dygraph.addEvent(y, "mouseup", i)), c.fgcanvas_.style.cursor = "col-resize", D.cover(), !0 }, a = function (t) { if (!f) return !1; Dygraph.cancelEvent(t); var e = t.clientX - _; if (Math.abs(e) < 4) return !0; _ = t.clientX; var a, i = c.getZoomHandleStatus_(); v == c.leftZoomHandle_ ? (a = i.leftHandlePos + e, a = Math.min(a, i.rightHandlePos - v.width - 3), a = Math.max(a, c.canvasRect_.x)) : (a = i.rightHandlePos + e, a = Math.min(a, c.canvasRect_.x + c.canvasRect_.w), a = Math.max(a, i.leftHandlePos + v.width + 3)); var n = v.width / 2; return v.style.left = a - n + "px", c.drawInteractiveLayer_(), m && r(), !0 }, i = function () { return f ? (f = !1, D.uncover(), Dygraph.removeEvent(y, "mousemove", a), Dygraph.removeEvent(y, "mouseup", i), c.fgcanvas_.style.cursor = "default", m || r(), !0) : !1 }, r = function () { try { var e = c.getZoomHandleStatus_(); if (c.isChangingRange_ = !0, e.isZoomed) { var a = t(e); c.dygraph_.doZoomXDates_(a[0], a[1]) } else c.dygraph_.resetZoom() } finally { c.isChangingRange_ = !1 } }, n = function (t) { if (c.isUsingExcanvas_) return t.srcElement == c.iePanOverlay_; var e = c.leftZoomHandle_.getBoundingClientRect(), a = e.left + e.width / 2; e = c.rightZoomHandle_.getBoundingClientRect(); var i = e.left + e.width / 2; return t.clientX > a && t.clientX < i }, o = function (t) { return !x && n(t) && c.getZoomHandleStatus_().isZoomed ? (Dygraph.cancelEvent(t), x = !0, _ = t.clientX, "mousedown" === t.type && (Dygraph.addEvent(y, "mousemove", s), Dygraph.addEvent(y, "mouseup", l)), !0) : !1 }, s = function (t) { if (!x) return !1; Dygraph.cancelEvent(t); var e = t.clientX - _; if (Math.abs(e) < 4) return !0; _ = t.clientX; var a = c.getZoomHandleStatus_(), i = a.leftHandlePos, r = a.rightHandlePos, n = r - i; i + e <= c.canvasRect_.x ? (i = c.canvasRect_.x, r = i + n) : r + e >= c.canvasRect_.x + c.canvasRect_.w ? (r = c.canvasRect_.x + c.canvasRect_.w, i = r - n) : (i += e, r += e); var o = c.leftZoomHandle_.width / 2; return c.leftZoomHandle_.style.left = i - o + "px", c.rightZoomHandle_.style.left = r - o + "px", c.drawInteractiveLayer_(), m && h(), !0 }, l = function () { return x ? (x = !1, Dygraph.removeEvent(y, "mousemove", s), Dygraph.removeEvent(y, "mouseup", l), m || h(), !0) : !1 }, h = function () { try { c.isChangingRange_ = !0, c.dygraph_.dateWindow_ = t(c.getZoomHandleStatus_()), c.dygraph_.drawGraph_(!1) } finally { c.isChangingRange_ = !1 } }, p = function (t) { if (!f && !x) { var e = n(t) ? "move" : "default"; e != c.fgcanvas_.style.cursor && (c.fgcanvas_.style.cursor = e) } }, g = function (t) { "touchstart" == t.type && 1 == t.targetTouches.length ? e(t.targetTouches[0]) && Dygraph.cancelEvent(t) : "touchmove" == t.type && 1 == t.targetTouches.length ? a(t.targetTouches[0]) && Dygraph.cancelEvent(t) : i(t) }, d = function (t) { "touchstart" == t.type && 1 == t.targetTouches.length ? o(t.targetTouches[0]) && Dygraph.cancelEvent(t) : "touchmove" == t.type && 1 == t.targetTouches.length ? s(t.targetTouches[0]) && Dygraph.cancelEvent(t) : l(t) }, u = function (t, e) { for (var a = ["touchstart", "touchend", "touchmove", "touchcancel"], i = 0; i < a.length; i++) c.dygraph_.addAndTrackEvent(t, a[i], e) }, this.setDefaultOption_("interactionModel", Dygraph.Interaction.dragIsPanInteractionModel), this.setDefaultOption_("panEdgeFraction", 1e-4); var A = window.opera ? "mousedown" : "dragstart"; this.dygraph_.addAndTrackEvent(this.leftZoomHandle_, A, e), this.dygraph_.addAndTrackEvent(this.rightZoomHandle_, A, e), this.isUsingExcanvas_ ? this.dygraph_.addAndTrackEvent(this.iePanOverlay_, "mousedown", o) : (this.dygraph_.addAndTrackEvent(this.fgcanvas_, "mousedown", o), this.dygraph_.addAndTrackEvent(this.fgcanvas_, "mousemove", p)), this.hasTouchInterface_ && (u(this.leftZoomHandle_, g), u(this.rightZoomHandle_, g), u(this.fgcanvas_, d)) }, t.prototype.drawStaticLayer_ = function () { var t = this.bgcanvas_ctx_; t.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h); try { this.drawMiniPlot_() } catch (e) { console.warn(e) } var a = .5; this.bgcanvas_ctx_.lineWidth = 1, t.strokeStyle = "gray", t.beginPath(), t.moveTo(a, a), t.lineTo(a, this.canvasRect_.h - a), t.lineTo(this.canvasRect_.w - a, this.canvasRect_.h - a), t.lineTo(this.canvasRect_.w - a, a), t.stroke() }, t.prototype.drawMiniPlot_ = function () { var t = this.getOption_("rangeSelectorPlotFillColor"), e = this.getOption_("rangeSelectorPlotStrokeColor"); if (t || e) { var a = this.getOption_("stepPlot"), i = this.computeCombinedSeriesAndLimits_(), r = i.yMax - i.yMin, n = this.bgcanvas_ctx_, o = .5, s = this.dygraph_.xAxisExtremes(), l = Math.max(s[1] - s[0], 1e-30), h = (this.canvasRect_.w - o) / l, p = (this.canvasRect_.h - o) / r, g = this.canvasRect_.w - o, d = this.canvasRect_.h - o, u = null, c = null; n.beginPath(), n.moveTo(o, d); for (var y = 0; y < i.data.length; y++) { var _ = i.data[y], v = null !== _[0] ? (_[0] - s[0]) * h : 0 / 0, f = null !== _[1] ? d - (_[1] - i.yMin) * p : 0 / 0; (a || null === u || Math.round(v) != Math.round(u)) && (isFinite(v) && isFinite(f) ? (null === u ? n.lineTo(v, d) : a && n.lineTo(v, c), n.lineTo(v, f), u = v, c = f) : (null !== u && (a ? (n.lineTo(v, c), n.lineTo(v, d)) : n.lineTo(u, d)), u = c = null)) } if (n.lineTo(g, d), n.closePath(), t) { var x = this.bgcanvas_ctx_.createLinearGradient(0, 0, 0, d); x.addColorStop(0, "white"), x.addColorStop(1, t), this.bgcanvas_ctx_.fillStyle = x, n.fill() } e && (this.bgcanvas_ctx_.strokeStyle = e, this.bgcanvas_ctx_.lineWidth = 1.5, n.stroke()) } }, t.prototype.computeCombinedSeriesAndLimits_ = function () { var t, e = this.dygraph_, a = this.getOption_("logscale"), i = e.numColumns(), r = e.getLabels(), n = new Array(i), o = !1; for (t = 1; i > t; t++) { var s = this.getOption_("showInRangeSelector", r[t]); n[t] = s, null !== s && (o = !0) } if (!o) for (t = 0; t < n.length; t++) n[t] = !0; var l = [], h = e.dataHandler_, p = e.attributes_; for (t = 1; t < e.numColumns() ; t++) if (n[t]) { var g = h.extractSeries(e.rawData_, t, p); e.rollPeriod() > 1 && (g = h.rollingAverage(g, e.rollPeriod(), p)), l.push(g) } var d = []; for (t = 0; t < l[0].length; t++) { for (var u = 0, c = 0, y = 0; y < l.length; y++) { var _ = l[y][t][1]; null === _ || isNaN(_) || (c++, u += _) } d.push([l[0][t][0], u / c]) } var v = Number.MAX_VALUE, f = -Number.MAX_VALUE; for (t = 0; t < d.length; t++) { var x = d[t][1]; null !== x && isFinite(x) && (!a || x > 0) && (v = Math.min(v, x), f = Math.max(f, x)) } var m = .25; if (a) for (f = Dygraph.log10(f), f += f * m, v = Dygraph.log10(v), t = 0; t < d.length; t++) d[t][1] = Dygraph.log10(d[t][1]); else { var D, A = f - v; D = A <= Number.MIN_VALUE ? f * m : A * m, f += D, v -= D } return { data: d, yMin: v, yMax: f } }, t.prototype.placeZoomHandles_ = function () { var t = this.dygraph_.xAxisExtremes(), e = this.dygraph_.xAxisRange(), a = t[1] - t[0], i = Math.max(0, (e[0] - t[0]) / a), r = Math.max(0, (t[1] - e[1]) / a), n = this.canvasRect_.x + this.canvasRect_.w * i, o = this.canvasRect_.x + this.canvasRect_.w * (1 - r), s = Math.max(this.canvasRect_.y, this.canvasRect_.y + (this.canvasRect_.h - this.leftZoomHandle_.height) / 2), l = this.leftZoomHandle_.width / 2; this.leftZoomHandle_.style.left = n - l + "px", this.leftZoomHandle_.style.top = s + "px", this.rightZoomHandle_.style.left = o - l + "px", this.rightZoomHandle_.style.top = this.leftZoomHandle_.style.top, this.leftZoomHandle_.style.visibility = "visible", this.rightZoomHandle_.style.visibility = "visible" }, t.prototype.drawInteractiveLayer_ = function () { var t = this.fgcanvas_ctx_; t.clearRect(0, 0, this.canvasRect_.w, this.canvasRect_.h); var e = 1, a = this.canvasRect_.w - e, i = this.canvasRect_.h - e, r = this.getZoomHandleStatus_(); if (t.strokeStyle = "black", r.isZoomed) { var n = Math.max(e, r.leftHandlePos - this.canvasRect_.x), o = Math.min(a, r.rightHandlePos - this.canvasRect_.x); t.fillStyle = "rgba(240, 240, 240, 0.6)", t.fillRect(0, 0, n, this.canvasRect_.h), t.fillRect(o, 0, this.canvasRect_.w - o, this.canvasRect_.h), t.beginPath(), t.moveTo(e, e), t.lineTo(n, e), t.lineTo(n, i), t.lineTo(o, i), t.lineTo(o, e), t.lineTo(a, e), t.stroke(), this.isUsingExcanvas_ && (this.iePanOverlay_.style.width = o - n + "px", this.iePanOverlay_.style.left = n + "px", this.iePanOverlay_.style.height = i + "px", this.iePanOverlay_.style.display = "inline") } else t.beginPath(), t.moveTo(e, e), t.lineTo(e, i), t.lineTo(a, i), t.lineTo(a, e), t.stroke(), this.iePanOverlay_ && (this.iePanOverlay_.style.display = "none") }, t.prototype.getZoomHandleStatus_ = function () { var t = this.leftZoomHandle_.width / 2, e = parseFloat(this.leftZoomHandle_.style.left) + t, a = parseFloat(this.rightZoomHandle_.style.left) + t; return { leftHandlePos: e, rightHandlePos: a, isZoomed: e - 1 > this.canvasRect_.x || a + 1 < this.canvasRect_.x + this.canvasRect_.w } }, t }(), Dygraph.PLUGINS.push(Dygraph.Plugins.Legend, Dygraph.Plugins.Axes, Dygraph.Plugins.RangeSelector, Dygraph.Plugins.ChartLabels, Dygraph.Plugins.Annotations, Dygraph.Plugins.Grid), Dygraph.DataHandler = function () { }, Dygraph.DataHandlers = {}, function () { "use strict"; var t = Dygraph.DataHandler; t.X = 0, t.Y = 1, t.EXTRAS = 2, t.prototype.extractSeries = function () { }, t.prototype.seriesToPoints = function (e, a, i) { for (var r = [], n = 0; n < e.length; ++n) { var o = e[n], s = o[1], l = null === s ? null : t.parseFloat(s), h = { x: 0 / 0, y: 0 / 0, xval: t.parseFloat(o[0]), yval: l, name: a, idx: n + i }; r.push(h) } return this.onPointsCreated_(e, r), r }, t.prototype.onPointsCreated_ = function () { }, t.prototype.rollingAverage = function () { }, t.prototype.getExtremeYValues = function () { }, t.prototype.onLineEvaluated = function () { }, t.prototype.computeYInterpolation_ = function (t, e, a) { var i = e[1] - t[1], r = e[0] - t[0], n = i / r, o = (a - t[0]) * n; return t[1] + o }, t.prototype.getIndexesInWindow_ = function (t, e) { var a = 0, i = t.length - 1; if (e) { for (var r = 0, n = e[0], o = e[1]; r < t.length - 1 && t[r][0] < n;) a++, r++; for (r = t.length - 1; r > 0 && t[r][0] > o;) i--, r-- } return i >= a ? [a, i] : [0, t.length - 1] }, t.parseFloat = function (t) { return null === t ? 0 / 0 : t } }(), function () { "use strict"; Dygraph.DataHandlers.DefaultHandler = function () { }; var t = Dygraph.DataHandlers.DefaultHandler; t.prototype = new Dygraph.DataHandler, t.prototype.extractSeries = function (t, e, a) { for (var i = [], r = a.get("logscale"), n = 0; n < t.length; n++) { var o = t[n][0], s = t[n][e]; r && 0 >= s && (s = null), i.push([o, s]) } return i }, t.prototype.rollingAverage = function (t, e) { e = Math.min(e, t.length); var a, i, r, n, o, s = []; if (1 == e) return t; for (a = 0; a < t.length; a++) { for (n = 0, o = 0, i = Math.max(0, a - e + 1) ; a + 1 > i; i++) r = t[i][1], null === r || isNaN(r) || (o++, n += t[i][1]); s[a] = o ? [t[a][0], n / o] : [t[a][0], null] } return s }, t.prototype.getExtremeYValues = function (t) { for (var e, a = null, i = null, r = 0, n = t.length - 1, o = r; n >= o; o++) e = t[o][1], null === e || isNaN(e) || ((null === i || e > i) && (i = e), (null === a || a > e) && (a = e)); return [a, i] } }(), function () { "use strict"; Dygraph.DataHandlers.DefaultFractionHandler = function () { }; var t = Dygraph.DataHandlers.DefaultFractionHandler; t.prototype = new Dygraph.DataHandlers.DefaultHandler, t.prototype.extractSeries = function (t, e, a) { for (var i, r, n, o, s, l, h = [], p = 100, g = a.get("logscale"), d = 0; d < t.length; d++) i = t[d][0], n = t[d][e], g && null !== n && (n[0] <= 0 || n[1] <= 0) && (n = null), null !== n ? (o = n[0], s = n[1], null === o || isNaN(o) ? h.push([i, o, [o, s]]) : (l = s ? o / s : 0, r = p * l, h.push([i, r, [o, s]]))) : h.push([i, null, [null, null]]); return h }, t.prototype.rollingAverage = function (t, e) { e = Math.min(e, t.length); var a, i = [], r = 0, n = 0, o = 100; for (a = 0; a < t.length; a++) { r += t[a][2][0], n += t[a][2][1], a - e >= 0 && (r -= t[a - e][2][0], n -= t[a - e][2][1]); var s = t[a][0], l = n ? r / n : 0; i[a] = [s, o * l] } return i } }(), function () { "use strict"; Dygraph.DataHandlers.BarsHandler = function () { Dygraph.DataHandler.call(this) }, Dygraph.DataHandlers.BarsHandler.prototype = new Dygraph.DataHandler; var t = Dygraph.DataHandlers.BarsHandler; t.prototype.extractSeries = function () { }, t.prototype.rollingAverage = function () { }, t.prototype.onPointsCreated_ = function (t, e) { for (var a = 0; a < t.length; ++a) { var i = t[a], r = e[a]; r.y_top = 0 / 0, r.y_bottom = 0 / 0, r.yval_minus = Dygraph.DataHandler.parseFloat(i[2][0]), r.yval_plus = Dygraph.DataHandler.parseFloat(i[2][1]) } }, t.prototype.getExtremeYValues = function (t) { for (var e, a = null, i = null, r = 0, n = t.length - 1, o = r; n >= o; o++) if (e = t[o][1], null !== e && !isNaN(e)) { var s = t[o][2][0], l = t[o][2][1]; s > e && (s = e), e > l && (l = e), (null === i || l > i) && (i = l), (null === a || a > s) && (a = s) } return [a, i] }, t.prototype.onLineEvaluated = function (t, e, a) { for (var i, r = 0; r < t.length; r++) i = t[r], i.y_top = DygraphLayout.calcYNormal_(e, i.yval_minus, a), i.y_bottom = DygraphLayout.calcYNormal_(e, i.yval_plus, a) } }(), function () { "use strict"; Dygraph.DataHandlers.CustomBarsHandler = function () { }; var t = Dygraph.DataHandlers.CustomBarsHandler; t.prototype = new Dygraph.DataHandlers.BarsHandler, t.prototype.extractSeries = function (t, e, a) { for (var i, r, n, o = [], s = a.get("logscale"), l = 0; l < t.length; l++) i = t[l][0], n = t[l][e], s && null !== n && (n[0] <= 0 || n[1] <= 0 || n[2] <= 0) && (n = null), null !== n ? (r = n[1], o.push(null === r || isNaN(r) ? [i, r, [r, r]] : [i, r, [n[0], n[2]]])) : o.push([i, null, [null, null]]); return o }, t.prototype.rollingAverage = function (t, e) { e = Math.min(e, t.length); var a, i, r, n, o, s, l, h = []; for (i = 0, n = 0, r = 0, o = 0, s = 0; s < t.length; s++) { if (a = t[s][1], l = t[s][2], h[s] = t[s], null === a || isNaN(a) || (i += l[0], n += a, r += l[1], o += 1), s - e >= 0) { var p = t[s - e]; null === p[1] || isNaN(p[1]) || (i -= p[2][0], n -= p[1], r -= p[2][1], o -= 1) } h[s] = o ? [t[s][0], 1 * n / o, [1 * i / o, 1 * r / o]] : [t[s][0], null, [null, null]] } return h } }(), function () { "use strict"; Dygraph.DataHandlers.ErrorBarsHandler = function () { }; var t = Dygraph.DataHandlers.ErrorBarsHandler; t.prototype = new Dygraph.DataHandlers.BarsHandler, t.prototype.extractSeries = function (t, e, a) { for (var i, r, n, o, s = [], l = a.get("sigma"), h = a.get("logscale"), p = 0; p < t.length; p++) i = t[p][0], o = t[p][e], h && null !== o && (o[0] <= 0 || o[0] - l * o[1] <= 0) && (o = null), null !== o ? (r = o[0], null === r || isNaN(r) ? s.push([i, r, [r, r, r]]) : (n = l * o[1], s.push([i, r, [r - n, r + n, o[1]]]))) : s.push([i, null, [null, null, null]]); return s }, t.prototype.rollingAverage = function (t, e, a) { e = Math.min(e, t.length); var i, r, n, o, s, l, h, p, g, d = [], u = a.get("sigma"); for (i = 0; i < t.length; i++) { for (s = 0, p = 0, l = 0, r = Math.max(0, i - e + 1) ; i + 1 > r; r++) n = t[r][1], null === n || isNaN(n) || (l++, s += n, p += Math.pow(t[r][2][2], 2)); l ? (h = Math.sqrt(p) / l, g = s / l, d[i] = [t[i][0], g, [g - u * h, g + u * h]]) : (o = 1 == e ? t[i][1] : null, d[i] = [t[i][0], o, [o, o]]) } return d } }(), function () { "use strict"; Dygraph.DataHandlers.FractionsBarsHandler = function () { }; var t = Dygraph.DataHandlers.FractionsBarsHandler; t.prototype = new Dygraph.DataHandlers.BarsHandler, t.prototype.extractSeries = function (t, e, a) { for (var i, r, n, o, s, l, h, p, g = [], d = 100, u = a.get("sigma"), c = a.get("logscale"), y = 0; y < t.length; y++) i = t[y][0], n = t[y][e], c && null !== n && (n[0] <= 0 || n[1] <= 0) && (n = null), null !== n ? (o = n[0], s = n[1], null === o || isNaN(o) ? g.push([i, o, [o, o, o, s]]) : (l = s ? o / s : 0, h = s ? u * Math.sqrt(l * (1 - l) / s) : 1, p = d * h, r = d * l, g.push([i, r, [r - p, r + p, o, s]]))) : g.push([i, null, [null, null, null, null]]); return g }, t.prototype.rollingAverage = function (t, e, a) { e = Math.min(e, t.length); var i, r, n, o, s = [], l = a.get("sigma"), h = a.get("wilsonInterval"), p = 0, g = 0, d = 100; for (n = 0; n < t.length; n++) { p += t[n][2][2], g += t[n][2][3], n - e >= 0 && (p -= t[n - e][2][2], g -= t[n - e][2][3]); var u = t[n][0], c = g ? p / g : 0; if (h) if (g) { var y = 0 > c ? 0 : c, _ = g, v = l * Math.sqrt(y * (1 - y) / _ + l * l / (4 * _ * _)), f = 1 + l * l / g; i = (y + l * l / (2 * g) - v) / f, r = (y + l * l / (2 * g) + v) / f, s[n] = [u, y * d, [i * d, r * d]] } else s[n] = [u, 0, [0, 0]]; else o = g ? l * Math.sqrt(c * (1 - c) / g) : 1, s[n] = [u, d * c, [d * (c - o), d * (c + o)]] } return s } }();
//# sourceMappingURL=dygraph-combined.js.map;
/**
 * Synchronize zooming and/or selections between a set of dygraphs.
 *
 * Usage:
 *
 *   var g1 = new Dygraph(...),
 *       g2 = new Dygraph(...),
 *       ...;
 *   var sync = Dygraph.synchronize(g1, g2, ...);
 *   // charts are now synchronized
 *   sync.detach();
 *   // charts are no longer synchronized
 *
 * You can set options using the last parameter, for example:
 *
 *   var sync = Dygraph.synchronize(g1, g2, g3, {
 *      selection: true,
 *      zoom: true
 *   });
 *
 * The default is to synchronize both of these.
 *
 * Instead of passing one Dygraph objet as each parameter, you may also pass an
 * array of dygraphs:
 *
 *   var sync = Dygraph.synchronize([g1, g2, g3], {
 *      selection: false,
 *      zoom: true
 *   });
 */
(function () {
    /* global Dygraph:false */
    'use strict';

    Dygraph.synchronize = function (/* dygraphs..., opts */) {
        if (arguments.length === 0) {
            throw 'Invalid invocation of Dygraph.synchronize(). Need >= 1 argument.';
        }

        var OPTIONS = ['selection', 'zoom'];
        var opts = {
            selection: true,
            zoom: true
        };
        var dygraphs = [];

        var parseOpts = function (obj) {
            if (!(obj instanceof Object)) {
                throw 'Last argument must be either Dygraph or Object.';
            } else {
                for (var i = 0; i < OPTIONS.length; i++) {
                    var optName = OPTIONS[i];
                    if (obj.hasOwnProperty(optName)) opts[optName] = obj[optName];
                }
            }
        };

        if (arguments[0] instanceof Dygraph) {
            // Arguments are Dygraph objects.
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] instanceof Dygraph) {
                    dygraphs.push(arguments[i]);
                } else {
                    break;
                }
            }
            if (i < arguments.length - 1) {
                throw 'Invalid invocation of Dygraph.synchronize(). ' +
                      'All but the last argument must be Dygraph objects.';
            } else if (i == arguments.length - 1) {
                parseOpts(arguments[arguments.length - 1]);
            }
        } else if (arguments[0].length) {
            // Invoked w/ list of dygraphs, options
            for (var i = 0; i < arguments[0].length; i++) {
                dygraphs.push(arguments[0][i]);
            }
            if (arguments.length == 2) {
                parseOpts(arguments[1]);
            } else if (arguments.length > 2) {
                throw 'Invalid invocation of Dygraph.synchronize(). ' +
                      'Expected two arguments: array and optional options argument.';
            }  // otherwise arguments.length == 1, which is fine.
        } else {
            throw 'Invalid invocation of Dygraph.synchronize(). ' +
                  'First parameter must be either Dygraph or list of Dygraphs.';
        }

        if (dygraphs.length < 2) {
            throw 'Invalid invocation of Dygraph.synchronize(). ' +
                  'Need two or more dygraphs to synchronize.';
        }

        // Listen for draw, highlight, unhighlight callbacks.
        if (opts.zoom) {
            attachZoomHandlers(dygraphs);
        }

        if (opts.selection) {
            attachSelectionHandlers(dygraphs);
        }

        return {
            detach: function () {
                for (var i = 0; i < dygraphs.length; i++) {
                    var g = dygraphs[i];
                    if (opts.zoom) {
                        g.updateOptions({ drawCallback: null });
                    }
                    if (opts.selection) {
                        g.updateOptions({
                            highlightCallback: null,
                            unhighlightCallback: null
                        });
                    }
                }
                // release references & make subsequent calls throw.
                dygraphs = null;
                opts = null;
            }
        };
    };

    // TODO: call any `drawCallback`s that were set before this.
    function attachZoomHandlers(gs) {
        var block = false;
        for (var i = 0; i < gs.length; i++) {
            var g = gs[i];
            g.updateOptions({
                drawCallback: function (me, initial) {
                    if (block || initial) return;
                    block = true;
                    var range = me.xAxisRange();
                    var yrange = me.yAxisRange();
                    for (var j = 0; j < gs.length; j++) {
                        if (gs[j] == me) continue;
                        gs[j].updateOptions({
                            dateWindow: range,
                            valueRange: yrange
                        });
                    }
                    block = false;
                }
            }, false /* no need to redraw */);
        }
    }

    function attachSelectionHandlers(gs) {
        var block = false;
        for (var i = 0; i < gs.length; i++) {
            var g = gs[i];
            g.updateOptions({
                highlightCallback: function (event, x, points, row, seriesName) {
                    if (block) return;
                    block = true;
                    var me = this;
                    for (var i = 0; i < gs.length; i++) {
                        if (me == gs[i]) continue;
                        var idx = dygraphsBinarySearch(gs[i], x);
                        if (idx !== null) {
                            gs[i].setSelection(idx, seriesName);
                        }
                    }
                    block = false;
                },
                unhighlightCallback: function (event) {
                    if (block) return;
                    block = true;
                    var me = this;
                    for (var i = 0; i < gs.length; i++) {
                        if (me == gs[i]) continue;
                        gs[i].clearSelection();
                    }
                    block = false;
                }
            });
        }
    }

    // Returns the index corresponding to xVal, or null if there is none.
    function dygraphsBinarySearch(g, xVal) {
        var low = 0,
            high = g.numRows() - 1;

        while (low < high) {
            var idx = (high + low) >> 1;
            var x = g.getValue(idx, 0);
            if (x < xVal) {
                low = idx + 1;
            } else if (x > xVal) {
                high = idx - 1;
            } else {
                return idx;
            }
        }

        // TODO: give an option to find the closest point, i.e. not demand an exact match.
        return null;
    }

})();;
(function () {
    amp.plugin('noFullScreen', function (options) {
        var player = this;
        var mediaPlay = player.mediaPlayer;

        player.addEventListener(amp.eventName.loadeddata, function () {
            $(".vjs-fullscreen-control").hide();
        });
    });
}).call(this);;
(function () {
    amp.plugin('cyoa-od', function (options) {
        // remember the video player instance
        var vidPlayer = this;
        var topicid;
        //Initialize current with empty object
        options.options.current = {};

        if (options !== undefined && options.options !== undefined && Object.keys(options.options).length > 1) {
            // dynamically create the html for CYOA
            var vidContainer = $("#" + this.id());
            var $html = '<div id="playerTopics"><div class="cyoa-section" style="display:none;"><div class="cyoa-header"><div class="header-text" title="{header}">{header}</div><div class="countdown"></div><div class="header-timer"><span><hr></span></div ></div><div class="cyoa-topics">{topics}</div></div></div>';
            var $topicTemplate = '<div class="cyoa-topic"><a data-topic="{code}" class="mps_track topic-link" title="{scode}"><img src="https://mediastream.microsoft.com/{src}" alt="{title}"/></a></div>';
            var $topicHtml = "";
            $.each(options.options.topics, function (key, value) {
                console.log(key);
                if ((key !== "config")) {
                    $topicHtml += $topicTemplate.replace("{code}", key).replace("{scode}", value.scode).replace("{src}", value.img).replace("{title}", value.title);
                }
            });
            $html = $html.replace(/\{header\}/g, options.options.header).replace("{topics}", $topicHtml);
            vidContainer.append($html);
            initEvents();

            function initEvents() {
                //Init Events on CYOA Tiles
                $('#playerTopics').on("click", ".topic-link", function () {
                    //selectCYOATile($(this).attr('data-topic'));
                    topicid = $(this).attr('data-topic');
                    $("#playerTopics .topic-link").removeClass("cyoa-select");
                    $(this).addClass("cyoa-select");
                    
                });

                $('#playerTopics').on("keydown", ".topic-link", function (e) {
                    if (e.which === 13) {
                        //selectCYOATile($(this).attr('data-topic'));
                        topicid = $(this).attr('data-topic');
                        $("#playerTopics .topic-link").removeClass("cyoa-select");
                        $(this).addClass("cyoa-select");
                    }
                });
            }

            // hook the timeupdate to get the current playback time
            vidPlayer.addEventListener("timeupdate", function () {
                var videoPosition = vidPlayer.currentTime();
                var $timer = $("#playerTopics").find(".header-timer");
                var $countdown = $("#playerTopics").find(".countdown");

                if (videoPosition >= options.options.timeStart && videoPosition <= options.options.timeEnd) {
                    if (!options.options.isDisplayed) {
                        options.options.isDisplayed = true;
                        showKeyPoint('.cyoa-section');
                    }

                    var progress = parseInt(((videoPosition - options.options.timeStart) / (options.options.timeEnd - options.options.timeStart)) * 100);
                    if (progress > 100) {
                        progress = 100;
                        if (topicid && topicid.length > 0 && !IsDefaultTopic()) {
                            vidPlayer.pause();
                            selectCYOATile(topicid);
                        }
                    }
                    var countdown = parseInt(options.options.timeEnd - videoPosition) + 1;
                    $countdown.text(countdown);
                    $timer.find('hr').width(progress + "%");
                    if (countdown < 1) {
                        if (topicid && topicid.length > 0 && !IsDefaultTopic()) {
                            vidPlayer.pause();
                            selectCYOATile(topicid);
                        }
                    }
                } else {
                    if (options.options.isDisplayed) {
                        hideKeyPoint('.cyoa-section');
                        options.options.isDisplayed = false;
                        if (topicid && topicid.length > 0 && !IsDefaultTopic()) {
                            vidPlayer.pause();
                            selectCYOATile(topicid);
                        }
                    }
                }
            });

        }
        // loadstart is the earliest event we can hook, use it to initialize our plugin
        vidPlayer.addEventListener("loadstart", function () {
            console.log("player is ready!");
        });

        vidPlayer.addEventListener('ended', function () {
            var redirect_url = getUrlParameter('cyoa_redirect');
            if (redirect_url !== undefined && redirect_url !== null && redirect_url.trim() !== "") {
                $(".cyoa-popup").remove();
                options.callback("");
            }
        });

        function IsDefaultTopic() {
            var isDefault = false;
            $.each(options.options.topics, function (key, value) {
                if ((key !== "config") && (topicid && topicid.length > 0)) {
                    if (topicid == key) {
                        isDefault = value.default === "True";
                    }
                }
            });

            return isDefault;
        }

        function getUrlParameter(name) {
            name = name.replace(/[\\[]/g, '\\[').replace(/[\]]/g, '\\]');
            var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
            var results = regex.exec(location.search);
            return results === null ? undefined : decodeURIComponent(results[1].replace(/\+/g, ' '));
        };

        function selectCYOATile(dataTopicIdx) {
            var topic = dataTopicIdx;
            if (options.options.current.selection !== topic) {
                options.options.current.selection = topic;
                options.options.current.currentTime = vidPlayer.currentTime();
                $(".hoveropacity").removeClass("hoveropacity");
                $(this).parent().siblings().find('.topic-link').addClass("hoveropacity");

                if (options.options.current.selection && options.options.current.selection.length > 0) {
                    var streamobj = options.options.topics[options.options.current.selection];
                    if (streamobj.scode) {
                        options.callback(streamobj);
                    }
                    options.options.current.selection = "";
                }

                hideKeyPoint('.cyoa-section');
            }
        }

        function showKeyPoint(identifier) {
            $(identifier).show();
        }

        // hide a keypoint item in the required container
        function hideKeyPoint(identifier) {
            // hide the div
            $(identifier).hide();
        }

    });
}).call(this);

;
(function () {
    amp.plugin('AD', function (opt) {
        var ampPlayer = this;
        var audiotrackTextChange = false;
        ampPlayer.addEventListener('loadeddata', function () {
            var UserPreferedAudio;
            try {
                if (ampPlayer.currentAudioStreamList()) {

                    updateAudioTrackLabels();
                    var ad = getAdValue();

                    var isAD = false;
                    var ele = $('#hdnloggedinuseremail1')[0];
                    var userId = "";
                    if (ele != null && ele.value != null && ele.value != undefined) {
                        userId = ele.value;
                    }

                    if (ad && ad.length > 0) {
                        for (var i = 0; i < ampPlayer.currentAudioStreamList().streams.length; i++) {
                            if (ampPlayer.currentAudioStreamList().streams[i].language.toLowerCase() == ad.toLowerCase()
                                || ampPlayer.currentAudioStreamList().streams[i].name.toLowerCase() == ad.toLowerCase()) {
                                ampPlayer.currentAudioStreamList().switchIndex(i);
                                isAD = true;
                                break;
                            }
                        }
                    }


                    if (isAD == false) {
                        let userPreference = "english";
                        try {
                            userPreference = (window.localStorage.getItem(userId + '_audio') == null ||
                                              window.localStorage.getItem(userId + '_audio') == "undefined" ||
                                              window.localStorage.getItem(userId + '_audio') == undefined) ?
                                              userPreference : window.localStorage.getItem(userId + '_audio');
                        }
                        catch (ex) {

                        }
                        
                        for (var i = 0; i < ampPlayer.currentAudioStreamList().streams.length; i++) {
                            try {
                                let audioName = ampPlayer.currentAudioStreamList().streams[i].title;
                                if (audioName == null || audioName == undefined) {
                                    audioName = ampPlayer.currentAudioStreamList().streams[i].name;
                                }
                                if (audioName.toLowerCase() == userPreference.toLowerCase()) {
                                    UserPreferedAudio = audioName;
                                    ampPlayer.currentAudioStreamList().switchIndex(i);
                                    break;
                                }
                            } catch (e) {
                            }
                        }
                    }

                    var index = ampPlayer.currentAudioStreamList().enabledIndices;

                    if (index >= 0) {
                        try {
                            window.localStorage.setItem(userId + '_audio', UserPreferedAudio);
                        }
                        catch (ex) { }
                    }
                }
            }
            catch (ex) {
                logError("can't select language : " + ex.message);
            }
        });

        ampPlayer.addEventListener('playing', function () {
            try {
                //if (audiotrackTextChange == false) {
                //    updateAudioTrackLabels();
                //}
                $(".amp-audiotracks-control").find(".vjs-menu-item").keyup(function (e) {
                    if (e.keyCode == 13) {
                        userPreferenceSetting();
                    }
                });
                $(".amp-audiotracks-control .vjs-menu-item").bind("click touchend", function () {
                    userPreferenceSetting();
                });
            }
            catch (ex) {
                logError("can't select language : " + ex.message);
            }
        });

        function userPreferenceSetting() {
            var index = ampPlayer.currentAudioStreamList().enabledIndices;
            var ele = $('#hdnloggedinuseremail1')[0];
            var userId = "";
            if (ele != null && ele.value != null && ele.value != undefined) {
                userId = ele.value;
            }
            if (index >= 0) {
                try {
                    var selectedAudioLanguage = ampPlayer.currentAudioStreamList().streams[index].title;
                    if (selectedAudioLanguage == null || selectedAudioLanguage == undefined) {
                        selectedAudioLanguage = ampPlayer.currentAudioStreamList().streams[index].name;
                    }
                    window.localStorage.setItem(userId + '_audio', selectedAudioLanguage);
                }
                catch (ex) {

                }
            }
        }

        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];
        }

        function updateAudioTrackLabels() {
            try {
                if (ampPlayer.currentAudioStreamList() && $(".amp-audiotracks-control").find(".vjs-menu-item").length > 0) {
                    audiotrackTextChange = true;
                    var textHtml = '<span class="vjs-control-text"> </span>';
                    $(".amp-audiotracks-control").find(".vjs-menu-item").each(function () {
                        var $this = $(this);
                        if ($this.attr("aria-label") == "mandarin") {
                            $this.html('中文 (Zhōngwén), 汉语, 漢語' + textHtml);
                        }
                        else if ($this.attr("aria-label") == "multiple languages") {
                            const track = getLocalizedValue('Original');
                            $this.html(track + textHtml);
                        }
                        else if ($this.attr("aria-label") == "audio description") {
                            const track = getLocalizedValue('Audio Description');
                            $this.html(track + textHtml);
                        }
                        else if ($this.attr("aria-label") == "no linguistic content/not applicable") {
                            const track = getLocalizedValue('Audio Description');
                            $this.html(track + textHtml);
                        }
                        else if ($this.attr("aria-label").length > 0) {
                            const track = getLocalizedValue($this.attr("aria-label"));
                            $this.html(track[0].toUpperCase() + track.substring(1) + textHtml);
                        }

                    });
                }
            }
            catch (ex) { }
        }

        function getLocalizedValue(localeKey) {
            var audioLocStrings = {
                "fr": {
                    "arabic": "Arabe",
                    "bulgarian": "Bulgare",
                    "czech": "Tchèque",
                    "danish": "Danoise",
                    "dutch": "Néerlandaise",
                    "english": "Anglaise",
                    "finnish": "Finlandaise",
                    "french": "Français",
                    "german": "Allemande",
                    "greek": "Grecque",
                    "hindi": "Hindi",
                    "hungarian": "Hongroise",
                    "indonesian": "Indonésienne",
                    "italian": "Italienne",
                    "japanese": "Japonaise",
                    "korean": "Coréenne",
                    "norwegian": "Norvégienne",
                    "mandarin": "Mandarine",
                    "polish": "Polonais",
                    "portuguese - brazil": "Portugais - Brésil",
                    "portuguese - portugal": "Portugais - Portugal",
                    "romanian": "Roumaine",
                    "russian": "Russe",
                    "slovak": "Slovaque",
                    "slovene": "Slovène",
                    "spanish": "Espagnole",
                    "swedish": "Suédoise",
                    "thai": "Thaïlandais",
                    "turkish": "Turque",
                    "vietnamese": "Vietnamienne",
                    "audio description": "Description audio",
                    "original": "Originale"
                },
                "de": {
                    "arabic": "Arabisch",
                    "bulgarian": "Bulgarisch",
                    "czech": "Tschechisch",
                    "danish": "Dänisch",
                    "dutch": "Niederländisch",
                    "english": "Englisch",
                    "finnish": "Finnisch",
                    "french": "Französisch",
                    "german": "Deutsch",
                    "greek": "Griechisch",
                    "hindi": "Hindi",
                    "hungarian": "Ungarisch",
                    "indonesian": "Indonesisch",
                    "italian": "Italienisch",
                    "japanese": "Japanisch",
                    "korean": "Koreanisch",
                    "norwegian": "Norwegisch",
                    "mandarin": "Mandarin",
                    "polish": "Polieren",
                    "portuguese - brazil": "Portugiesisch (Brasilien",
                    "portuguese - portugal": "Portugiesisch - Portugal",
                    "romanian": "Rumänisch",
                    "russian": "Russisch",
                    "slovak": "Slowakisch",
                    "slovene": "Slowenisch",
                    "spanish": "Spanisch",
                    "swedish": "Schwedisch",
                    "thai": "Thailändisch",
                    "turkish": "Türkisch",
                    "vietnamese": "Vietnamesisch",
                    "audio description": "Audiobeschreibung",
                    "original": "Original"
                },
                "es": {
                    "arabic": "Arábica",
                    "bulgarian": "Búlgara",
                    "czech": "Checa",
                    "danish": "Danesa",
                    "dutch": "Holandesa",
                    "english": "Inglesa",
                    "finnish": "Finlandesa",
                    "french": "Francés",
                    "german": "Alemana",
                    "greek": "Griega",
                    "hindi": "Hindi",
                    "hungarian": "Húngara",
                    "indonesian": "Indonesia",
                    "italian": "Italiana",
                    "japanese": "Japonesa",
                    "korean": "Coreana",
                    "norwegian": "Noruega",
                    "mandarin": "Mandarín",
                    "polish": "Polaca",
                    "portuguese - brazil": "Portuguesa - Brasil",
                    "portuguese - portugal": "Portuguesa - Portugal",
                    "romanian": "Rumana",
                    "russian": "Rusa",
                    "slovak": "Eslovaca",
                    "slovene": "Eslovena",
                    "spanish": "Española",
                    "swedish": "Sueca",
                    "thai": "Tailandesa",
                    "turkish": "Turca",
                    "vietnamese": "Vietnamita",
                    "audio description": "Descripción de audio",
                    "original": "Original"
                },
                "ja": {
                    "arabic": "アラビア語",
                    "bulgarian": "ブルガリア語",
                    "czech": "チェコ語",
                    "danish": "デンマーク語",
                    "dutch": "オランダの",
                    "english": "英語",
                    "finnish": "フィンランド語",
                    "french": "フランス語",
                    "german": "ドイツ人",
                    "greek": "ギリシャ語",
                    "hindi": "ヒンディー語",
                    "hungarian": "ハンガリー語",
                    "indonesian": "インドネシア語",
                    "italian": "イタリア語",
                    "japanese": "日本",
                    "korean": "韓国語",
                    "norwegian": "ノルウェー語",
                    "mandarin": "官話",
                    "polish": "研磨",
                    "portuguese - brazil": "ポルトガル語-ブラジル",
                    "portuguese - portugal": "ポルトガル語-ポルトガル",
                    "romanian": "ルーマニア語",
                    "russian": "ロシア",
                    "slovak": "スロバキア",
                    "slovene": "スロベニア語",
                    "spanish": "スペイン語",
                    "swedish": "スウェーデンの",
                    "thai": "タイ語",
                    "turkish": "トルコ語",
                    "vietnamese": "ベトナム語",
                    "audio description": "音声説明",
                    "original": "オリジナル"
                },
                "zh": {
                    "arabic": "阿拉伯",
                    "bulgarian": "保加利亚语",
                    "czech": "捷克语",
                    "danish": "丹麦语",
                    "dutch": "荷兰语",
                    "english": "英语",
                    "finnish": "芬兰",
                    "french": "法语",
                    "german": "德语",
                    "greek": "希腊语",
                    "hindi": "印地语",
                    "hungarian": "匈牙利",
                    "indonesian": "印度尼西亚",
                    "italian": "意大利语",
                    "japanese": "日本人",
                    "korean": "韩国人",
                    "norwegian": "挪威",
                    "mandarin": "普通话",
                    "polish": "抛光",
                    "portuguese - brazil": "葡萄牙语 - 巴西",
                    "portuguese - portugal": "葡萄牙语 - 葡萄牙",
                    "romanian": "罗马尼亚语",
                    "russian": "俄语",
                    "slovak": "斯洛伐克语",
                    "slovene": "斯洛文尼亚",
                    "spanish": "西班牙语",
                    "swedish": "瑞典",
                    "thai": "泰国",
                    "turkish": "土耳其",
                    "vietnamese": "越南语",
                    "audio description": "音频描述",
                    "original": "原来的"
                }
            };
            try {
                var loc = CaptionManager.GetLangCodeFromQueryString(getQuerystring("loc"));
                if (audioLocStrings[loc] != null && audioLocStrings[loc] != undefined && audioLocStrings[loc][localeKey.toLowerCase()] != null && audioLocStrings[loc][localeKey.toLowerCase()] != undefined)
                    return audioLocStrings[loc][localeKey.toLowerCase()];
                else
                    return localeKey;
            } catch (ex) {
            }
            return localeKey;
        }

        function getUserCultureAudioLanguage(locKey) {
            var lang = CaptionManager.GetLangCodeFromQueryString(locKey); //If No locKey matches then default langCode will be "en".
            var userCultureLang = '';
            try {
                var userCulAudioLang = {
                    "en": "English",
                    "fr": "French",
                    "de": "German",
                    "es": "Spanish",
                    "ja": "Japanese",
                    "zh": "Mandarin"
                }
                if (null != userCulAudioLang[lang] || userCulAudioLang[lang] != undefined)
                    userCultureLang = userCulAudioLang[lang];

            } catch (ex) {

            }

            return userCultureLang;
        }

        function getAdValue() {
            var ad = getQuerystring("ad");
            var locParam = getQuerystring("loc");

            if (locParam && locParam.length > 0) //First preference will be ?loc param.
                ad = getUserCultureAudioLanguage(locParam); //If No locparam matches then default language will be "English".

            return ad;
        }
    });
}).call(this);;

(function () {
    amp.plugin('VIInsights', function (opt) {
        var myPlayer = this;

        var vidContainer = $("#" + this.id());
        var $html = '<div class="vii-insights-container displayNone">'
            + '<iframe width="580" height="780" src="' + opt.viiUrl + '" frameborder="0" allowfullscreen></iframe></div>';
        
        vidContainer.append($html);

        myPlayer.addEventListener('loadedmetadata', function () {
            this.videobreakdown({
                videoId: opt.videoId,
                accountId: opt.accountId,
                syncTranscript: true,
                syncLanguage: true,
                accessToken: opt.accessTokenVI
            });
            if ($(".amp-controlbaricons-right").find(".vjs-vii-button").length == 0) {
                $(".amp-controlbaricons-right").prepend('<div class="vjs-menu-button vjs-menu-button-popup vjs-control vjs-button outline-enabled-control vjs-vii-button amp-vii-control" tabindex="0" role="region" aria-live="off" aria-haspopup="true"></div>')
                var $divAlshtml = $('<div class="vjs-control-content"><span class="glyphicon glyphicon-flash" style="padding: 6px;font-size: 14px;"></span><span class="vjs-control-text">Show Insights</span></div>');

                $('.vjs-vii-button').html($divAlshtml);
                $(".vjs-vii-button").removeClass("vjs-hidden");
                $('.vjs-vii-button').attr("aria-label", "Show Insights");
                $('.vjs-vii-button').attr("title", "Show Insights");

            }
        });

        function toggleInsights() {
            if ($('.vii-insights-container').hasClass('displayNone')) {
                $('.vii-insights-container').removeClass('displayNone');
                var src = $(".vii-insights-container iframe").attr("src");
                $(".vii-insights-container iframe").attr("src","");
                $(".vii-insights-container iframe").attr("src",src);
            } else {    
                $('.vii-insights-container').addClass('displayNone');
            }
        }

        $(document).on("keyup", ".amp-controlbaricons-right .vjs-menu-button", function (e) {
            if (e.keyCode === 13) {
                if ($(this).hasClass("vjs-vii-button")) {
                    toggleInsights();
                }
            }
            else if (e.keyCode === 9) {
                
            }
            else if (!$(this).hasClass("vjs-vii-button")) {
                
            }

        });
        $(document).on("keydown", ".vjs-vii-button .vjs-menu-item", function (e) {
            if (e.keyCode == 38) { // up
                $(this).prev().focus();
            }
            else if (e.keyCode == 40) { // down
                $(this).next().focus();
            }
            else if (e.keyCode == 13) { // click
                $(this).click();
            }
        });

        $(document).on('keydown', ".amp-vii-control", function (e) {
            if (e.keyCode == 32) { // space
                $(".vjs-vii-button").click();
            }
        });

        $(document).on("click", ".vjs-vii-button", function () {
            toggleInsights();
        });
        $(document).on("touchstart", ".vjs-vii-button .vjs-menu-item", function () {
            $(this).click();
        });

        $(document).on("click", ".vjs-vii-button .vjs-menu-item", function () {
            //Main Click Code
            toggleInsights();
        });

    });
}).call(this);

;
(function () {
    amp.plugin('sessionendnotice', function (options) {
        var videoshortcode = options.videoshortcode;
        var player = this;
        player.addEventListener('ended', function () {
            window.parent.postMessage({ type: "sessionend", data: { sessionCode: videoshortcode } }, "*");
            console.log('Session ' + videoshortcode + ' has been ended');
        });
    });
}).call(this);;
(function () {
    amp.plugin('commoncode', function (options) {
        $(".vjs-control-bar").mouseover(function () {
            $(".vjs-player").attr('title', '');
        });

        $(".vjs-control-bar").mouseleave(function () {
            $(".vjs-player").attr('title', 'Press space key to play/pause the video');
        });
    });
}).call(this);;
/**
 * AMP & Video Breakdown - Communication Plugin
 * Copyright (c) 2016 Microsoft
 * @author Ori Ziv
 * @version v0.8.80
 * @desc Make your amp player listen to .postMessage() events from videobreakdowns iframes
 *       and change the player currentTime() accordingly.
 * @link https://www.videobreakdown.com
 */

(function () {
    'use strict';

    if (!('amp' in window)) {
        throw "Azure Media Player not found!";
    }




    function VIPlugin(options) {
        var playerInstance = this, addedTracks = [], messageListener = null;

        if (options && options.syncTranscript) {
            playerInstance.on("timeupdate", function () {
                // Pass message to other iframe.
                if ('postMessage' in window) {
                    var iframes = window.document.getElementsByTagName('iframe');
                    try {
                        for (var index = 0; index < iframes.length; index++) {
                            iframes[index].contentWindow.postMessage({ currentTime: playerInstance.currentTime(), origin: "https://www.videoindexer.ai" }, "*");
                        }
                    } catch (error) {
                        throw error;
                    }
                }
            });
        }

        // Return VTT file url for a specific breakdown.
        function getSubtitlesUrl(lang) {
            var urlParams = { accessToken: options.accessToken, language: lang };
            var encodedParams = toUrl(urlParams);
            return ("https://www.videoindexer.ai/api/v2/accounts/" + options.accountId + "/videos/" + options.videoId + "/captions/?" + encodedParams);
        }

        // Jump to specific time from mesage payload
        function notifyPlayer(evt) {

            if (!evt) {
                return;
            }
            var origin = evt.origin || evt.originalEvent.origin;

            // Validate that event comes from videobreakdown domain.
            if ((origin === "https://www.videoindexer.ai" || origin === "https://www.videobreakdown.com") && (evt.data.time !== undefined || evt.data.currentTime !== undefined || evt.data.language !== undefined)) {
                if (evt.data.time) {
                    playerInstance.currentTime(evt.data.time);
                }

                if (evt.data.language && options && options.syncLanguage) {
                    if (!options.videoId) {
                        return;
                    }
                    addDynamicVtt(evt.data.language);
                }

                // Confirm arrival to source
                if ('postMessage' in window) {
                    try {
                        evt.source.postMessage({ confirm: true, data: evt.data }, origin);
                    } catch (error) {
                        throw error;
                    }
                }
            }
        }

        function clearMessageEvent() {
            if (window.removeEventListener) {
                window.removeEventListener("message", messageListener, true);
            } else if (window.detachEvent) {
                window.detachEvent("message");
            }
        }

        // Convert url params object to string url
        function toUrl(data) {
            var ret = [];
            for (var d in data) {
                if (data[d]) {
                    ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
                }
            }
            return ret.join('&');
        }



        // Add VB Dynamic VTT based on widget selection.
        function addDynamicVtt(lang) {
            if (!lang) {
                return;
            }

            // If we added it already return.
            if (addedTracks.indexOf(lang) !== -1) {
                return;
            }
            try {
                playerInstance.addRemoteTextTrack(createTrack(lang)).track;
                addedTracks.push(lang);
                if (isCaptionsOn()) {
                    disableAllLanguages();
                    selectCaptions(lang.name);
                } else {
                    disableAllLanguages();
                }
            } catch (e) {
            }
        }

        // Unselect all closed captions tracks
        function disableAllLanguages() {
            for (var i = 0; i < playerInstance.textTracks_.length; i++) {
                if (playerInstance.textTracks_.tracks_[i].mode != "disabled") {
                    playerInstance.textTracks_.tracks_[i].mode = "disabled";
                }
            }
        }

        // Check if some caption is on
        function isCaptionsOn() {
            for (var i = 0; i < playerInstance.textTracks_.length; i++) {
                if (playerInstance.textTracks_.tracks_[i].mode != "disabled") {
                    return true;
                }
            }
            return false;
        }

        // Select specific caption by language.
        function selectCaptions(lang) {
            for (var i = 0; i < playerInstance.textTracks_.length; i++) {
                if (playerInstance.textTracks_.tracks_[i].label == lang) {
                    playerInstance.textTracks_.tracks_[i].mode = "showing";
                    break;
                }
            }
        }

        // Create Vtt Track
        function createTrack(lang) {
            return {
                kind: "captions",
                src: getSubtitlesUrl(lang.key),
                // srclang: "en", 
                label: lang.name
            }
        }

        // Listen to message event
        messageListener = window.addEventListener("message", notifyPlayer, false);

        // Get subtitles
        this.getSubtitlesUrl = getSubtitlesUrl;

        // Clear the event if window unloads
        window.onunload = clearMessageEvent;
    }


    // Register Plugin on AMP
    window.amp.plugin('videobreakdown', VIPlugin);
}).call(this);;
