<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Map</title>

<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<link href="https://api.mapbox.com/mapbox-gl-js/v3.9.4/mapbox-gl.css" rel="stylesheet">
<script src="https://api.mapbox.com/mapbox-gl-js/v3.9.4/mapbox-gl.js"></script>

  
<style>


@import url('https://fonts.googleapis.com/css?family=Lexend+Deca:300,400,600');
.font_lexend
{
	font-family: "Lexend Deca", sans-serif;
}


	
body { margin: 0; padding: 0;
font-family: "Lexend Deca", sans-serif;
    background-color: #17212c;
 }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
.div_row
{
	margin:5px; 
	vertical-align:middle;
}
.row_bold
{
	
	font-family: "Lexend Deca", sans-serif;
}
.row_capital
{
	text-transform: capitalize;
}
.row_lc
{
	text-transform: lowercase;
}
.rowlt a
{
	color: white !important;
}
.searchbar
{
	/*
	position:absolute;
	top:10px;
	right:10px;
	z-index:99999;
	*/
	margin-top: 10px;
	    vertical-align: middle;
}

#address
{
	border: none;
	box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
    padding: 9px;
    border-radius: 6px;
    margin-right: 6px;
    margin-top: 1px;
	font-size: 15px;
	min-width: 265px;
	    vertical-align: middle;
}

.filter-btn {
	box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
    background-color: #fff;
    border: none;
    padding: 7px;    
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    transition: background-color 0.2s;
	margin-top: 1px;
	    border-radius: 6px;
		    vertical-align: middle;
  }

  .filter-btn:hover {
    background-color: #eee;
  }

  .filter-btn svg {
    pointer-events: none;
  }
  
.ui-menu .ui-menu-item {
    font-size: 13px;
}

.leftbar
	{
		display:inline-block;
		
		padding:10px;
		text-align:left;
		width:200px;
		color:white;
		max-height:270px;
		overflow-y:auto;
		box-sizing: border-box;
		vertical-align: top;
		overflow-x: hidden;
		
		position:absolute;
		top:310px;
		left:10px;
		z-index:99999;
		
	}
	
	
.scroll::-webkit-scrollbar {
    width: 10px;
	overflow-x: hidden;
}

.scroll::-webkit-scrollbar-track {
    
	background-color:#eee;
    border-radius: 10px;
}

.scroll::-webkit-scrollbar-thumb {
	
	background-color:#89c64c;
    border-radius: 10px;
	border:1px solid rgba(0,0,0,0.2);
    -webkit-box-shadow: 0 0 6px rgba(0,0,0,0.2); 
}
.mypopup 
{
	width:500px;
	font-family: "Lexend Deca", sans-serif;
	color: #333;
}

.toplayer
{
	z-index:9999;
	position:absolute;
	top:50px;
	left:20px;
	background:#ffffff66;
	
	padding:10px;
	border-radius:10px;
}
.locname
{
	background:#ffffff77;
	color:#111;
	
	    background: #55555577;
    color: #ffffff;
	
	border-radius:10px;
	padding:5px;
	padding-left:9px;
	padding-right:9px;
	margin:5px;
	cursor:pointer;
}

#loadingbar
{
	position:absolute;
	z-index:999;
	padding:10px;
	top:50px;
	border-radius:10px;
	background-color: #ffffff66;
	color: black;
	 top: 50%;  
    left: 50%; 

    transform: translate(-50%, -50%);
}
.credits
{
	padding: 0 4px 0 4px; 
	color:#bbb !important; 
	background-color: #666;
	border-radius:6px;
}
.mapboxgl-ctrl-attrib
{
	font-size:11px;
}

.eventname
{
	font-size:12px;
}
.homebtn
{
	margin-top:15px;
	text-align:right;
	margin-right:5px;
}
.mybtn
{
	width:120px;
	text-align:center;
	background-color: white;
	    padding: 8px 19px;
	border-radius:8px;
	color: #3a345c !important;
	font-size: 14px;
	font-style: bold;
	    text-decoration: none;
	cursor:pointer;
}

