<?php
	require("__include-common.php");
	require("../account/__logincheck.php");
	if (photo_GALLERY_99_USE <> 'YES') {
		header("Location: index.php");
	}
	if (photo_JPEG_RESIZE <> 'YES' or !defined("photo_GALLERY_99_TEMP_DIR") or photo_GALLERY_99_TEMP_DIR.'' == '') {
		header("Location: index.php");
	}
	if ($_SESSION['photo_open_path'] == '') {
		header("Location: index.php");
	}
	if (empty($_SESSION['photo'])) {
		header("Location: index.php");
	}
	if (empty($_SESSION['photo_img_count'])) {
		header("Location: index.php");
	}
	if ($_SESSION['photo_img_count'] < 1) {
		header("Location: index.php");
	}
	if (intval($_GET['page']) < 0) {
		header("Location: index.php?page=".$_GET['idxp']);
	}
	if (intval($_GET['page']) >= $_SESSION['photo_img_count']) {
		header("Location: index.php?page=".$_GET['idxp']);
	}
	$open_path = $_SESSION['photo_open_path'];
	if (defined("photo_LIMITED_IMAGES_FOLDER") and photo_LIMITED_IMAGES_FOLDER <> '') {
		if ($_SESSION['システム管理者'] <> 'YES' or photo_LIMITED_ADMIN_NOLIMIT <> 'YES') {
			$len = strlen(photo_LIMITED_IMAGES_FOLDER);
			if (substr($open_path.'/', 0, $len+1) <> photo_LIMITED_IMAGES_FOLDER.'/') {
				header("Location: index.php");
			}
		}
	}
	if (!defined("MERGING_IMAGE_BOXES_SIZE_SELECT")) {
		define("MERGING_IMAGE_BOXES_SIZE_SELECT", "100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250");
	}
	if ($_COOKIE['merging_image_boxes_size'].'' <> '') {
		$boxes_size = intval($_COOKIE['merging_image_boxes_size']);
	} else if (defined("MERGING_IMAGE_BOXES_SIZE")) {
		$boxes_size = intval(MERGING_IMAGE_BOXES_SIZE);
	} else {
		$boxes_size = 120;
	}
	$boxes_chk5 = $boxes_size * 5;
	$boxes_chk6 = $boxes_size * 6;
	$boxes_img = $boxes_size - 10;

	$bg_files = array();
	if (!defined("MERGING_IMAGE_BOXES_BACKGROUND")) {
		$background = 'MergingImageBoxes/bg.jpg';
	} else {
		$bg_path = realpath(MERGING_IMAGE_BOXES_BACKGROUND);
		$files = scandir($bg_path);
		$bg_cnt = 0;
		foreach ($files as $file) {
			if (is_ext_filename_str($file, 'jpg,jpeg,png,gif')) {
				$bg_files[] = $file;
				$bg_cnt++;
			}
		}
		$bg_idx = mt_rand(0, $bg_cnt-1);
		$background = MERGING_IMAGE_BOXES_BACKGROUND.'/'.$bg_files[$bg_idx];
	}
	if (!defined("MERGING_IMAGE_BOXES_H1_TITLE")) {
		define("MERGING_IMAGE_BOXES_H1_TITLE", "Merging Image Boxes <span>with jQuery</span>");
	}
	if (!defined("MERGING_IMAGE_BOXES_DESCRIPTION")) {
		define("MERGING_IMAGE_BOXES_DESCRIPTION", "Click on the thumbs or the large image");
	}
?>
<!DOCTYPE html>
<html>
    <head>
        <title>MyHome Photo Merging Image Boxes with jQuery</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <meta name="description" content="Merging Image Boxes with jQuery" />
        <meta name="keywords" content="jquery, merge, effect, images, photos, animation, background-image"/>
		<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"/>
        <link rel="stylesheet" href="MergingImageBoxes/css/style-ok2nd.css" media="screen"/>
		<script src="MergingImageBoxes/js/cufon-yui.js"></script>
		<script src="MergingImageBoxes/js/ChunkFive_400.font.js"></script>
		<script>
			Cufon.replace('h1',{ textShadow: '1px 1px #fff'});
			Cufon.replace('.description',{ textShadow: '1px 1px #fff'});
			Cufon.replace('a',{ textShadow: '1px 1px #fff', hover : true});
		</script>
        <style>
			body{
				background:#f0f0f0 url(<?= $background ?>) repeat top left;
			}
			.description{
				position:fixed;
				right:10px;
				top:10px;
				font-size:12px;
				color:#888;
			}
			span#reference{
				color:#888;
				position:fixed;
				left:20px;
				bottom:20px;
				font-size:12px;
			}
			span#reference a{
				color:#888;
				text-transform:uppercase;
				text-decoration:none;
				padding-right:20px;
			}
			span#reference a:hover{
				color:#444;
			}
			.im_wrapper div{
				width:<?= $boxes_size ?>px;
				height:<?= $boxes_size ?>px;
			}
			.im_wrapper div img{
				width:<?= $boxes_img ?>px;
				height:<?= $boxes_img ?>px;
			}
	</style>
    </head>
    <body>
		<h1><?= MERGING_IMAGE_BOXES_H1_TITLE ?></h1>
		<div class="description"><?= MERGING_IMAGE_BOXES_DESCRIPTION ?></div>
		<div id="im_wrapper" class="im_wrapper">
