<?php 
	$config = $_GET["sect"];
	$dive = $_GET["dive"];

	// Some fuckers put in a URL for me to suck down.  Get rid of it,
	// config files can only be local
	$bad = array("http:","https:","ftp:/");
	$config = str_replace($bad,"",$config);
	$dive = str_replace($bad,"",$dive);

	@include_once "body.inc";
	include_once "exif.inc";
	include_once "common.inc";
	include_once "viewlog.inc";
	include_once "viewlog_config.inc";
	include_once "notes.inc";

	if ( $config ) {
		@include_once "$config.cfg";
	} elseif ( $dive ) {
		// Emulate config file
		$index = "/greg/diving/$dive";
		$handle = GetHandle('ggulik');
		mysql_select_db('ggulik');
		$sql = "SELECT dive_site FROM dive_log WHERE dive_number = $dive";
		$result = mysql_query($sql);
		$line = mysql_fetch_assoc($result);
		$title = $line["dive_site"];
		$sql = "SELECT file_name, pictext FROM pic_log WHERE dive_number = $dive";
		$result = mysql_query($sql);
		while ( $line = mysql_fetch_assoc($result) ) {
			$caption[$line["file_name"]] = trim($line["pictext"]);
		}
		

	} else {
		@include_once ".cfg";
	}

	# For testing only
	$basehref = "";

	# Slideshow speed
	$speed = 6;	// 6 seconds

	if ($_GET["gallery"] == 1) {

		///////////////////////////////////////////////////////////////
       		// Show an index for a particular section.
		///////////////////////////////////////////////////////////////
		@include_once "top.inc";

		echo <<<EOF
<TABLE ID="navigation" BORDER=0 CELLSPACING=0 WIDTH="100%">
<COL /><COL /><COL /><COL />
EOF;
		echo "<tr><td align=center colspan=3><b>$title</b><br>$body</th></tr>\n";
		echo "<tr><th colspan=3><font class='minus1'>(Click on thumbnail for full-size image)</font></th></tr>";
		// for now...
		$self = "./";
		$section = $_GET["sect"];

		// Now loop through and show the thumbnails
		$row = 0;
		$column = 0;
		foreach (array_keys($caption) as $filename) {

			if ($column == 0) {
				echo "<TR VALIGN=TOP>";
			}

			echo '<td width="33%">';
			showslide($filename,$section);
			echo "</td>\n";

			$column ++;

			if ($column > 2) {
				echo "</TR>\n";
				$column = 0;
				$row++;
			}
		}

		// Add some blank boxes with the right color...
		if ($column > 0) {
			while ($column < 3) {
				echo "<TD>&nbsp;</TD>";
				$column++;
			}
		}

		echo "</TABLE>\n";

		@include_once "bottom.inc";

		Viewlog_Register($_SERVER["SCRIPT_NAME"]);








	} else {

?>
<script src="/greg/util.js"></script>
<script src="/greg/screenfull.min.js"></script>
<meta name="apple-mobile-web-app-capable" content="yes" />
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"> -->
<style>
body {
	margin: 0px;
}
.white {
	color: #FFF;
}
.title {
	text-shadow: 2px 2px rgb(180,180,180);
	font-size: 14pt;
}
.page-switcher {
	background: rgb(100, 100, 100);
	background: rgba(100, 100, 100, 0.2);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99A8A8A8, endColorstr=#80C8C8C8);
	border: none; 
	top: 0;
	bottom: 0;
	font-size: 36px;
	margin: 0;
	max-width: 150px;
	min-width: 90px;
	height: 100%;
	outline: none;
	padding: 0;
/*	position: absolute; */
	z-index: 10;
}
.slidebutton {
	vertical-align: middle;
	padding: 1px;
	border: 1px solid #021a40;
	background-color:rgb(200,210,200);
	-moz-border-radius: 3px;
	-webkit-border-radius: 3px;
	-khtml-border-radius: 3px;
	border-radius: 3px;
}
.slidebutton:hover {
	background-color:rgb(230,230,230);
}
.goback {
	position: absolute;
	top: 5px;
	left: 10px;
	align: left;
	background:url(/gif/back.png);
	width: 29px;
	height: 29px;
}
.exifbutton {
	margin: 5px;
}
.fullscreenbutton {
	margin: 8px;
}
.navbutton {
	opacity:0.7;
}
.navbutton:hover {
	opacity:1.0;
}
#container {
	width: 100%;
	height: 100%;
}
#leftbody, #rightbody {
/*	border:3px solid red;	*/
}
#leftbutton, #rightbutton {
	position: absolute;
	text-shadow: 2px 2px rgb(20,20,20);
	z-index: 55;
}
#navigation {
	margin: 2px;
	position: absolute;
	top: 0px;
	left: 2px;
	right: 2px;
	border: 2px solid rgb(210,210,210);
	color: black;
	background: rgb(200, 200, 200);
	background: rgba(200, 200, 200, 0.75);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99A8A8A8, endColorstr=#99C8C8C8);
	z-index: 99;
	padding: 0px;
	text-align: center;
}
#exif {
	position: absolute;
	bottom: 12px;
	left: 12px;
	border: 2px solid rgb(120,120,120);
	background: rgb(200, 200, 200);
	background: rgba(200, 200, 200, 0.75);
	filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#99A8A8A8, endColorstr=#99C8C8C8);
	z-index: 100;
	padding: 0px;
}
#thetable { 
	position: absolute;
	left: 0px;
	right: 0px;
	top: 0px;
	height: 100%;
	width: 100%;
	z-index: 50;
}
#theimage0 {
	overflow: hidden;
	position: absolute;
}
#theimage1 {
	overflow: hidden;
	position: absolute;
}
#theimgcontainer0 { 
	position: absolute;
	left: 0px;
	top: 0px;
	width: 100%;
	height: 100%;
	overflow: hidden;
}
#theimgcontainer1 { 
	position: absolute;
	left: 0px;
	top: 0px;
	width: 100%;
	height: 100%;
	overflow: hidden;
}
#theytcontainer { 
	position: absolute;
	left: 0px;
	right: 0px;
	top: 0px;
	width: 100%;
	height: 100%;
	z-index: 51;
}
#audio-controls {
	display: block;
	position: absolute;
	bottom: 0px;
	left: 0px;