.mybtnblue
{
	background-color: #0d434d;
	color: white !important;
	opacity:0.9;
}
#questionBox a
{
	background: #3DA7B0 !important;
    text-decoration: none !important;
    color: white !important;
    padding: 5px 14px;
    margin-top: 10px;
    display: block;
    width: fit-content;
    border-radius: 7px;
}
.jdpopup
	{
		
		padding:0px;
		padding-right:0px;
		text-align: left !important;
		background: #f29060;
		color:#272727;
		
		color:#ffffff;
		width:80%;
		
		max-height:90vh;
		display:none;
		z-index:999999;
		box-shadow: rgba(10, 10, 11, 0.2) 0px 7px 29px 0px;
		
		max-width: 400px;
		position: absolute;
		margin-left: auto;
		margin-right: auto;
		left: 0;
		right: 0;
		top: 95px;
		text-align: center;
		    
	}
	
	.jdpopup .close {
	  position: absolute;
	 top: 7px;
    right: 16px;
	  transition: all 200ms;
	  font-size: 30px;
	  font-weight: bold;
	  text-decoration: none;
	  color: #ccc;
	      padding-left: 5px;
		  cursor:pointer;
}
.jdpopup .close:hover {
  color: #06D85F;
}
.jdpopup_inner {
	max-height: 95%;
	text-align: left !important;
	line-height: 27px;
      min-height:80px;
	  padding: 0px;
	  text-align: center !important;
    text-transform: uppercase;
    font-size: 14px;
	    overflow-x: hidden;
}

.jdpopup_inner a
{
	color: #2b82cb;
	color:rgb(5,99, 193);
}

.popupinnercontent
{
	overflow-y: auto;
	max-height:400px;
	    padding: 20px;
}

.row_lbl
{
	display:inline-block;
	width:100px;
	
}
.row_val
{
	display:inline-block;
	
}
.dplogo
{
	max-width: 59px;
    position: absolute;
    top: 4px;
    left: 14px;
    z-index: 999;
    opacity: 0.8;
}
a.mapboxgl-ctrl-logo
{
	opacity: 0.6;
	scale: 0.9;
}

.divbg
{
	background-repeat: no-repeat;
	    height: 237px;
    width: 400px;
    background-size: cover;
}
.divlogo
{
	text-align:center;
	max-height: 122px;
	padding-top:5px;
}
.divlogo img
{
	max-height: 100px;
    max-width: 350px;
	padding-top: 4px;
    padding-bottom: 4px;
}
.pad8
{
	    padding-bottom: 8px;
    padding-top: 5px;
}

.popup_heading
{
	font-size: 19px;
    padding-top: 10px;
}

#backtohome
{
	display:none;
}

.div_filter
{
	text-align:right;
	    position: absolute;
     top: 67px;
    right: 3px;
    z-index: 9999;
	    background-color: #33333378;
    text-align: left;
    padding: 5px;
    border-radius: 6px;
    font-size: 13px;
    color: white;
	    max-height: 30vh;
    overflow-y: auto;
	    max-width: 224px;
}

#dd_month
{
	padding:6px;
	border-radius:7px;
	    margin-right: 5px;
		    min-width: 120px;
}

.div_filter label {
  display: block;
  margin-bottom: 2px;
  padding-left: 25px; /* adjust based on checkbox width */
  text-indent: -20px; /* pull first line back */
}

.div_filter input[type="checkbox"] {
  margin-left: -5px; /* pull checkbox back into visible space */
  margin-right: 5px;
}

.topbar {
    height: 65px;
    position: absolute;
    z-index: 99;
    top: 1px;
    width: 100%;
    margin-left: auto;
    margin-right: auto;
    left: 0;
    right: 0;
    text-align: center;
	
	 display: flex;
    justify-content: center; /* center horizontally */
    align-items: center;  
}

.backdrop-blur {
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
    background-color: hsla(0, 0%, 100%, .3);
    box-shadow: rgba(0, 0, 0, 0.16) 0px 1px 8px;
}

#ui-id-1
{
	max-height: 400px;
    overflow-y: auto;
	font-family: "Lexend Deca", sans-serif;
	    max-width: 300px;
    overflow-x: hidden;
}

#sector-legend
{
	opacity:0.9;
	position:absolute; bottom:18px; right:5px; background:#fff; padding:8px; font-size:12px; border-radius:5px;
}

