﻿//////////////////////////////////
//
//  Youhou! I can do some JS too!
//	Mostly with jQuery but I've also used MooTools & Scriptaculous a few years ago.
//  I'm glad you are having a look here, I hope it means you're interested ?
//  I don't consider myself a JS developer at all, it's just that I like to know how things work :).
//
//	\o/
//
//////////////////////////////////

var cvX;
var cvTitleX;
var state = "closed";
var diff;
var imgLoadedCount = 0;
var isMoving = false;

var currentProject = -1;
var currentStep = 0;
var currentMessage = -1;
var nextStep;
var savedStep;
var totalScreens;

var nbProjects;
var projects = [];
var steps = [];
var messagesTop = []
	messagesTop[0] = "Ok, there's a huge scroll here<br>I'm aware of that";
	messagesTop[1] = "Stop now";
	messagesTop[2] = "Rhhoooo !";
	messagesTop[3] = "Come on! Have another look at <a href=\"javascript:goto($('#cv').position().top - 96, 500)\">my CV</a> or at <a href='javascript:gotoProjects()'>my work</a>";
	messagesTop[4] = "Still here ?";
	messagesTop[5] = "I can sing something for you then";
	messagesTop[6] = "Laaaaaaaa laaa laa <br>La laa lala lalaaaaa<br>Lalaa laaaaaaaaaaa lala<br>Lalala la la lalalaaa";
	messagesTop[7] = "I wish I could yodle.<br> It would be awesome on my CV.";
	messagesTop[8] = "I also do like to listen to Coupé Décalé when I'm working.";
	messagesTop[9] = "Too bad I don't know how to translate 'gâter le coin' in dutch.";
	messagesTop[10] = "Ok, one special gift for you : have you seen this <a href='http://"+location.host+location.pathname+"'>website ?</a><br>Lekker!";

var messagesBottom = [];
	messagesBottom[0] = "Hola!<br> nothing left down there!";
	messagesBottom[1] = "Hola!<br> nothing left down there!";
	messagesBottom[2] = "I should be debugging this site instead of writing these things";
	messagesBottom[3] = "I'm not even sure anybody will see them ...";
	messagesBottom[4] = "Hey!<br> If you read this, can you send me <a href=\"mailto:francois.chay@gmail.com?subject=I've%20been%20there\">a mail</a> ?";
	messagesBottom[5] = "You can join unicorns' pictures too.<br>I like unicorns' pictures.";
	messagesBottom[6] = "Or narwhals.<br>The most underrated animals on earth.";
	messagesBottom[7] = "It's like a mix between unicorns and dolphins.";
	messagesBottom[8] = "They are so awesome I'm sure God took a day off after he created them.";
	messagesBottom[9] = "Anyway, as I said there's nothing left here.";
	messagesBottom[10] = "No";
	messagesBottom[11] = "Still nothing";
	messagesBottom[12] = "But <a href=\"javascript:goto($('#cv').position().top - 96, 500)\">my CV</a> is still upthere";
	messagesBottom[13] = "And <a href='javascript:gotoProjects()'>my projects</a> on the left";
	messagesBottom[14] = "Tadaaa ! The end \\o/ !";
	messagesBottom[15] = "No, really this time";
	messagesBottom[30] = "Rhooooooo !!!!";
	
	
	

jQuery(document).ready(function()
{
	jQuery.easing.def = "easeInOutCirc";
	
	cvX = 100+Math.floor($("#cv").offset().left / 100)*100;
	nbProjects = $("#projects h3").length;
	
	$("#facebook, #twitter").fadeTo(0, 0);
	
	setCV();
	setNav();
	setListeners();
	setPosition();
	
	handleScroll();
})


//////////////////////////////////////
//
//  Init
//
//////////////////////////////////////

function setCV()
{
	if($(window).width() > 1200)
	{
		cvTitleX = 1200;
	}
	else
	{
		// dirty tricks
		if($(window).width() < 1100)
		{
			cvTitleX =  20;
			$("#cv").css("width", "800px");
		}
		else
		{
			cvTitleX =  1000;
			$("#cv div").css("width", "350px");
		}
		$("#cvTitle").html("<br/><br/><a href='javascript:void(0)'>About me →</a>");
	}
	
	$("#cvTitle").css("left", cvTitleX);
	
	$("#cv").css("left", cvX+"px");
	$("#cv").css("margin-left", "0px");
	$("#cvTitle").click(gotoCV);
	diff = Math.abs($("#projects").offset().left - $("#cv").offset().left);
}

function setNav()
{
	$("#projects h3").each(function(i){
		projects.push($("#projects h3")[i])
	});
	
	$(".project-content div").each(function(i){
		steps.push($(".project-content div")[i])
	});

	$("#previous").click(onPreviousClick);
	$("#next").click(onNextClick);
	
	$("#total").html("/"+nbProjects+"<br/>");
	
	$("#infosNav .forCv").animate({opacity:1}, 50);
}

