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

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

interface Movie {
	public function isMovieValid($region, $date);
	public function getMovieFilename($region, $date);
}

interface Map {
	public function getMapList($region, $date);
}

class MapRecord {
	public $x, $y, $circlesize;
	public $title, $url;
};

interface Legend {
	public function getLegend();
	public function getLegendText();
}
interface DataLink {
	public function getDataLinks($region, $date);
}

interface Info {
	public function getInfo();
	public function getInfoTitle();
}

class IDB extends SQLite3 implements Map, Movie, Legend, DataLink, Info {
	function __construct() {
		$this->open('index.db', SQLITE3_OPEN_READONLY);
	}
	function getNearestDate($region, $date) {
		$dt = $date->format('Y-m-d H:i:s');
		$rpid = $this->querySingle("SELECT rpid FROM region_product WHERE region = 'Au' AND product = 'image'", false);
		$val = $this->querySingle("SELECT * FROM files WHERE rpid = '$rpid' AND Datetime(date) = '$dt'", true);
		if (count($val) > 0) return new DateTime($val['date']);
		$n = $this->getNextDate($region, $date);
		$p = $this->getPreviousDate($region, $date);
		if ($n === null) {
			if ($p === null) return null;
			return $p;
		}
		else if ($p === null) {
			return $n;
		}
		// Find the closest
		$d0 = $date - $p;
		$d1 = $n - $date;
		if ($d0 > $d1) return $p;
		return $n;
	}
	function getNextDate($region, $date) {
		$dt = $date->format('Y-m-d H:i:s');
		$rpid = $this->querySingle("SELECT rpid FROM region_product WHERE region = 'Au' AND product = 'image'", false);
		$val = $this->querySingle("SELECT * FROM files WHERE rpid = '$rpid' AND Datetime(date) > '$dt' ORDER BY date ASC", true);
		if (count($val) > 0) return new DateTime($val['date']);
		return null;
	}
	function getPreviousDate($region, $date) {
		$dt = $date->format('Y-m-d H:i:s');
		$rpid = $this->querySingle("SELECT rpid FROM region_product WHERE region = 'Au' AND product = 'image'", false);
		$val = $this->querySingle("SELECT * FROM files WHERE rpid = '$rpid' AND Datetime(date) < '$dt' ORDER BY date DESC", true);
		if (count($val) > 0) return new DateTime($val['date']);
		return null;
	}
	function getDateString($date) {
		return $date->format('d M Y H:i');
	}
	function getFilename($region, $date) {
		$dt = $date->format('Y-m-d H:i:s');
		$rpid = $this->querySingle("SELECT rpid FROM region_product WHERE region = 'Au' AND product = 'image'", false);
		$val = $this->querySingle("SELECT * FROM files WHERE rpid = '$rpid' AND Datetime(date) = '$dt'", true);
		return $val['file_name'];
	}
	function isDateValid($region,$date) {
		return ($date !== null);
	}
    public function getMapList($region, $date) {
		$dt = $date->format('Y-m-d H:i:s');
		$rpid = $this->querySingle("SELECT rpid FROM region_product WHERE region = 'Au' AND product = 'tag'", false);
		$filename = $this->querySingle("SELECT file_name FROM files WHERE rpid = '$rpid' AND Datetime(date) = '$dt'", false);
		$a = array();
		if (!is_null($filename)) {
			$results = $this->query("SELECT * FROM tags WHERE tagfile = '$filename' ORDER BY 'order' ASC");
			while ($val = $results->fetchArray()) {
				$r = new MapRecord();
				$r->x = $val['x'];
				$r->y = $val['y'];
				$r->circlesize = $val['sz'];
				$r->title = $val['title'];
				$r->url = $val['url'];
				if (substr($r->url,0,3) === 'TS ') {
					$titleX = str_replace(' ','_',$r->title);
					$r->url = "waves3ts.php?region=".$titleX;
				}
				array_push($a,$r);
			}
		}
		return $a;
    }
	function getMinDate($region) {
		$rpid = $this->querySingle("SELECT rpid FROM region_product WHERE region = 'Au' AND product = 'image'", false);
		$val = $this->querySingle("SELECT min(date) FROM files WHERE rpid = '$rpid'", false);
		if (!is_null($val)) return new DateTime($val);
		return null;
	}
	function getMaxDate($region) {
		$rpid = $this->querySingle("SELECT rpid FROM region_product WHERE region = 'Au' AND product = 'image'", false);
		$val = $this->querySingle("SELECT max(date) FROM files WHERE rpid = '$rpid'", false);
		if (!is_null($val)) return new DateTime($val);
		return null;
	}
	function isMovieValid($region, $date) {
		return !is_null($this->getMovieFilename($region,$date));
	}
	function getMovieFilename($region, $date) {
		$rpid = $this->querySingle("SELECT rpid FROM region_product WHERE region = 'Au' AND product = 'movie'", false);
		$dt = $date->format('Y-m').'-01 00:00:00';
		$filename = $this->querySingle("SELECT file_name FROM files WHERE rpid = '$rpid' AND Datetime(date) = '$dt'", false);
		return $filename;
	}
	function getLegend() {
		return array(
			'<span style="color:#FF00FF;">&#9675;</span>' => 'ExampleSymbol',
		);
	}
	function getLegendText() {
		return 'Legend text goes here';
	}
	function getDataLinks($region, $date) {
		return array(
			'DatasetName' => 'about:blank',
		);
	}
	public function getInfo() {
		return file_get_contents('info.html');
	}
	public function getInfoTitle() {
		return 'Surface waves';
	}
};


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