.iconall
{
	width:36px;
	height:36px;
	background-size: 36px 36px;
	background-size: contain;
	background-repeat: no-repeat;
	background-position: center;
  cursor: pointer;
}




.detailsbtn
{
	margin-top:15px;
	background: #f29060;
	background: #3da7b0;
	color: black;
	padding:9px;
	border-radius: 7px;
	text-decoration:none;
}

.bottombar
{
	position:absolute;
	bottom:20px;
	left:14px;
	z-index:99;
}
.linkbtn
{
	background-color: #3da7b0;
	color: white;
	font-size:13px;
	padding:6px;
	border-radius:7px;
	text-decoration:none;
	
}

#quizContent
{
	
}
#questionHeader
{
	margin-bottom:40px; margin-top:15px; font-size:18px; font-weight:bold;
}


 #quizSidebar {
  position: absolute;
  top: 0;
  left: 0;
  width: 320px;
  height: 100%;
  background: #f29060;
  box-shadow: 2px 0 8px rgba(0,0,0,0.2);
  z-index: 999;
  display: flex;
  flex-direction: column;
  padding: 20px;
  transition: all 0.3s ease;
  overflow-y: auto;
      opacity: 0.9;
	      box-sizing: border-box;
}

#quizSidebar h2 {
  margin-top: 0;
}

#questionBox {
  font-size: 18px;
  font-weight: bold;
  margin: 15px 0;
}

#answerBox {
  font-size: 16px;
  color: #444;
  margin: 45px 0 45px 0;
}

#nextBtn {
  padding: 10px 18px;
  border: none;
  border-radius: 6px;
  background: #3da7b0;
  color: #fff;
  cursor: pointer;
}


.red-pin {
  width: 14px;
  height: 14px;
  background: red;
  border-radius: 50%;
  position: relative;
  border: 2px solid white;
  box-shadow: 0 0 3px rgba(0,0,0,0.4);
}

.red-pin::after {
  content: "";
  position: absolute;
  left: 50%;
  top: 100%;
  width: 2px;
  height: 12px;
  background: red;
  transform: translateX(-50%);
}


@media only screen and (max-width: 680px) {

	#questionHeader	
	{
		margin-bottom:8px; margin-top:8px; 
	}

	#answerBox {
	  font-size: 16px;
	  color: #444;
	  margin: 10px 0 20px 0;
	}

	.bottombar
	{
		position:absolute;
		bottom:20px;
		right:14px;
		left: unset;
	}
	
	.div_filter
	{
		height: 186px;
        overflow-y: auto;
		display:none;
	}
	.leftbar
	{
		
		width:180px;
		
		max-height: 200px;
        bottom: 45px;
        left: 1px;
        top: unset;
		
	}
	
	.searchbar
	{
		
		top:10px;
		right:5px;
	}

	#address
	{
		    min-width: 183px;
	}
	
	.divbg
	{
		height: 187px;
		width: 345px;
	}
	.divlogo
	{
		max-height: 102px;
		padding-top:5px;
		
	}
	.divlogo img
	{
		max-height: 80px;
		max-width: 300px;
	}
	.dplogo
	{
		display:none;
	}
	
	
	
  }
  


@media (max-width: 768px) {
  #quizSidebar {
    width: 100%;
    height: auto;
    box-shadow: 0 2px 6px rgba(0,0,0,0.15);
  }
}
 
  
</style>
</head>
<body>

<div id="quizSidebar">
  <div id="quizContent">
    <h2>StoryMapQuiz</h2>
	<div id="questionHeader" ></div>
    <div id="questionBox"></div>
    <div id="answerBox"></div>
    <button id="nextBtn" style="display:none;">Next</button>
  </div>
  
  <div class='bottombar'>
	<a class='linkbtn' href="https://docs.google.com/forms/d/e/1FAIpQLSeadpW2jghlVoCWxIOzU2q4lZNJKaLpStny9sFlb--2p4uXPg/viewform?usp=header" target="_blank">Feedback</a>
  </div>
</div>


	  <div id='jdpopup' class="jdpopup">
   <a class="close" onclick='hidePopup()'>&times;</a>
   <div class='jdpopup_inner' id="popupcontent">
	

	
   </div>

   </div>
	
<div id="map"></div>
<div id='loadingbar'>Loading data...</div>


 	
<div id="sector-legend"></div>

   <script src="https://cdn.jsdelivr.net/npm/jquery@2.2.4/dist/jquery.min.js"></script>