/*	border: 2px solid red;	*/
}
body {
	background-color: rgb(100, 100, 100);
}
</style>
<script>

var browser = new Object();
var curImg = new Object();
curImg.slideshow = false;
curImg.volume = 1;	// 0 = mute, 1 = low, 2 = medium, 3 = high
curImg.size = [$(window).width(), $(window).height()];
curImg.container = 0;
curImg.direction = 1;

var music = '<?php echo @$music; ?>';

var kenburns = new Object();
kenburns.running = false;
kenburns.def = new Object();
kenburns.def.seconds = <?php echo $speed - 1; ?>;
kenburns.percent = 10;
kenburns.seconds = kenburns.def.seconds;


if (!window.console) console = {log: function() {}}; 	// IE workaround

/* From: http://mobile.tutsplus.com/tutorials/mobile-web-apps/remove-address-bar/ */
function hideAddressBar()
{
	/Mobile/.test(navigator.userAgent) && !location.hash && setTimeout(function () {
	    if (!pageYOffset) window.scrollTo(0, 1);
	}, 1000);
}


function fitImage(width, height, towidth, toheight) {
	xscale = width / towidth;
	yscale = height / toheight;

	// Recalculate new size with default ratio
	if (yscale > xscale){
		newWidth = Math.round(width * (1/yscale));
		newHeight = Math.round(height * (1/yscale));
	} else {
		newWidth = Math.round(width * (1/xscale));
		newHeight = Math.round(height * (1/xscale));
	}

	return [newWidth, newHeight];
}


function resizeTo(target, size) {
	$(target).css('background-size', size[0] + 'px ' + size[1] + 'px');
}


function resizeToImg(target, size) {
	$(target).css({width: size[0], height: size[1]});
	curImg.size = size;
}


function centerObject(elem) {
	
	$(elem).css('left', (browser.width - $(elem).width()) / 2);
	$(elem).css('top', (browser.height - $(elem).height()) / 2);

	curImg.height =  $(elem).height();
	curImg.width =  $(elem).width();
	curImg.left = (browser.width - $(elem).width()) / 2;
	curImg.top = (browser.height - $(elem).height()) / 2;

// console.log("curImg:");
// console.log(curImg);
}