if (isset($_SESSION['date'])) $date = $_SESSION['date'];
else $date = gmdate('YmdHis');

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

$product = new IDB();
$region = 'Au';

$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 = '/s3.php?file=WAVES/'.$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)";
}

$dts = $product->getMinDate(null)->format('Ymd');
$dte = $product->getMaxDate(null)->format('Ymd');
$dt = $dte;
if (!is_null($dto)) $dt = $dto->format('Ymd');


if (($product instanceof Map) && (!is_null($imgfile))) {
	//$isize = getimagesize($imgfile);
	$isize = array(1936,1246);  // Hack until y tag is inverted
	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;
			$y = $m->y;
			//echo "\t<area shape=\"circle\" class=\"url\" coords=\"$x,$y,$m->circlesize\" href=\"#\" title=\"$m->title\" data-url=\"$m->url\">\n";
			echo "\t<area shape=\"circle\" coords=\"$x,$y,$m->circlesize\" href=\"$m->url\" title=\"$m->title\">\n";
		}
	}
	echo "</map>\n";
}

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

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

?>

<!--
<div class="alert alert-danger" role="alert">
	<p>We are working on resuming near real-time data availability. Thank you for your patience.</p>
</div>
-->

<div class="row">
	<!--
	<div id="sidebar" class="col-md-2 panel">
<?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>
	-->
    <!--<div id="content" class="col-md-10">-->
    <div id="content" class="col-md-12">
		<!--<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">
                                <?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 Movie): ?>
                    <li class="previous">
                        <?php
                            if (is_null($dto)||!$product->isMovieValid($region, $dto)) {
                                echo "<a class=\"disabled\" href=\"#\" alt=\"Movie\" title=\"Movie\">\n";
                            } else {
								$mfilename = '/s3.php?file=WAVES/'.$product->getMovieFilename($region, $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 img-responsive" id="videoplayer" controls>
                        </video>
                        <?php else: ?>
                        <video id="videoplayer" class="img-responsive" controls>
								$mfilename = '/s3.php?file=WAVES/'.$product->getMovieFilename($region, $dto);
                                <source src="<?php echo '/s3.php?file=WAVES/'.$product->getMovieFilename($mname, $dto)?>" type="video/mp4">
                        </video>
                        <?php endif; ?>
                </div>


	</div>
		<nav class="navbar navbar-default mapNavbar visible-xs visible-sm" 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="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="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 Movie): ?>
                    <li class="previous">
                        <?php
                            if (is_null($dto)||!$product->isMovieValid($region, $dto)) {
                                echo "<a class=\"disabled\" href=\"#\" alt=\"Movie\" title=\"Movie\">\n";
                            } else {
								$mfilename = '/s3.php?file=WAVES/'.$product->getMovieFilename($region, $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="about2" 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>
</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>
<script>


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];
}
*/

+function($) {
	$('.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;?>";
	// 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 = 'waves3.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 = 'waves3.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 = 'waves3.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 = 'waves3.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 = 'waves3.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 = 'waves3.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();
	
} (jQuery);

</script>
