// START

var rl;
$(document).ready(function(e) 
{
	rl = new RomainLagrange();
	rl.init();
});


function RomainLagrange()
{
	this.init =  function()
	{
		initUrl();
		initTitle();
		initInfos();
		initImages();
	}
	
	/**********************
	*	TITLE
	**********************/
	
	function initTitle()
	{
		$('article header').each(function() 
		{
			var target = $(this);
			
			var hwidth = $(this).find('h2').width();
			var imgwidth = 0;
			var hx = Math.round((904 - imgwidth - hwidth) / 2) + 'px';
			
			target.css('margin-left', hx);

			if($('a img', target).length > 0)
			{
				$('a img', target).imagesLoaded(function(e) 
				{
					imgwidth = $(this).width(); 
					hx = Math.round((904 - imgwidth - hwidth) / 2) + 'px';
					
					target.css({'margin-left' : hx, 'visibility' : 'visible'});
				});
			}
			else
			{
				target.css({'visibility' : 'visible'});
			}
		});
	}
	
	/**********************
	*	INFOS
	**********************/
	
	function initInfos()
	{
		$('#informations').fadeOut(0);
		$('#show_informations').click(showInformations);
		$('#hide_informations').click(hideInformations);
	}
	
	function showInformations()
	{
		$('#informations').stop().css({'visibility' : 'visible'}).fadeIn(100, hideProjects);	
	}
	
	function hideProjects()
	{
		$('#page').css({'display' : 'none'});
	}
	
	function hideInformations()
	{
		$('#page').css({'display' : 'block'});
		$('#informations').stop().fadeOut(500);
	}
	
	/**********************
	*	IMAGES
	**********************/

	function initImages()
	{
		$('.images img').click(clickImage);
	}
	
	function clickImage()
	{
		$(this).parent().append($(this));
	}
	
	/**********************
	*	URL
	**********************/
	
	var pos = -1;
	var url;
	var path = '';
	var urls = [];
	function initUrl()
	{
		$('html,body').scrollTop(0);
		
		$('article').each(function(index, element)
		{
            urls.push($(this).attr('id'));
        });
		
		path = $(location).attr('href').split("#")[1];
		
		if(path)
		{
			getPos();
			
			if(pos != -1)
			{
				move(2000);	
			}
		}
		
		$(document).keydown(keyPressed);
		
		
		$(window).scroll(changeUrl);
	}
	
	function keyPressed(e)
	{
		e.preventDefault();
		var code = (e.keyCode ? e.keyCode : e.which);
		
		switch (code) 
		{
			case 38:
				if(pos == 0 || pos == -1)
				{
					pos = urls.length - 2;	
				}
				else
				{
					pos--;
				}
				move(250);
				break;
			case 40:
				if(pos == urls.length - 2)
				{
					pos = 0;
				}
				else
				{
					pos++;
				}
				move(250);
				break;
		}
	}
	
	function move(time)
	{
		$('html,body').stop().animate({scrollTop: $("#"+urls[pos]).offset().top}, time, changeUrl);
	}
	
	function getPos()
	{
		for (var i = 0; i < urls.length; i++)
		{
			if(urls[i] == path)
			{
				pos = i;
			}
		}
	}
	
	function changeUrl()
	{
		url = $('article:in-viewport:first').attr('id');    
			
		if(url != path)
		{
			path = url;
			//$(location).attr('href', $(location).attr('href').split("#")[0] + '#' + url);
			getPos();
		}
	}
}
