/**
 * ...
 * @author Kano
 */

var jky = {};
jky.init = function ()
{
	jky.init404();
	jky.zoomOpened = false;
	jky.menuOpened = false;
	jky.initWindow();
	jky.initMenu();
	jky.initCredits();
	jky.initPage();
}

jky.init404 = function ()
{
	if($("body").hasClass("error404")) document.location.href = "http://www.romain-laurent.com";
}

// ------------------------------------------------------------------------------------------------------------------------ ZOOM

// Called from inline JS onclick=jky.showZoom(url)
jky.showZoom = function (url)
{
	if (jky.zoomOpened) 
	{
		jky.hideZoom();
		return;
	}
	
	jky.zoomOpened = true;
	
	//console.log(url);
	
	if($("#zoomContent").length == 0)
	{
		var image = new Image();
		image.id = "zoomContent";
		
		$(".entry-content").append(image);
		
		$(".smallLoader").show();
		
		$(image).load(jky.handleZoomComplete);
		image.src = url;
	}
	
	else jky.displayZoom();
	
}

jky.handleZoomComplete = function (e)
{
	//console.log("jky.handleZoomComplete", e.target);
	$("#zoomContent").click(jky.hideZoom);
	jky.displayZoom();
}

jky.hideZoom = function ()
{
	jky.zoomOpened = false;
	
	
	$("#zoomContent").fadeOut();
}

jky.displayZoom = function ()
{
	$(".smallLoader").hide();
	$("#zoomContent").hide().fadeIn();
	//console.log("COMPLETE");
}

// ------------------------------------------------------------------------------------------------------------------------ CREDITS

// Activate toggle on click
jky.initCredits = function ()
{
	$("#credits").click(jky.toggleCredits);
}

// Togle credits display
jky.toggleCredits = function ()
{
	$("#creditsContent").slideToggle("fast");
}

// ------------------------------------------------------------------------------------------------------------------------ MENU

// Activate the menu behaviour
jky.initMenu = function ()
{
	// Activate work menu toggle display on click
	var work = $("#work");
	work.click(jky.toggleWorkMenu);
	
	$(".current_page_ancestor,.current_page_item").click(jky.toggleWorkMenu);
	
	// Hide work menu when on click out
	$(document).click(jky.clickBody);
	
	
	var $items = $(".work.column .content li");
	$items.click(jky.setCurrentItem);
	
	if (!jky.isHome()) 
	{
		var url = document.location.href;	
		
		
		var link;
		var item;
		
		// Browse the items to display only the one that matches the current URL
		for (var i = 0; i < $items.length; i ++)
		{
			item = $items[i];
			link = $("a", item)[0];
			href = link.href;
			
			if (url.indexOf(href) != -1) 
			{
				$(item).show();
				break;
			}
		}
	}
}

// Add the "current_page_item" class to the selected element so that the close animation doesn't hide all the elements
jky.setCurrentItem = function (e)
{
	var tagName = $(e.target).parent()[0].tagName;
	
	if (tagName != "LI") 
	{
		return false;
	}
	
	if($(e.target).parent().hasClass("current_page_ancestor") || $(e.target).parent().hasClass("current_page_item")) 
	{
		return false;
	}
	
	$(".work.column .content li").removeClass("current_page_ancestor")
	$(".work.column .content li").removeClass("current_page_item");
	
	$(e.target).parent().addClass("current_page_item");
	
	//var workMenuContent = $(".work.column .content li:not(.current_page_item,.current_page_ancestor)");
	//workMenuContent.slideToggle(100);
	jky.toggleWorkMenu(e);
	
	$("#work").parent().addClass("current_page_ancestor");
	
	return true;
}

// Toggle the work menu display
jky.toggleWorkMenu = function (e)
{
	//console.log("toggleWorkMenu");
	jky.menuOpened = !jky.menuOpened;
	
	var workMenuContent = $(".work.column .content li:not(.current_page_item,.current_page_ancestor)");
	
	if (jky.menuOpened) 
	{
		workMenuContent.slideDown(100);
	}
	else 
	{
		workMenuContent.slideUp(100);
	}
	
	if(jky.isHome()) 
	{
		if (jky.menuOpened) $("#work").parent().addClass("current_page_ancestor");
		else $("#work").parent().removeClass("current_page_ancestor");
	}
	
	return false;
}

// Click on any part of the page closes the menu
jky.clickBody = function (e)
{
	if (jky.menuOpened) jky.toggleWorkMenu(e);
	
	
	// Hide all items except the current one
	//var workMenuContent = $(".work.column .content li:not(.current_page_item,.current_page_ancestor)");
	//workMenuContent.slideUp("fast");
	
	
}