function setListeners()
{
	$("#download").click(track("cv/download"));
	$("#cvTitle a:first").mouseover(slideCvIn);
	$().mousemove(function(e){handleMouse(e)});
	$().mouseup(function(){handleScroll()});
	$().mousewheel(function(e,delta){handleScroll(e, delta)});
	$().keydown(function (e){onKeyPress(e)});
}

function setPosition()
{
	if(location.hash.length > 0) 
	{
		var pos = location.href.indexOf("#") + 1;
		
		var target = location.href.substr(pos, location.href.length);
		
		goto($("#project-"+target));
	}
}


//////////////////////////////////////
//
//  Update
//
//////////////////////////////////////

function updateCount()
{
	if(currentProject == -1)	$("#count").html("");
	else 						$("#count").html("<span id='current'>"+(currentProject+1)+"</span>/"+nbProjects);
	
	updateUrl();
}

function updateUrl(target)
{
	var dest;
	
	if(location.hash.length > 0) 
	{
		var pos = location.href.substring("#");
		dest = location.href.substr(0, pos) + "#" + currentProject;
	}
	else
	{
		dest = location.href+"#"+currentProject;
	}
	
	window.location = dest;
	
	var currentTitle = $("#project-"+currentProject+" h3").text();
	var url = "http://"+location.host+"/content/facebookshare/"+$("#project-"+currentProject+" .page").text();
	
	$("#facebook").attr("share_url", url);
	$("#facebook").attr("href", "http://www.facebook.com/sharer.php?u="+url);
	$("#facebook").click(function(){track('/social/facebook/'+currentTitle);});
	
	$("#twitter").attr("href", "http://twitter.com/home?status=François Chay — "+currentTitle+" : "+$("#project-"+currentProject+" .link").text());
	$("#twitter").click(function(){track('/social/twitter/'+currentTitle);});
}

function updateHead()
{
	$("link#image_src").attr("href", "http://"+location.host+"/"+$("#project-"+currentProject+" img:first").attr("src"));
	$("meta#title").attr("content", $("#project-"+currentProject+" h3").text());
	$("meta#description").attr("content", $("#project-"+currentProject+" p:first").text().toLowerCase());
}


//////////////////////////////////////
//
//  Events
//
//////////////////////////////////////

function onload(e)
{
	if(imgLoadedCount == $("#projects img").length) handleScroll();
	imgLoadedCount ++;
}

function onPreviousClick()
{	
	if((currentProject - 1) == -1)	goto(0, 1500);
	else if(currentProject >= 0) 	goto($(projects[currentProject - 1]).offset().top - 55, 1500);
}

function onNextClick()
{
	if(currentProject + 1 == projects.length)	goto(0, 1500);
	else										goto($(projects[currentProject + 1]).offset().top - 55, 1500);
}

function handleMouse(e)
{
	if(e.pageX > (cvX-300) && e.pageX < (cvX-200) && state != "cv")
	{
		$("#cv").css("top", $().scrollTop() + 4);
	}
}

function handleScroll(e, delta)
{
	handleCV();
	
	// Projects
	for(var i = 0; i < projects.length; i++)
	{
		if($().scrollTop() < $(projects[0]).position().top)
		{
			setCurrentProject(-1, true);
			break;
		}
		else if(i < projects.length - 1 && $().scrollTop() > $(projects[i]).position().top - 10 
				&& $().scrollTop() < $(projects[i+1]).position().top)
		{
			setCurrentProject(i, true);
			break;
		}
		else if(i == projects.length - 1 
				&& $().scrollTop() > $(projects[projects.length - 1]).position().top - 10)
		{
			setCurrentProject(projects.length - 1, true);
		}
	}
	
	// Steps
	for(i = 0; i < steps.length; i++)
	{
		if($(steps[i]).offset().top - $().scrollTop() > 50 
			&& $(steps[i]).offset().top - $().scrollTop() < 200)
		{
			currentStep = i;
			//$(steps[i]).fadeTo(0, 1);
			break;
		}
		else
		{
			//$(steps[i]).fadeTo(0, 0.5);
		}
	}
	
	isMoving = false;
}

