
$("head").append("<link href='https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.min.css' rel='stylesheet' type='text/css'>").hide().show(0);
$("head").append("<link href='https://live4.brownrice.com/node_modules/@fortawesome/fontawesome-free/css/all.min.css' rel='stylesheet' type='text/css'>").hide().show(0);
$("head").append("<link href='https://live4.brownrice.com/player.css?rev=20250529' rel='stylesheet' type='text/css'>").hide().show(0);
$("head").append("<script async src='https://www.googletagmanager.com/gtag/js?id=G-ZMDJMNVFHZ'></script>").hide().show(0);
$("head").append("<script type='text/javascript' src='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1'></script>").hide().show(0);
$("head").append("<script type='text/javascript' src='https://code.jquery.com/ui/1.12.1/jquery-ui.min.js'></script>").hide().show(0);

$(document).ready(function() {

    // load google tag data
    window.dataLayer = window.dataLayer || [];
    function gtag() {dataLayer.push(arguments);}
    gtag('js', new Date());
    window.draggingList = false;

    
    gtag('config', 'G-ZMDJMNVFHZ');

    
        var disabled = false;

        var defaultPausetime = '600';var pausetime = defaultPausetime;var autostart = false;
console.log('Autoplay is OFF');let video_classes = 'vjs-fluid';

        var camera = window.camera = new Array();
        camera['num']             = '1'; //The number of the camera
        camera['uid']             = 'b99d3e10ae21051c716e';
        camera['vuid']            = 'video_b99d3e10ae21051c716e';
        camera['name']            = 'lacrosserivercam';
        camera['typeid']          = '6';
        camera['image']           = 'https://live7.brownrice.com/cam-images/lacrosserivercam.jpg';
        camera['banner']          = '';
        camera['logo']            = '';
        camera['logo2']           = "";
        camera['logo3']           = "";
        camera['widgetCode']      = "";
        camera['bannerLink']      = "";
        camera['link']            = "https://hosting.brownrice.com/web-camera-software";
        camera['link2']           = "https://hosting.brownrice.com/web-camera-software";
        camera['roomforcontrols'] = false;
        camera['roomforcontrols'] = camera['roomforcontrols'] ? true : false;
        camera['ptzControls']     = false;
        camera['muted']           = false;
        camera['hide_audio_controls'] = false;
        camera['width']           = '';
        camera['height']          = '';
        camera['aspect_w']        = "0";
        camera['aspect_h']        = "0";
        camera['allowed_urls']    = "";
        camera['embedoptions']    = "playsinline";
        camera['isLive'] = true;
        camera['showingRecordings'] = false;
        camera['showingTimelapses'] = false;
        camera["loadingTimelapse"] = false;
        camera["loadingRecording"] = false;
        camera["playingTimelapse"] = false;
        camera["playingRecording"] = false;
        camera["listingTimelapses"] = true;
        camera["listingRecordings"] = false;
        camera["hideCtrl"] = false;
        camera["nvrEnabled"] = "0";
        camera["onDemand"] = false;
        camera["showViewers"] = true;

        // escape double-quotes and newlines again for adding to GET string later
        camera["logo3"] = camera["logo3"].replace(/"/g, '\\"').replace(/\n/g, '');
        camera["widgetCode"] = camera["widgetCode"].replace(/"/g, '\\"').replace(/\n/g, '');

        // only show controls if widgetCode is set and hideCtrl isn't already true
        camera["showWidget"] = (camera["hideCtrl"] || camera["widgetCode"] == '') ? false : true;

        // match for parent URL for later use
        var parentUrl;
        parentUrl = document.referrer;
        console.log("Parent URL: " + parentUrl);
        if (parentUrl == "") {
            parentUrl = parent.location.host;
            console.log("Parent URL 2nd try: " + parentUrl);
        }

        // allowed embed URLs
        camera['allowed_urls'] = "";

        // set the offline bit
        camera["offline"] = "";

        // check allowed URLs
        if (camera['allowed_urls'] != '' && parentUrl != '') {
            console.log('Processing allowed URLs:' + camera['allowed_urls']);
            var allowed_urls = new RegExp(camera['allowed_urls'] + "|brownrice|google");
            var restrict = true;
            var allowed = allowed_urls.test(parentUrl);
            console.log('URL allowed: ' + allowed);
        } else {
            var restrict = false;
        }

        
        camera['servername'] = "live7.brownrice.com";
        camera['streamurl'] = "https://623bf6bf3ce68.streamlock.net:444";

        
        console.log('PTZ area: ' + camera['roomforcontrols']);
        console.log('Player server: live4.brownrice.com');
        console.log('Streaming server: ' + camera['servername']);

        // load correct stream url
        if (camera['typeid'] == '20') {
            // transcoded url
            var url_rtsp = camera["url_rtsp"] = "" + camera['streamurl'] + "/" + camera['name'] + "/" + camera['name'] + ".stream_360p/playlist.m3u8";

        } else if (camera['typeid'] == '5') {
            // radio stream
            var url_rtsp = camera["url_rtsp"] = "" + camera['streamurl'] + "/" + camera['name'] + "/" + camera['name'] + ".stream_aac/playlist.m3u8";
        } else {
            // normal rtsp url
            var url_rtsp = camera["url_rtsp"] = "" + camera['streamurl'] + "/" + camera['name'] + "/" + camera['name'] + ".stream/main_playlist.m3u8";
        }

        // preload background image
        camera['poster'] = camera['image'];

        console.log('Poster image: ' + camera['poster']);

        // dimensions of widget area
        if (camera['showWidget']) {
            var video_height = $(document).height()-120;
        } else {
            var video_height = $(document).height();
        }

        var video_width = $(document).width();
        var myDiv = "cam-embed-" + camera['uid'];
        $("head").append("<style type='text/css' id='css-" + myDiv + "'></style>").hide().show(0);

        $("#bri_cam_" + camera['num']).after("<div id='" + myDiv + "'></div>");
        $("#" + myDiv).hide();
        if (camera['width'] != "" || camera['height'] != "") {
            $("#" + myDiv).wrap("<div style='width: " + camera['width'] + "; height: " + camera['height'] + ";'></div>");
        } else {
            $("#" + myDiv).wrap("<div style='height: " + video_height + ";'></div>");
        }

        // if camera has unusual aspect ratios we'll set them in the embed code
        // with the aspect_r var
        if (camera['aspect_w'] != '0' && camera['aspect_h'] != '0') {
            var aspect_r = "data-setup='{\"aspectRatio\": \""+camera['aspect_w']+"\:"+camera['aspect_h']+"\"}'";
        } else {
            var aspect_r = '';
        }

        if (camera.offline == "offline" && !camera.loadingTimelapse && !camera.loadingRecording) {
            // build this is scheduled downtime, remove all controls and stop auto start

            // if scheduled offline time remove controls and remove autostart
            $("#" + myDiv).append("<video id='" + camera['vuid'] + "' " + aspect_r + " class='video-js vjs-default-skin " + video_classes + "' preload='none' poster='" + camera['poster'] + "'></video>");
        } else if (disabled == true) {
            console.log("Disabled: " + disabled)

            
            // if user clicked cancel on password button then we display this
            $("#" + myDiv).append("<video id='" + camera['vuid'] + "' " + aspect_r + " class='video-js vjs-default-skin " + video_classes + "' preload='none' poster=' https://live4.brownrice.com/images/webcam-protected.png'></video>");
        } else if (restrict == false || allowed == true) {
            // if this is a URL that is allowed to play the video build the full player
            if (camera.loadingTimelapse) {
                // loading directly into a timelapse
                $("#" + myDiv).append("<div class='wrapper'><div class='overlay'></div><div class='zoom'><div id='slider-vertical' style='height:200px'></div></div><video id='" + camera['vuid'] + "' " + aspect_r + " class='video-js vjs-default-skin vjs-big-play-centered " + video_classes + "' controls "+ autostart +" preload='auto' poster='" + camera.timelapseThumbnail + "' "+ camera['embedoptions'] +"><source src='" + camera.timelapseStream + "' type='application/x-mpegURL'></video></div>");
                $(".vjs-vidsource-live").show();
            } else if (camera.loadingRecording) {
                // loading directly into a recording
                $("#" + myDiv).append("<div class='wrapper'><div class='overlay'></div><div class='zoom'><div id='slider-vertical' style='height:200px'></div></div><video id='" + camera['vuid'] + "' " + aspect_r + " class='video-js vjs-default-skin vjs-big-play-centered " + video_classes + "' controls "+ autostart +" preload='auto' poster='" + camera.recordingThumbnail + "' "+ camera['embedoptions'] +"><source src='" + camera.recordingStream + "' type='application/x-mpegURL'></video></div>");
                $(".vjs-vidsource-live").show();
            } else {
                // loading live player
                $("#" + myDiv).append("<div class='wrapper'><div class='overlay'></div><div class='zoom'><div id='slider-vertical' style='height:200px'></div></div><video id='" + camera['vuid'] + "' " + aspect_r + " class='video-js vjs-default-skin vjs-big-play-centered " + video_classes + "' controls "+ autostart +" preload='auto' poster='" + camera['poster'] + "' "+ camera['embedoptions'] +"><source src='" + url_rtsp + "' type='application/x-mpegURL'></video></div>");
            }
        } else {
            // not allowed to embed pop-up
            alert("This web site is not allowed to embed this webcam.  Please see https://www.brownrice.com for further information.");
        }

        // Camera controls
        if (!camera.hideCtrl) {
            if (camera.showWidget) {
                $("#" + myDiv).append("<div id='control-container-" + myDiv + "' / style=\"display: none;\">");
            }

            // read cookie function
            function getCookie(w) {
                cName = "";
                pCOOKIES = new Array();
                pCOOKIES = document.cookie.split('; ');
                for (bb = 0; bb < pCOOKIES.length; bb++) {
                    NmeVal = new Array();
                    NmeVal = pCOOKIES[bb].split('=');
                    if (NmeVal[0] == w) {
                        cName = unescape(NmeVal[1]);
                    }
                }
                return cName;
            }

            // set cookie if not found
            var cameracookie;

            // retrieve cookie
            cameracookie = getCookie('cameracookie');

            if (cameracookie === '') {
                // generate random string
                var text = "";
                var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

                for ( var i=0; i < 8; i++ ) {
                    text += possible.charAt(Math.floor(Math.random() * possible.length));
                }

                // set the cookie name and cookie value
                document.cookie="cameracookie=" + text;

                // and set the var to pass to our next script since the cookie just got set
                cameracookie = text;
            }

            // location of bri camera control server-side script
            // necessary for both the camera-controls and the widget area, so include either way
            var control_script = "https://live4.brownrice.com/cam-control/camera-controller.php?camera=" + camera['name'] + "&servername=" + camera['servername'] + "&myDiv=" + myDiv + "&myHeight=" + video_height + "&myWidth=" + video_width + "&showWidget=" + camera['showWidget'] + "&widgetCode=" + camera['widgetCode'] + "&camerasession=" + cameracookie + "&rev=20250508";

            var loaded = false;

            // if playing, then we'll show the controller
           function checkPlayStatus() {
                if (!player.paused() && camera.isLive) {
                    // load up the PTZ room for controls area
                    if (!loaded) {
                        $.getScript(control_script, function() {
                            // success
                            // console.log(control_script);
                            // set loaded bit
                            loaded = true;
                        });
                    }

                    if (camera.showWidget) {
                        $("#control-container-" + myDiv).fadeIn('slow');
                    }

                    if (camera.showViewers) {
                        $(".viewers-" + myDiv).fadeIn();
                    }
                    if (camera['roomforcontrols']) {
                        $(".control-" + myDiv).fadeIn();
                    }
                } else {
                    if (camera.showWidget) {
                        // video is no longer playing, so we'll hide the controller
                        $("#control-container-" + myDiv).fadeOut('slow');
                    }

                    if (camera.showViewers) {
                        $(".viewers-" + myDiv).fadeOut();
                    }
                    if (camera['roomforcontrols']) {
                        $(".control-" + myDiv).fadeOut();
                    }

                    // kill control sesssion, too
                    if (loaded && chkCtlInterval) {
                        killSession(true);
                        setTimeout(function() {
                            // kill the control session again in five seconds, just to be sure it goes away
                            killSession();
                        }, 5000);
                    }
                }
            }

            // End Camera controls table ------------------------------------------------
        }

        (function(window, videojs) {
            let playerOptions = {
                inactivityTimeout: camera['roomforcontrols'] ? (60*1000) : (5*1000), // show control-bar for 60s if controls enabled, 5s otherwise
                // inactivityTimeout: 0, // don't hide control-bar; for development
                html5: {
                    // disable the cc button
                    nativeTextTracks: false
                },
                controlBar: {},
                userActions: {},
                plugins: {}
            };

            if (true || !camera['servername'].match(/^streamer/)) {
                // not on streamer servers so load chromecast stuff
                console.log("loading chromecast");
                playerOptions.techOrder = [ 'chromecast', 'html5' ];
                playerOptions.plugins.chromecast = {}
            }

            if (camera['roomforcontrols'] && camera['ptzControls']) {
                playerOptions.userActions.click = false;
            }

            // hide all audio controls
            if (camera['hide_audio_controls']) {
                playerOptions.muted = true; // mute by default if they're hiding audio controls
                playerOptions.controlBar.volumePanel = false;
            } else if (camera['muted']) {
                // mute audio by default
                playerOptions.muted = true;
            }

            // manually set camera-offline message
            if (camera.onDemand) {
                videojs.addLanguage('en', {"The media could not be loaded, either because the server or network failed or because the format is not supported.": "Connecting to on-demand camera, please stand by..."});
            } else {
                videojs.addLanguage('en', {"The media could not be loaded, either because the server or network failed or because the format is not supported.": "The webcam that you are attempting to view appears to be offline. Please contact the owner of this camera and let them know about the issue."});
            }

            // initialize player
            var player = window.player = videojs(camera['vuid'], playerOptions);

                        // add BRI logo with link to brownrice.com
            var briButton = player.controlBar.addChild('button', {}, 11);
            var briButtonDom = briButton.el();
            briButtonDom.innerHTML = '<a style="text-decoration:none" href="https://hosting.brownrice.com/web-camera-software" target="_blank"><img style="width:25px" src="https://live4.brownrice.com/images/bri_logo_icon.png"></a>';
            briButton.controlText("Hosted by Brownrice Internet"); // set hover-text
            briButton.addClass("vjs-bri-button");
            
            // pass camera name for easier reference
            var stream_name = camera['name'];

            // this fires every second or so while the video is playing.
            // functions send google analytics events
            var playing = 99;
            player.on('timeupdate', function(e) {
                playing++;
                if (playing == 1) {
                    // video has been loaded but play button not yet pressed

                    // fire google tag event
                    if (camera.playingRecording) {
                        gtag('event', `${stream_name}_recording_loaded`, {
                            "camera_name": stream_name
                        });
                    } else if (camera.playingTimelapse) {
                        gtag('event', `${stream_name}_timelapse_loaded`, {
                            "camera_name": stream_name
                        });
                    } else {
                        gtag('event', `${stream_name}_video_loaded`, {
                            "camera_name": stream_name
                        });
                    }
                } else if (playing > 1 && playing <= 2) {
                    // video was played for at least one second
                    var watchedseconds = player.currentTime();

                    // fire google tag event
                    if (camera.playingRecording) {
                        gtag('event', `${stream_name}_recording_played`, {
                            "camera_name": stream_name
                        });
                    } else if (camera.playingTimelapse) {
                        gtag('event', `${stream_name}_timelapse_played`, {
                            "camera_name": stream_name
                        });
                    } else {
                        gtag('event', `${stream_name}_video_played`, {
                            "camera_name": stream_name
                        });
                    }
                }
            });

            // reset GA loop count when new video is loaded
            player.on('loadedmetadata', function() {
                playing = 0;
            });

            
            
            var isAutoplayEnabled = player.autoplay();
            // Initialize a flag to track the first interaction
            var firstTouch = true;
            // Function to toggle play/pause
            function togglePlayback() {
                if (player.paused()) {
                    player.play();
                } else {
                    player.pause();
                }
            }

            // Listening for touch events (for mobile devices)
            player.on('touchmove', function(event) {
                window.draggingList = true;
            });

            player.on('touchstart', function(event) {
                // Prevent any additional default action
                if (window.draggingList) {
                    event.preventDefault();
                    window.draggingList = false;
                } else {
                    // Prevent-default if the touch event target isn't part of the player's control bar, a logo/banner link, or the timelapse list is shown
                    if (!(player.controlBar.el().contains(event.target) || $(event.target).hasClass("logolink") || $(event.target).hasClass("preset-select") || $("#timelapse-overlay").is(":visible") || $("#recording-overlay").is(":visible"))) {
                        event.preventDefault();
                        // tap not in control bar and timelapse list is hidden, play or pause video
                        if (!isAutoplayEnabled && firstTouch) {
                            // Skip the first touch interaction for playback
                            firstTouch = false;
                        } else {
                            // Handle play/pause on subsequent touches
                            togglePlayback();
                        }
                    }
                }
            });
            player.on('pause', function() {
                // Modify the style to show the big play button when the video is paused
                if (!player.ended()) {
                    player.bigPlayButton.el().style.display = 'block';
                }
                checkPlayStatus();
            });
            player.on('play', function() {
                // Hide the big play button when the video is playing
                player.bigPlayButton.el().style.display = 'none';
                toggleTimelapses("hide");
                toggleRecordings("hide");
                checkPlayStatus();
            });
            player.on('ended', function() {
                // Make sure the button shows up when the video ends
                player.bigPlayButton.el().style.display = 'block';
                checkPlayStatus();
            });
            if (camera['nvrEnabled'] == 1) {
                console.log('nvr enabled')
                // Override the default duration display update
                var durationDisplay = player.controlBar.durationDisplay;
                var durationDisplayContent = durationDisplay.contentEl();
                // Select the elements with the classes `vjs-progress-control` and `vjs-seek-to-live-control`
                var progressControl = document.querySelector('.vjs-progress-control');
                var seekToLiveControl = document.querySelector('.vjs-seek-to-live-control');
                var liveControl = document.querySelector('.vjs-live-control');
                var mouseControl = document.querySelector('.vjs-mouse-display');
                var mouseControlWhenClicking = document.querySelector('.vjs-progress-holder');
                // Check if the elements exist and change their display style
                if (progressControl) {
                    progressControl.style.display = 'flex';
                }
                if (seekToLiveControl) {
                    seekToLiveControl.style.display = 'block';
                }
                if (liveControl) {
                    liveControl.style.display = 'none';
                }
                // Function to update the duration display
                function updateDurationDisplay() {
                    var seekable = player.seekable();
                    if (seekable && seekable.length > 0) {
                        var nvrWindowLength = seekable.end(0) - seekable.start(0);
                        var displayTime = Math.round(nvrWindowLength); // rounded to nearest second
                        var minutes = Math.floor(displayTime / 60);
                        var seconds = displayTime % 60;
                        durationDisplayContent.textContent = minutes + ':' + (seconds < 10 ? '0' + seconds : seconds);
                    }
                }
                // Update duration display on relevant events
                player.on('timeupdate', updateDurationDisplay);
                player.on('loadedmetadata', updateDurationDisplay);

                var maxNvrLength = 3600;  // Maximum DVR length in seconds, e.g., 60 minutes
                player.on('timeupdate', function() {
                    var seekable = this.seekable();
                    if (seekable.length > 0) {
                        var nvrLength = seekable.end(0) - seekable.start(0);
                        if (nvrLength > maxNvrLength) {
                            var allowedStart = seekable.end(0) - maxNvrLength;
                        }
                    }
                });
            }

            console.log('Timeout set to: ' + pausetime + ' seconds.');

            if (pausetime > 0) {
                // Adjust pausetime based on seekable length
                if (camera['nvrEnabled'] == 1) {
                    player.on('loadedmetadata', function(e) {
                        if (camera.isLive && player.liveTracker.seekableEnd() > 0) {
                            pausetime = (Number(defaultPausetime) + player.liveTracker.seekableEnd());
                            console.log('Adjusted Pausetime with DVR window: ' + pausetime);
                        }
                    });
                }

                // player timeout function
                player.on('timeupdate', function(e) {
                    if (player.currentTime() >= pausetime && window.camera.isLive) {
                        console.log('Timeout exceeded, pausing video');
                        player.pause();
                        pausetime = pausetime * 2;
                        console.log('Current Pausetime (doubled): '+ pausetime);
                    }
                });
            }

            const overlay = player.overlay({
            overlays: [
                        ]
            });

            if (camera.listingTimelapses) {
                // create timelapse loading spinner
                var timelapseLoadingSpinner = player.controlBar.addChild('button', {}, 11);
                timelapseLoadingSpinnerDom = timelapseLoadingSpinner.el();
                timelapseLoadingSpinnerDom.id = "vjs-timelapse-loading-button";
                timelapseLoadingSpinnerDom.innerHTML = '<span class = "loader"></span>';
                timelapseLoadingSpinner.controlText("Loading Timelapses");
                timelapseLoadingSpinner.addClass("vjs-loading-button");

                // create timelapse button
                var timelapseButton = player.controlBar.addChild('button', {}, 11);
                var timelapseButtonDom = timelapseButton.el();
                timelapseButtonDom.innerHTML = '<img src="https://live4.brownrice.com/images/timelapse.svg" style="height:15px; margin-top:3px;">';
                timelapseButton.controlText("View Timelapses"); // set hover-text
                timelapseButton.addClass("vjs-timelapse-button");
                $(".vjs-timelapse-button").on("touchstart click", function () { toggleTimelapses();});
                $(".vjs-timelapse-button").hide();

                // fetch timelapse list
                const timelapseId = "0";
                const queryString = timelapseId ? `&timelapseId=${timelapseId}` : "";
                $.get(`https://live4.brownrice.com/list-timelapses.php?sn=${camera.name}${queryString}`)
                    .done(function(data) {
                        if (data && data != "NO_TIMELAPSES") {
                            let jsonData = JSON.parse(data);
                            overlay.add({
                                align: "top",
                                content: jsonData.overlay,
                                start: 'showTimelapses',
                                end: 'hideTimelapses'
                            });
                            $("head").append(jsonData.script).hide().show(0);
                            $("#vjs-timelapse-loading-button").fadeOut(() => {
                                $(".vjs-timelapse-button").fadeIn();
                            });
                        } else {
                            $("#vjs-timelapse-loading-button").fadeOut();
                        }
                    }).fail(function() {
                        $("#vjs-timelapse-loading-button").fadeOut();
                    });
            }

            if (camera.listingRecordings) {
                // create recording loading spinner
                var recordingLoadingSpinner = player.controlBar.addChild('button', {}, 11);
                recordingLoadingSpinnerDom = recordingLoadingSpinner.el();
                recordingLoadingSpinnerDom.id = "vjs-recording-loading-button";
                recordingLoadingSpinnerDom.innerHTML = '<span class = "loader"></span>';
                recordingLoadingSpinner.controlText("Loading Recordings");
                recordingLoadingSpinner.addClass("vjs-loading-button");

                // create recording button
                var recordingButton = player.controlBar.addChild('button', {}, 11);
                var recordingButtonDom = recordingButton.el();
                recordingButtonDom.innerHTML = '<img src="https://live4.brownrice.com/images/recording.svg" style="height:15px; margin-top:3px; fill: white; stroke: white;">';
                recordingButton.controlText("View Recordings"); // set hover-text
                recordingButton.addClass("vjs-recording-button");
                $(".vjs-recording-button").on("touchstart click", function () { toggleRecordings();});
                $(".vjs-recording-button").hide();

                // fetch recording list
                const recordingId = "0";
                const queryString = recordingId ? `&recordingId=${recordingId}` : "";
                $.get(`https://live4.brownrice.com/list-recordings.php?sn=${camera.name}${queryString}`)
                    .done(function(data) {
                        if (data && data != "NO_RECORDINGS") {
                            let jsonData = JSON.parse(data);
                            overlay.add({
                                align: "top",
                                content: jsonData.overlay,
                                start: 'showRecordings',
                                end: 'hideRecordings'
                            });
                            $("head").append(jsonData.script).hide().show(0);
                            $("#vjs-recording-loading-button").fadeOut(() => {
                                $(".vjs-recording-button").fadeIn();
                            });
                        } else {
                            $("#vjs-recording-loading-button").fadeOut();
                        }
                    }).fail(function() {
                        $("#vjs-recording-loading-button").fadeOut();
                    });
            }

            if (!camera.offline) {
                // create live button (only shows if the video-source has been switched to non-live)
                var liveButton = player.controlBar.addChild('button', {}, 11);
                var liveButtonDom = liveButton.el();
                liveButtonDom.innerHTML = '<img src="https://live4.brownrice.com/images/live.svg" style="height:21px; fill: white; stroke: white;">';
                liveButton.controlText("View Live Video"); // set hover-text
                liveButton.addClass("vjs-live-button");

                // add onclick for button
                $(".vjs-live-button").on("touchstart click", function(event) {
                    playVideo($(".vjs-vidsource-live")[0], camera["url_rtsp"], camera["poster"], "", "live");
                });

                if (!camera.loadingTimelapse && !camera.loadingRecording) {
                    $(".vjs-live-button").hide(); // hide button to switch back to live
                }
            }

            
            // control and viewer count
            if (camera.roomforcontrols) {
                // create presetSelect menu
                var presetSelectButton = player.controlBar.addChild('component', {
                    controlText: 'Select View',
                }, 11);
                var presetSelectButtonDom = presetSelectButton.el();
                ptzInstructions = camera['ptzControls'] ? " or click video &#8593;" : "";
                presetSelectButtonDom.innerHTML = "<select id='Preset-" + myDiv + "' class='preset-select' title='Select View'><option value='' selected='selected'>Select view" + ptzInstructions + "</option></select><div class='loading'><img src='https://live4.brownrice.com/images/rolling.svg' style='height:18px'></div>";
                presetSelectButton.addClass("vjs-preset-button");
                presetSelectButton.addClass("preset-" + myDiv);
                $(".preset-" + myDiv).hide();

                // create control-camera button
                var ptzControlButton = player.controlBar.addChild('button', {
                    controlText: 'Control Camera',
                }, 11);

                var ptzControlDom = ptzControlButton.el();
                ptzControlDom.innerHTML = '<img src="https://live4.brownrice.com/images/dpad.svg" style="height:15px">';
                ptzControlButton.addClass("vjs-camcontrol-button");
                // ptzControlButton.addClass("no-padding");
                ptzControlButton.addClass("no-margin");
                ptzControlButton.addClass("flex-center-parent");
                ptzControlButton.addClass("control-" + myDiv);
                $(".control-" + myDiv).hide();
            }

            if (camera.showViewers) {
                // show viewers on control bar
                var viewersButton = player.controlBar.addChild('component', {
                    controlText: 'Current Viewers',
                }, 11);
                var viewersButtonDom = viewersButton.el();
                viewersButtonDom.innerHTML = "<div class='flex-center-parent' title='Calculating Viewers'><span>Calculating&nbsp;</span><img src='https://live4.brownrice.com/images/eye.svg' style='height:15px'><span></div>";
                viewersButtonDom.id = "viewing-" + myDiv;
                viewersButton.addClass("vjs-viewers-button");
                viewersButton.addClass("viewers-" + myDiv);
                $(".viewers-" + myDiv).hide();
            }

            // do not display ads to android users
            var isAndroid = /android/i.test(navigator.userAgent.toLowerCase());

            if (isAndroid == false) {
                // add google tag events for clicked logos
                $( "#link_1_" + camera['uid']).click(function() {
                    var url_value = $(this).attr("href");
                    console.log( "Logo1 clicked and user sent to "+ url_value );
                    gtag('event', `${stream_name}_logo1_click`, {
                        "destination_url": url_value
                    });
                });
                $( "#link_2_" + camera['uid']).click(function() {
                    var url_value = $(this).attr("href");
                    console.log( "Logo2 clicked and user sent to "+ url_value );
                    gtag('event', `${stream_name}_logo2_click`, {
                        "destination_url": url_value
                    });
                });
            }

            // open timelapses box when timelapse ends
            player.on('ended', function(e) {
                if (window.camera.playingTimelapse) {
                    toggleTimelapses("show");
                } else if (window.camera.playingRecording) {
                    toggleRecordings("show");
                }
            });

        })(window, window.videojs);

        $(".video-js").css("height", "100%").css("width", "100%");
        $("#" + myDiv).css("height", "100%").css("max-height", "100%").css("max-width", "100%");
        $("#" + camera['vuid']).css("max-height", "100%").css("max-width", "100%").css("display", "block");

        if (typeof center !== 'undefined') {
            $("#" + myDiv).children("div").first().css("margin", "0 auto");
            $("#" + myDiv).css("margin", "0 auto").css("display", "inline");
        }

        $("#" + myDiv).show();

        $("body").css("margin", "0px");

        if ((camera.listingTimelapses || camera.listingRecordings) && disabled == false && (restrict == false || allowed == true)) {
            // display control bar even if camera is offline so timelapses/recordings can still be played
            $(".vjs-control-bar").attr("style", "display: flex !important;");
        }
        $(".thumbnail-icon").click(function (event) {
        event.stopPropagation();
    });

    checkPlayStatus();
});

// toggle the timelapses overlay
function toggleTimelapses(hideShow = "") {
    if (hideShow !== "show" && (window.camera['showingTimelapses'] || hideShow == "hide")) {
        window.camera['showingTimelapses'] = false;
        player.trigger('hideTimelapses');
    } else {
        // now set timelapse overlay to showable (so it doesn't flash as visible on pageload)
        $(".vjs-vidsource-banner").css("display", "inline");
        if (!window.camera.offline) {
            if (camera["isLive"]) {
                $(".vjs-vidsource-live").hide();
            } else {
                $(".vjs-vidsource-live").show();
            }
        }

        // hide recordings overlay and show timelapses
        toggleRecordings("hide");
        window.camera['showingTimelapses'] = true;
        player.trigger('showTimelapses');
    }
}

// toggle the timelapses overlay
function toggleRecordings(hideShow = "") {
    if (hideShow !== "show" && (window.camera['showingRecordings'] || hideShow == "hide")) {
        window.camera['showingRecordings'] = false;
        player.trigger('hideRecordings');
    } else {
        // now set recording overlay to showable (so it doesn't flash as visible on pageload)
        $(".vjs-vidsource-banner").css("display", "inline");
        if (!window.camera.offline) {
            if (camera["isLive"]) {
                $(".vjs-vidsource-live").hide();
            } else {
                $(".vjs-vidsource-live").show();
            }
        }

        // hide timelapses overlay and show recordings
        toggleTimelapses("hide");
        window.camera['showingRecordings'] = true;
        player.trigger('showRecordings');
    }
}

function playVideo(element, stream_url, poster_url, filename = "", type) {
    toggleTimelapses("hide");
    toggleRecordings("hide");

    console.log(element);

    if (type == "live") {
        window.camera.isLive = true;
        window.camera.playingRecording = false;
        window.camera.playingTimelapse = false;
        if (!window.camera.offline) {
            $(".vjs-live-button").hide(); // hide button to switch back to live
        }
                    } else {
        window.camera.isLive = false;
        window.camera.playingRecording = (type == "recording");
        window.camera.playingTimelapse = (type == "timelapse");
        if (!window.camera.offline) {
            $(".vjs-live-button").show(); // show button to switch back to live
        }
                    }

    $(".vjs-vidsource-container").removeClass("vjs-vidsource-current");
    if (element) {
        element.classList.add("vjs-vidsource-current");
    }

    console.log("Playing " + (window.camera.isLive ? "livestrea" : (window.camera.playingTimelapse ? "timelapse" : (window.camera.playingRecording ? "recording" : "unknown"))) + ".");

    playVideoSrc(stream_url, poster_url);

    return false;
}

function playVideoSrc(stream_url, poster_url) {
    player.src({type: "application/x-mpegURL", src: stream_url});
    player.poster(poster_url);
    if (!window.camera.isLive) {
        player.currentTime(0);
    }
    player.play();
}

function copyEmbedLink(element) {
    navigator.clipboard.writeText(element.href).then(() => {
        let originalColor = $(element).parent().css("background-color");
        $(element).parent().animate({backgroundColor: "rgba(46, 139, 87, 0.4)"}, "fast", () => {
            setTimeout(() => {
                $(element).parent().animate({backgroundColor: originalColor}, "slow");
            }, 1000);
        });
    });

    return false;
}

function tryOndemandStream() {
    // check if the playlist exists
    camera.onDemandTries++;
    $.get(camera.url_rtsp, () => {
            // playlist exists, hide spinner and reload camera
            $(".vjs-error-display").removeClass("content-loader");
            $(".vjs-loading-spinner").css("display", "");
            $(`#${camera.vuid}`).removeClass("vjs-waiting");
            player.load();
        })
        .fail(() => {
            if (camera.onDemandTries <= 12) {
                // update to cheeky error message and do this again in five seconds
                $(".vjs-error-display").html($(".vjs-error-display").html().replace(camera.cheekyMessages[camera.onDemandTries - 1], camera.cheekyMessages[camera.onDemandTries]));
                setTimeout(() => {
                    tryOndemandStream();
                }, 5000);
            } else {
                // update to actual error message and hide spinner
                $(".vjs-error-display").html($(".vjs-error-display").html().replace(camera.cheekyMessages[camera.onDemandTries - 1], "The webcam that you are attempting to view appears to be offline. Please contact the owner of this camera and let them know about the issue."));
                $(".vjs-error-display").removeClass("content-loader");
                $(".vjs-loading-spinner").css("display", "");
                $(`#${camera.vuid}`).removeClass("vjs-waiting");

                            }
        });
}