jky.closeWorkMenu = function ()
{
	//console.log("CLOSE WorkMenu");
	jky.menuOpened = true;
	jky.toggleWorkMenu();
}

// ------------------------------------------------------------------------------------------------------------------------ PAGE

jky.isHome = function ()
{
	var url = document.location.href;
	var isHome = (url.indexOf(".com/") == url.length - 5);
	
	return isHome;
}

jky.isWork = function ()
{
	var url = document.location.href;
	var isWork = url.indexOf("/work/") != -1 && url.indexOf("/work/") != url.length - 6;
	
	return isWork;
}

jky.isInfo = function ()
{
	var url = document.location.href;
	var isInfo = url.indexOf("/info/") != -1 && url.indexOf("/info/") == url.length - 6;
	
	return isInfo;
}

jky.initPage = function ()
{
	var url = document.location.href;
	
	if(jky.isHome())
	{
		jky.initHome();
	}
	if(jky.isWork())
	{
		var projectPath = url.substr(url.indexOf("/work/"));
		
		// Do not count the first slash
		//ex: projectPath = "/work/burnout/brunout-2/" --> ["", "work", "something-real", ""]
		var depth = projectPath.split("/").length - 4;
		var isProjectHome = depth == 0;
		jky.initProjectPage(url, isProjectHome);
	}
}

jky.initHome = function ()
{
	// TODO: récupérer la liste des images en lien et en afficher une au hasard
	var list = $(".entry-content li");
	list.hide();
	
	// Select a random item
	var n = Math.round(Math.random() * (list.length - 1));
	var li = list[n];
	
	// Create the image
	var image = new Image();
	image.src = $(li).text();
	
	// Insert image inside .entry-content
	$(".entry-content").append(image);
	
	if(image.complete) jky.handleHomeComplete();
	else $(image).load(jky.handleHomeComplete);
}

jky.handleHomeComplete = function ()
{
	jky.handleResize();
	$(".entry-content img").fadeIn();
}

jky.initProjectPage = function (url, isProjectHome)
{
	var $list;
	
	if(isProjectHome)
	{
		$list = $("#tree li a[href='"+url+"']").parent();
	}
	else
	{
		$list = $("#tree li a[href='"+url+"']").parent().parent().parent();
	}
	
	var $pages = $("a", $list);
	
	
	var href;
	
	var prevUrl;
	var nextUrl;
	
	for (var i = 0; i < $pages.length; i ++)
	{
		href = $pages[i].href;
		//console.log(href);
		
		if(href == url) 
		{
			var prevIndex = i - 1;
			if(prevIndex < 0) prevIndex = $pages.length - 1
			
			var nextIndex = i + 1;
			if(nextIndex >= $pages.length) nextIndex = 0; 
			
			prevUrl = $pages[prevIndex] ? $pages[prevIndex].href : "";
			nextUrl = $pages[nextIndex] ? $pages[nextIndex].href : "";

			//console.log("PREV", prevUrl);
			//console.log("NEXT", nextUrl);
			
			// Image count
			if($pages.length > 1) 
			{
				
				$(".work.column .current_page_ancestor,.work.column .current_page_item")[0].innerHTML +=  "<span>"+(i+1) + " of " + $pages.length + "</span>";
				jky.buildButtons(prevUrl, nextUrl);
			}
		}
	}
	
	var content = $("#content");
	var $img = $("#content .entry-content img");
	
	if($img.length)
	{
		$img.hide();
		$("#credits").hide();
		
		var img = $img[0];
		$(content).append("<div id='loader'></div>");
		
		//alert(img.complete);
		
		if(!img.complete)
		{	
			//$(img).css("visibility", "hidden");
			$(img).load(jky.imageComplete);
		}
		else
		{
			//alert("here");
			jky.imageComplete();
			//alert("here 2");
		}
	}
	
	var player = $(".entry-content iframe");
	if(player.length)
	{
		jky.handleResize();
	}
}

jky.imageComplete = function (e)
{
	//alert("jky.imageComplete");
	var $img = $("#content .entry-content img");
	
	// Fit image to window
	jky.handleResize();
	
	// Fade in image
	$img.css("visibility", "visible");
	$img.hide().fadeIn();
	$("#credits").show();
	
	// Hide loader
	$("#loader").hide();
}