function handleCV()
{
	if(state != "cv")
	{
		if(($(projects[projects.length-1]).position().top + $(projects[projects.length-1]).height()) 
			> ($("#cv").position().top + $("#cv").height()))
		{
			placeCv();
		}
	}
	else
	{
		var cvTop = $("#cv").position().top - $().scrollTop();
		var cvBottom = cvTop + $("#miscellaneous").position().top + $("#miscellaneous").height();
		
		if(cvTop > $(window).height())
		{
			var pos = Math.floor(cvTop / $(window).height()) - 1;
			var messageText = messagesTop[pos];
			if(messageText != $("#message").html() && messageText != "" && pos != currentMessage)
			{
				$("#message").fadeOut(100, function(){$("#message").html(messageText); $("#message").fadeIn(100);});				
				currentMessage = pos;
			}
		}
		else if(cvBottom < 0)
		{
			var currentScreen = Math.floor(($(document).height() - $().scrollTop()) / $(window).height()) +4;
			var pos = totalScreens - currentScreen;
			var messageText = messagesBottom[pos];
			
			if(messageText != $("#message").html() && messageText != "" && pos != currentMessage)
			{
				$("#message").fadeOut(100, function(){$("#message").html(messageText); $("#message").fadeIn(100);});
			}
			
			currentMessage = pos;
		}
		else
		{
			$("#message").fadeOut(50);
		}
		
	}
}

function onKeyPress(e)
{
	if(state != "cv")
	{
		e.preventDefault();
		switch(e.keyCode)
		{
			case 33: 	onPreviousClick();
						break;
			case 34:	onNextClick();
						break;
			case 35:	goto($(projects[projects.length - 1]), 1500);
						break;
			case 36:	goto(0, 1500);
						break;
			case 37:	gotoProjects();
						break;
			case 38:	gotoPreviousImage();
						break;
			case 39:	gotoCV();
						break;
			case 40:	gotoNextImage();
						break;
		}
	}
	else
	{
		switch(e.keyCode)
		{
			case 35:	e.preventDefault();
						break;
			case 36:	e.preventDefault();
						break;
			case 37:	e.preventDefault();
						gotoProjects();
						break;
		}
		handleScroll();
	}
	
}


//////////////////////////////////////
//
//  Animation
//
//////////////////////////////////////

function placeCv()
{
	totalScreens = Math.floor(($(document).height() - $().scrollTop()) / $(window).height());
	
	$("#cv").css("top", $().scrollTop());
}

function slideCvIn()
{
	$("#cvTitle a:first").unbind('mouseover', slideCvIn);
	
	state = "cvSlidedIn";
	$("#cv").animate({left: cvX-100}, 100);
	$("#projects").animate({left: 150}, 200);
	
	$("#cvTitle a:first").mouseout(slideCvOut);
}

function slideCvOut()
{
	$("#cvTitle a:first").unbind('mouseout', slideCvOut);
	
	state = "closed";
	$("#cv").animate({left: cvX}, 200);
	$("#projects").animate({left: 200}, 100);
	
	$("#cvTitle a:first").mouseover(slideCvIn);
}

function slideProjectsIn()
{
	$("#cvTitle a:first").unbind('mouseover', slideProjectsIn);
	
	state = "projectsSlidedIn";
	$("#cv").animate({left: 200}, 100);
	
	$("#cvTitle a:first").mouseout(slideProjectsOut);
}

function slideProjectsOut()
{
	$("#cvTitle a:first").unbind('mouseout', slideProjectsOut);
	
	state = "cv";
	$("#cv").animate({left: 100}, 200);
	
	$("#cvTitle a:first").mouseover(slideProjectsIn);
}


//////////////////////////////////////
//
//  Navigation
//
//////////////////////////////////////

function goto(target, time)
{
	if(!isMoving)
	{
		isMoving = true;
		$.scrollTo(target, time, {axis:"y", onAfter: handleScroll});
	}
}

function gotoCV()
{
	placeCv();
	track("cv");
	
	$("#cvTitle a:first").unbind('mouseover', slideCvIn);
	$("#cvTitle a:first").unbind('mouseout', slideCvOut);
	
	state = "cv";
	savedStep = currentStep;
	
	$("#cvTitle").animate({left: 20}, 100);
	$("#cvTitle").html("<br/><br/><a href='javascript:void(0)'>← Back to projects</a>");
	$("#cvTitle, #cv, #cv h4").unbind('click', gotoCV);
	$("#cvTitle").click(gotoProjects);
	
	$("#cv").css("cursor", "default");
	$("#cv").animate({left: 100}, 100);
	
	$("#nav").animate({left: 0, opacity:0}, 50);
	$("#infosNav .forProjects").animate({opacity:.3}, 50);
	$("#infosNav .forCv").animate({opacity:1}, 50);
	
	$("#intro").animate({left: -($("#projects").width() - 100)}, 100);
	$("#projects").animate({left: -($("#projects").width() - 00)}, 100, jQuery.easing.def, onGoToCV);
	$("#projects").css("cursor", "pointer");
	$("#projects").click(gotoProjects);
	
	$("#cvTitle a:first").mouseover(slideProjectsIn);
	updateUrl("cv");
}

