<?php
$title = "OceanCurrent";
ini_set('include_path', './' . PATH_SEPARATOR . '../' . PATH_SEPARATOR . ini_get('include_path'));

include_once("include/header.php");
$docroot = $_SERVER["DOCUMENT_ROOT"];

// Load up the product list and classes
//$pfiles = glob('.'.$BASEDIR.'product_classes/[0-9]*_*.php');
$pfiles = glob('./product_classes/[0-9]*_*.php');
$products = array();
$productnames = array();
foreach ($pfiles as $p) {
	//error_log('loading '.$p);
	require($p);
	$classnames = preg_split('/[0-9]+_(.*)\.php/', basename($p),-1,PREG_SPLIT_DELIM_CAPTURE);
	$classname = $classnames[1];
	if (new $classname() instanceof Product) {
		array_push($products, new $classname());
		array_push($productnames, $classname);
	}
}

function is_gif_file( $file )
{
	if ( substr($file,-4) === '.gif' ) return true;
	return false;
}

function is_fli_file( $file )
{
	if ( substr($file,-4) === '.fli' ) return true;
	return false;
}

function get_latest( $directory ) {
	return null;
	if ( !file_exists( $directory )) return null;
	if (true) {
		$files = glob($directory.'/[0-9]*.gif');
		if (count($files) <= 0) return null;
		return $files[count($files)-1];
	}
	else {
		$files = scandir( $directory );
		$files = array_filter( $files, 'is_gif_file' );
		if (count($files) <= 0) return null;
		$sfiles = sort($files);
		return $directory.'/'.$files[count($files)-1];
	}
}

function get_latest_fli( $directory ) {
	if ( !file_exists( $directory )) return null;
	$files = scandir( $directory );
	$files = array_filter( $files, 'is_fli_file' );
	if (count($files) <= 0) return null;
	$sfiles = sort($files);
	return $directory.'/'.$files[count($files)-1];
}

if (isset($_REQUEST['product'])) $_SESSION['product'] = $_REQUEST['product'];
if (isset($_REQUEST['region'])) $_SESSION['region'] = $_REQUEST['region'];
if (isset($_REQUEST['date'])) $_SESSION['date'] = $_REQUEST['date'];
if (isset($_REQUEST['rtype'])) $_SESSION['rtype'] = $_REQUEST['rtype'];

if (isset($_SESSION['product'])) $productname = $_SESSION['product'];
else {
	$productname = 'fourhour';
	if (isset($_SESSION['region'])) {
		$rx = $_SESSION['region'];
		if ($rx==='TasE'||$rx==='Coffs'||$rx==='Rottnest') $productname = 'snapshot';
		$limited6day = array("Fiji", "JBGulf", "RowleyAtolls", "ScottMore",
			"TopEnd", "SGoC", "Torres", "Solomon",
			"Vanuatu", "NewCal", "PNGSol");

		if (in_array($rx, $limited6day)) $productname = 'daily';
		$_SESSION['product'] = $productname;
	}
	if (isset($_SESSION['rtype'])) {
		$rt = $_SESSION['rtype'];
		if ($rt==='SR'||$rt==='AR') {
			$productname = 'daily';
			$_SESSION['product'] = $productname;
		}
	}
}
if (isset($_SESSION['rtype'])) $rtype = $_SESSION['rtype'];
else $rtype = 'DR';

// Force the SR and AR to daily products regardless of the original
if ($rtype==='SR'||$rtype==='AR') {
	if ((substr($productname,0,5) !== 'daily' ) 
			&& (substr($productname,0,11) !== 'climatology' ) 
			&& (substr($productname,0,11) !== 'oceancolour' )
			&& (substr($productname,0,4) !== 'gsla' )
			&& (substr($productname,0,4) !== 'ntsl' )
			&& (substr($productname,0,4) !== 'swot' )
		) {
		$productname = 'daily';
		$_SESSION['product'] = $productname;
	}
}
// Force DR oceancolour to CHL subproduct because it's an ugly mess of inconsistent directories
if (($rtype==='DR') && (substr($productname,0,11) === 'oceancolour' )) {
	$productname = 'oceancolour.CHL';
	$_SESSION['product'] = $productname;
}

if (isset($_SESSION['region'])) {
	$region = $_SESSION['region'];
	// Fix the productname so it sticks (needed for above hack to work)
	$_SESSION['product'] = $productname;
}
else $region = '';
if (isset($_SESSION['date'])) $date = $_SESSION['date'];
else $date = gmdate('YmdHis');

// Madeleine would like to show a background when the page first starts up
// so flag that we need to show the region dialog but fix a default region.
if (strlen($region) > 0) $show_region_dialog = 0;
else {
	$show_region_dialog = 1;
	// Set a default region just to show a background (hopefully)
	$region = 'SNSW';
}

$oproductname = $productname;

if (strpos($productname,'.')) {
	// Split product and subproduct
	$a = explode('.', $productname);
	$productname = $a[0];
	$subproductname = $a[1];
}

/*
echo "<code>";
print_r($_SESSION);
echo "</code>";
*/

if (!in_array($productname, $productnames)) {
	echo "<h2>Whoops - unknown product \"$productname\"</h2>\n";
	foreach($productnames as $p) {
		echo "<p>$p</p>\n";
	}
	return;
}

//error_log('date='.$date);

$product = new $productname();
if ($product instanceof SubProduct) {
	if (isset($subproductname)) {
		$product->setSubProduct($subproductname);
		$_SESSION['sp_'.$productname] = $subproductname;
	}
	elseif (isset($_SESSION['sp_'.$productname])) {
		$subproductname = $_SESSION['sp_'.$productname];
		$product->setSubProduct($subproductname);
	}
	else {
		$subproductname = $product->getSubProduct();
	}
}

if ($product instanceof RegionType) {
	$product->setRegionType($rtype);
}
// We also need to set the region type for all products if applicable
// so the region exists stuff will work and we can click on the buttons...
foreach ($products as $p) {
	if ($p instanceof RegionType) $p->setRegionType($rtype);
}
	

//error_log("rtype=$rtype");
//error_log("product=$productname");

// Convert date into DateTime object
$dt0 = DateTime::createFromFormat('YmdHis', $date);
//error_log('dto='.$dto->format('YmdHis'));
//echo "<code>".$dt0->format('YmdHis')."</code>\n";
$dto = $product->getNearestDate($region, $dt0);
//echo "<code>".$dto->format('YmdHis')."</code>\n";
if (!$product->isDateValid($region,$dt0)) $dto = null;

