<?php
//ini_set('display_errors', 'On');
require("/data/www/mmab/nwps/query_post_validation.php");
// nwpsloop.php
// Ray Ball
// WFO Mobile, Alabama
// ray.ball@noaa.gov
//
$startHour = 0;
$nwpsSiteNames = array(
	'BRO'=>'Brownsville, Texas',
	'CRP'=>'Corpus Christi, Texas',
	'HGX'=>'Houston/Galveston, Texas',
	'JAX'=>'Jacksonville, Florida',
	'KEY'=>'Key West, Florida',
	'LCH'=>'Lake Charles, Louisiana',
	'LIX'=>'New Orleans/Baton Rouge, Louisiana',
	'MFL'=>'Miami-South Florida, Florida',
	'MLB'=>'Melbourne, Florida',
	'MOB'=>'Mobile/Pensacola, Alabama/Florida',
	'NHC'=>'TAFB Atlantic',
	'SJU'=>'San Juan, Puerto Rico',
	'SRH'=>'Southern Region',
	'TAE'=>'Tallahassee, Florida',
	'TBW'=>'Tampa Bay, Florida',
        'CHS'=>'Charleston, South Carolina',
        'ILM'=>'Wilmington, North Carolina',
        'MHX'=>'Morehead City, North Carolina',
        'AKQ'=>'Wakefield, North Carolina',
        'LWX'=>'Baltimore Washington',
        'PHI'=>'Mt. Holly, Philadelphia',
        'OKX'=>'New York, New York',
        'BOX'=>'Boston/Taunton, MA',
        'GYX'=>'Gray/Portland, Maine',
        'CAR'=>'Caribou, Maine',
        'SEW'=>'Seattle, Washington',
        'PQR'=>'Portland, Oregon',
        'MFR'=>'Medford, Oregon',
        'EKA'=>'Eureka, California',
        'MTR'=>'Monterey, California',
        'LOX'=>'Los Angeles, California',
        'SGX'=>'San Diego, California',
        'HFO'=>'Hawaii',
        'GUM'=>'Guam',
        'AER'=>'Anchorage, Alaska',
        'ALU'=>'Anchorage-Aleutian Islands, Alaska',
        'AJK'=>'Juneau, Alaska',
        'AFG'=>'Fairbanks, Alaska',
        'GLW'=>'Great Lakes'
);
$nwpsSites = array_keys($nwpsSiteNames);

$nwpsLoopNames = array(
	'sigwaveheight'=>'Wave Height',
	'wind'=>'Wind Speed',
           'swell'=>'Swell',
	'waveperiod'=>'Wave Period',
	//'wavelength'=>'Wave Length',
	//'depth'=>'Ocean Depth',
	'cur'=>'Current',
	'wlev'=>'Tide+Surge',
	'erosion'=>'Dune Erosion',
	'owash'=>'Overwash',
	'rip'=>'Rip Currents',
	'systrk1'=>'Wave Systems',
);
$nwpsLoops = array_keys($nwpsLoopNames);

$addlLoopNames = array(
	'shiproute'=>'Transects'
);
$addlLoops = array_keys($addlLoopNames);

$mainPage = "https://polar.ncep.noaa.gov/nwps";
$images = "https://polar.ncep.noaa.gov/nwps/images";
$nwpsPageTitle = "NWPS - Nearshore Wave Prediction System";