function onGoToCV()
{
	//$("#projects").css("position", "fixed");
}

function gotoProjects()
{
	$("#message").fadeOut(0);
	$("#message").html("");
	
	$("#cvTitle a:first").unbind('mouseout', slideProjectsOut);
	$("#cvTitle a:first").unbind('mouseover', slideProjectsIn);
	
	state = "closed";
	
	$("#cvTitle").animate({left: cvTitleX}, 200);
	if(cvTitleX < 1200)	$("#cvTitle").html("<br/><br/><a href='javascript:void(0)'>About me →</a>");
	else 				$("#cvTitle").html("<br/><a href='javascript:void(0)'>About me →</a>");
	$("#cvTitle, #cv, #cv h4").unbind('click', gotoProjects);
	$("#cvTitle, #cv, #cv h4").click(gotoCV);
	
	$("#cv").css("cursor", "pointer");
	$("#cv").animate({left: cvX}, 200);
	
	$("#projects").css("cursor", "default");
	$("#projects").animate({left: 200}, 100, jQuery.easing.def, gotoSavedStep);
	$("#intro").animate({left: 300}, 100);
	
	$("#nav").animate({left: 1000, opacity:1}, 50);
	$("#infosNav .forProjects").animate({opacity:1}, 50);
	$("#infosNav .forCv").animate({opacity:.3}, 50);
	
	$("#cvTitle a:first").mouseover(slideCvIn);
	updateUrl();
}

function gotoNextImage()
{
	nextStep = (currentStep == steps.length-1)? 0:currentStep + 1;
	currentStep = nextStep;
	goto($(steps[nextStep]).offset().top - 124, 500);
}

function gotoPreviousImage()
{
	previousStep = (currentStep == 0)? steps.length - 1:currentStep - 1;
	currentStep = previousStep;
	goto($(steps[previousStep]).offset().top - 124, 500);
}

function gotoSavedStep()
{
	goto($(steps[savedStep]).offset().top - 124, 500);
}

function setCurrentProject(id, update)
{
	if(id != currentProject && id < projects.length & id >= -1)
	{
		var previousProject = currentProject;
		
		// CurrentProject
		if(id <= -1)
		{
			currentProject = -1; 
			currentStep = 0;
		}
		else if(id >= projects.length - 1)
		{
			currentProject = projects.length - 1;
		}
		else
		{
			currentProject = id;
		}
		
		// Previous
		if(currentProject == -1)
		{
			$("#previous").fadeOut(500, function(){
				$("#previous").html("");
			});
		}
		else if(currentProject == 0)
		{
			$("#previous").fadeOut(500, function(){
				$("#previous").html("Intro");
				$("#previous").fadeIn(500);
			});
		}
		else
		{
			if($("#previous").html() != "Previous project")
			{
				$("#previous").fadeOut(500, function(){
					$("#previous").html("Previous project"); 
					$("#previous").fadeIn(500);
				});
			}
		}
		
		// Next
		if(currentProject == projects.length - 1)
		{
			$("#next").fadeOut(500, function(){
				$("#next").html("Back to top"); 
				$("#next").fadeIn(500);
			});
		}
		else
		{
			if($("#next").html() != "Next project")
			{
				$("#next").fadeOut(500, function(){
					$("#next").html("Next project"); 
					$("#next").fadeIn(500);
				});
			}
		}
		
		// Social
		if(currentProject == -1)
		{
			$("#facebook, #twitter").fadeTo(0, 0);
		}
		else
		{
			$("#facebook, #twitter").fadeTo(0, 1);
		}
		
		
		
		if(update != undefined) updateCount();
		updateUrl();
		updateHead();
		
		track($("#project-"+currentProject+" h3").text());
	}
}


//////////////////////////////////////
//
//  Utils
//
//////////////////////////////////////

function trimPx(value)
{
	var pos = value.indexOf("px");
	var output = value.substring(0, pos);
	
	return parseInt(output);
}

function encodeURL(url)
{
	var output = url.toString();
	var pos;
	
	pos = output.indexOf(":");
	output = output.substring(0, pos)+ "%3A" + url.toString().substring(pos+1, url.toString().length);
	
	//pos = output.indexOf("#");
	//output = output.substring(0, pos)+"?v="+Math.random()+ "%23" + output.substring(pos+1, output.length);
	//output = output.substring(0, pos)+"%23" + output.substring(pos+1, output.length);
	
	while(output.indexOf("/") > -1)
	{
		pos = output.indexOf("/");
		output = output.substring(0, pos)+ "%2F" + output.substring(pos+1, output.length);
	}
	
	return output;
}

function track(page)
{
	pageTracker._trackPageview(page);
}

function log(value)
{
	if(value) 	console.log(value);
	else		console.log();
}