if (!is_null($dto)) {
	//echo "<code>".$dto->format('YmdHis')."</code>\n";
	//error_log('dto='.$dto->format('YmdHis'));

	$prev = $product->getPreviousDate($region, $dto);
	if (!is_null($prev)) {
		$prev = $prev->format('YmdHis');
		//error_log('prev='.$prev);
	}
	$next = $product->getNextDate($region, $dto);
	if (!is_null($next)) {
		$next = $next->format('YmdHis');
		//error_log('next='.$next);
	}
	$imgNameDate = $product->getDateString($dto);
	$imgfile = $product->getFilename($region, $dto);
}
else {
	$prev = null;
	$next = null;
	$imgNameDate = $product->getDateString($dt0);
	$imgfile = null;
}
function ds2d($d) {
	// php to js date splitter
	$y = substr($d,0,4);
	$m = substr($d,4,2);
	$d = substr($d,6,2);
	return "new Date($y,$m-1,$d)";
}

if ($product instanceof DateSelect) $dts = $product->getMinDate($region);
else if ($rtype == 'SR' || $rtype == 'AR') $dts = '20151001';
else $dts = "20040101";

$dte = date_create('now')->format('Ymd');
$dt = $dte;
if (!is_null($dto)) $dt = $dto->format('Ymd');

if (($product instanceof Map) && (!is_null($imgfile))) {
	$isize = getimagesize($imgfile);
	echo "<map id=\"tagmap\" name=\"tagmap\">\n";
	foreach($product->getMapList($region,$dto) as $m) {
		if (!$m instanceof MapRecord) {
			error_log('MapList returned non MapRecord');
		}
		else {
			$x = $m->x;
			$y = $isize[1]-$m->y;
			echo "\t<area shape=\"circle\" class=\"url\" coords=\"$x,$y,$m->circlesize\" href=\"#\" title=\"$m->title\" data-url=\"$m->url\">\n";
		}
	}
	echo "</map>\n";
}

// Sidebar: to show or not to show that is the question?
if (isset($_SESSION['sidebar'])) $show_sidebar = $_SESSION['sidebar'];
else $show_sidebar = true;

if (isset($_REQUEST['movie']) && $_REQUEST['movie']) $showmovie = true;
else $showmovie = false;

$ipermlink="product=$oproductname&region=$region&date=$date&rtype=$rtype";
$mpermlink=$ipermlink.'&movie=1';
if ($showmovie) $permlink = $mpermlink;
else $permlink = $ipermlink;


$imap1 = array(
	array("Fiji","Fiji",176.0,180.0,-20.0,-15.0,null),
	array("JBGulf","JBGulf",127.0,133.0,-15.6,-10.0,null),
	array("RowleyAtolls","RowleyAtolls",118.5,120.5,-18.5,-16.5,null),
	array("ScottMore","ScottMore",121.5,124.0,-14.5,-11.3,null),
	array("TopEnd","TopEnd",133,138,-13,-10,null),
	array("SGoC","SGoC",135.3,141.8,-18,-12.5,null),
	array("Torres","Torres",139.5,144.5,-13,-9,null),
	array("Solomon","Solomon",154,163,-12.5,-4.7,null),
	array("Vanuatu","Vanuatu",163,173,-21,-12,null),
	array("NewCal","NewCal",162.5,169.8,-24,-18,null),

	array("Forster", "Forster",150.8,155,-34.3,-31,null),
	array("TimorP","Timor Passage-Darwin",122.6,132.6,-14.5,-7.5,get_latest("TimorP")),
	//array("Broome","Broome",118.6,126.7,-20.1,-13.5,get_latest("Broome")),
	array("Bass","Bass Strait",143,151,-42,-37,get_latest("SST_4hr/SST/Bass")),
	array("Rowley","Rowley",116,124,-21,-14,get_latest("Rowley")),
	array("Kimberley","Kimberley",118.6,127,-18,-11.7,get_latest("Kimberley")),
	array("XmasI","Christmas Is.",100,110,-12,-5,get_latest("XmasI")),
	array("NWS","NW shelf",112,119,-23.5,-18,get_latest("NWS")),
	array("Ningaloo","Ningaloo",110,117,-27,-20,get_latest("Ningaloo")),
	array("Rottnest","Rottnest Is.",114.4,116.2,-33.1,-31.6,get_latest("Rottnest")),
	array("DonPer","Dongara-Perth",112,116.3,-33.1,-30.1,get_latest("DonPer")),
	array("Dongara","Dongara",111.3,115.6,-30.1,-27.1,get_latest("Dongara")),
	array("Perth","Perth",109.2,116.9,-34.8,-26,get_latest("Perth")),
	array("CLeeu","Cape Leeuwin",110,117.9,-38,-30.1,get_latest("CLeeu")),
	array("SAgulfs","SA gulfs",134,141.3,-39.5,-34.2,get_latest("SAgulfs")),
	array("EGAB","Eastern GAB",128.2,137.5,-36.9,-31.3,get_latest("EGAB")),
	array("RechEyre","Esperance-Eyre Pen.",124,136.5,-38.1,-31.3,get_latest("RechEyre")),
	array("Adelaide","Adelaide-Melbourne",135,147,-44,-33,get_latest("Adelaide")),
	array("Coffs","Coffs Harbour",152.6,154.9,-31.4,-29.6,get_latest("Coffs")),
	array("SNSW","Southern NSW",149.5,155.5,-37.4,-31.6,get_latest("SNSW")),
	array("Brisbane2","Brisbane",152,156,-29.5,-24.5,get_latest("Brisbane2")),
	array("Bris-Syd","Brisbane-Sydney",150.6,157.5,-34.4,-27,get_latest("Bris-Syd")),
	array("SGBR","Southern GBR",148.9,157,-26,-20,get_latest("SGBR")),
	array("CGBR","Central GBR",145,153,-21.2,-14.5,get_latest("CGBR")),
	array("NGBR","Northern GBR",141,151.5,-15.2,-7.5,get_latest("NGBR")),

	array("PNGSol","PNGSol",140,165,-14,0,null),

	array("Brisbane","Brisbane-Newcastle",151,159,-33,-23,get_latest("Brisbane")),
	array("LordHoweS","Lord Howe Is.-Sydney",150,161,-36,-29.8,get_latest("LordHoweS")),
	array("TasSE","Tasmania-SE",145.5,149,-44.6,-42,get_latest("SST_4hr/SST/TasSE")),
	array("TasE","Tasmania-east",144.5,153,-45.6,-40,get_latest("TasE")),
	array("Syd-Hob","Sydney-Hobart",147,156.5,-44,-33,get_latest("Syd-Hob")),
	array("Tas","Tasmania",141,152,-47,-40,get_latest("Tas")),
	array("AlbEsp","Albany-Esperance",114,125,-38.5,-33,get_latest("AlbEsp")),
	array("GoC","Gulf of Carpentaria",132,143,-18,-8,get_latest('SST_4hr/SST/GoC')),
	array("Indo","Indonesia",110,130,-13,-4,get_latest('SST_4hr/SST/Indo')),
	array("NingLeeu","Ningaloo-Cape Leeuwin",109.2-1.0,116.6,-34.5,-21,get_latest("SST_4hr/SST/NingLeeu")),
	array("NZNI","New Zealand North",170.0,180.0,-42.0,-33.0,get_latest("SST_4hr/SST/NZNI")),
	array("NZSI","New Zealand South",164.0,177.0,-48.0,-39.0,get_latest("SST_4hr/SST/NZSI"))
);

