Source: site.view [edit]
Function name: home2
Arguments:
Description:
Page type: html
Render function:  
Module: sportstreak

Page source:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sports Streak</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            font-family: Arial, sans-serif;
            display: flex;
            flex-direction: column; /* stack items vertically */
            justify-content: center; /* Center horizontally */
            align-items: center; /* Center vertically */
            height: 100vh;
            background: #000; /* fallback color */
        }
        .main-container {
            display: flex;
            flex-direction: column; /* stack items vertically */
            align-items: center; /* Center items horizontally */
        }
        .background-wrapper {
            width: 400px; /* fixed width for the background image */
            height: 800px; /* fixed height of the background image */
            background: url('/images/ss-instructions.jpg') no-repeat top center;
            background-size: cover;
            position: relative;
            margin-bottom: 20px; /* space between background and download buttons */
        }
        .container {
            text-align: center;
            width: 80%;
            max-width: 300px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            margin-top: 0px; /* initial margin-top value */
        }
        .play-button {
            background: #FFD700;
            border: none;
            border-radius: 50px; /* significantly rounded corners */
            padding: 36px 100px; /* larger padding */
            font-size: 36px; /* larger font size */
            font-weight: bold; /* make the font bold */
            cursor: pointer;
            margin-bottom: 20px;
            display: none;
        }
        .image-container-wrapper {
            display: none; /* initially hide the wrapper */
        }
        .image-container {
            width: 130px;
            height: 185px;
            top: 130px;
            background-color: #fff; /* for visualization */
            border: 1px solid #000;
            display: inline-block;
            position: absolute;
            cursor: pointer; /* Make the container look clickable */
        }
        #img-player1 {
            left: 30px; /* position 30px from the left */
            top: 525px;
            display: none;
        }
        #img-player2 {
            right: 30px; /* position 30px from the right */
            top: 525px;
            display: none;
        }
        .label {
            display: none;
            margin-top: 5px;
            font-weight: bold;
            color: #FFF;           
        }
        .question {
            font-size: 24px;
            margin-bottom: 120px;
            position: absolute;
            width: 100%;
            color: #FFF;
            top: 0px; /* move the question to the same position as the play button */
        }
        .scores {
            position: absolute;
            top: 290px; /* initial position from the top */
            font-size: 48px; /* bigger font size */
            background: #fff; /* white background */
            color: #000; /* black font color */
            border-radius: 5px;
        }
        #today {
            left: 18px; /* position from the left */
            padding: 5px 10px; /* reduced vertical padding */
        }
        #total {
            right: 18px; /* position from the right */
            padding: 5px 10px; /* reduced vertical padding */
        }
        #timer {
            left: 170px; /* position from the right */
            font-weight: bold;
            font-size: 64px;
            padding: 0px 10px; 
        }        
        .download-buttons {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
        }
        .download-buttons img {
            width: 120px;
            margin: 0 10px; /* space between the buttons */
        }
        .top-message, .bottom-message {
            position: absolute;
            width: 100%;
            text-align: center;
            font-size: 30px; /* large text size */
            color: #FFF; /* white text color */
            display: none;
            padding: 0 20px; /* horizontal padding for bigger spacing */
            box-sizing: border-box;
        }
        .top-message {
            top: 250px; /* position 200px from the top */
        }
        .bottom-message {
            top: 450px; /* position 600px from the top */
        }
        .hidden {
           display: none;
        }

        #videoPane {
           position: fixed;
           top: 50%;
           left: 50%;
           transform: translate(-50%, -50%);
           background-color: rgba(0, 0, 0, 0.8);
           padding: 20px;
           border-radius: 10px;
           z-index: 1000;
        }
    </style>
