<?php
$title = "FishSOOP";
ini_set('include_path', './' . PATH_SEPARATOR . '../' . PATH_SEPARATOR . ini_get('include_path'));
include_once("include/header.php");

if (!isset($_REQUEST['region'])) die('400');
if (!isset($_REQUEST['date'])) die('400');

$region = normalise_path($_REQUEST['region']);
$date = $_REQUEST['date'];

$idate = DateTime::createFromFormat('Ymd', $date);
$imgNameDate = $idate->format('d M Y');

$YY = $idate->format('Y');

$imgfile = '/fishsoop/'.$region.'/'.$YY.'/'.$idate->format('Ymd').'.gif';
$htmlfile = '../fishsoop/'.$region.'/'.$YY.'/'.$idate->format('Ymd').'.html';

$permlink="region=$region&date=$date";

// parse the html if we can
$dom = new DOMDocument;
$dom->loadHTMLFile($htmlfile);

// extract the bits we need
$xpath = new DOMXPath($dom);
//$prev2 = $xpath->query('//a[text()="<<<"]')->item(0);
//$prev1 = $xpath->query('//a[text()="<<"]')->item(0);
$prev = $xpath->query('//a[text()="<"]')->item(0)->getAttribute('href');
$next = $xpath->query('//a[text()=">"]')->item(0)->getAttribute('href');

// Chop off the .html suffix
if (!is_null($prev)) $prev = substr($prev, 0, -5);
if (!is_null($next)) $next = substr($next, 0, -5);

// Do the date array
$ymd_dates = array();
$date_list = array();

// Try globbing all the files first
$files = glob('../fishsoop/'.$region.'/2*/2*.html');

$i = 0;
$idx = -1;
foreach ($files as $file) {
	//$idom = new DOMDocument;
	//$idom->loadHTMLFile($file);
	//$ixpath = new DOMXPath($idom);

	//$v = explode('_', basename($file));
	//$dates[] = $v[0];
	//$cycles[] = substr($v[2],0,-4);

	// Create a nested date array
	//$y = substr($v[0],0,4);
	//$m = substr($v[0],4,2);
	//$d = substr($v[0],6,2);
	$bname = basename($file);
	$y = substr($bname,0,4);
	$m = substr($bname,4,2);
	$d = substr($bname,6,2);
	if (!array_key_exists($y, $ymd_dates)) $ymd_dates[$y] = array();
	if (!array_key_exists($m, $ymd_dates[$y])) $ymd_dates[$y][$m] = array();
	//$ymd_dates[$y][$m][] = array($d,substr($v[2],0,-4));
	$ymd_dates[$y][$m][] = array($d, substr($bname,0,8));

	// Try to deal with next/previous properly given
	$dt = substr($bname,0,8);
	$date_list[] = $dt;
	if ($date === $dt) $idx = $i;

	$i++;
}

// try to fix the cross year boundaries or
// null out dates which are the same as our curent one
if ($prev === $date) {
	if ($idx == 0) $prev = null;
	else $prev = $date_list[$idx-1];
}

if ($next === $date) {
	if ($idx == count($date_list)-1) $next = null;
	else $next = $date_list[$idx+1];
}

// Deal with the image map
echo "<map id=\"imapx\" name=\"imapx\">\n";
$ndom = new DOMDocument();
foreach($xpath->query('//area[@shape="rect"]') as $n) {
	//echo "<code>n=$n</code>\n";
	$ndom->appendChild($ndom->importNode($n,true));
}
echo $ndom->saveHTML();
echo "</map>\n";


?>

<div class="col-md-10 panel panel-default">
	<nav class="navbar navbar-default mapNavbar" role="navigation">
		<div class="container-fluid">
			<ul class="pager pagerMargins">
				<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"/>
						<button id="dsa" type="button" class="btn btn-default btn-xs" title="Calendar"><span class="glyphicon glyphicon-calendar"></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>
				<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-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 echo "<img class=\"img-responsive\" src=\"$imgfile\" usemap=\"#imapx\">"; ?>
	</div>
</div>
<div id="dsModal" class="modal fade" role="dialog">
	<div class="modal-dialog">
		<div class="modal-content">
			<div class="modal-header">
				<button type="button" class="close" data-dismiss="modal">&times;</button>
				<h4 class="modal-title text-center">Select date</h4>
			</div>
			<div class="modal-body yscrollable">
				<div class="table-responsive">
					<table class="table table-condensed">
						<tbody>
						<?php 
						foreach ($ymd_dates as $yk => $y) {
							echo "<tr><td colspan=\"2\" class=\"text-center\"><strong>$yk</strong></td></tr>\n";
							foreach($y as $mk => $m) {
								$md = DateTime::createFromFormat('m', $mk)->format('M');
								echo "<tr><td>$md</td><td>";
								foreach($m as $d) {
									echo "<a href=\"#\" class=\"npbut dlink\" data-date=\"$d[1]\">$d[0]</a>";
								}
								echo "</td></tr>\n";
							}
						}
						?>
						</tbody>
					</table>
				</div>
			</div>
		</div>
	</div>
</div>

<?php
include("include/sfooter.php");
?>

<script src="<?php echo $BASEDIR ?>js/soceancolour.js"></script>
<script src="<?php echo $BASEDIR ?>js/imageMapResizer.min.js"></script>


<script>
$('.npbut').click(function(){
	var r = "<?php echo $region?>";
	var d = $(this).attr('data-date');
	var data = {'region': r, 'date': d};
	$.post('fsa.php', data, function(data) { document.write(data); document.close(); });
});
$('.dswitch').change(function() {
});

$('#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();
});

$('#dsa').click(function(){
	$('#dsModal').modal('show', true);
});

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


</script>


