
    <!DOCTYPE html>
    <html>
       <head>
        
	<script src="js/jsani/lib/jquery-1.11.1.min.js"></script>
	<script src="js/jsani/lib/jquery-ui-1.11.2/jquery-ui.min.js"></script>
	<link href="js/jsani/lib/jquery-ui-1.11.2/jquery-ui.min.css" rel="stylesheet" type="text/css">
	<script src="js/jsani/jquery.jsani.min.js"></script>
        <link href="js/jsani/jquery.jsani.min.css" rel="stylesheet" type="text/css">

       </head>

<style type="text/css">
html, body {
  height: 100%;
  font-family: Arial, sans-serif;
}

#caminfo {
  height: 100%;
}

table {
  border-collapse: collapse;
  width: 100%;
  margin: 10px 0;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  border-radius: 8px;
  overflow: hidden;
  table-layout: fixed;
}

table, th, td {
  border: 1px solid #ddd;
  padding: 6px 10px;
  text-align: left;
}

th {
  background-color: #f2f2f2;
  font-weight: bold;
  color: #333;
  width: 25%;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}

tr:hover {
  background-color: #f5f5f5;
}

a {
  color: #0066cc;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}
</style>
<body>


<div style="display: flex; flex-direction: column; align-items: center; width: 100%;">
    <div style="width: 800px; margin-bottom: 20px;">
        <div id="caminfo">
            <table>
                <tbody id="camstats"></tbody>
            </table>
            <form onsubmit="return false;" method="post" name="gifit" style="margin-top: 10px;">
                <input type="submit" name="stopit" value="Stop Auto Refresh" onclick="stoptimer()"/>
            </form>
        </div>
    </div>
    
    <div style="width: 800px; margin: auto;">
        <div id="animation_1"></div>
    </div>
</div>

<div id="archive">
<label>Current archive length is 10 days</label>
 <form onsubmit="return false;" method="post" name="archive">
  <label for="archive">Enter Ending Date Time For Archive Data (YYYY-MM-DD HH:MM) UTC</label>
  <input type="text" id="dtg" name="dtg">
 <br>
<label for="frames">Enter Desired Number of Frames:</label>
  <input type="text" id="frames" name="frames" value="20" size="4">
  <input type="submit" name="submit" value="Submit" onclick="archiveshow()" />
  </form>
<br>

 <form onsubmit="return false;" method="post" name="gifit">
  <label for="gifit">Enter frame delay and last frame delay (ms) to make an animated gif from loaded frames (will take a couple seconds).</label>
  <br>

  <label for="delay">Delay</label>
  <input type="text" id="delay" name="delay" value="20" size="6">
  <label for="delay">Last Frame Delay</label>
  <input type="text" id="lastdelay" name="lastdelay" value="200" size="6">
 <label for="maxh">Constrain Horizonal Size</label>
  <input type="text" id="maxh" name="maxh" value="500" size="6">
 <label for="maxv">Constrain Vertical Size</label>
  <input type="text" id="maxv" name="maxv" value="400" size="6">
 <label for="delay">Last Frame Delay</label>
  <input type="submit" name="gifit" value="Make GIF" onclick="makemp4()"/>
  </form>



  

</div>


<script>

<?php 

$camid = pg_escape_string($_GET['camid']);
echo('var camid = ' . $_GET["camid"] . ';'); 
if($_GET['dtg'] ?? null){
$endtime = pg_escape_string($_GET['dtg']);
}
if($_GET['camimages'] ?? null){
$camimages = $_GET['camimages'];
echo('var camimages = ' . $_GET["camimages"] . ';'); 
}
if(!$_GET['camimages'] ?? null){
echo('var camimages = ' . 20 . ';'); 
}




if($_GET['dtg'] ?? null){
echo('var camtime = ' . json_encode($_GET["dtg"]). ';'); 
}





?>

externalcam = [];


function archiveshow() {
    archive = document.getElementById("dtg").value;
    archive=archive.trim().replace(/ /g, '+');
    altframes = document.getElementById("frames").value;
    camimages = altframes;
    window.open("one.php?camid=" + camid + "&camimages=" + camimages + "&dtg=" + archive);
}




function doTheInsert(label1, value1, label2, value2) {
  var newRow = document.createElement('tr');
  newRow.innerHTML = '<th>' + label1 + '</th><td>' + value1 + '</td><th>' + label2 + '</th><td>' + value2 + '</td>';
  document.getElementById('camstats').appendChild(newRow);
}

function updatetable() {
  $.getJSON("main.php?service=single&camid=" + camid, function(caminfo){
    document.getElementById('camstats').innerHTML = '';
    
  
    // Add header row
    var headerRow = document.createElement('tr');
    headerRow.innerHTML = '<th colspan="4" style="text-align: center; background-color: #e0e0e0; font-size: 1.2em;">Camera Information</th>';
    document.getElementById('camstats').appendChild(headerRow);
    
    doTheInsert('State', caminfo[0]['state'], 'County', caminfo[0]['county']);
    doTheInsert('Public Zone', caminfo[0]['pzone'], 'CWA', caminfo[0]['cwa']);
    doTheInsert('Elevation', caminfo[0]['elevation'] + ' feet', 'Direct link to feed', '<a href="' + caminfo[0]['url'] + '" target="_blank">View Feed</a>');
    
    // Helper function to format permission value
    function formatPermission(perm) {
        if (perm === 't') return 'Yes';
        if (perm === 'f') return 'No';
        return 'Unsure';
    }
    
    if (caminfo[0]['source'] == null) {
      doTheInsert('Source for sharing', 'none', 'Permission to share', formatPermission(caminfo[0]['permission']));
    } else {
      doTheInsert('Source for sharing', '<a href="' + caminfo[0]['source'] + '" target="_blank">Source Link</a>', 'Permission to share', formatPermission(caminfo[0]['permission']));
    }
    
    doTheInsert('Description', '<a href="' + googleMap(caminfo[0]['lat'], caminfo[0]['lon']) + '" target="_blank">' + caminfo[0]['description'] + '</a>', '', '');
    
    // Add hydro status row
    // Handle cases where hydro might not be in the response
    var hydroValue = (caminfo[0].hasOwnProperty('hydro') && caminfo[0]['hydro'] !== null) ? caminfo[0]['hydro'] : false;
    // Convert to display string
    var hydroDisplay = hydroValue ? 'Yes' : 'No';
    // For passing to toggle function, we need to ensure it's in a consistent format
    var hydroPassValue = hydroValue;
    var hydroButton = '<button onclick="toggleHydro(\'' + camid + '\', ' + hydroPassValue + ')">Toggle Hydro Status</button>';
    doTheInsert('Hydro', hydroDisplay + ' ' + hydroButton, '', '');
    
    // Add airport status row
    // Handle cases where airport might not be in the response
    var airportValue = (caminfo[0].hasOwnProperty('airport') && caminfo[0]['airport'] !== null) ? caminfo[0]['airport'] : false;
    // Convert to display string
    var airportDisplay = airportValue ? 'Yes' : 'No';
    // For passing to toggle function, we need to ensure it's in a consistent format
    var airportPassValue = airportValue;
    var airportButton = '<button onclick="toggleAirport(\'' + camid + '\', ' + airportPassValue + ')">Toggle Airport Status</button>';
    doTheInsert('Airport', airportDisplay + ' ' + airportButton, '', '');
    
    document.title = 'Cam: ' + caminfo[0]['description'];
  });
}

function googleMap(lat, lon){
        return "http://maps.google.com/maps?t=k&q=loc:" + lat + "+" + lon + "&basemap=satellite";
}




function getcam() {
if (typeof camtime !== 'undefined') {
    var reqstring = "main.php?service=individualcam&camid=" + camid + '&camimages=' + camimages + '&dtg=' + camtime;
    
} else {
    var reqstring = "main.php?service=individualcam&camid=" + camid + '&camimages=' + camimages;
    
}

//$.getJSON("main.php?service=individualcam&camid=" + camid + '&camimages=' + camimages, function(data){
$.getJSON(reqstring, function(data){    
 var camlist = [];
 var filetimes = [];

 for(var i in data){
  camlist.push(data[i].filepath);
  filetimes.push('<a href="./camdata/' + data[i].filepath + '">Pause Loop and click this to view image directly</a>      ' + 'Image Retrieved: ' + data[i].dateutc + ' UTC');
  externalcam.push("./camdata/" + data[i].filepath);
  }
camlist.reverse();
filetimes.reverse();
externalcam.reverse();
var animation = $("#animation_1").jsani({
                                baseDir: './camdata',
                                imageSrcs: camlist,
                                aniWidth: 800,
                                aniHeight: 600,
                                //initdwell: 200,
				frameLabels: filetimes,
                                controls: ['framelabel', 'stopplay', 'firstframe', 'previous', 'next', 'lastframe', 'looprock', 'slow', 'fast'],
                                last_frame_pause: 8,
                                //first_frame_pause: 1,
                                //frame_pause: '0:5, 3:6'
                        });


updatetable();
});

}


getcam();

//    window.setInterval('refresh()', 60000); 	
    const myInterval = setInterval('refresh()', 60000);
    function refresh() {
        window.location.reload();
    }

function stoptimer() {
  clearInterval(myInterval);
}





function toggleHydro(camid, currentValue) {
    // Invert the boolean value
    var newValue = !currentValue;
    console.log('Toggling hydro for camid:', camid, 'from', currentValue, 'to', newValue);
    
    // Send AJAX request to update the hydro value
    $.ajax({
        type: "POST",
        url: 'main.php?service=update_field',
        data: {camid: camid, field: 'hydro', value: newValue},
        dataType: 'json',
        success: function(response) {
            console.log('Response:', response);
            if (response.success) {
                // Refresh the table to show updated value
                updatetable();
            } else {
                alert('Failed to update hydro status: ' + (response.message || 'Unknown error'));
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            alert('Error updating hydro status: ' + error);
        }
    });
}

function toggleAirport(camid, currentValue) {
    // Invert the boolean value
    var newValue = !currentValue;
    console.log('Toggling airport for camid:', camid, 'from', currentValue, 'to', newValue);
    
    // Send AJAX request to update the airport value
    $.ajax({
        type: "POST",
        url: 'main.php?service=update_field',
        data: {camid: camid, field: 'airport', value: newValue},
        dataType: 'json',
        success: function(response) {
            console.log('Response:', response);
            if (response.success) {
                // Refresh the table to show updated value
                updatetable();
            } else {
                alert('Failed to update airport status: ' + (response.message || 'Unknown error'));
            }
        },
        error: function(xhr, status, error) {
            console.log('AJAX Error:', status, error);
            alert('Error updating airport status: ' + error);
        }
    });
}

function makemp4() {
    var delay = document.getElementById("delay").value;
    var lastdelay = document.getElementById("lastdelay").value;
    var maxh = document.getElementById("maxh").value;
    var maxv = document.getElementById("maxv").value;
    $.ajax({
        type: "POST",
        url: 'main.php?service=mp4',
        data: {data: externalcam, images: camimages, delay: delay, lastdelay: lastdelay, maxh: maxh, maxv: maxv},
        success: function(data) {
            var giffy = document.createElement('img');
            giffy.src = `data:image/gif;base64,${data}`;
            var outputImg = document.createElement('a');
            outputImg.innerHTML = "Click here or on the image to save gif <br>";
            outputImg.appendChild(giffy);
            outputImg.href = giffy.src;
            outputImg.download = "loof.gif";
            giffy.href = giffy.src;
            giffy.download = "loop.gif";             
            outputImg.appendChild(giffy)
            document.body.appendChild(outputImg);
            //document.body.appendChild(giffy);
            //window.open('about:blank').document.body.appendChild(outputImg);
            //var OpenWindow = window.open('about:blank','_blank');
            //OpenWindow.document.body.appendChild(outputImg);
        }
    });





}







</script>

<div id='hidden' style="display: none;">
</div>


</body>
</html>