$imap2 = array(
	array("SE","South East",145,162.5,-45,-24.5,get_latest("STATE_daily/SST/SE")),
	array("SW","South West",101,125,-40,-20,get_latest("STATE_daily/SST/SW")),
	array("NE","North East",142,160,-27,-7,get_latest("STATE_daily/SST/NE")),
	array("NW","North West",101.1,132,-25,-5,get_latest("STATE_daily/SST/NW")),
	array("GAB","South",120,150,-46,-30,get_latest("STATE_daily/SST/GAB")),
	array("SO","Southern Ocean",130,155,-55,-35,get_latest("STATE_daily/SST/SO")),
	array("NZ","New Zealand",160,180,-50,-30,get_latest("STATE_daily/SST/NZ")),
	array("Au","Australia/NZ",100.5,179.5,-49.0,-5.5,get_latest("STATE_daily/SST/Au")),
);

$imap3 = array(
	array("Au","Australia/NZ",100.5,179.5,-49.5,-5.5,get_latest("STATE_daily/SST/Au")),
);

// SST_entry region is 100 -> 180, -50 -> -5
$xscale = 999.0/80.0;
$xoffset = -100.0;
$yscale = 625.0/-45.0;
$yoffset = 4.5;

?>
<map id="imap1" name="imap1">
	<?php
	for($i=0;$i<count($imap1);$i++) {
		$r = $imap1[$i];
		$x0 = intval(($r[2]+$xoffset)*$xscale);
		$y0 = intval(($r[4]+$yoffset)*$yscale);
		$x1 = intval(($r[3]+$xoffset)*$xscale);
		$y1 = intval(($r[5]+$yoffset)*$yscale);
		echo "<area shape=\"rect\" coords=\"$x0,$y0,$x1,$y1\" data-region=\"$r[0]\" data-href=\"$r[6]\" alt=\"$r[0]\" title=\"$r[1]\">\n";
	}
	?>
</map>
<map id="imap2" name="imap2">
	<?php
	for($i=0;$i<count($imap2);$i++) {
		$r = $imap2[$i];
		$x0 = intval(($r[2]+$xoffset)*$xscale);
		$y0 = intval(($r[4]+$yoffset)*$yscale);
		$x1 = intval(($r[3]+$xoffset)*$xscale);
		$y1 = intval(($r[5]+$yoffset)*$yscale);
		//echo "<area shape=\"rect\" coords=\"$x0,$y0,$x1,$y1\" data-region=\"$r[0]\" data-href=\"$r[6]\" alt=\"$r[0]\" title=\"$r[1]\" data-svg-class=\"mapify-invalid\" data-hover-class=\"bogushover\">\n";
		echo "<area shape=\"rect\" coords=\"$x0,$y0,$x1,$y1\" data-region=\"$r[0]\" data-href=\"$r[6]\" alt=\"$r[0]\" title=\"$r[1]\">\n";
	}
	?>
</map>
<map id="imap3" name="imap3">
	<?php
	for($i=0;$i<count($imap3);$i++) {
		$r = $imap3[$i];
		$x0 = intval(($r[2]+$xoffset)*$xscale);
		$y0 = intval(($r[4]+$yoffset)*$yscale);
		$x1 = intval(($r[3]+$xoffset)*$xscale);
		$y1 = intval(($r[5]+$yoffset)*$yscale);
		echo "<area shape=\"rect\" coords=\"$x0,$y0,$x1,$y1\" data-region=\"$r[0]\" data-href=\"$r[6]\" alt=\"$r[0]\" title=\"$r[1]\">\n";
	}
	?>
</map>

<div class="row">
	<?php if ($show_sidebar): ?>
	<div id="sidebar" class="col-md-2 panel">
	<?php else: ?>
	<div id="sidebar" class="hidden col-md-2 panel">
	<?php endif ?>
		<p><a id="rbutton" href="#" class="subdued-button btn btn-success btn-block" type="button">Select region</a></p>
		<div class="hidden-xs hidden-sm btn-group-vertical btn-block">
<?php
			foreach ($products as $p) {
				$name = $p->getLongName();
				$cls = "btn btn-block product-button";
				if ($name === $product->getLongName()) $cls = $cls.' btn-primary active';
				else {
					if (!$p->isRegionExists($region)) $cls = $cls.' disabled';
					elseif (!$p->isDateValid($region,$dt0)) $cls = $cls.' disabled';
					else $cls = $cls.' btn-info';
				}
				$pname = get_class($p);
				echo "<a type=\"button\" data-product=\"$pname\" class=\"$cls\">$name</a>\n";
			}
?>
		</div>
		<div class="visible-xs visible-sm form-group">
			<select id="product-select" class="form-control">