<?php
	if ($_GET['page'].'' <> '') {
		$start = intval($_GET['page']);
	} else {
		$start = 0;
	}
	$img_count = $_SESSION['photo_img_count'];
	if ($img_count - $start > 24) {
		$img_count = $start + 24;
	}
	$posx = 0;
	$posy = 0;
	$white_num = 24 - ($img_count - $start);
	$cnt = 100;
	for ($ix=$start; $ix<$img_count; $ix++) {
		$img_file = $open_path.'/'.$_SESSION['photo'][$ix]['file'];
		if ($_SESSION['photo'][$ix]['type'] == 'video') {
			$img = 'video-jpeg.php?file='.urlencode($img_file).'&ss='.$_SESSION['video_thumb_ss'];
		} else {
			$img = 'img-view.php?img='.urlencode($img_file).'&size='.$boxes_chk6.'&temp=y&jpg='.substr(++$cnt,1,2);
		}
?>
		<div style="background-position:<?= $posx ?>px <?= $posy ?>px;"><img src="<?= $img ?>" alt="" /></div>
<?
		if ($posx <= -$boxes_chk5) {
			$posx = 0;
			$posy = $posy - $boxes_size;
		} else {
			$posx = $posx - $boxes_size;
		}
	}
	for ($ix=0; $ix<$white_num; $ix++) {
?>
		<div style="background-position:<?= $posx ?>px <?= $posy ?>px;"><img src="image/white.jpg" alt="" /></div>
<?php
		if ($posx <= -$boxes_chk5) {
			$posx = 0;
			$posy = $posy - $boxes_size;
		} else {
			$posx = $posx - $boxes_size;
		}
	}