<script>
	
function hidePopup()
{
	
	document.getElementById('jdpopup').style.display = 'none';
}

	
const sectorColors = {};
const colorPalette = [
  '#FF5733', '#33B5FF', '#8E44AD', '#28B463', '#F1C40F',
  '#FF33A1', '#1ABC9C', '#E67E22', '#3498DB', '#E74C3C'
];
let colorIndex = 0;	
var markers_array = [];	

	mapboxgl.accessToken = "pk.eyJ1Ijoid2F5bmVqcGFya2VyIiwiYSI6ImNqNTRzbXBpcDA0ZjEzNGxpcHZucGowN3QifQ.d7-EZpzjcPOp8ErF_ObM0A";
var zoomLevel;	
	var coords_array = [37.0380, -121.91982];
	//var coords_array = [36.974385439343926, -122.01927009222906];
	coords_array.reverse();
	
	var filter_profile = [];
	var filter_sector = [];
var data_;


let quizQuestions = [];
let currentQuestion = 0;
let quizResults = [];
let quizActive = false;

    const map = new mapboxgl.Map({
        container: 'map',
        zoom: 12,
		minZoom: 3,
		center: coords_array,
        pitch: 29,
        bearing: 0,
       // style: 'mapbox://styles/mapbox/satellite-streets-v12',
        style: 'mapbox://styles/mapbox/streets-v12',
		projection: 'globe', 
		customAttribution:
    '<a style="padding: 0 2px 0 2px; color:#fff; background-color: #aaa;" target="_blank" href=https://www.mapjay.com/>MapJay.com</a>',
		
	
		
    });
	

	
map.on('style.load', () => {
	
	map.setFog({
        'color': 'rgb(186, 210, 235)', // Lower atmosphere
        'high-color': 'rgb(36, 92, 223)', // Upper atmosphere
        'horizon-blend': 0.02, // Atmosphere thickness (default 0.2 at low zooms)
        'space-color': 'rgb(11, 11, 25)', // Background color
        'star-intensity': 0.6 // Background star brightness (default 0.35 at low zoooms )
    });
	
map.addSource('mapbox-dem', {
'type': 'raster-dem',
'url': 'mapbox://mapbox.mapbox-terrain-dem-v1',
'tileSize': 512,
//'maxzoom': 8
});
// add the DEM source as a terrain layer with exaggerated height
map.setTerrain({ 'source': 'mapbox-dem', 'exaggeration': 2.1 });
});
	
	let show = false; //or true, etc.                   

// Add a circle 
map.on('load', () => {
  
  const miles = 20;
  const radiusInMeters = miles * 1609.34; // convert to meters

  // Add GeoJSON source as a single point
  map.addSource('circle-center', {
    type: 'geojson',
    data: {
      type: 'FeatureCollection',
      features: [{
        type: 'Feature',
        geometry: { type: 'Point', coordinates: coords_array }
      }]
    }
  });

  // Add the circle layer (outlined only)
  map.addLayer({
    id: 'circle-outline',
    type: 'circle',
    source: 'circle-center',
    paint: {
      'circle-radius': {
        stops: [
          [0, 0],
          [20, radiusInMeters / 0.075] // tweak factor keeps size consistent
        ],
        base: 2
      },
      'circle-color': 'rgba(0,0,0,0)', // no fill
      'circle-stroke-color': '#007AFF',
      'circle-stroke-width': 2
    }
  });
});
	
	

loadData();
	
function loadData()
{
	var rand = Math.floor(Math.random() * 100); //to append in csv for no cache.
	rand = 2;
	//$("#total_s").html("Loading....");
	jQuery.ajax({
		//url: "data.csv",   
		url: "https://docs.google.com/spreadsheets/d/e/2PACX-1vT4ceiU81GZJcpDi20qkjgQyVhhcka_AtTC-O4PHnrCXAqsXKUzE0BTWL6H4LhuUeMV4ZkygPley2J4/pub?gid=1302437318&single=true&output=csv",   
		async: false,
		success: function (csvd) {
			data_ = csvToArray(csvd);
		},
		dataType: "text",
		complete: function () {
			
				createMarkers();
				$("#loadingbar").hide();
				
				
				hideAllMarkers();
				prepareQuiz();
				
			}

			
		});	
}