<?php
			foreach ($products as $p) {
				$name = $p->getLongName();
				$attr = "";
				if ($name === $product->getLongName()) $attr = 'selected';
				else {
					if (!$p->isRegionExists($region)) $attr = 'disabled';
					elseif (!$p->isDateValid($region,$dt0)) $attr = 'disabled';
					//else $cls = $cls.' btn-info';
				}
				$pname = get_class($p);
				echo "<option data-product=\"$pname\" $attr>$name</option>\n";
			}
?>
			</select>
		</div>
<?php
		if ($product instanceof DataLink) {
			echo "<p class=\"hidden-xs hidden-sm \"/>\n";
			echo "<div class=\"btn-group-vertical btn-block col-md-pull hidden-xs hidden-sm\">\n";
			echo "<h4>Data sources</h4>\n";
			foreach ($product->getDataLinks($region, $date) as $d => $datalink) {
				if (!is_null($datalink)) {
					echo "<a id=\"dbutton\" target=\"_blank\" href=\"$datalink\" class=\"subdued-button btn btn-success btn-block\" type=\"button\">$d</a>\n";
				} else {
					echo "<a id=\"dbutton\" href=\"#\" class=\"subdued-button disabled btn btn-success btn-block\" type=\"button\">$d</a>\n";
				}
			}
			echo "</div>\n";
		}
?>
<?php
		if ($product instanceof Legend) {
			echo "<div id=\"legend\" class=\"product-legend-panel panel panel-primary btn hidden-xs hidden-sm\">\n";
			//echo "<a href=\"#\" id=\"legend\">\n";
			echo "<h4 class=\"text-left\">Legend</h4>\n";
			echo "<dl class=\"dl-horizontal product-legend\">\n";
			foreach ($product->getLegend() as $k => $v) {
				echo "<dt>$k</dt><dd>$v</dd>\n";
			}
			echo "</dl>\n";
			//echo "</a>\n";
			echo "<h6><small>Click for more<br>information</small></h6>\n";
			echo "</div>\n";
		}
?>
	</div>
	<?php if ($show_sidebar): ?>
    <div id="content" class="col-md-10">
	<?php else: ?>
    <div id="content" class="col-md-12">
	<?php endif; ?>
		<!--<div id="xsidebar">&#171;</div>-->
		<nav class="navbar navbar-default mapNavbar hidden-xs hidden-sm" role="navigation">
			<div class="container-fluid">
				<ul class="pager pagerMargins">
					<li class="previous">
						<!--<button type="button" id="sidebarCollapse" class="btn btn-default" title="Sidebar">
							<span id="sidebarbutton" class="glyphicon glyphicon-chevron-left"></span>
						</button>
						-->
						<a id="sidebarCollapse" class="btn btn-default" title="Toggle sidebar">
							<?php if ($show_sidebar): ?>
							<span id="sidebarbutton" class="glyphicon glyphicon-chevron-left"></span>
							<?php else: ?>
							<span id="sidebarbutton" class="glyphicon glyphicon-chevron-right"></span>
							<?php endif; ?>
						</a>
					</li>
					<li class="previous">
                                <?php if (is_null( $prev )) {
                                        echo "<a class=\"disabled\" href=\"#\" alt=\"Previous\" title=\"Previous\">\n";
                                } else {
                                        echo "<a class=\"npbut\" href=\"#\" data-date=\"$prev\" alt=\"Previous\" title=\"Previous\">\n";
                                } ?>
                                        <span class="glyphicon glyphicon-step-backward" aria-hidden="true"></span>
                                </a>
					</li>
					<li class="previous">
						<span class=""><?php echo $imgNameDate ?>
							<input class="hidden" id="dsel" type="text"/>
							<?php if ($product instanceof DateSelector): ?>
							<button id="dsa" type="button" class="btn btn-default btn-xs" title="Calendar"><span class="glyphicon glyphicon-calendar"></span></button>
							<?php else: ?>
							<button id="ddsa" type="button" class="btn btn-default btn-xs" title="Calendar"><span class="glyphicon glyphicon-calendar"></span></button>
							<?php endif; ?>
							<button id="rsa" type="button" class="btn btn-default btn-xs rsa" title="Reset"><span class="glyphicon glyphicon-repeat"></span></button>
						</span>
					</li>
					<li class="previous">
                                <?php if (is_null( $next )) {
                                        echo "<a class=\"disabled\" href=\"#\" alt=\"Next\" title=\"Next\">\n";
                                } else {
                                        echo "<a class=\"npbut\" href=\"#\" data-date=\"$next\" alt=\"Next\" title=\"Next\">\n";
                                } ?>
                                        <span class="glyphicon glyphicon-step-forward" aria-hidden="true"></span>
                                </a>
					</li>
					<?php if ($product instanceof SubProduct): ?>
					<li class="previous">
						<small class="subproductMenu"><select class="cswitch btn btn-default btn-primary" data-toggle="popover">
						<?php
							$plist = $product->getList();
							foreach( $plist as $key => $val ) {
								$flags = '';
								if ($key===$subproductname)
									$flags = $flags.' selected';
								if (!is_null($dto)&&!$product->isValid($key, $region, $dto))
									$flags = $flags.' disabled';
								echo "<option value=\"$key\" $flags>$val</option>\n";
							}
						?>
						</select></small>
					</li>
					<?php endif; ?>
					<?php if ($product instanceof Movie): ?>
					<li class="previous">
						<?php 
							if ($product instanceof SubProduct) $mname = $subproductname.'.'.$region;
							else $mname = $region;
							if (is_null($dto)||!$product->isMovieValid($mname, $dto)) {
								echo "<a class=\"disabled\" href=\"#\" alt=\"Movie\" title=\"Movie\">\n";
							} else {
								$mfilename = $product->getMovieFilename($mname, $dto);
								echo "<a class=\"movie\" href=\"#\" data-filename=\"$mfilename\" alt=\"Movie\" title=\"Movie\">\n";
							}
						?>
							<span class="glyphicon glyphicon-film" aria-hidden="true"></span>
						</a>
					</li>
					<?php endif; ?>
					<?php if ($product instanceof Info): ?>
					<li class="previous">
						<a href="#" id="about" class="about" alt="about">
							<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>
						</a>
					</li>
					<?php endif; ?>
					<li class="previous" >
						<a id="permlink" type="button" class="btn btn-default" data-toggle="popover" data-placement="bottom" 
							title="Direct link to this graph" data-ilink="<?php echo $ipermlink ?>" data-mlink="<?php echo $mpermlink?>" data-real-content="<?php echo $permlink ?>">
							<small>
								<span class="glyphicon glyphicon-share" aria-hidden="true"></span> Permlink
							</small>
						</a>
					</li>

				</ul>
			</div>
		</nav>

		<div id="icontent" <?php if ($showmovie) echo "class=\"hidden\""; ?>>