?>
		</div>
		<div id="im_loading" class="im_loading"></div>
		<div id="im_next" class="im_next"></div>
		<div id="im_prev" class="im_prev"></div>
        <div>
            <span id="reference" style="display: inline;">
	Size：<select onchange="imageSizeChange(this)">
	<?php
		$keyary = explode(",", MERGING_IMAGE_BOXES_SIZE_SELECT);
		foreach ($keyary as $size) {
	?>
		<option value="<?= $size ?>"<?= $size == $boxes_size ? " selected" : "" ?>><?= $size*6 ?> px
	<?php
		}
	?>
		</select>
            </span>
		</div>
        <!-- The JavaScript -->
	<script src="../scripts/jquery-1.4.3.js"></script>
	<script src="../scripts/jquery.cookie.js"></script>
	<script>
	document.onkeydown = keyPress;
	function keyPress( e ) {
		e = e || window.event;
		if (e.keyCode == 27) {		// ESC ：Exit, Return
			window.location.href = "index.php?page=<?= $_GET['idxp'] ?>";
		} else if (e.keyCode == 37 || e.keyCode == 100 || e.keyCode == 33 || e.keyCode == 29) {	// ←, Page Up, 無変換 ：Page Prev
			window.location.href = "?page=<?= $start - 24 ?>&idxp=<?= $_GET['idxp'] ?>";
		} else if (e.keyCode == 39 || e.keyCode == 102 || e.keyCode == 34) {	// →, Page Down ：Page Next
			window.location.href = "?page=<?= $start + 24 ?>&idxp=<?= $_GET['idxp'] ?>";
		} else if (e.keyCode == 13 || e.keyCode == 32) {			// Enter, Space ：Page Next
			window.location.href = "?page=<?= $start + 24 ?>&idxp=<?= $_GET['idxp'] ?>";
		} else {
			return true;	// その他 (ファンクションキーなどを有効にするため)
		}
		return false;
	}
	</script>
	<script>
	function imageSizeChange(sel) {
		for (i = 0; i < sel.options.length; i++) {
			if (sel.options[i].selected == true) {
				size = sel.options[i].value;
			}
		}
		$.cookie('merging_image_boxes_size', size, { path:'<?= MY_SESSION_PATH ?>', expires:365 });
		window.location.href = "?page=<?= $_GET['page'] ?>&idxp=<?= $_GET['idxp'] ?>";
	}
	</script>
		<script src="MergingImageBoxes/js/jquery.transform-0.9.1.min.js"></script>
		<script>
			//Paul Irish smartresize : http://paulirish.com/2009/throttled-smartresize-jquery-event-handler/
			(function($,sr){
				// debouncing function from John Hann
				// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
				var debounce = function (func, threshold, execAsap) {
					var timeout;
					return function debounced () {
						var obj = this, args = arguments;
						function delayed () {
							if (!execAsap)
								func.apply(obj, args);
							timeout = null;
						};
						if (timeout)
							clearTimeout(timeout);
						else if (execAsap)
							func.apply(obj, args);
						timeout = setTimeout(delayed, threshold || 100);
					};
				}
				//smartresize
				jQuery.fn[sr] = function(fn){  return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
			})(jQuery,'smartresize');
		</script>
        <script>
	var thumbs_size = <?= $boxes_size ?>;
            $(function() {
				//check if the user made the
				//mistake to open it with IE
				var ie 			= false;
				if ($.browser.msie)
					ie = true;
				//flag to control the click event
				var flg_click	= true;
				//the wrapper
                var $im_wrapper	= $('#im_wrapper');
				//the thumbs
				var $thumbs		= $im_wrapper.children('div');
				//all the images
				var $thumb_imgs = $thumbs.find('img');
				//number of images
				var nmb_thumbs	= $thumbs.length;
				//image loading status
				var $im_loading	= $('#im_loading');
				//the next and previous buttons
				var $im_next	= $('#im_next');
				var $im_prev	= $('#im_prev');
				//number of thumbs per line
				var per_line	= 6;
				//number of thumbs per column
				var per_col		= Math.ceil(nmb_thumbs/per_line)
				//index of the current thumb
				var current		= -1;
				//mode = grid | single
				var mode		= 'grid';
				//an array with the positions of the thumbs
				//we will use it for the navigation in single mode
				var positionsArray = [];
				for(var i = 0; i < nmb_thumbs; ++i)
					positionsArray[i]=i;
				
				
				//preload all the images
				$im_loading.show();
				var loaded		= 0;
				$thumb_imgs.each(function(){
					var $this = $(this);
					$('<img/>').load(function(){
						++loaded;
						if(loaded == nmb_thumbs*2)
							start();
					}).attr('src',$this.attr('src'));
					$('<img/>').load(function(){
						++loaded;
						if(loaded == nmb_thumbs*2)
							start();
				//	}).attr('src',$this.attr('src').replace('/thumbs',''));
					}).attr('src',$this.attr('src').replace('&temp=y','&temp=c'));
				});
				
				//starts the animation
				function start(){
					$im_loading.hide();
					//disperse the thumbs in a grid
					disperse();
				}
				
				//disperses the thumbs in a grid based on windows dimentions
				function disperse(){
					if(!flg_click) return;
					setflag();
					mode			= 'grid';
					//center point for first thumb along the width of the window
					var spaces_w 	= $(window).width()/(per_line + 1);
					//center point for first thumb along the height of the window
					var spaces_h 	= $(window).height()/(per_col + 1);
					//let's disperse the thumbs equally on the page
					$thumbs.each(function(i){
						var $thumb 	= $(this);
						//calculate left and top for each thumb,
						//considering how many we want per line
						var left	= spaces_w*((i%per_line)+1) - $thumb.width()/2;
						var top		= spaces_h*(Math.ceil((i+1)/per_line)) - $thumb.height()/2;
						//lets give a random degree to each thumb
						var r 		= Math.floor(Math.random()*41)-20;
						/*
						now we animate the thumb to its final positions;
						we also fade in its image, animate it to 115x115,
						and remove any background image	of the thumb - this
						is not relevant for the first time we call disperse,
						but when changing from single to grid mode
						 */
						if(ie)
							var param = {
								'left'		: left + 'px',
								'top'		: top + 'px'
							};
						else
							var param = {
								'left'		: left + 'px',
								'top'		: top + 'px',
								'rotate'	: r + 'deg'
							};
						$thumb.stop()
						.animate(param,700,function(){
							if(i==nmb_thumbs-1)
								setflag();
						})
						.find('img')
						.fadeIn(700,function(){
							$thumb.css({
								'background-image'	: 'none'
							});
							$(this).animate({
								'width'		: '<?= $boxes_img ?>px',
								'height'	: '<?= $boxes_img ?>px',
								'marginTop'	: '5px',
								'marginLeft': '5px'
							},150);
						});
					});
				}
				
				//controls if we can click on the thumbs or not
				//if theres an animation in progress
				//we don't want the user to be able to click
				function setflag(){
					flg_click = !flg_click
				}
				
				/*
				when we click on a thumb, we want to merge them
				and show the full image that was clicked.
				we need to animate the thumbs positions in order
				to center the final image in the screen. The
				image itself is the background image that each thumb
				will have (different background positions)
				If we are currently seeing the single image,
				then we want to disperse the thumbs again,
				and with this, showing the thumbs images.
				 */
				$thumbs.bind('click',function(){
					if(!flg_click) return;
					setflag();
					
					var $this 		= $(this);
					current 		= $this.index();
					
					if(mode	== 'grid'){
						mode			= 'single';
						//the source of the full image
						var image_src	= $this.find('img').attr('src').replace('&temp=y','&temp=c');
						$thumbs.each(function(i){
							var $thumb 	= $(this);
							var $image 	= $thumb.find('img');
							//first we animate the thumb image
							//to fill the thumbs dimentions
							$image.stop().animate({
								'width'		: '100%',
								'height'	: '100%',
								'marginTop'	: '0px',
								'marginLeft': '0px'
							},150,function(){
								//calculate the dimentions of the full image
								var f_w	= per_line * thumbs_size;
								var f_h	= per_col * thumbs_size;
								var f_l = $(window).width()/2 - f_w/2
								var f_t = $(window).height()/2 - f_h/2
								/*
								set the background image for the thumb
								and animate the thumbs postions and rotation
								 */
								if(ie)
									var param = {
										'left'	: f_l + (i%per_line)*thumbs_size + 'px',
										'top'	: f_t + Math.floor(i/per_line)*thumbs_size + 'px'
									};
								else
									var param = {
										'rotate': '0deg',
										'left'	: f_l + (i%per_line)*thumbs_size + 'px',
										'top'	: f_t + Math.floor(i/per_line)*thumbs_size + 'px'
									};
								$thumb.css({
									'background-image'	: 'url('+image_src+')'
								}).stop()
								.animate(param,1200,function(){
									//insert navigation for the single mode
									if(i==nmb_thumbs-1){
										addNavigation();
										setflag();
									}
								});
								//fade out the thumb's image
								$image.fadeOut(700);
							});
						});
					}
					else{
						setflag();
						//remove navigation
						removeNavigation();
						//if we are on single mode then disperse the thumbs
						disperse();
					}
				});
				
				//removes the navigation buttons
				function removeNavigation(){
					$im_next.stop().animate({'right':'-50px'},300);
					$im_prev.stop().animate({'left':'-50px'},300);
					$('#reference').css('display','inline');			// ok.2nd
				}
				
				//add the navigation buttons
				function addNavigation(){
					$im_next.stop().animate({'right':'0px'},300);
					$im_prev.stop().animate({'left':'0px'},300);
					$('#reference').css('display','none');				// ok.2nd
				}
				
				//User clicks next button (single mode)
				$im_next.bind('click',function(){
					if(!flg_click) return;
					setflag();
					
					++current;
					var $next_thumb	= $im_wrapper.children('div:nth-child('+(current+1)+')');
					if($next_thumb.length>0){
						var image_src	= $next_thumb.find('img').attr('src').replace('&temp=y','&temp=c');
						var arr 		= Array.shuffle(positionsArray.slice(0));
						$thumbs.each(function(i){
							//we want to change each divs background image
							//on a different point of time
							var t = $(this);
							setTimeout(function(){
								t.css({
									'background-image'	: 'url('+image_src+')'
								});
								if(i == nmb_thumbs-1)
									setflag();
							},arr.shift()*20);
						});
					}
					else{
						setflag();
						--current;
						return;
					}
				});
				
				//User clicks prev button (single mode)
				$im_prev.bind('click',function(){
					if(!flg_click) return;
					setflag();
					--current;
					var $prev_thumb	= $im_wrapper.children('div:nth-child('+(current+1)+')');
					if($prev_thumb.length>0){
						var image_src	= $prev_thumb.find('img').attr('src').replace('&temp=y','&temp=c');
						var arr 		= Array.shuffle(positionsArray.slice(0));
						$thumbs.each(function(i){
							var t = $(this);
							setTimeout(function(){
								t.css({
									'background-image'	: 'url('+image_src+')'
								});
								if(i == nmb_thumbs-1)
									setflag();
							},arr.shift()*20);
						});
					}
					else{
						setflag();
						++current;
						return;
					}
				});
				
				//on windows resize call the disperse function
				$(window).smartresize(function(){
					removeNavigation()
					disperse();
				});
				
				//function to shuffle an array
				Array.shuffle = function( array ){
					for(
					var j, x, i = array.length; i;
					j = parseInt(Math.random() * i),
					x = array[--i], array[i] = array[j], array[j] = x
				);
					return array;
				};
            });
        </script>
    </body>
</html>