function fileCount ($dir,$field,$startHour) {
	//$fieldModTime = filemtime($dir."/swan_".$field."_hr0".$startHour.".png");
	if($startHour < 12) {
		$fieldModTime = filemtime($dir."/swan_".$field."_hr00".$startHour.".png");
	}
	else {
		$fieldModTime = filemtime($dir."/swan_".$field."_hr0".$startHour.".png");
	}
	$currentTime = time();
	$runTimeDiff = $currentTime - $fieldModTime;
	$fieldPattern = $field."_hr\d\d\d\.png";
	$fileList = array();
	$numberList = array();
		if (is_dir($dir)) {
			if ($dh = opendir($dir)) {
				while (($file = readdir($dh)) !== false) {
					$fileModTime = filemtime("$dir/$file");
					preg_match ('/(\d\d\d)/',$file,$fileHour);
					$fileHourInt = intval($fileHour[0]);
					if ((preg_match("/$fieldPattern/",$file)) and 
                        ($fileModTime < ($fieldModTime + 1800)) and 
                        ($fileModTime > ($fieldModTime - 1800)) and 
                        ($fileHourInt >= $startHour)) {
							preg_match("/(\d\d\d)/",$file,$matches);
							array_push($numberList,$matches[0]);
							array_push($fileList,$file);
					}
				}
				closedir($dh);
			}
		}
	$frameCount = count($fileList);
	sort($numberList);
	$fileInterval = (($numberList[($frameCount-1)]-$numberList[0])/($frameCount-1));
	return array ($frameCount,$runTimeDiff,$fileInterval);
}
function initialImage ($frameCount,$nwpsImageDir,$loop,$startHour,$nwpsLoops,$site,$nwpsSites) {
	// Let's make certain that what is being asked for is in the site arrays
	$site = strtoupper($site);
	if (!in_array ($site,$nwpsSites)) {
		echo "<div align=\"center\" style=\"font-size: 16px;font-weight: bold;width: 802px; height: 504px\"><br>The requested site \"$site\" does not exist.</div>";
	}
	// Let's make certain that what is being asked for is in the loop arrays
	// else if ((!in_array ($loop,$nwpsLoops)) or (!in_array($loop,$shipRoutes))) {
		// echo "<div align=\"center\" style=\"font-size: 16px;font-weight: bold;width: 802px; height: 504px\"><br>The requested field does not exist.</div>";
	// }
	// Let's make certain the directory exists
	else if (!is_dir("/data/www/mmab".$nwpsImageDir)) {
		echo "<div align=\"center\" style=\"font-size:16px;font-weight: bold;width: 802px; height:504px\"><br>The requested domain does not exist.</div>";
	}
	// And, finally, let's make certain there are files in the directory
	else if ($frameCount > 0) {
		echo "<IMG SRC=\"/nwps/images/rtimages/mob/loading.gif\" NAME=\"animation\" border=\"1\" width=\"800\" height=\"503\"/>";
		echo "<script type=\"text/javascript\">preloadImages(images)</script>";
	}
	else {
		echo "<div align=\"center\" style=\"font-size: 16px;font-weight: bold;width: 802px; height: 504px\"><br>No Images Available</div>";
	}
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta name="DC.title" content="<?php print $nwpsPageTitle ?>" />
<meta name="DC.description" content="NOAA's National Weather Service" />
<meta http-equiv="REFRESH" content="600">
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE">
<meta http-equiv="PRAGMA" content="NO-CACHE">
<link href="https://polar.ncep.noaa.gov/nwps/css/default/secondary.css" title="nwsstyle" rel="stylesheet" type="text/css" media="all" />
<style type="text/css">
<!--
.style1 {
	font-size: 14px
}
.style2 {
	font-size: small;
	font-weight: bold;
}
body {
	font:		MessageBox;
	font:		Message-Box;
	
}
button {
	border-radius: 4px;
	border:1px solid #d6bcd6;
	height: 22px;
	background:linear-gradient(to bottom, #ededed 5%, #bab1ba 100%);

}
.input1 {
	width:				37px;
	text-align:			right;
	padding:			1px;
	margin-right:		5px;
	font-size: small;
	font-weight: bold;
	border-style:none;
}
input, select, button {
	vertical-align:		middle;
}
#normalfields {
	display:inline;
}
#shiproute {
	display:none;
}
#control-table {
	border-radius: 10px;
}

#button-round {
	border-radius: 20px;
}
#button-left {
	border-top-left-radius: 20px;
	border-bottom-left-radius: 20px;
}
#button-right {
	border-top-right-radius: 20px;
	border-bottom-right-radius: 20px;
}
#button-shiproute {
	height: auto;
	width: 120px;
}
-->
</style>
</head>
<!--
<body onLoad="window.focus()">
-->
<body onLoad="animate_f()">

<?php
date_default_timezone_set('UTC');
$lastmodified = date('j-M-Y g:i A T',getlastmod());

$_GET = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
// initialize variables
$site = "";
$loop = "";
$cg = "";

$siteinput = CleanQueryAsString($_GET["site"]);
$cginput = CleanQueryAsString($_GET["cg"]);
$loopinput = CleanQueryAsString($_GET["loop"]);

// Get the script's 'site' and 'loop' arguments
$site = strtoupper($siteinput);
$loop = ($loopinput);
$cg = (int)$cginput;

// If the input wasn't a number, default it to 1
if ($cg <= 0) {
    $cg = 1;
}

// Let's make certain that the argument variables are set
if ((!isset ($loop)) or ($loop == "")) {
	$loop = "sigwaveheight";
}
else if (!isset ($site)) {
	header ("Location: $mainPage");
}

if ((!isset ($cg)) or ($cg == "")) {
	$cg = "1";
}

