html(lang='en', xmlns='http://www.w3.org/1999/xhtml', itemscope='itemscope')
    head
        script(type='text/javascript', src='/lib/clappr/0.2.57/dist/clappr.min.js')
        script(type='text/javascript', src='/lib/clappr/level-selector.js')
        script(type='text/javascript', src='/lib/clappr/clappr-chromecast-plugin.js')
        script(type='text/javascript', src='https://smartplugin.youbora.com/v5/javascript/clappr/5.3.1/sp.min.js')

        style.
            body {
                margin: 0 !important;
            }

            #player {
                position: absolute !important;
                width: 100% !important;
                height: 100% !important;
                overflow: hidden;
            }

            #pause-button {
                display: block;
                width: 100%;
                height: 25%;
                margin: 0 auto;
                opacity: 0.75;
                -webkit-transition: opacity 0.1s ease;
                -moz-transition: opacity 0.1s ease;
                transition: opacity 0.1s ease;
            }

            #airplayButtonId {
                fill: white;
                margin-left: -30px;
            }

            #best-practice-text {
                background-color: rgba(0, 0, 0, .60);
                min-height: 100%;
            }

            .best-practice-outer {
                text-align: left;
                padding: 15px !important;
                font-size: 14px !important;
                display: block;
                text-overflow: ellipsis;
                overflow: hidden;
                max-height: 95%;
                display: -webkit-box;
                -webkit-line-clamp: 7;
                -webkit-box-orient: vertical;
            }

            .best-practice-title {
                font-weight: bold !important;
                margin-bottom: 11px !important;
                margin-top: 10px !important;
            }

            ul {
                margin-left: 3% !important;
            }

            #infoButtonId {
                height: '32px';
                width: '32px';
                display: 'block';
                position: "absolute";
                marginTop: "-33px !important";
                marginLeft: "-80px !important";
            }
    body
        block content
            div(id="player")
            script(type="text/javascript").
                var pauseButton = document.createElement('div');
                pauseButton.setAttribute('id', 'pause-button');
                pauseButton.style.display = 'none';
                pauseButton.attribute = 'data-poster';
                pauseButton.className = 'media-control-button media-control-icon paused';
                pauseButton.innerHTML = '<svg class="poster-icon" xmlns="http://www.w3.org/2000/svg" viewBox="-22 -10 60 50" data-poster><path fill="#010101" style="fill:white;" d="M1.712 14.76H6.43V1.24H1.71v13.52zm7.86-13.52v13.52h4.716V1.24H9.573z"></path></svg>';

                var videoId = '#{videoId}';
                var videoTitle = !{JSON.stringify(videoTitle)};
                var videoDuration = '!{videoDuration}';
                var userId = '#{userId}';
                var userName = !{JSON.stringify(userName)};
                var userEmail = '#{userEmail}';
                var MEDIA_TYPE = '!{mediaType}';
                var passcode = '!{passcode}';
                var now = 0;
                var watchedSeconds = [];
                var haveStoredView = false;
                var haveStartedTracking = false;
                var haveSeekedToResumePoint = false;
                var autoplay = true;
                var qualityLabels = '!{qualityLabels}';
                var isOneTimeScreener = '!{isOneTimeScreener}';
                var lastWatchedSecond = #{lastWatchedSecond};
                var source = "#{sourceUrl}";
                var youboraAccount = '!{youboraAccount}';
                var playerLogs = [];
                var playerErrorQueue = [];
                var isSendingError = false;

                (function () {
                    var oldLog = console.log;
                    console.log = function (message) {
                        if (playerLogs.length >= 300) {
                            playerLogs.shift();
                        }
                        playerLogs.push(message);
                        oldLog.apply(console, arguments);
                    };
                }());

                function preload(url) {
                    var request = new XMLHttpRequest();
                    request.open('GET', url, true);
                    request.send(null);
                }

                if(MEDIA_TYPE === 'film') {
                    preload(source);
                    preload(source.replace('/manifest.m3u8', '/hls_720p/manifest.m3u8'));
                    preload(source.replace('/manifest.m3u8', '/decrypt.key'));
                }

                if(MEDIA_TYPE === 'trailer') {
                    preload(source);
                    preload(source.replace('/trailer-manifest.m3u8', '/hls_720p/trailer-manifest.m3u8'));
                }

                if (isOneTimeScreener || MEDIA_TYPE === 'trailer') {
                    autoplay = false;
                }

                var AirplayPlugin = Clappr.UICorePlugin.extend({
                    name: 'airplay-plugin',
                    bindEvents: function() {
                        this.listenTo(this.core.mediaControl, Clappr.Events.MEDIACONTROL_SHOW, this.render);
                    },
                    render: function() {
                        if(Clappr.Browser.isSafari) {
                            var airplayElement = document.createElement('div');
                            airplayElement.setAttribute('id', 'airplayButtonId');
                            airplayElement.style.height = '32px';
                            airplayElement.style.width = '32px';
                            airplayElement.style.display = 'inline-block';
                            airplayElement.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0px" y="0px" width="32px" height="32px" viewBox="0 0 1024 1024" enable-background="new 0 0 1024 1024" xml:space="preserve"><g><polygon fill="#FFFFFF" points="258.314,830 765.686,830 512,537.429"/><polygon fill="#FFFFFF" points="364.306,633 194,633 194,274 830,274 830,633 659.694,633 686.99,665 861,665 861,243 163,243 163,665 337.01,665"/></g></svg>';

                            this.$el = airplayElement;

                            if (!$('#airplayButtonId').length) {
                                this.core.mediaControl.$el.find('.media-control-right-panel').append(this.$el)
                            }
                        }
                    }
                });

                var InfoButtonPlugin = Clappr.UICorePlugin.extend({
                    name:'info-plugin',
                    initialize: function(){
                        console.log('info button plugin initialise');
                    },
                    bindEvents: function () {
                        this.listenTo(this.core.mediaControl, Clappr.Events.MEDIACONTROL_SHOW, this.render);
                    },
                    render: function() {
                        if (!$('#infoButtonId').length) {
                            var infoButton = document.createElement('div');
                            infoButton.setAttribute('id', 'infoButtonId');
                            infoButton.style.height = '32px';
                            infoButton.style.width = '32px';
                            infoButton.style.display = 'inline-block';
                            infoButton.style.position = "absolute";
                            if (Clappr.Browser.isSafari) {
                                infoButton.style.marginLeft = "-80px";
                            } else {
                                infoButton.style.marginLeft = "-70px";
                            }
                            infoButton.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 640 640"><path fill="#F4F4F4" d="M320.5 59.5c-144.146 0-261 116.854-261 261s116.854 261 261 261s261-116.854 261-261 S464.646 59.5 320.5 59.5z M320.5 566.892c-136.078 0-246.392-110.313-246.392-246.392S184.422 74.1 320.5 74.1 S566.892 184.4 566.9 320.5S456.578 566.9 320.5 566.892z"/><path fill="#F4F4F4" d="M334.563 205.27c16.286 0 28.17-15.406 28.17-31.252c0-9.684-5.723-16.286-17.166-16.286 c-14.966 0-26.85 14.085-26.85 30.812C318.717 196.9 324.4 205.3 334.6 205.27z"/><path fill="#F4F4F4" d="M346.888 414.344c-4.841 7.925-12.324 18.048-22.888 18.048c-5.283 0-10.124-3.962-10.124-12.323 c0-3.963 1.761-11.445 3.082-17.168l22.889-100.796c2.2-8.363 5.28-21.127 5.28-25.969c0-13.205-9.682-24.209-25.089-24.209 c-23.769 0-50.618 33.453-59.421 48.858l-1.761 3.081l9.684 7.043c7.922-12.325 22.007-32.572 34.332-32.572 c5.282 0 7 4.8 7 8.803c0 3.081-2.201 12.325-4.402 21.127l-21.128 93.314c-2.64 11.004-3.961 18.046-3.961 27.7 c0 17.2 10.1 29.5 25.1 29.491c28.61 0 48.417-33.013 59.421-51.499l-10.125-5.722L346.888 414.344z"/></svg>';
                            this.$el = infoButton;

                            if (!$('#infoButtonId').length) {
                                this.core.mediaControl.$el.find('.media-control-right-panel').append(this.$el)
                            }
                        }
                    }
                });

                var playerPlugins = [LevelSelector, AirplayPlugin, InfoButtonPlugin, ChromecastPlugin];
                if (MEDIA_TYPE === 'trailer') {
                    playerPlugins = [LevelSelector, AirplayPlugin, ChromecastPlugin];
                }

                var player = new Clappr.Player({
                    source: source,
                    parentId: "#player",
                    poster: '#{posterUrl}',
                    height: "100%",
                    width: "100%",
                    disableVideoTagContextMenu: true,
                    playbackConfig: {
                        preload: 'auto'
                    },
                    hlsjsConfig: {
                        startFragPrefetch: true,
                        abrEwmaFast: 10,
                        abrEwmaSlow: 60,
                        abrBandWidthUpFactor: 1.8,
                        abrBandWidthFactor: 1.8,
                        levelLoadingMaxRetry: 2,
                        fragLoadingMaxRetry: 2
                    },
                    events: {
                        onReady: onReady
                    },
                    chromecast: {
                        media: {
                            type: ChromecastPlugin.Movie,
                            title: videoTitle
                        }
                    },
                    mediacontrol: {seekbar: "#FAA633"},
                    plugins: {
                        'core': playerPlugins
                    },
                    levelSelectorConfig: {
                        title: 'Quality',
                        labels: !{JSON.stringify(qualityLabels)}
                    }
                });

                if (typeof $YB != "undefined" && youboraAccount) {
                    var videoType;
                    if (MEDIA_TYPE === 'film') {
                        videoType = 'film';
                    } else if (MEDIA_TYPE === 'trailer') {
                        videoType = 'trailer';
                    } else if (isOneTimeScreener) {
                        videoType = 'onetimescreener';
                    }

                    var youbora = new $YB.plugins.Clappr(player, {
                        accountCode: youboraAccount,
                        enableAnalytics: true,
                        username: userName && userEmail ? userName + ' - ' + userEmail : 'Anonymous',
                        parseHLS: true,
                        httpSecure: true,
                        media: {
                            title: videoTitle + " - " + videoType,
                            duration: parseInt(videoDuration),
                            isLive: false,
                            resource: source,
                            cdn: "cloudfront"
                        }
                    });

                    if (autoplay) {
                        youbora.playHandler();
                    }
                }

                function onReady() {
                    showChromecastButton();
                    hideHDButton();
                    resizeQualityPicker();

                    if (autoplay) {
                        this.play();
                    }
                }

                player.on(Clappr.Events.PLAYBACK_ERROR, function(error) {
                    console.error('PLAYBACK ERROR', error);
                    sendPlayerError(error);
                });

                player.on(Clappr.Events.PLAYER_ERROR, function(error) {
                    console.error('PLAYER ERROR', error);
                    sendPlayerError(error);
                });

                player.on(Clappr.Events.PLAYER_PLAY, function() {
                    $('#pause-button').hide();

                    addAirPlayAvailabilityChecker();
                    addBestVideoPracticesButton();
                    hideHDButton();

                    if (lastWatchedSecond && !haveSeekedToResumePoint) {
                        haveSeekedToResumePoint = true;
                        player.seek(lastWatchedSecond);
                    }

                    addPlayerView();
                    startTracking();
                });

                player.on(Clappr.Events.PLAYER_PAUSE, function(){
                    if (!$('#pause-button').length) {
                        document.querySelector(".container").appendChild(pauseButton);
                    }

                    hideHDButton();
                    pauseButton.style.display = 'block';
                });
             
                function hideHDButton() {
                    var hdElement = $("[data-hd-indicator]");
                    hdElement.hide();
                }

                function showChromecastButton() {
                    var chromecastButton = $(".chromecast-button");
                    chromecastButton.css('display', 'inline');
                }

                function resizeQualityPicker() {
                    var qualityPickerElement = $("[data-level-selector]");
                    qualityPickerElement.css('width','30px!important');
                    var soundElement = $(".drawer-icon-container");
                    soundElement.css('width','20px!important');
                }

                function addAirPlayAvailabilityChecker() {
                    var video = document.getElementsByTagName('video')[0];
                    video.setAttribute('x-webkit-airplay','allow');
                    video.addEventListener('webkitplaybacktargetavailabilitychanged', function(event) {
                        switch (event.availability) {
                            case "available":

                                break;
                        }

                        $('#airplayButtonId').click(function() {
                            video.webkitShowPlaybackTargetPicker();
                        });
                    });
                }

                function addBestVideoPracticesButton() {
                    var html = document.createElement('div');
                    html.setAttribute('id', 'best-practice-text');
                    html.style.color = 'white';
                    html.innerHTML = '<div class="best-practice-outer"><h3 class="best-practice-title">General Best Practices:</h3>' +
                             '<ul><li>For best results, please update your browser and operating system to the latest version. ' +
                            'You can check if you have the latest version of your browser at http://whatbrowser.org/ . </li>' +
                            '<li>You can utilize YouTube’s Video Quality Report to identify if your Internet Service Provider (ISP) may have issues with HD quality video streams.</li>' +
                            '</ul>'+
                            '<div class="best-practice-title"><img src="/img/apple_tv_icon.png" style="margin: 4px 7px -8px -3px;width:35px;height:35px;"/><h3 style="display:inline;">Apple TV</h3></div>' +
                            '<ul>' +
                            '<li>iOS devices are ideal for streaming on Apple TV.</li>' +
                            '<li>If you are going to stream from an Apple laptop or a desktop, please utilize the latest version of Safari and Apple OSX. Your laptop should be connected to the same wireless network as an Airplay device. To get the best results, utilize the Airplay icon on the video player.</li>' +
                            '<li>Depending on the speed of your wifi network, mirroring your screen from your desktop using Airplay while streaming HD content may result in a subpar experience.</li>' +
                            '</ul>' +
                            '<div class="best-practice-title"><img src="/img/chromecast icon.svg" style="margin: -5px -35px -11px -35px;width:100px;height:35px;"/><h3 style="display:inline;">ChromeCast</h3></div>' +
                            '<ul>' +
                            '<li>You must use Chrome to stream from ChromeCast.</li>' +
                            '<li>For optional viewing experience use the ChromeCast Icon located within the bottom bar of the video player.</li>' +
                            '<li>Depending on the speed of your wifi network, mirroring your screen from your desktop using the ChromeCast while streaming HD content may result in a subpar experience. </li>' +
                            '<li>For the best ChromeCast experience please ensure you are using the latest version of Chrome.</li>' +
                            '</ul>' +
                            '<h3 class="best-practice-title">Troubleshooting</h3>' +
                            '<ul>' +
                            '<li>Please try restarting your device or computer to see if that resolves your issue.</li>' +
                            '<li>If you are having streaming issues that cannot be resolved, please contact us and we will help you troubleshoot these issues.</li>'
                            '</ul>' +
                            '</div>';
                    html.style.display = 'none';
                    document.querySelector('.media-control').appendChild(html);

                    var showText = false;

                    $('#infoButtonId').click(function () {
                        if (showText) {
                            document.querySelector('#best-practice-text').style.display = 'none';
                            player.play();
                            showText = false;
                        } else {
                            document.querySelector('#best-practice-text').style.display = 'block';
                            player.pause();
                            showText = true;
                        }
                    });

                }
                
                function addPlayerView() {
                    if (haveStoredView) {
                        return;
                    }
                    haveStoredView = true;
                    var url;
                    if (isOneTimeScreener){
                        if(MEDIA_TYPE === 'film') {
                            url = '/api/video-entitlements-video/burner-link/'+ passcode +'/player-viewed';
                        }
                    } else{
                        url = MEDIA_TYPE === 'film' ?
                        '/api/video-entitlements-video/'+ videoId + '/' + userId + '/player-viewed' :
                        '/api/video-entitlements-video/' + videoId + '/trailer-player-viewed';
                    }
                    $.ajax({
                        type: 'POST',
                        url: url
                    });
                }

                function startTracking() {
                    if (haveStartedTracking) {
                        return;
                    }
                    haveStartedTracking = true;

                    var trackWatchedSecondsInterval = setInterval(function() {
                        if (!player.isPlaying()) {
                            return;
                        }
                        var currentTime = Math.floor(player.getCurrentTime());
                        if (isOneTimeScreener) {
                            if (now > currentTime) {
                                currentTime = now;
                            } else {
                                now = currentTime;
                            }
                        }
                        watchedSeconds.push('s' + currentTime);
                    }, 1000);

                    var sendWatchedSecondsInterval = setInterval(function() {
                        if (!player.isPlaying()) {
                            return;
                        }
                        var currentTime = Math.floor(player.getCurrentTime());
                        var data = {watchedSeconds: watchedSeconds, currentTime: currentTime};

                        var url;
                        if (isOneTimeScreener) {
                            if (MEDIA_TYPE === 'film') {
                                url = '/api/video-entitlements-video/burner-link/' + passcode +'/player-engagement';
                            }
                        } else {
                            url = MEDIA_TYPE === 'film' ?
                            '/api/video-entitlements-video/' + videoId + '/'+ userId + '/player-engagement' :
                            '/api/video-entitlements-video/' + videoId + '/trailer-player-engagement';
                        }
                        $.ajax({
                            type: 'POST',
                            url: url,
                            data: data
                        });
                        watchedSeconds = [];
                    }, 10000);
                }

                function sendPlayerError(playerError) {
                    if (isSendingError) {
                        playerErrorQueue.push(playerError);
                        return;
                    }

                    isSendingError = true;

                    if (playerError && playerError.error && playerError.error.data) {
                        var url = '/api/player-error';
                        var data = {
                            mediaType: MEDIA_TYPE,
                            details: playerError.error.data.details,
                            url: playerError.error.data.url,
                            eventFired: playerError.error.evt,
                            errorType: playerError.error.data.type,
                            errorTime: playerError.container ? playerError.container.currentTime : undefined,
                            fatal: playerError.error.data.fatal,
                            logs: playerLogs,
                            video: videoId
                        };

                        if (userId && userId.length > 1) {
                            data.user = userId;
                        }
                        var tryCount = 0;
                        var retryLimit = 4;

                        postPlayerError();

                        function postPlayerError() {
                            $.ajax({
                                type: 'POST',
                                url: url,
                                data: data,
                                success: function() {
                                    isSendingError = false;
                                    if (playerErrorQueue.length) {
                                        var nextError = playerErrorQueue.shift();
                                        if (nextError.errorType !== playerError.errorType && nextError.details !== playerError.details) {
                                            sendPlayerError(nextError);
                                        }
                                    }
                                },
                                error: function(xhr, textStatus, errorThrown) {
                                    tryCount += 1;
                                    if (textStatus == 'timeout' || textStatus == 'abort') {
                                        if (tryCount < retryLimit) {
                                            setTimeout(postPlayerError, 5000);
                                        } else {
                                            isSendingError = false;
                                            if (playerErrorQueue.length) {
                                                var nextError = playerErrorQueue.shift();
                                                if (nextError.errorType !== playerError.errorType && nextError.details !== playerError.details) {
                                                    sendPlayerError(nextError);
                                                }
                                            }
                                        }
                                    }
                                    if (xhr.status == 500) {
                                        isSendingError = false;
                                        return;
                                    } else {
                                        isSendingError = false;
                                        return;
                                    }
                                }
                            });
                        }
                    }
                }