<?php
		if (strlen($region)>0) {
			if (!is_null($imgfile)) {
				if ($product instanceof Map) {
					echo "<img class=\"img-responsive\" src=\"$imgfile\" usemap=\"#tagmap\">";
				}
				else {
					echo "<img class=\"img-responsive\" src=\"$imgfile\">";
				}
			}
			else {
				$s = $product->getDateString($dt0);
				echo "<h3>$s is not available for this product and/or region</h3>\n";
			}
		}
?>
		</div>
		<div id="mcontent">
			<?php if (!$showmovie): ?>
			<video class="hidden" id="videoplayer" controls>
				<source src="" type="video/mp4">
			</video>
			<?php else: ?>
			<video id="videoplayer" controls>
				<source src="<?php echo $product->getMovieFilename($mname, $dto)?>" type="video/mp4">
			</video>
			<?php endif; ?>
		</div>
		<nav class="navbar navbar-default mapNavbar visible-xs visible-sm" role="navigation">
			<div class="container-fluid">
				<ul class="pager pagerMargins">
					<li class="previous">
						<!--<button type="button" id="sidebarCollapse" class="btn btn-default" title="Sidebar">
							<span id="sidebarbutton" class="glyphicon glyphicon-chevron-left"></span>
						</button>
						-->
						<a id="sidebarCollapse-xs" class="btn btn-default" title="Toggle sidebar">
							<?php if ($show_sidebar): ?>
							<span id="sidebarbutton-xs" class="glyphicon glyphicon-chevron-left"></span>
							<?php else: ?>
							<span id="sidebarbutton-xs" class="glyphicon glyphicon-chevron-right"></span>
							<?php endif; ?>
						</a>
					</li>
					<li class="previous">
                                <?php if (is_null( $prev )) {
                                        echo "<a class=\"disabled\" href=\"#\" alt=\"Previous\" title=\"Previous\">\n";
                                } else {
                                        echo "<a class=\"npbut\" href=\"#\" data-date=\"$prev\" alt=\"Previous\" title=\"Previous\">\n";
                                } ?>
                                        <span class="glyphicon glyphicon-step-backward" aria-hidden="true"></span>
                                </a>
					</li>
					<li class="previous">
						<span class=""><?php echo $imgNameDate ?>
							<input class="hidden" id="dsel2" type="text"/>
							<?php if ($product instanceof DateSelector): ?>
							<button id="dsa2" type="button" class="btn btn-default btn-xs" title="Calendar"><span class="glyphicon glyphicon-calendar"></span></button>
							<?php else: ?>
							<button id="ddsa2" type="button" class="btn btn-default btn-xs" title="Calendar"><span class="glyphicon glyphicon-calendar"></span></button>
							<?php endif; ?>
							<button id="rsa2" type="button" class="rsa btn btn-default btn-xs" title="Reset"><span class="glyphicon glyphicon-repeat"></span></button>
						</span>
					</li>
					<li class="previous">
                                <?php if (is_null( $next )) {
                                        echo "<a class=\"disabled\" href=\"#\" alt=\"Next\" title=\"Next\">\n";
                                } else {
                                        echo "<a class=\"npbut\" href=\"#\" data-date=\"$next\" alt=\"Next\" title=\"Next\">\n";
                                } ?>
                                        <span class="glyphicon glyphicon-step-forward" aria-hidden="true"></span>
                                </a>
					</li>
					<?php if ($product instanceof SubProduct): ?>
					<li class="previous">
						<small class="subproductMenu"><select class="cswitch btn btn-default btn-primary" data-toggle="popover">
						<?php
							$plist = $product->getList();
							foreach( $plist as $key => $val ) {
								$flags = '';
								if ($key===$subproductname)
									$flags = $flags.' selected';
								if (!is_null($dto)&&!$product->isValid($key, $region, $dto))
									$flags = $flags.' disabled';
								echo "<option value=\"$key\" $flags>$val</option>\n";
							}
						?>
						</select></small>
					</li>
					<?php endif; ?>
					<?php if ($product instanceof Movie): ?>
					<li class="previous">
						<?php 
							if ($product instanceof SubProduct) $mname = $subproductname.'.'.$region;
							else $mname = $region;
							if (is_null($dto)||!$product->isMovieValid($mname, $dto)) {
								echo "<a class=\"disabled\" href=\"#\" alt=\"Movie\" title=\"Movie\">\n";
							} else {
								$mfilename = $product->getMovieFilename($mname, $dto);
								echo "<a class=\"movie\" href=\"#\" data-filename=\"$mfilename\" alt=\"Movie\" title=\"Movie\">\n";
							}
						?>
							<span class="glyphicon glyphicon-film" aria-hidden="true"></span>
						</a>
					</li>
					<?php endif; ?>
					<?php if ($product instanceof Info): ?>
					<li class="previous">
						<a href="#" id="about" class="about" alt="about">
							<span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span>
						</a>
					</li>
					<?php endif; ?>
					<li class="previous" >
						<a id="permlink2" type="button" class="btn btn-default" data-toggle="popover" data-placement="bottom" 
							title="Direct link to this graph" data-ilink="<?php echo $ipermlink ?>" data-mlink="<?php echo $mpermlink?>" data-real-content="<?php echo $permlink ?>">
							<small>
								<span class="glyphicon glyphicon-share" aria-hidden="true"></span> Permlink
							</small>
						</a>
					</li>

				</ul>
			</div>
		</nav>
<?php
		if ($product instanceof DataLink) {
			echo "<p class=\"visible-xs visible-sm \"/>\n";
			echo "<div class=\"row\">\n";
			echo "<div class=\"container btn-group xbtn-group-justified col-md-pull visible-xs visible-sm\">\n";
			echo "<h4>Data sources</h4>\n";
			foreach ($product->getDataLinks($region, $date) as $d => $datalink) {
				if (!is_null($datalink)) {
					echo "<a id=\"dbutton\" target=\"_blank\" href=\"$datalink\" class=\"subdued-button btn btn-success\" type=\"button\">$d</a>\n";
				} else {
					echo "<a id=\"dbutton\" href=\"#\" class=\"subdued-button disabled btn btn-success\" type=\"button\">$d</a>\n";
				}
			}
			echo "</div>\n";
			echo "</div>\n";
		}