</head>
<body onload="onLoad()">
    <script src="https://cdn.jsdelivr.net/npm/annyang@2.6.1/dist/annyang.min.js"></script>
 
    <div class="main-container">
        <div class="background-wrapper" id="background-wrapper">
            <div class="container" id="main-container">
                <button class="play-button" id="play-button" style="position: absolute; left: 4px; top: 5px;" onclick="switchBackground('game','true')">PLAY</button>
                <button class="play-button" id="share-button" style="position: absolute; left: 4px; top: 190px;" onclick="share()">SHARE</button>
                <button class="play-button" id="next-button" style="position: absolute; left: 4px; top: 225px; padding: 0px 100px;" >NEXT</button>
                <div class="image-container-wrapper" id="image-container-wrapper">
                    <div class="question" id="question">WHO IS YOUR FAVORITE PLAYER</div>
                </div>
            </div>
            <div class="image-container" id="img-player1" onclick="playerClicked('1')"></div>
            <div class="image-container" id="img-player2" onclick="playerClicked('2')"></div>
            <div class="label" id="p1Name" style="position: absolute; left: 30px; top: 740px;">Player 1</div>
            <div class="label" id="p2Name" style="position: absolute; right: 30px; top: 740px;">Player 2</div>
            <div id="today" class="scores">0 0</div>
            <div id="timer" class="scores">1 0</div>
            <div id="total" class="scores">0 0</div>

            <div id="videoPane" class="hidden">
                  <video id="video" width="600" controls>
                      <source id="videoSource" src="/images/swish.mp4" type="video/mp4">
                      Your browser does not support the video tag.
                  </video>
            </div>
            <div class="top-message" id="topmsg">Top</div>
            <div class="bottom-message" id="bottommsg">Bottom</div>
        </div>
        <div class="download-buttons">
            <a href="#"><img src="/images/google-button.png" alt="Google Play" onclick="clearToday()"></a>
            <a href="#"><img src="/images/apple-button.png" alt="App Store"></a>
        </div>
    </div>

    <script>
        var round = 0;
        var total = 10;
        var whoWon = '';      
        var dt = '';
        var p1Name = '';
        var p2Name = '';
        var p1Stat = 0;
        var p2Stat = 0;
        var stat = '';
        var timeLeft = 10;
        var countdown;
        var currentListener = null;
        var ttsMsg = '';

        var today;
        var yesterday;
        var todayCookie;
        var yesterdayCookie;
        var sssession = "";

        const timerElement = document.getElementById('timer');
        const videoPane = document.getElementById('videoPane');
        const video = document.getElementById('video');
        const videoSource = document.getElementById('videoSource');


        const rightMessages = [
          "Right!",
          "Correct!",
          "Yup!",
          "Swish!",
          "Nailed it!"
        ];

       const wrongMessages = [
          "Bonk!",
          "Sorry.",
          "Fail.",
          "Airball!",
          "Oops!"
        ];

        // Function to get a random message from the array
        function getRandomMessage(messages) {
            const randomIndex = Math.floor(Math.random() * messages.length);
            return messages[randomIndex];
        }

        function tts(text) {
            const utterance = new SpeechSynthesisUtterance(text);
            utterance.lang = 'en-US';
            window.speechSynthesis.speak(utterance);
        }

        function getScoreString(num) {
           let ones = num % 10;
           let tens = Math.floor(num / 10);           
           tens = tens % 10;
           return tens + " " + ones;
        }

        // Function to get the value of a specific cookie by name
        // If none found, returns ""
        function getCookie(name) {
            let cookieArray = document.cookie.split(';');
            for(let i = 0; i < cookieArray.length; i++) {
                let cookie = cookieArray[i];
                while (cookie.charAt(0) == ' ') {
                    cookie = cookie.substring(1);
                }
                if (cookie.indexOf(name + '=') == 0) {
                    return cookie.substring(name.length + 1, cookie.length);
                }
            }
            return "";
        }

        // Function to set a cookie
        function setCookie(name, value, expiryDays) {
            let date = new Date();
            date.setTime(date.getTime() + (expiryDays*24*60*60*1000));
            let expires = "expires=" + date.toUTCString();
            document.cookie = name + "=" + value + ";" + expires + ";path=/";
        }

        function deleteCookie(name) {
           document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
        }

        // Return just the date, in format 12/31/2023
        function formatDate(date) {
           let year = date.getFullYear();
           let month = date.getMonth() + 1; // getMonth() is zero-indexed
           let day = date.getDate();
           return `${month.toString().padStart(2, '0')}/${day.toString().padStart(2, '0')}/${year}`;
        }


        function copyStringToClipboard(str) {
          // Create a new text area
          var textArea = document.createElement("textarea");
          textArea.value = str;

          // Make sure it's not visible
          textArea.style.position = 'fixed';
          textArea.style.left = '-9999px';
          textArea.style.top = '-9999px';

          document.body.appendChild(textArea);
          textArea.focus();
          textArea.select();

          var ret = true;

          // Copy the text
          try {
              document.execCommand('copy');
          } catch (err) {
              console.error('Unable to copy to clipboard', err);
              ret = false;
          }

          // Remove the text area
          document.body.removeChild(textArea);
          return ret;
        }

        // Copies the link to a clipboard to share
        function share() {
           let url = "http://sports-streak.com/dispatch-share.html?redirect=" + btoa('{ "round":' + round + ', "total": ' + total + ', "date": "' + today + '" }');
           if (copyStringToClipboard(url)) {
              alert("A link was copied to your clipboard that you can share with friends to show off your great score!");
           }
        }

        function updateScores() {       
           document.getElementById('today').textContent = getScoreString(round);
           document.getElementById('total').textContent = getScoreString(total);
        }

        function handleClick(wonRound) {
           if (wonRound) {
              switchBackground('game', 'false');
           }
           else {
             switchBackground('end', 'false');
           }
        }


        function showVideo(videoName) {

           // Change the source of the video
           videoSource.src = videoName; // Update this with the new video file path
    
          // Load the new video
          video.load();

           // Show the video pane
           videoPane.classList.remove('hidden');
    
           // Play the video
           video.play();

           // Add multiple event listeners for robustness
           const closeVideoPane = () => {
               videoPane.classList.add('hidden');
               video.currentTime = 0; // Reset video time
               if (ttsMsg != '') {
                  tts(ttsMsg);  
                  ttsMsg = '';
               }
           };       

           video.addEventListener('ended', closeVideoPane);
           video.addEventListener('pause', () => {
               if (video.currentTime === video.duration) {
                   closeVideoPane();
               }
           });

           // For iPhone specific handling, close the pane on 'timeupdate' if the video has ended
           video.addEventListener('timeupdate', () => {
               if (video.currentTime >= video.duration) {
                   closeVideoPane();
               }
           });      
        }
  
        async function nextQuestion() {
            updateScores();
            try {
                var url = 'https://sports-streak.com/site/api';
                if (dt != '') {
                   url = url + ":" + dt + "," + round
                }
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                const data = await response.json();
                console.log(data);
                document.getElementById('question').textContent = data.preQuestion + " " + data.stat + "?";
                document.getElementById('img-player1').innerHTML = "<img width='130' height='184' src='" + data.p1Image + "'>";
                document.getElementById('img-player2').innerHTML = "<img width='130' height='184' src='" + data.p2Image + "'>";
                document.getElementById('p1Name').innerHTML = data.p1Name;
                document.getElementById('p2Name').innerHTML = data.p2Name;
                whoWon = data.whoWon;
                dt = data.date;
                p1Name = data.p1Name;
                p2Name = data.p2Name;
                p1Stat = data.p1Stat;
                p2Stat = data.p2Stat;
                stat = data.stat;

                timeLeft = 10;
                countdown = setInterval(() => {
                   if (timeLeft <= 1) {
                      clearInterval(countdown);
                      timerElement.textContent = getScoreString(0);
                      handleClick(false);
                   } else {
                      if (timeLeft < 5)
                         timerElement.style.color = "#FF0000";
                      else 
                         timerElement.style.color = "#000000";
                      timeLeft--;
                      timerElement.textContent = getScoreString(timeLeft);
                   }
                }, 1000);

                // Process the data as needed
            } catch (error) {
                console.error('There has been a problem with your fetch operation:', error);
            }
        }

      function switchBackground(scene, wonRound) {
            // Remove the previous listener if it exists
            if (currentListener) {
                document.getElementById('question').removeEventListener('click', currentListener);
                document.getElementById('next-button').removeEventListener('click', currentListener);
                currentListener = null;
            }

            if (scene == "game") {
               document.getElementById('timer').style.display = 'block';
               document.getElementById('background-wrapper').style.backgroundImage = "url('http://sports-streak.com/images/ss-game.jpg')";
               document.getElementById('play-button').style.display = 'none';
               document.getElementById('share-button').style.display = 'none';
               document.getElementById('next-button').style.display = 'none';
               document.getElementById('img-player1').style.display = 'block';
               document.getElementById('img-player2').style.display = 'block';
               document.getElementById('p1Name').style.display = 'block';
               document.getElementById('p2Name').style.display = 'block';
               document.getElementById('today').style.top = '49px';
               document.getElementById('timer').style.top = '43px';
               document.getElementById('total').style.top = '49px';
               document.getElementById('image-container-wrapper').style.display = 'block';
               nextQuestion();
            }

            if (scene == "results") {
               clearInterval(countdown);
               if (wonRound) {
                  showVideo("/images/swish.mp4");
               } else {
                  showVideo("/images/clunk.mp4");
               }

               var msg = "";
               document.getElementById('background-wrapper').style.backgroundImage = "url('http://sports-streak.com/images/ss-results.jpg')";
               document.getElementById('question').style.display = 'none';  
               document.getElementById('share-button').style.display = 'none';
               document.getElementById('next-button').style.display = 'block';
               document.getElementById('question').style.cursor = 'pointer';
               if (wonRound) {
                  round = round + 1;
                  total = total + 1;
                  updateScores();
                  msg = getRandomMessage(rightMessages);

               } else {
                  if (timeLeft > 0)
                      msg = getRandomMessage(wrongMessages);
                  else
                      msg = "Time Expired.";

                  // remember today's score
                  setCookie("ss" + today, btoa('{ "round":' + round + ', "total": ' + total + " }"), 90);
               };       
               let stats = 
               ttsMsg = msg + " " + stat + ": " + p1Name + " " + p1Stat + ". " + p2Name + " " + p2Stat + ".";  

               document.getElementById('question').innerHTML = "<p>" + msg + "</p><p>" + stat + ":" + "</p>" + 
                  p1Name + ": " + p1Stat + "<br>" + p2Name + ": " + p2Stat;
               document.getElementById('question').style.display = 'block';
               document.getElementById('img-player1').style.display = 'none';
               document.getElementById('img-player2').style.display = 'none';
               document.getElementById('p1Name').style.display = 'none';
               document.getElementById('p2Name').style.display = 'none';
               // Define the new listener
               currentListener = function() {
                   handleClick(wonRound);
               };
               // Add the new listener
               document.getElementById('question').addEventListener('click', currentListener);
               document.getElementById('next-button').addEventListener('click', currentListener);
            }

            if (scene == "end") {
               document.getElementById('background-wrapper').style.backgroundImage = "url('http://sports-streak.com/images/ss-end.jpg')";
               document.getElementById('play-button').style.display = 'none';
               document.getElementById('share-button').style.display = 'block';
               document.getElementById('next-button').style.display = 'none';
               document.getElementById('img-player1').style.display = 'none';
               document.getElementById('img-player2').style.display = 'none';
               document.getElementById('p1Name').style.display = 'none';
               document.getElementById('p2Name').style.display = 'none';
               document.getElementById('today').style.top = '49px';
               document.getElementById('timer').style.top = '43px';
               document.getElementById('total').style.top = '49px';
               document.getElementById('image-container-wrapper').style.display = 'block';
               document.getElementById('question').style.display = 'none';  
               document.getElementById('topmsg').style.display = 'block';
               document.getElementById('bottommsg').style.display = 'block';
               document.getElementById('topmsg').innerHTML = "<p><p>Nailed a " + round + "-point streak today, soaring to a total of " + total + "!";
               document.getElementById('bottommsg').innerHTML = "Swing by tomorrow to up your game...";
            }
        }

        function playerClicked(player) {
            var won = (player == whoWon || whoWon == "0");
            switchBackground("results", won)
        }


        // Loads the cookies from today and yesterday.  If yesterday exists, starts total count from then.
        // If today already exists, don't allow playing game, just display a message.
        function onLoad() {
       
           round = 0;
           total = 0;

           sssession = getCookie("sssession");

           if (sssession != "") {
              fetchWebService("https://sports-streak.com/site/getSessionData:" + sssession).then(data => {
 
                 // Copy the user data to a global variable so other functions can easily access
                 gUData = JSON.parse(JSON.stringify(data));

                 if ('name' in data) {
                    document.getElementById("login").innerText = data.name;
                    console.log("Logged in: " + JSON.stringify(data));
                 } else {
                   console.log("Login not found: " + sssession);
                 }
              });
           }

           today = formatDate(new Date());   // as formatted string  eg 11/31/2023
           yesterday = formatDate(new Date(new Date().getTime() - 86400000));

           yesterdayCookie = getCookie("ss" + yesterday);
           if (yesterdayCookie != "")
              yesterdayCookie = JSON.parse( atob( yesterdayCookie ) );
           else {
              yesterdayCookie = {}
           }

           if ("total" in yesterdayCookie) {
              total = yesterdayCookie.total
           }

           todayCookie = getCookie("ss" + today);
           if (todayCookie != "")
              todayCookie = JSON.parse( atob( todayCookie ) );
           else {
              todayCookie = {}
           }

           console.log(todayCookie);


           // If we already played today, update screen but don't allow play
           /*
           if ("total" in todayCookie) {
              round = todayCookie.round;
              total = todayCookie.total;
              document.getElementById('share-button').style.top = '4px;';
              document.getElementById('share-button').style.display = 'block';
              updateScores();
              alert("On " + today + ", you got " + round + " questions right, bringing your total streak to " + total);

           } 
           else { */

              round = todayCookie.round;
              total = todayCookie.total;

              updateScores();
              document.getElementById('play-button').style.display = 'block';
              document.getElementById('timer').style.display = 'none';
           // }           
        }

    
        function clearToday() {
            today = formatDate(new Date());   // as formatted string  eg 11/31/2023
            deleteCookied("ss" + today);
            today = '';
        }

    </script>
</body>
</html>