function centerObjectYT(elem) {
	
	$(elem).css('margin-left', (browser.width - $(elem).width()) / 2);
	$(elem).css('margin-top', (browser.height - $(elem).height()) / 2);
}


function dirname(path) {
	return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
}

$(document).ready(function() {

	var slideDelay = <?php echo $speed; ?>;
	browser.width = $(window).width();
	browser.height = $(window).height();

	var fadeTimer;
	var fadeTimerLB;
	var fadeTimerRB;
	var slideTimer;
	var ytTmpl = "<iframe style=\"display:block;\" id=\"ytplayer\" width=\"800\" height=\"600\" src=\"//www.youtube.com/embed/{{videoid}}\" frameborder=\"0\" allowfullscreen></iframe>";


	function windowresize(container) {
		browser.width = $(window).width();
		browser.height = $(window).height();

		if ( container === undefined ) {
			container = curImg.container;
		}
// console.log("windowresize(" + container + ")");
// console.log(curImg);

		var newSize = fitImage(curImg.width, curImg.height, browser.width, browser.height);

		resizeToImg('#theimage'+container, newSize);
		$('#theytcontainer').css({width: browser.width, height: browser.height});

		if (curImg.youtube) {
			centerObjectYT('#ytplayer');
		} else {
			centerObject('#theimage'+container);
		}

		if ( screenfull.isFullscreen || ! screenfull.enabled) {
			$('#fullscreenbutton').fadeOut();
		} else {
			$('#fullscreenbutton').fadeIn();
		}
	}


	function kenburnsStart() {
		if (! curImg.slideshow) {
			return;
		}
		d = Math.round((Math.random()*20) - 10);
console.log("Rotate " + d + " degrees");

		aSettings = {
			width: curImg.width * 1.1,
                        height: curImg.height * 1.1,
                        left: '-=' + (Math.random() * (curImg.width * 0.1)) + 'px',
                        top: '-=' + (Math.random() * (curImg.height * 0.1)) + '50px',
			'-moz-transform':	'rotate('+d+'deg)',
			'-webkit-transform':	'rotate('+d+'deg)',
			'-o-transform':		'rotate('+d+'deg)',
			'-ms-transform':	'rotate('+d+'deg)',
			'transform':		'rotate('+d+'deg)'
                };
		$('#theimage'+curImg.container).animate(aSettings, { duration: kenburns.def.seconds * 1000, queue: false} );

		return;
	}


	function setImage(index) {
		curImg.index = index;

		$('#exif').slideUp('slow');

		// Is it youtube?
		if ( imgArray[index].file.substring(0,7) == "youtube" ) {
			curImg.youtube = true;
// console.log("It's youtube!");
// console.log("Video id is " + imgArray[index].file.split('/')[1] );
			$('#theytcontainer').fadeTo(0,0);
			$('#theytcontainer').html(ytTmpl.replace('{{videoid}}', imgArray[index].file.split('/')[1]));

			// Set initial caption and image
			$('#thetitle').html(imgArray[curImg.index].caption);
			document.title = imgArray[curImg.index].caption;
			document.location.hash = '#' + curImg.file;
			// $('#theytcontainer').show();
			$('#theytcontainer').fadeTo('slow',1);
			$('#theimgcontainer0, #theimgcontainer1').hide();

			setTimeout(windowresize, 200);	// Need a short delay to give iframe chance to load, IE needs it
		} else {
			curImg.youtube = false;

			$('#theytcontainer').hide();
			$('#theytcontainer').html(' ');

			// Get actual image size
			var img = new Image();
			img.onload = function() {
// console.log("image loading complete...");
				curImg.width = this.width;
				curImg.height = this.height;

				newContainer = 1 - curImg.container;
				windowresize(newContainer);
//				hideAddressBar();

				if (curImg.index == 0)
					$("#leftbutton").css('visibility','hidden');
				else
					$("#leftbutton").css('visibility','visible');
				if (curImg.index >= imgArray.length-1)
					$("#rightbutton").css('visibility','hidden');
				else
					$("#rightbutton").css('visibility','visible');
				// Set initial caption and image
				$('#thetitle').html(imgArray[curImg.index].caption);
				document.title = $("<div/>").html(imgArray[curImg.index].caption).text();
				document.location.hash = '#' + curImg.file;

				$('#theimgcontainer'+curImg.container).css('z-index', 3);
				$('#theimgcontainer'+newContainer).css('z-index', 2);
				$('#theimage'+newContainer).attr('src', imgArray[index].file );
				$('#theimgcontainer'+newContainer).fadeTo(0,1);
				$('#theimgcontainer'+curImg.container).fadeTo('slow', 0, function () {
					if (curImg.youtube) {
						$('#exifbutton').hide();
						$('#theimgcontainer0').hide();
						$('#theimgcontainer1').hide();
					} else {
						$('#exifbutton').show();
						$('#theimgcontainer'+curImg.container).css('z-index', 2);
						$('#theimgcontainer'+(1-curImg.container)).css('z-index', 3);
					}
				});
				curImg.container = 1 - curImg.container;

				kenburnsStart();
			}
			// Trigger image load
			curImg.file = imgArray[index].file;
			img.src = imgArray[index].file;
		}


		// Register the view
		if (imgArray[index].file.charAt(0) === '/') {
			path = imgArray[index].file;
		} else {
			path = dirname(window.location.pathname) + "/" + imgArray[index].file;
		}
		$.ajax({
			url: "/greg/view?" + path,
			type: 'get',
			async: true,
			cache: true,
			success: function(data) {
			}
		});

		// Try to preload the next image
		if ( (index + curImg.direction) < imgArray.length) {
			var imgPre = new Image();
			imgPre.src = imgArray[index+curImg.direction].file;
		}
	}


	function incrImage(by) {
		curImg.direction = by;
// console.log("incrImage(" + by + ")");
		if ( (curImg.index + by) < 0 || (curImg.index + by) >= imgArray.length) {
			if (curImg.slideshow)
				$('#slidestatus').text(' ended...');
			$('#slidepause').trigger('click');
			return;
		}

		curImg.index += by;
		setImage(curImg.index);
// console.log("setImage complate");
		if (curImg.slideshow) {
			clearTimeout(slideTimer);
			slideTimer = setTimeout(function() {
				$('#rightbutton').trigger('click');
			}, slideDelay * 1000);
		}
	}


	function setVolume() {
		$('#audio-player')[0].volume = (curImg.volume / 3) * .6666;
	}


	function setVolumeButton() {
		$('#high-bt').hide();
		$('#med-bt').hide();
		$('#low-bt').hide();
		$('#mute-bt').hide();
		switch (curImg.volume) {
		case 0:
			$('#mute-bt').show();
			$('#audio-message').text("Volume MUTE");
			break;
		case 1:
			$('#low-bt').show();
			$('#audio-message').text("Volume Low");
			break;
		case 2:
			$('#med-bt').show();
			$('#audio-message').text("Volume Medium");
			break;
		case 3:
			$('#high-bt').show();
			$('#audio-message').text("Volume High");
			break;
		}
	}



	var imgArray = new Array(<?php
	$first = true;
	foreach ($caption as $key => $value) {
		if (! $first) echo ", ";
		echo "{file:'$key', caption:'" . preg_replace('/\s+/'," ",str_replace("'","\'",$value)) . "'}\n";
		$first = false;
	}

	?>);
	startIndex = 0;
	// Find index of first image
	for (i = 0 ; i < imgArray.length ; i++) {
		if ( imgArray[i].file == document.location.hash.replace('#','') ) {
			startIndex = i;
			curImg.index = i;
			break;
		}
	}

	$(window).bind("resize", function(){ windowresize(); });  

	$('#return').css( 'cursor', 'pointer' );
	$('#goback').css( 'cursor', 'pointer' );
	$('#leftbutton').css( 'cursor', 'pointer' );
	$('#rightbutton').css( 'cursor', 'pointer' );
	$('#exifbutton').css( 'cursor', 'pointer' );
	$('#fullscreenbutton').css( 'cursor', 'pointer' );

	$('#exif').hide();
//	$('#leftbutton').hide();
//	$('#rightbutton').hide();
	$('#slidepause').hide();
	$('#pause-bt').hide();
	$('#high-bt').hide();
	$('#med-bt').hide();
	$('#mute-bt').hide();
	$('#theytcontainer').hide();
	setVolumeButton();

	// When the mouse moves make the navigation appear momentarily
	$('#leftbody, #leftbutton').mousemove(function(event) {
		$('#rightbutton').fadeTo('fast', 0);
		clearTimeout(fadeTimerLB);
		$('#leftbutton').stop(true,true).fadeTo('fast', 1);
		fadeTimerLB = setTimeout("$('#leftbutton').fadeTo(1000, 0);", 2000);
	});
	$('#rightbody, #rightbutton').mousemove(function(event) {
		$('#leftbutton').fadeTo('fast', 0);
		clearTimeout(fadeTimerRB);
		$('#rightbutton').stop(true,true).fadeTo('fast', 1);
		fadeTimerLB = setTimeout("$('#rightbutton').fadeTo(1000, 0);", 2000);
	});
	$('#theimgcontainer0, #theimgcontainer1, #leftbody, #rightbody, #theytcontainer').mousemove(function(event) {
		clearTimeout(fadeTimer);
		$('#navigation').stop(true,true).fadeIn('fast');
		fadeTimer = setTimeout("$('#navigation').fadeOut(2000);", 3000);
	});
	$('#leftbutton, #leftbody').click(function(event) {
		event.stopPropagation();
		incrImage(-1);
		$('#theimgcontainer0').trigger('mousemove');
	});
	$('#rightbutton, #rightbody').click(function(event) {
		event.stopPropagation();
		incrImage(1);
		$('#theimgcontainer0').trigger('mousemove');
	});
//	$('#leftbutton, #leftbody, #rightbutton, #rightbody').dblclick(function(event) {
//		event.stopPropagation();
//		$(target).css({width: curImg.width, height: curImg.height});
//	});
	$('#return, #goback').click(function(event) {
		window.location='<?php echo $index; ?>' + document.location.hash;
	});
	$('#exif').click(function(event) {
		$('#exif').slideUp('slow');
	});
	var target = $('#container')[0]; // Get DOM element from jQuery collection
	$('#fullscreenbutton').click(function(event) {
/// console.log(screenfull.enabled);
		if (screenfull.enabled) {
			screenfull.request(target);
			$('#fullscreenbutton').fadeOut();
		}
	});
	$('#exifbutton').click(function(event) {
		if ( imgArray[curImg.index].file[0] == '/' )
			path = imgArray[curImg.index].file;
		else
			path = dirname(window.location.pathname) + "/" + imgArray[curImg.index].file;
		$.ajax({
			url: "/greg/exif?" + path,
			type: 'get',
			async: true,
			cache: true,
			success: function(data) {
				// exifData = $.parseJSON(data);
				if (Object.keys(data).length > 0) {
					$('#exifdata').find("tr:gt(0)").remove();
					$.each(data, function(key, value) {
						$('#exifdata').append('<tr><th>' + key + '</th><td>' + value + '</td></tr>');
					});
					$('#exif').slideDown('slow');
				} else
					$('#exifbutton').hide();
			}
		});
	});
	$('#slideplay').click(function(event) {
		curImg.slideshow = true;
		kenburnsStart();
		$('#play-bt').click();
		$('#slideplay').hide();
		$('#slidepause').show();
		$('#slidestatus').text(' playing...');
		slideTimer = setTimeout(function() {
			$('#rightbutton').trigger('click');
		}, slideDelay * 1000);
	});
	$('#slidepause').click(function(event) {
		curImg.slideshow = false;
		$('#theimage'+curImg.container).stop();
		clearTimeout(slideTimer);
		$('#pause-bt').click();
		$('#slideplay').show();
		$('#slidepause').hide();
		$('#slidestatus').text('');
	});

	// Audio controls
	$("#play-bt").click(function(){
		$('#audio-player')[0].play();
		setVolume();
		setVolumeButton();
		$('#audio-message').text("Music started");
		$('#pause-bt').show();
		$('#play-bt').hide();
	});
	$("#pause-bt").click(function(){
		$('#audio-player')[0].pause();
		$('#audio-message').text("Music paused");
		$('#pause-bt').hide();
		$('#play-bt').show();
	});
	$("#stop-bt").click(function(){
		$('#audio-player')[0].pause();
		$('#audio-player')[0].currentTime = 0;
		$('#audio-message').text("Music Stopped");
	});
	$("#volume-bt").click(function(){
		curImg.volume += 1;
		if (curImg.volume > 3) curImg.volume = 0;
		setVolume();
		setVolumeButton();
	});
//	$('.swipe').swipe({
//		swipeLeft: function() {
//			$('#rightbutton').trigger('click');
//		},
//		swipeRight: function() {
//			$('#leftbutton').trigger('click');
//		}
//	});
	$(document.body).keydown(function(e) {
		var keyCode = e.keyCode || e.which, arrow = {left: 37, up: 38, right: 39, down: 40 };

// console.log("keyCode = " + e.keyCode);
		if (e.keyCode == 32) {
			if (curImg.slideshow)
				$('#slidepause').trigger('click');
			else
				$('#slideplay').trigger('click');
		} else if (e.keyCode == 27) {
			$('#goback').trigger('click');
		} else if (e.which == arrow.left || e.which == arrow.up) {
			$('#leftbutton').trigger('click');
		} else if (e.which == arrow.right || e.which == arrow.down) {
			$('#rightbutton').trigger('click');
		}
	});

	setImage(startIndex);

});
</script>
<div id="container" style="position: relative;">