?>
<?php
		if ($product instanceof Legend) {
			echo "<div id=\"xlegend\" class=\"product-legend-panel panel panel-primary btn visible-xs visible-sm\">\n";
			//echo "<a href=\"#\" id=\"legend\">\n";
			echo "<div class=\"panel-header\">\n";
			echo "<h4 class=\"text-left\">Legend</h4>\n";
			echo "</div>\n";
			echo "<div class=\"panel-body\">\n";
			//echo "<dl class=\"dl-horizontal product-legend\">\n";
			foreach ($product->getLegend() as $k => $v) {
				//echo "<div class=\"col-xs-2 col-sm-2\">\n";
				//echo "<dt>$k</dt><dd>$v</dd>\n";
				echo "<span class=\"col-xs-4 col-sm-2\">$k $v</span>\n";
				//echo "</div>\n";
			}
			//echo "</dl>\n";
			//echo "</a>\n";
			echo "</div>\n";
			echo "</div>\n";
		}
?>
	</div>
</div>

<div id="regionModal" class="modal fade" role="dialog">
	<div class="modal-dialog modal-lg">
		<div class="modal-content">
			<div class="modal-header">
				<h4 class="modal-title">Select region</h4>
			</div>
			<div class="modal-body in">
				<div class="col-md-12 btn-block btn-group-horizontal ">
					Product availability:
<?php
			foreach ($products as $p) {
				$pname = get_class($p);
				if ($p instanceOf RegionSelect) {
					$cls = "btn-outline rselect";
					$bname = $p->getSelectableRegionButtonName();
				}
				else {
					$cls = "btn disabled";
					$bname = get_class($p);
				}
				echo "<button type=\"button\" data-product=\"$pname\" class=\"$cls\">$bname</button>\n";
			}
?>
					
				</div>
				<div class="col-md-6">
								<img class="img-responsive" id="imap1img" width="999px" height="625px" border="0" src="SST_entry/latest.gif" usemap="#imap1">
				</div>
				<div class="col-md-6">
								<img class="img-responsive" id="imap2img" width="999px" height="625px" border="0" src="SST_entry/latest.gif" usemap="#imap2">
				</div>
			</div>
			<div class="modal-footer">
			</div>
		</div>
	</div>
</div>

<div class="modal" id="aboutModal" role="dialog" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				<?php if ($product instanceof Info) {
					$t = $product->getInfoTitle();
					echo "<h4 class=\"model-title text-center\">$t</h4>";
				} ?>
			</div>
			<div class="modal-body">
				<?php if ($product instanceof Info) echo $product->getInfo(); ?>
			</div>
		</div>
	</div>
</div>

<div class="modal" id="legendModal" role="dialog" aria-hidden="true">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
				<?php if ($product instanceof Info) {
					$t = $product->getInfoTitle();
					echo "<h4 class=\"model-title text-center\">$t</h4>";
				} ?>
			</div>
			<div class="modal-body">
				<?php if ($product instanceof Legend) echo $product->getLegendText(); ?>
			</div>
		</div>
	</div>
</div>

<?php
include_once("include/sfooter.php");
?>
<script src="<?php echo $BASEDIR ?>js/soceancolour.js"></script>
<script src="<?php echo $BASEDIR ?>js/imageMapResizer.min.js"></script>
<link href="<?php echo $BASEDIR ?>css/jquery-ui.min.css" rel="stylesheet">
<script src="<?php echo $BASEDIR ?>js/jquery-ui.js"></script>
<!--<script src="<?php echo $BASEDIR ?>js/jquery.imagemapster.min.js"></script>-->
<link href="<?php echo $BASEDIR ?>css/mapify.css" rel="stylesheet">
<script src="<?php echo $BASEDIR ?>js/mapify.js"></script>
<!-- Override CSS with our preferred version -->
<link href="<?php echo $BASEDIR ?>css/oceancurrent.css" rel="stylesheet">
<script>


function set_region_and_type(region, rtype) {
	var data = {'name': 'rtype', 'rtype': rtype};
	$.ajax({
		url: "set.php",
		data: data,
		success: function(res, status) {
			$('#regionModal').hide();
			//var data = {'name': 'region', 'region': region};
			window.location = 'product.php';
		}
	});
}

var sdate = <?php echo ds2d( $dts );?>;
var edate = <?php echo ds2d( $dte );?>;
/*
var invalid_dates = new Map();

function date_checker(d) {
	//console.log('date_checker'+d);
	if (d<sdate||d>edate) return [false,"",null];
	if (invalid_dates.has(d.toDateString())) return [false,"",null];
	return [true,"",null];
}
*/

var selectable_regions = {
<?php
	$pnum = 0;
	for ($i=0;$i<count($products);$i++) {
		$p = $products[$i];
		if ($p instanceof RegionSelect) {
			$pnum++;
		}
	}
	$cn = 0;
	echo "\tproducts: [";
	for ($i=0;$i<count($products);$i++) {
		$p = $products[$i];
		if ($p instanceof RegionSelect) {
			$pname = $productnames[$i];
			echo "\"$pname\"";
			$cn++;
			if ($cn != $pnum) echo ",";
		}
	}
	echo "],\n";
	$cn = 0;
	for ($i=0;$i<count($products);$i++) {
		$p = $products[$i];
		if ($p instanceof RegionSelect) {
			//if ($cn != 0) echo ", ";
			$bname = $p->getSelectableRegionButtonName();
			$pname = $productnames[$i];
			echo "\t$pname: {\n";
			echo "\t\tlabel: \"$bname\",\n";
			$rlist = ['DR','SR'];
			foreach ($rlist as $rt) {
				echo "\t\t$rt: [";
				$rs = $p->getSelectableRegions($rt);
				for($j=0;$j<count($rs);$j++) {
					if ($j!=0) echo ", ";
					echo "\"$rs[$j]\"";
				}
				if ($rt != $rlist[count($rlist)-1]) echo "],\n";
				else echo "]\n";
			}
			$cn++;
			if ($cn == $pnum) echo "\t}\n";
			else echo "\t},\n";
		}
	}
?>
};