$siteName = $nwpsSiteNames[$site];
$site = strtolower($site);
$siteUpper = strtoupper($site);
$nwpsImageDir = "/nwps/images/rtimages/$site/nwps/CG$cg";
list ($maxFrames,$howOldRun,$fileInterval) = fileCount ("/data/www/mmab$nwpsImageDir",$loop,$startHour);
$J = "i*FINT";
?>
<title><?php print $nwpsPageTitle ?></title>
<script type="text/JavaScript">
	onLoad="window.focus()" 
	siteId = "<?php echo $siteUpper; ?>";
	MAX_FRAMES=<?php echo $maxFrames; ?>;
	fileInterval=<?php echo $fileInterval; ?>;
	cg=<?php echo $cg; ?>;
	var frame = 0;
	var timeout_id = null;
	J = <?php echo $startHour; ?>;
	var images = new Array(MAX_FRAMES);
	for (var i = 0; i < MAX_FRAMES; i++) {
		images[i] = new Image();        
        if (J<12) {
          images[i].src = "<?php echo $nwpsImageDir ?>\/swan_<?php echo $loop ?>_hr00"+ J + ".png";
        }
        else {
          if (J<100) {
            images[i].src = "<?php echo $nwpsImageDir ?>\/swan_<?php echo $loop ?>_hr0"+ J + ".png";
          }
          else {
            images[i].src = "<?php echo $nwpsImageDir ?>\/swan_<?php echo $loop ?>_hr"+ J + ".png";
          } 
        }                
		J = J + fileInterval;
	}

  // Now get to the functions
function preloadImages(srcs) {
    if (!preloadImages.cache) {
        preloadImages.cache = [];
    }
    var img;
	var loadedImages = 0;
	function imageLoadPost(){
        loadedImages++
        if (loadedImages==srcs.length){
			document.animation.src = images[0].src;
        }
    }
    for (var i = 0; i < srcs.length; i++) {
        img = new Image();
        img.src = srcs[i].src;
        preloadImages.cache.push(img);
		img.onload=function(){
            imageLoadPost()
        }
        img.onerror=function(){
			imageLoadPost()
        }
    }
 }
 function animate_ff() {
  document.animation.src = images[frame].src;
  frame = (frame + 1) % MAX_FRAMES;
 if (frame==0) {
    if (timeout_id) clearTimeout(timeout_id);
    timeout_id = setTimeout("animate_ff()", 3000);
  }
 else{
    if (timeout_id) clearTimeout(timeout_id);
      timeout_id = setTimeout("animate_ff()", 150);
  }
 }

function animate_f() {
  document.animation.src = images[frame].src;
  frame = (frame + 1) % MAX_FRAMES;

 if (frame==0) {
    if (timeout_id) clearTimeout(timeout_id);
    timeout_id = setTimeout("animate_f()", 3000);
 }
 else{
    if (timeout_id) clearTimeout(timeout_id);
      timeout_id = setTimeout("animate_f()", 700);
 }
}

function animate_fb() {
  frame = (frame - 1) % MAX_FRAMES;
  if (frame < 0) frame += MAX_FRAMES;
  document.animation.src = images[frame].src;
  if (frame==0) {
    if (timeout_id) clearTimeout(timeout_id);
    timeout_id = setTimeout("animate_fb()", 3000);
 }
 else{
    if (timeout_id) clearTimeout(timeout_id);
      timeout_id = setTimeout("animate_fb()", 150);
 }
}

function animate_b() {
  frame = (frame - 1) % MAX_FRAMES;
  if (frame < 0) frame += MAX_FRAMES;
  document.animation.src = images[frame].src;
  if (frame==0) {
    if (timeout_id) clearTimeout(timeout_id);
    timeout_id = setTimeout("animate_b()", 3000);
 }
 else{
    if (timeout_id) clearTimeout(timeout_id);
      timeout_id = setTimeout("animate_b()", 350);
 }
}

function step_loop(size) {
  frame = (frame + size) % MAX_FRAMES;
  if (frame < 0) frame += MAX_FRAMES;
  document.animation.src = images[frame].src;
}
function current(){
  frame = MAX_FRAMES-1;
  document.animation.src = images[frame].src;
}

function setImageSize() {
	if (screen.width > 1280) {
		var imageWidth = 1024;
		var imageHeight = 768;
	}
	else {
		//var imageWidth = 800;
		//var imageHeight = 600;
		var imageWidth = 800;
		var imageHeight = 503;
	}
	document.write ("width="+imageWidth+" height="+imageHeight);
}

function nwpsLoop(loop) {
	var url = "/nwps/nwpsloop.php?site="+siteId+"&loop="+loop+"&cg="+cg;
	window.location.href = url;
}

function routeButtons() {
	normalfields.style.display = "none";
	shiproute.style.display = "inline";
}