function createMarkers()
{
	
			var pinHtml = "";
			
			var marker;					
				var counter = 0;
				var sidebar_elem = "";
				
				//Place Name	Story Title	address	latitude	longitude	actionUrl	date	icon (pending)	mapmeId		description	categories
				//0  Place Name
				//1  Story title
				//2 address
				//3 lat
				//4 lng
				//5 actionUrl
				//6 date
				//7 icon.
				
				for(var i=1; i<data_.length; i++) 
				{
						var icon_class_name = "iconall";
						var icon_sidebarclass_name = "iconall";
						iconImageURL = "";
						var iconfound = 0;		
						if(data_[i][7].trim() != "")
						{
							icon_class_name = "iconall icon_some";							
							iconImageURL = data_[i][7];
							iconfound = 1;
						}
						
						var pinHtml = "";	
						
					
						pinHtml += "<div class='popupinnercontent scroll'>";
						pinHtml += "<div><div class='popup_heading row_bold'>"+data_[i][0]+"<span class='popupicon'></span></div></div>";					
						
						if(data_[i][1] != '') 
						{
							pinHtml += "<div class='row'><div class='rowit row_bold rowlt'> "+data_[i][1]+"</div></div>";
						}
						if(data_[i][2] != '') 
						{
							pinHtml += "<div class='rowad'></div>";
							pinHtml += "<div class='row'><div class='rowlt row_capital'> "+data_[i][2]+"</div></div>";
						}
						
						if(data_[i][5] != '') 
						{
							pinHtml += "<div class='row'><div class='rowlt' style='margin-top: 10px;'><a class='detailsbtn' target='_blank' href='"+data_[i][5]+"'>Details</a></div></div>";
						}
						

						pinHtml += "</div>";
						
									
  
						latlng_array = [];
						
						if(data_[i][4] != '' && typeof data_[i][4] != 'undefined')
						{
							//latlng_array = data_[i][4].split(",");
							var lat = parseFloat(data_[i][3]);
							var lng = parseFloat(data_[i][4]);
							latlng_array = [lng, lat];
							//latlng_array.reverse();	
								//console.log(latlng_array);
								
								const popup = new mapboxgl.Popup({ offset: 10, className: 'mypopup', anchor: 'bottom', maxWidth: '350px', autoPan:true }).setHTML(pinHtml);
								//popup.setMaxWidth("400px");
								counter = i;

							
								el = document.createElement('div');
								 el.className =  icon_class_name;
								 el.style.backgroundImage = "url("+iconImageURL+")";
								 el.index = counter;
								 el.pinHtml = pinHtml;
							//	 el.innerHTML = counter;
								 el.latlng_array = latlng_array;
								 el.addEventListener('click', function(e){
									$('.mapboxgl-popup').remove();
									e.stopPropagation();
									map.setCenter(map.getCenter());
									
									ltlng = e.target.latlng_array;
									
									map.flyTo({
											
											center: ltlng, //e.target.latlng_array,
											offset: [2,15],
											//zoom: 12, 
											duration: zoom_duration, 											 
											essential: true 
										
										});
										
										setTimeout(function(){
											
													if (!popup.isOpen()) {
														//map.setCenter(map.getCenter());
														//popup.setLngLat(map.getCenter());
														popup.addTo(map);
														
													} else {
														popup.remove();
													}
											
												
										}, zoom_duration+5);
								  });
								
							var markerColor = "#f29060";
							
							
							if(iconfound)
							{
								marker1 = new mapboxgl.Marker(el);
							}
							else
							{
								
								marker1 = new mapboxgl.Marker({ "color": markerColor, "scale":"0.9" }) 
							//	marker1 = new mapboxgl.Marker({ "color": "#0d434d", "scale":"0.8" }) 
								//marker1 = new mapboxgl.Marker({  "scale":"0.9" }) 
							}
								
									marker1.setLngLat(latlng_array)									
									marker1.addTo(map);
									
								
								
								marker1.counter = counter;
								marker1.popup = popup;
								marker1.latlng_array = latlng_array;
								marker1.getElement().dataset.pinHtml = pinHtml; 
								marker1.pinHtml = pinHtml; 
								
								
								marker1.getElement().addEventListener('click', function(e){ 
									
										e.stopPropagation();
										$(".jdpopup").show();	
										$('#popupcontent').html(this.pinHtml);
										
										map.flyTo({
											center: this.latlng_array,
											zoom: Math.max(map.getZoom(), 11), // zoom in to at least 13, or keep current if closer
											speed: 1.2,                        // animation speed
											curve: 1.4,                         // animation curve
											essential: true
										  });
										//$("#backtohome").show();
									}.bind(marker1));
									
									
								markers_array.push(marker1);
							
						} //end filter if.
				
				}//end for loop
				
				


}