function set_region_selector(product) {
	// First rewind any class settings on the map
	$("map[name='imap1'] > area").each(function () {
		$(this).removeAttr('data-svg-class');
		$(this).removeAttr('data-hover-class');
	});
	$("map[name='imap2'] > area").each(function () {
		$(this).removeAttr('data-svg-class');
		$(this).removeAttr('data-hover-class');
	});
	var found = false;
	for(let i=0;i<selectable_regions['products'].length;i++) {
		if (selectable_regions['products'][i] == product) {
			found = true;
			break;
		}
	}
	if (!found) return;
	// DR first
	var rlist = selectable_regions[product]['DR'];
	$("map[name='imap1'] > area").each(function () {
		var r = $(this).attr('data-region');
		var found = false;
		for(let i=0;i<rlist.length;i++) {
			if (rlist[i] == r) {
				found = true;
				break;
			}
		}
		if (!found) {
			$(this).attr('data-svg-class', 'mapify-deselected');
			$(this).attr('data-hover-class', 'mapify-deselected-hover');
		}
	});
	// SR next
	var rlist = selectable_regions[product]['SR'];
	$("map[name='imap2'] > area").each(function () {
		var r = $(this).attr('data-region');
		var found = false;
		for(let i=0;i<rlist.length;i++) {
			if (rlist[i] == r) {
				found = true;
				break;
			}
		}
		if (!found) {
			$(this).attr('data-svg-class', 'mapify-deselected');
			$(this).attr('data-hover-class', 'mapify-deselected-hover');
		}
	});
	// Move these externally so we can just set the attributes
	//$('#imap1img, #imap2img').unmapify();
	//$('#imap1img, #imap2img').mapify();
};