function fieldButtons() {
	normalfields.style.display = "inline";
	shiproute.style.display = "none";
}
</script>
</head>
<body>
<div style="padding:10px;">
<table border="0" cellspacing="0" cellpadding="2" width="970" id="control-table" style="background-color:#e1e1e1;border:1px solid darkgray" >
  <tbody>
	<tr>
		<td><div align="center" style="font-size: 18px;font-weight: bold;position: relative"><?php print "$siteName"; ?></div></td>
		<td>&nbsp;</td>
	</tr>
    <tr>
      <td valign="top">
        <!--      
        <div id="loop" style="width:800px;height:503px;padding-left:10px;"><?php initialImage($maxFrames,$nwpsImageDir,$loop,$startHour,$nwpsLoops,$site,$nwpsSites); ?></div>
        -->
        <div id="loop" style="width:800px;height:503px;padding-left:10px;"><?php initialImage($maxFrames,$nwpsImageDir,$loop,0,$nwpsLoops,$site,$nwpsSites); ?></div>
		<div class="style1" align="center" style="padding:3px;"><a href="https://polar.ncep.noaa.gov/nwps" target="_blank">Project Details</a> &bull; <a href="https://products.weather.gov/PDD/GulfStreamForecast.pdf" target="_blank">Product Description</a> &bull; <a href="https://www.surveymonkey.com/r/Gulf_Stream" target="_blank">Survey</a></div>
		</td>
      <td valign="top" align="center">
	  
        <div id="normalfields">
		<table border="0" cellspacing="0" cellpadding="2" width="155">		
		<?php
		foreach ($nwpsLoops as $loopField) { 
			echo "<tr>";
			echo "<td align=\"center\"><button style=\"width:120px;\" onClick=\"nwpsLoop('$loopField')\" />";
			echo "$nwpsLoopNames[$loopField]";
			echo "</button></td>";
			echo "</tr>";
		}
		foreach ($addlLoops as $addlField) {
			if (file_exists($siteUpper."_".$addlField.".inc")) {
				include($siteUpper."_shiproute.inc");
				echo "<tr>";
				echo "<td align=\"center\"><button style=\"width:120px;\" onClick=\"routeButtons()\" />";
				echo "$addlLoopNames[$addlField]";
				echo "</button></td>";
				echo "</tr>";
			}
			
		}			
		?>
		          <tr>
            <td>&nbsp;</td>
          </tr>
        </table>
		</div>
		
		<div id="shiproute">
		<table border="0" cellspacing="0" cellpadding="2" width="155">
		<?php
		if (in_array($loop,$shipRoutes)) {
			echo "<script>routeButtons()</script>";
		}
		foreach ($shipRoutes as $routeField) { 
			echo "<tr>";
			echo "<td align=\"center\"><button id=\"button-shiproute\" onClick=\"nwpsLoop('$routeField')\" />";
			echo "$shipRouteNames[$routeField]";
			echo "</button></td>";
			echo "</tr>";
		}
		echo "<tr>";
		echo "<td align=\"center\"><br><button style=\"width:75px;\" onClick=\"fieldButtons()\" />";
		echo "< Back";
		echo "</button><br><br></td>";
		echo "</tr>";
		?>

        </table>
		</div>
     
        <table id="control-table" border="0" cellspacing="0" cellpadding="2" width="150">
          <tbody>
            <tr>
              <td><div align="right">
                  <button title="Back up one frame" onClick="step_loop(-1)" id="button-left" />&lt Step</button>
                </div></td>
              <td><div align="left">
                  <button title="Advance forward one frame" onClick="step_loop(1)" id="button-right" />Step &gt;</button></div></td>
            </tr>
            <tr>
              <td><div align="right">
                  <button title="Loop backward slowly" onClick="animate_b()" id="button-left" /> &lt; </button>
                </div></td>
              <td><div align="left">
                  <button title="Loop forward slowly" onClick="animate_f()" id="button-right" /> &gt; </button>
                </div></td>
            </tr>
            <tr>
              <td><div align="right">
                  <button title="Loop backward quickly" onClick="animate_fb()" id="button-left" /> &lt;&lt; </button>
                </div></td>
              <td><div align="left">
                  <button title="Loop forward quickly" onClick="animate_ff()" id="button-right" /> &gt;&gt; </button>
                </div></td>
            </tr>
            <tr>
              <td colspan="2"><div align="center">
                  <button title="Most recent image" onClick="current()" id="button-round" />Current</button>
                </div></td>
            </tr>
            <tr>
              <td colspan="2"><div align="center">
                  <button title="Stop" onClick="if (timeout_id) clearTimeout(timeout_id); timeout_id = null; " id="button-rectangle" />Stop</button>
                </div></td>
            </tr>
          
          </tbody>
        </table>

                  <br><button style="width:120px;" onClick="self.close()">Close Window</button>
                </div><p><div align="center"><?php if ($howOldRun > 86400 && $maxFrames > 0) {echo "<b><font color=\"red\">Caution:<br>This run is over<br>24 hours old.<br><br>Please check<br>the dates on<br>the images.</font></b>";} ?></div></p>
		</td>
    </tr>
  </tbody>
</table>
</div>
</body>
</html>