<div id="theimgcontainer0"><img id="theimage0"></div>
<div id="theimgcontainer1"><img id="theimage1"></div>

<div id="theytcontainer"></div>

<div id="exif">
<table align=center id="exifdata" border=0>
<tr><th colspan=2>IMAGE META-DATA</th></tr>
<tr><th>Var</th><td>value</td></tr>
<tr><th>Var2</th><td>value2</td></tr>
</table>
</div>

<button id="leftbutton" class="navbutton page-switcher white title swipe" style="width: 31px; left: 0px; padding-bottom: 0px;">&lt;</button>
<button id="rightbutton" class="navbutton page-switcher white title swipe" style="width: 31px; right: 0px; padding-bottom: 0px;">&gt;</button>

<table id="thetable" border=0 cellspacing=0 class="swipe">
<col /> <col />
<tr valign="bottom"><td width="50%" height="100%" id="leftbody" align="left" class="swipe">
</td>
<td width="50%" height="100%" id="rightbody" align="right" class="swipe">
</td></tr>
</table>

<div id="navigation">

<div align="left" id="goback" title="Exit slideshow" class="navbutton goback">&nbsp;</div>

<img align="right" id="exifbutton" class="navbutton exifbutton" title="Show EXIF data for this image" src="/gif/info.png">
<img align="right" id="fullscreenbutton" class="navbutton fullscreenbutton" title="Switch to fullscreen" src="/gif/fullscreen.png">

<?php if ($music): ?>
<div id="audio-controls">
&#9835;
<audio id="audio-player" src="<?php echo $music; ?>"/></audio>
<img class="slidebutton" id="play-bt" src="/gif/play.png"><img class="slidebutton" id="pause-bt" src="/gif/pause.png">
	<span id="volume-bt">
	<img class="slidebutton" id="high-bt" src="/gif/volume-high.png"><img class="slidebutton" id="med-bt" src="/gif/volume-med.png"><img class="slidebutton" id="low-bt" src="/gif/volume-low.png"><img class="slidebutton" id="mute-bt" src="/gif/volume-mute.png">
	</span>
<span id="audio-message"></span>
</div>
<?php endif; ?>
<span title="Return to page" id="return" class="title"><?php echo $title; ?>
<br><span id="thetitle" class="title"></span><br>
</span><br>
<span id="slidecontrol" class="smaller">Slideshow<span id="slidestatus"></span>: 
<img class="slidebutton" id="slideplay" src="/gif/play.png">
<img class="slidebutton" id="slidepause" src="/gif/pause.png">
</span>
</div>

</div>
<?php

	}
?>

</BODY>