+function($) {
	/*
	$.getJSON("pdates.php", {'region': "<?php echo $region?>", 'product': "<?php echo $productname?>"}, function(data) {
		//console.log(data);
	});
	$.ajax({
		url: "pdates.php",
		data: {'region': "<?php echo $region?>", 'product': "<?php echo $productname?>"},
		success: function(res, status) {
			//console.log(data);
		}
	});
	*/
	$("map[name='imap1'] > area").each(function () {
		$(this).click( function() {
			var region = $(this).attr('data-region');
			var data = {'name': 'region', 'region': region};
			var data2 = {'name': 'rtype', 'rtype': 'DR'};
			$.when(
				$.ajax({
					url: "set.php",
					data: data,
				}),
				$.ajax({
					url: "set.php",
					data: data2,
				})
			).done(function(first_call, second_call) {
				$('#regionModal').hide();
				window.location = 'product.php';
			});
		})
	})
	$("map[name='imap2'] > area").each(function () {
		$(this).click( function() {
			var region = $(this).attr('data-region');
			//var dt = "<?php echo $dt?>";
			//window.location = 'sst.php?link='+region+'/'+dt+'.html';
			//
			var data = {'name': 'region', 'region': region};
			var data2 = {'name': 'rtype', 'rtype': 'SR'};
			$.when(
				$.ajax({
					url: "set.php",
					data: data,
				}),
				$.ajax({
					url: "set.php",
					data: data2,
				})
			).done(function(first_call, second_call) {
				$('#regionModal').hide();
				window.location = 'product.php';
			});
		})
	})
	$("map[name='imap3'] > area").each(function () {
		$(this).click( function() {
			var region = $(this).attr('data-region');
			//var dt = "<?php echo $dt?>";
			//window.location = 'sst.php?link='+region+'/'+dt+'.html';
			//
			var data = {'name': 'region', 'region': region};
			var data2 = {'name': 'rtype', 'rtype': 'AR'};
			$.when(
				$.ajax({
					url: "set.php",
					data: data,
				}),
				$.ajax({
					url: "set.php",
					data: data2,
				})
			).done(function(first_call, second_call) {
				$('#regionModal').hide();
				window.location = 'product.php';
			});
		})
	})
	$('#regionModal').on('shown.bs.modal', function() {
		//console.log('create mapify object(s)');
		//$('#imap1img, #img2img').mapify();
		$(this).find('.in').find('img').mapify();
		//$('#imap2img').mapify();
	});
	$('#regionModal').on('hide.bs.modal', function() {
		//console.log('kill mapify object(s)');
		$('#imap1img, #imap2img').unmapify();
		//$('#imap2img').unmapify();
	});
	$('.collapse').on('shown.bs.collapse', function() {
		//console.log('shown collapse');
		$(this).find('img').mapify();
	});
	$('.collapse').on('hide.bs.collapse', function() {
		//console.log('hide collapse');
		$(this).find('img').unmapify();
	});
	var region = "<?php echo $region;?>";
	if (<?php echo $show_region_dialog?>) $('#regionModal').modal();
	$('#rbutton').click( function() {
		$('#regionModal').modal('show');
		set_region_selector("<?php echo $productname;?>");
	});
	// We need to do this after the modal has shown so the size gets through.
	// There will still be a problem if the modal is shown, minimised and
	// the window resized before being shown again.
	$('.npbut').click(function() {
		var dt = $(this).attr('data-date');
		var data = {'name': 'date', 'date': dt};
		$.ajax({
			url: "set.php",
			data: data,
			success: function(res, status) {
				window.location = 'product.php';
			}
		});
	});
	$('.product-button').click( function() {
		var pname = $(this).attr('data-product');
		var data = {'name': 'product', 'product': pname};
		$.ajax({
			url: "set.php",
			data: data,
			success: function(res, status) {
				window.location = 'product.php';
			}
		});
	});
	$('#product-select').change( function() {
		var pname = $("#product-select option:selected").attr('data-product');
		var data = {'name': 'product', 'product': pname};
		$.ajax({
			url: "set.php",
			data: data,
			success: function(res, status) {
				window.location = 'product.php';
			}
		});
	});
	$('.cswitch').change(function() {
		var name = "<?php echo $productname;?>."+$(this).val();
		var data = {'name': 'product', 'product': name};
		$.ajax({
			url: "set.php",
			data: data,
			success: function(res, status) {
				window.location = 'product.php';
			}
		});
		
	});
	$('.rsa').click(function() {
		var dt = new Date();
		var yyyy = ""+dt.getUTCFullYear();
		var mm = ""+(dt.getUTCMonth()+1);
		var dd = ""+dt.getUTCDate();
		var hh = ""+dt.getUTCHours();
		var mn = ""+dt.getUTCMinutes();
		var ss = ""+dt.getUTCSeconds();
		if (mm.length==1) mm = "0"+mm;
		if (dd.length==1) dd = "0"+dd;
		if (hh.length==1) hh = "0"+hh;
		if (mn.length==1) mn = "0"+mn;
		if (ss.length==1) ss = "0"+ss;
		var dtstr = ""+yyyy+mm+dd+hh+mn+ss;
		var data = {'name': 'date', 'date': dtstr};
		$.ajax({
			url: "set.php",
			data: data,
			success: function(res, status) {
				window.location = 'product.php';
			}
		});
	});
    var cdate = <?php echo ds2d( $dt );?>;
	$('#dsel').datepicker({
		dateFormat: "yymmdd",
		minDate: sdate,
		maxDate: edate,
		changeMonth: true,
		changeYear: true,
		yearRange: sdate.getFullYear()+":"+edate.getFullYear(),
		//beforeShowDay: date_checker,
	});
	$("#dsel").datepicker("setDate", cdate);
	$("#dsel").change( function() {
		var d = $(this).datepicker('getDate');
		var ymd = ""+d.getFullYear();
		if( d.getMonth()<9) ymd += '0';
		ymd += d.getMonth()+1;
		if ( d.getDate()<10) ymd += '0';
		ymd += d.getDate();
		//console.log("ymd="+ymd+" d="+d);
		var dtstr = ymd+"120000";
		var data = {'name': 'date', 'date': dtstr};
		$.ajax({
			url: "set.php",
			data: data,
			success: function(res, status) {
				window.location = 'product.php';
			}
		});
	});
	$('#dsel2').datepicker({
		dateFormat: "yymmdd",
		minDate: sdate,
		maxDate: edate,
		changeMonth: true,
		changeYear: true,
		yearRange: sdate.getFullYear()+":"+edate.getFullYear(),
		//beforeShowDay: date_checker,
	});
	$("#dsel2").datepicker("setDate", cdate);
	$("#dsel2").change( function() {
		var d = $(this).datepicker('getDate');
		var ymd = ""+d.getFullYear();
		if( d.getMonth()<9) ymd += '0';
		ymd += d.getMonth()+1;
		if ( d.getDate()<10) ymd += '0';
		ymd += d.getDate();
		//console.log("ymd="+ymd+" d="+d);
		var dtstr = ymd+"120000";
		var data = {'name': 'date', 'date': dtstr};
		$.ajax({
			url: "set.php",
			data: data,
			success: function(res, status) {
				window.location = 'product.php';
			}
		});
	});
	$('#ddsa').click(function() {
		$('#dsel').datepicker("show");
	});
	$('#ddsa2').click(function() {
		$('#dsel2').datepicker("show");
	});
	$('.url').click(function() {
		var url = $(this).attr('data-url');
		if (url.length > 0) window.location = url;
	});

	$('#sidebarCollapse').on('click', function() {
		$('#sidebar').toggleClass('hidden');
		$('#content').toggleClass('col-md-10').toggleClass('col-md-12');
		$('#sidebarbutton').toggleClass('glyphicon-chevron-left').toggleClass('glyphicon-chevron-right');

		$.ajax({
			url: "set.php",
			data: {'name': 'sidebar', 'sidebar': $('#sidebar').hasClass('hidden')?'0':'1'}
		});
	});
	$('#sidebarCollapse-xs').on('click', function() {
		$('#sidebar').toggleClass('hidden');
		//$('#content').toggleClass('col-md-10').toggleClass('col-md-12');
		$('#sidebarbutton-xs').toggleClass('glyphicon-chevron-left').toggleClass('glyphicon-chevron-right');

		$.ajax({
			url: "set.php",
			data: {'name': 'sidebar', 'sidebar': $('#sidebar-xs').hasClass('hidden')?'0':'1'}
		});
	});
	$('.movie').click(function() {
		var filename = $(this).attr('data-filename');
		$('#videoplayer').toggleClass('hidden').attr('src', filename);
		$('#icontent').toggleClass('hidden');

		var plink = $('#videoplayer').hasClass('hidden') ? $('#permlink').attr('data-ilink') : $('#permlink').attr('data-mlink');
		$('#permlink').attr('data-real-content', plink);
		$('#permlink2').attr('data-real-content', plink);
	});

	$('#permlink').popover({
		content: function() {
			// permlink
			var doc_referrer = getDocumentReferrer();
			var i = doc_referrer.indexOf('?');
			if ( i > 0 ) doc_referrer =  doc_referrer.slice(0,i)
			i = doc_referrer.indexOf('#');
			if ( i > 0 ) doc_referrer =  doc_referrer.slice(0,i)
			return doc_referrer + "?" + $(this).attr('data-real-content');
		}
	});

	// highlight ready for copying
	$('#permlink').on('shown.bs.popover', function () {
		$(this + ' .popover-content').selectText();
	});
	$('#permlink2').popover({
		content: function() {
			// permlink
			var doc_referrer = getDocumentReferrer();
			var i = doc_referrer.indexOf('?');
			if ( i > 0 ) doc_referrer =  doc_referrer.slice(0,i)
			i = doc_referrer.indexOf('#');
			if ( i > 0 ) doc_referrer =  doc_referrer.slice(0,i)
			return doc_referrer + "?" + $(this).attr('data-real-content');
		}
	});

	// highlight ready for copying
	$('#permlink2').on('shown.bs.popover', function () {
		$(this + ' .popover-content').selectText();
	});

	$('.about').click(function(){
		$('#aboutModal').modal('show');
	});
	$('.product-legend-panel').click(function(){
		$('#legendModal').modal('show');
	});

	/*
	$('img[usemap]').maphilight({
        'fillColor': 'FF7251',
        'fillOpacity': 0.4,
        'strokeColor': '00FF00',
        'strokeOpacity': 1,
        'strokeWidth': 2,
		'alwaysOn': true
	});
	*/
	//$('img[usemap]').maphilight();

	$('#tagmap').imageMapResize();

	$('.rselect').click(function(){
		var p = $(this).attr('data-product');
		set_region_selector(p);
		$('#imap1img, #imap2img').unmapify();
		$('#imap1img, #imap2img').mapify();
	});
	
} (jQuery);

</script>