jky.buildButtons = function (prevUrl, nextUrl)
{
	jky.prevUrl = prevUrl;
	jky.nextUrl = nextUrl;
	
	var entry = $(".entry-content");
	
	var buttons = "<div id='buttons'>";
	if(prevUrl != "") buttons += "<div class='hit prev'></div>";
	if(nextUrl != "") buttons += "<div class='hit next'></div>";
	
	buttons += "</div>";
	
	entry.prepend(buttons);
	
	$("#buttons .prev").click(jky.openPrevUrl);
	$("#buttons .prev").mousemove(jky.showPrevTooltip);
	$("#buttons .prev").mouseleave(jky.hideTooltip);
	
	$("#buttons .next").click(jky.openNextUrl);
	$("#buttons .next").mousemove(jky.showNextTooltip);
	$("#buttons .next").mouseleave(jky.hideTooltip);

	$("body").append("<div id='tooltip'></div>");
}

jky.showPrevTooltip = function (e)
{	
	jky.toltipOffset = -18;
	$("#tooltip").show();
	$("#tooltip").css("left", e.clientX + jky.toltipOffset)
				.css("top", e.clientY - 15)
				.css("background-position", "top right");
}

jky.showNextTooltip = function (e)
{
	jky.toltipOffset = 5;
	$("#tooltip").show();
	$("#tooltip").css("left", e.clientX + jky.toltipOffset)
				.css("top", e.clientY - 15)
				.css("background-position", "top left");
}

jky.hideTooltip = function ()
{
	$("#tooltip").hide();
}

jky.openPrevUrl = function ()
{
	document.location.href = jky.prevUrl;
}


jky.openNextUrl = function ()
{
	document.location.href = jky.nextUrl;
}


// ------------------------------------------------------------------------------------------------------------------------ WINDOW & RESIZE

jky.initWindow = function ()
{
	$(window).resize(jky.handleResize);
	jky.handleResize();
}

jky.handleResize = function (e)
{
	//("resize", window.innerWidth, window.innerHeight);
	
	var logo = $("#logo");
	var content = $(".entry-content");
	
	var w = window.innerWidth - 70;
	var h = window.innerHeight - 125;
	var r = w / h;
	
	var $img = $("#content .entry-content img");
	var $player = $("#content .entry-content iframe");
	
	if($img.length)
	{
		var img = $img[0];
		
		if(img.complete)
		{
			var imgWidth = img.naturalWidth;
			var imgHeight = img.naturalHeight;
			var imgRatio = imgWidth / imgHeight;
			
			var widthRatio = w / $img.width()
			var heightRatio = h / $img.height();
			
			w = Math.min(w, imgWidth);
			h = Math.min(h, imgHeight);
			w = Math.round(w);
			h = Math.round(h);
			
			var minRatio = Math.min(widthRatio, heightRatio);
			
			if(r <= imgRatio) 
			{
				content.width(w);
				content.height(Math.round(w / imgRatio));
				$("#contentFooter").width(w);
				$("#creditsContent").width(w);
				//$("body").css("background", "red");
			}
			else 
			{
				content.width(Math.round(h * imgRatio));
				content.height(h);
				
				$("#contentFooter").width(Math.round(h * imgRatio));
				$("#creditsContent").width(Math.round(h * imgRatio));
				//$("body").css("background", "blue");
			}
			
			// TODO: empécher l'agrandissement de la photo.
			//Max : 1500 px
		}
		else
		{
			// image.load -> calls handleResize();
		}
	}
	
	else if ($player.length) 
	{
		//console.log("RESIZE PLAYER");
		
		var playerWidth = 640//$player.width();
		var playerHeight = 360//$player.height();
		var playerRatio = playerWidth / playerHeight;
		
		var widthRatio = w / $player.width()
		var heightRatio = h / $player.height();
		
		//w = Math.min(w, playerWidth);
		//h = Math.min(h, playerHeight);
		w = Math.round(w);
		h = Math.round(h);
		
		var minRatio = Math.min(widthRatio, heightRatio);
		
		if(r <= playerRatio) 
		{
			content.width(w);
			content.height(Math.round(w / playerRatio));
			
			$player.width(w);
			$player.height(Math.round(w / playerRatio));
			
			$("#contentFooter").width(w);
			//$("body").css("background", "red");
		}
		else 
		{	
			content.width(Math.round(h * playerRatio));
			content.height(h);
			
			$player.width(Math.round(h * playerRatio));
			$player.height(h);
			
			$("#contentFooter").width(Math.round(h * playerRatio));
			//$("body").css("background", "blue");
		}
	}
}
	
$(document).ready(function(){jky.init()});
