/*!
 * Uniba Gallery Main Script
 */

(function($) {

	if (!window.console) {
		window.console = { log: $.noop };
	}
	
	if ($.blockUI) {
		$.blockUI.defaults.css = $.extend($.blockUI.defaults.css, {
			backgroundColor: "transparency",
			border: 0
		});
		$.blockUI.defaults.overlayCSS = $.extend($.blockUI.defaults.overlayCSS, {
			backgroundColor: "#ffffff",
			opacity: 1
		});
	}

	var $window = $(window),
		$document = $(document)
	;

//	$.fx.interval = 16;

	$window.bind("resize", function(event) {
		$(".follow-window-height").css({
			height: $window.height()
		})
		$(".follow-document-height").css({
			height: $document.height()
		});
		$(".follow-document-width").css({
			width: $document.width(),
			maxWidth: $document.width()
		});
		$(".follow-window-height-without-footer").css({
			height: $window.height() - $("footer").outerHeight()
		});
	});
		
	$(function() {
		dispatch(location.pathname);
	});
		
	// /gallery
	dispatch(".", function() {
		var timerId,
			activePage = 1,
			images = [],
			$content = $("#content"),
			$close = $(".close"),
			$prev = $(".prev"),
			$next = $(".next"),
			$progress = $("#progress"),
			$progressbar = $(".progressbar").first(),
			$galleryContainer = $(".gallery-container"),
			$thumbnail = $("#thumbnail"),
			$tooltip = $(".tooltip"),
			$hitArea,
			closeSize = {
				width: $close.outerWidth(),
				height: $close.outerHeight()
			},
			prevNextSize = {
				width: $prev.outerWidth(),
				height: $prev.outerHeight()
			},
			imageSize = {
				width: $galleryContainer.find(".gallery-image").eq(0).width(),
				height: $galleryContainer.find(".gallery-image").eq(0).height()
			},
			progressbarWidth = $progressbar.width(),
			hitArea = [
				[
					{ top: 0, left: 0, width: 757, height: 953 }
				],
				[
					{ top: 38, left: 22, width: 369, height: 494 }
				]
			],
			listItem = [
				{ thumb: "ref/images/thumb/eizo_s.png", link: "" },
				{ thumb: "ref/images/thumb/nabi_s.png", link: "" },
				{ thumb: "ref/images/thumb/NRK_s.png", link: "" },
				{ thumb: "ref/images/thumb/NRK'_s.png", link: "" },
				{ thumb: "ref/images/thumb/pacemaker_s.png", link: "" },
				{ thumb: "ref/images/thumb/redbook_s.png", link: "" },
				{ thumb: "ref/images/thumb/TDMS_s.png", link: "" },
				{ thumb: "ref/images/thumb/wasabeat_s.png", link: "" },
				{ thumb: "ref/images/thumb/yzcorp_s.png", link: "" },
				{ thumb: "ref/images/thumb/hillspost_s.png", link: "" }
			]
		;
		
		$("#listItem").tmpl(listItem).appendTo("#list");
		
		$.blockUI({ message: $progress });
		
		$(".images").find("li").find("img")
			.each(function(index) {
				images.push(this.src);
			})
		;
		
		$(".images").find("li").eq(0).css({ zIndex: 10 });
		
		preloadStart();
		
		function preloadStart() {
			var pos = 0,
				loaded = 0;
	    		imageObjectList = []
	    	;
	    	
			for (var i = 0; i < images.length; i++) {
				var object = new Image();
				imageObjectList.push(object);
				$(object).bind("load", function() {
					loaded++;
					var progressbarPos = parseInt((loaded / images.length * progressbarWidth) - progressbarWidth);
					$progressbar
						.stop()
						.animate({
							backgroundPositionX: progressbarPos
						}, 500, "easeInOutExpo")
					;
					
					if (loaded >= images.length) {
						preloadComplete();
					}
				});
				object.src = images[i];
			}
		};
		
		function preloadComplete() {
			$window.trigger("resize");
			
			setTimeout(function() {
				$.unblockUI({
					onUnblock: function() {
					//	$.blockUI({ message: $thumbnail });
						init();
					}
				});
			}, 1000);
		};

    function touchHandler(e) {
				if(e.touches.length >= 2) {
					return; // マルチタッチはキャンセル
				}
        var touch = e.touches[0];
        if (e.type == "touchstart") {
            startX = touch.pageX;
            startY = touch.pageY;
            diffX = diffY = 0;
        } else if (e.type == "touchmove") {
            diffX = touch.pageX - startX;
            diffY = touch.pageY - startY;
        } else if (e.type == "touchend") {
        		if (diffY < -200 || diffY > 200) {
        			return; // 縦スクロールは無視
        		}
            if (diffX > 200) {
                console.log("flick right(" + diffX + "," + diffY + ")" + getNext());
            		/*pageChange($galleryContainer, getNext(), function() {
								}); */
				$(".next").trigger("click");	
            } else if (diffX < -200) {
                console.log("flick left(" + diffX + "," + diffY + ")" + getPrev());
            		/*pageChange($galleryContainer, getPrev(), function() {
								}); */
				$(".prev").trigger("click");
            }
        }
    };
		
		function init() {
		
			// flick
      document.addEventListener("touchstart", touchHandler, false);
      document.addEventListener("touchmove", touchHandler, false);
      document.addEventListener("touchend", touchHandler, false);

			/*
			$("dt").addClass("before").each(function(i, n) {
				setTimeout(function() {
					$(n).removeClass("before").addClass("transition").addClass("after");
				}, i*150);
			});
			*/
		
			for (var i = 0, outerLen = hitArea.length; i < outerLen; ++i) {
				for (var j = 0, innerLen = hitArea[i].length; j < innerLen; ++j) {
					var style = hitArea[i][j];
					var $_hitArea = $("<div>").addClass("hit-area").data("style", style);
					$galleryContainer.find(".overlay").eq(i).append($_hitArea);
				}
			}
			
			$hitArea = $(".overlay .hit-area");
			var count = 0;
			
			$content.bind("touchstart", function(event) {
				$(this).trigger("click");
				return false;
			});
			$content.bind("click", function(event) {
				$thumbnail.toggle("blind", {}, "easeOutExpo");
			});
			$thumbnail.find("img").bind("click", function(event) {
				var index = $thumbnail.find("img").index(this);
				pageChange($galleryContainer, ++index, function() {
				});
			});
			
			$hitArea.bind("mouseenter", function(event) {
				var index = $hitArea.index(this);
				var pos = {
					top: $(this).position().top + $(this).height() - 10 - $tooltip.eq(index).innerHeight(),
					left: $(this).position().left + $(this).width() - 10 - $tooltip.eq(index).innerWidth()
				};
				
				if (pos.top < 10) {
					pos.top = 10;
				}
				if (pos.left < 10) {
					pos.left = 10;
				}
				
				var $activeTooltip = $tooltip.eq(index).css(pos).fadeIn(200);
				
				$tooltip.not($activeTooltip).fadeOut(600);
			});
			$tooltip.bind("mouseleave", function(event) {
//				$(this).fadeOut(600);
			});
			$(".images").bind("mouseleave", function(event) {
				$tooltip.fadeOut(600);
			});
			
			$close.css({ visibility: "visible", top: -closeSize.height, left: $document.width() - closeSize.width });
			$prev.css({ visibility: "visible", top: $document.height() / 2 - prevNextSize.height / 2, left: -prevNextSize.width });
			$next.css({ visibility: "visible", top: $document.height() / 2 - prevNextSize.height / 2, left: $document.width() });
			
			var widthRatio = $window.width() / imageSize.width;
			var heightRatio = $window.height() / imageSize.height;
			var ratio = 1;
			if (widthRatio > heightRatio) {
				ratio = heightRatio;
			}
			else {
				ratio = widthRatio;
			}
			
			ratio *= 0.85;
			
			$galleryContainer.find(".images").css({
				width: imageSize.width * ratio,
				height: imageSize.height * ratio,
				marginLeft: -((imageSize.width * ratio) - $window.width()) / 2
			});
			$galleryContainer
				.find("li:first").css({ zIndex: 10, visibility: "visible" }).end()
				.find("li:not(:first)").css({ visibility: "hidden" }).end()
			;
			$(".ui").css({ zIndex: 15 });
			
			$galleryContainer.find("li, .gallery-image").css({
				width: imageSize.width * ratio,
				height: imageSize.height * ratio
			});
						
			$galleryContainer
				.css({ visibility: "visible", opacity: 0 })
				.animate({ opacity: 1 }, 1000, "linear", function() {
					if ($.browser.msie && !$.support.opacity) {
						this.style.filter = "";
					}
					$window.trigger("resize");
				})
			;
			
			$galleryContainer.find("li").bind("click touchstart", function(event) {
				event.stopPropagation();
			});
			
			$window.bind("resize", function(event) {
				// console.log(["resize", timerId]);
				var delay = timerId === undefined ? 0 : 0;
				clearTimeout(timerId);
				timerId = setTimeout(function() {
					var closePos = { top: 0, left: $document.width() - closeSize.width },
						nextPos = { top: $document.height() / 2 - prevNextSize.height / 2, left: $document.width() - prevNextSize.width },
						prevPos = { top: $document.height() / 2 - prevNextSize.height / 2, left: 0 };
					;
					
					$close.stop().animate(closePos, 250, "easeOutExpo");
					$next.stop().animate(nextPos, 250, "easeOutExpo");
					$prev.stop().animate(prevPos, 250, "easeOutExpo");
				}, delay);
				
				var widthRatio = $window.width() / imageSize.width;
				var heightRatio = $window.height() / imageSize.height;
				var ratio = 1;
				if (widthRatio > heightRatio) {
					ratio = heightRatio;
				}
				else {
					ratio = widthRatio;
				}
				
				ratio *= 0.85;
				
				$galleryContainer.find(".images").stop().animate({
					width: imageSize.width * ratio,
					height: imageSize.height * ratio,
					marginLeft: -((imageSize.width * ratio) - $window.width()) / 2
				}, 500, "easeInOutSine");
				$galleryContainer.find("li, .gallery-image").stop().animate({
					width: imageSize.width * ratio,
					height: imageSize.height * ratio
				}, 500, "easeInOutSine");
								
				$hitArea.each(function(index) {
					var $this = $(this),
						style = $this.data('style'),
						computedStyle = $.extend({},
							style, {
								width: style.width * ratio,
								height: style.height * ratio,
								top: style.top * ratio,
								left: style.left * ratio
							});
					;
					$this.css(computedStyle);
				});
			});
			
			$window.bind("smartresize", function(event) {

			});
			
			$close.bind("click", function() {
				$("body")
					.animate({ opacity: 0 }, 1000, "easeOutExpo", function() { window.close(); });
				event.stopPropagation();
			}).bind("touchstart", function(event) { event.stopPropagation(); });
			
			$next.bind("click", function(event) {
				console.log("next");
				pageChange($galleryContainer, getNext(), function() {
				});
				event.stopPropagation();
			}).bind("touchstart", function(event) { event.stopPropagation(); });
			
			$prev.bind("click", function(event) {
				console.log("prev");
				pageChange($galleryContainer, getPrev(), function() {
				});
				event.stopPropagation();
			}).bind("touchstart", function(event) { event.stopPropagation(); });
		}
		
		function getNext() {
			var nextPage = activePage + 1;
			if (nextPage > $galleryContainer.find("li").length) {
				nextPage = 1;
			}
			
			activePage = nextPage;
			
			return nextPage;
		}
		
		function getPrev() {
			var prevPage = activePage - 1;
			if (prevPage < 1) {
				prevPage = $galleryContainer.find("li").length;
			}
			
			activePage = prevPage;
			
			return prevPage;
		}
		
		function pageChange($target, page, fn) {
			$hitArea.hide();
			$target
				.stop()
				.animate({ opacity: 0 }, 750, "easeOutExpo", function() {
					var active = $(this).find("li").eq(page - 1).css({ visibility: "visible", zIndex: 10 });
//					active.parents("li").css({ zIndex: 10 });
					var inactive = $(this).find("li").not(active).css({ visibility: "hidden", zIndex: 1 });
//					inactive.parents("li").css({ zIndex: 1 });
					$target.animate({ opacity: 1 }, 750, "linear", function() {
						if ($.browser.msie && !$.support.opacity) {
							this.style.filter = "";
						}
						$hitArea.show();
					});
				})
			;
		}
	});
	
	
	// all
	dispatch(".", function() {
			
	});
	
	function dispatch(path, func) {
		dispatch.path_func = dispatch.path_func || [];
		if (func) {
			return dispatch.path_func.push([path, func]);
		}
		var path_func = dispatch.path_func;
		for (var i = 0, l = path_func.length; i < l; ++i) {
			var func = path_func[i];
			var match = path.match(func[0]);
			match && func[1](match);
		}
	}

})(jQuery);