// hide all markers initially
function hideAllMarkers() {
  for (let i = 0; i < markers_array.length; i++) {
    markers_array[i].getElement().style.display = "none";
  }
}

// pick questions for today
function prepareQuiz() {
  const now = new Date();
  const mm = now.getMonth() + 1;       
  const dd = now.getDate();            
  const yy = String(now.getFullYear()).slice(-2);
  const yyyy = now.getFullYear();

  const todayShort = `${mm}/${dd}/${yy}`;   // e.g. 10/8/25
  const todayLong = `${mm}/${dd}/${yyyy}`;  // e.g. 10/8/2025

  console.log("Looking for:", todayShort, "or", todayLong); // debug check

  quizQuestions = data_.filter((row, index) => {
    if (index === 0) return false; // skip header

    let dateStr = row[6] ? row[6].toString().trim() : "";
    // normalize any quotes, spaces
    dateStr = dateStr.replace(/["']/g, "").trim();

    return (dateStr === todayShort || dateStr === todayLong);
  }).slice(0, 5);

  console.log("Matched questions:", quizQuestions.length);

  if (quizQuestions.length === 0) {
    document.getElementById("questionBox").innerHTML =
      `No questions available for today (${todayShort}).`;
    return;
  }

  quizActive = true;
  currentQuestion = 0;
  showQuestion();
}

function showQuestion() {
  if (currentQuestion >= quizQuestions.length) {
    showSummary();
    return;
  }

  const q = quizQuestions[currentQuestion];
  const place = q[0];
  const link = q[5]; //  5th index is the link column

  // update question header (static text)
  document.getElementById("questionHeader").innerHTML = "Find the following:";

  // clickable place name
  document.getElementById("questionBox").innerHTML = `
    Question ${currentQuestion + 1} of ${quizQuestions.length}:<br>
    <a href="${link}" target="_blank" style="font-weight:bold; color:#007AFF; text-decoration:none;">
      ${place}
    </a>
  `;

  document.getElementById("answerBox").innerHTML = "";
  document.getElementById("nextBtn").style.display = "none";
}



let tempMarker = null; // store temporary pin

map.on('click', function(e) {
  if (!quizActive) return;

  // Remove old temp marker if any
  if (tempMarker) {
    tempMarker.remove();
    tempMarker = null;
  }

  // Create custom red pin element
  const pinEl = document.createElement('div');
  pinEl.className = 'red-pin';

  // Create and add the marker
  tempMarker = new mapboxgl.Marker(pinEl)
    .setLngLat(e.lngLat)
    .addTo(map);

  // distance logic
  const q = quizQuestions[currentQuestion];
  const correctLat = parseFloat(q[3]);
  const correctLng = parseFloat(q[4]);
  const clickLat = e.lngLat.lat;
  const clickLng = e.lngLat.lng;

  const R = 3958.8;
  const dLat = (clickLat - correctLat) * Math.PI / 180;
  const dLon = (clickLng - correctLng) * Math.PI / 180;
  const a = Math.sin(dLat/2)**2 + Math.cos(correctLat * Math.PI/180) * Math.cos(clickLat * Math.PI/180) * Math.sin(dLon/2)**2;
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  const distance = R * c;

  const circleRadius = 20;
  let accuracyPercent = 0;
  if (distance <= circleRadius) {
    accuracyPercent = ((1 - (distance / circleRadius)) * 100).toFixed(0);
  }

  const accuracyText = `Accuracy: <strong>${accuracyPercent}%</strong>`;

  const marker = markers_array.find(m => {
    const pos = m.getLngLat();
    return Math.abs(pos.lat - correctLat) < 0.0001 && Math.abs(pos.lng - correctLng) < 0.0001;
  });
  if (marker) marker.getElement().style.display = "block";

  const result = distance.toFixed(1);
  quizResults.push({ place: q[0], distance: result, accuracy: accuracyPercent });
  document.getElementById("answerBox").innerHTML = `
    You were <strong>${result}</strong> miles away.<br>${accuracyText}
  `;
  document.getElementById("nextBtn").style.display = "inline-block";
});


// next button
document.getElementById("nextBtn").addEventListener('click', () => {
  // remove red pin when moving to next question
  if (tempMarker) {
    tempMarker.remove();
    tempMarker = null;
  }

  currentQuestion++;
  showQuestion();
});


function showSummary() {
  quizActive = false;
  let html = "<h3>Quiz Results</h3><ul>";
  quizResults.forEach(r => {
    html += `<li><strong>${r.place}</strong>: ${r.distance} miles away — Accuracy: ${r.accuracy}%</li>`;
  });
  html += "</ul>";
  document.getElementById("questionBox").innerHTML = html;
  document.getElementById("answerBox").innerHTML = "";
  document.getElementById("nextBtn").style.display = "none";
}





function isValidCoordinate(coord) {
  const regex = /^\s*-?\d+(\.\d+)?\s*,\s*-?\d+(\.\d+)?\s*$/;
  return regex.test(coord);
}




function csvToArray(text) {
    let p = '', row = [''], ret = [row], i = 0, r = 0, s = !0, l;
    for (l of text) {
        if ('"' === l) {
            if (s && l === p) row[i] += l;
            s = !s;
        } else if (',' === l && s) l = row[++i] = '';
        else if ('\n' === l && s) {
            if ('\r' === p) row[i] = row[i].slice(0, -1);
            row = ret[++r] = [l = '']; i = 0;
        } else row[i] += l;
        p = l;
    }
    return ret;
};	


function removeAllMarkers()
{
	for(var i=0; i<markers_array.length; i++)
	{
		markers_array[i].remove();
	}
	markers_array = [];
}

map.on('click', (e) => {
  console.log('Clicked coordinates:', e.lngLat);
  $(".jdpopup").hide();	
});


map.on('zoomend', function () {
   // myCallbackFunction();
});

map.once('moveend', function () {
    
   // myCallbackFunction(); // Call your function here
});

function myCallbackFunction() {
   zoomLevel = map.getZoom(); // Get current zoom level
   console.log("Zoom Level:", zoomLevel);

    if (zoomLevel >= 2.5 || zoomLevel < 1.9) {
     //   map.setLayoutProperty('my-layer', 'visibility', 'visible');  // Show layer
		$("#backtohome").show();
    } else {
     //   map.setLayoutProperty('my-layer', 'visibility', 'none');  // Hide layer
		$("#backtohome").hide();
    }
}
	
function resetMapZoom()
{
	map.flyTo({center:coords_array, zoom: 7, duration: 1000, essential: true});	
	$("#backtohome").hide();
}
function gotoloc( lat, lng)
{
	
	map.flyTo({center:[lng, lat], zoom: 5, duration: 1000, essential: true});	
	$("#backtohome").show();
}
function gotolocZoom( lat, lng, zoom)
{
	
	map.flyTo({center:[lng, lat], zoom: zoom, duration: 1000, essential: true});	
	$("#backtohome").show();
}
function gotoloc2( coords, zoom)
{
	coords.reverse();
	map.flyTo({center:coords, zoom: zoom, duration: 1000, essential: true});	
	$("#backtohome").show();
}
	
function gotothisloc( marker_counter)
{

	for(var i=0; i<markers_array.length; i++)
	{
		
		markers_array[i].popup.remove();
		if(markers_array[i].counter == marker_counter)
		{
			
			
			var thisloc = markers_array[i].getLngLat();
			map.flyTo({center:thisloc, zoom: 15, duration: 1000, essential: true});
			
			//markers_array[i].openPopup();
			
			$(".jdpopup").show();	
			$('#popupcontent').html(markers_array[i].pinHtml);
										
			markers_array[i].popup.addTo(map);
			
			
		}
		
	}

	
}

	
	
	
</script>

</body>
</html>