$(function(){

window.onunload = function(){}; 

var leftfixed;
var widthfixed;

function init()
{
	leftfixed = Math.floor($('.project_info').offset().left);
	widthfixed = Math.floor($('.project_info').width());
	
	if($(window).width() > 799)
	{
		$('.project_info').each(function()
		{
			$(this).css({"position":"absolute","top":"0","left":"","width":""});
		});
		
		$(window).scroll(projectRailScroll);
	
	}else
	{
		$('.project_info').each(function()
		{
			$(this).css({"position":"relative","left":"","width":""});
		});
		$(window).unbind("scroll");
	}
	
	toppos = ($(window).height() - $('.main').height()) / 2;

	$('.main').css('top',toppos);
	
	
}


$(window).resize(function()
{
	init();
});

var projectRailScroll = function()
{
	var firstProjectID = $(".entry:first").attr("id");
	firstProjectID =  "#"+firstProjectID;
	var feedHeaderHeight = 30;
	var previousProject = activeProjectHeight = activeProject = activeRailHeight = activeRailTop = activeProjectTop = "";
        
	$(".entry:in-viewport").each(function()
	{
		activeProject = "#"+$(this).attr("id");
		
	});
        
	activeProjectHeight = $(activeProject).height();
	activeProjectTop = ($(activeProject).length > 0) ? $(activeProject).offset().top : false;
	activeRailTop = $(activeProject+ " .project_rail").offset().top;
	activeRailHeight = $(activeProject+ " .project_rail").height(); 
	$(activeProject+ " .project_rail").css({"position":"fixed","top":feedHeaderHeight,"left":leftfixed,"width":widthfixed});
	var scrollTop = $(window).scrollTop();
	var activeTop = scrollTop + feedHeaderHeight;
	
	
	// When projects are below the scroll, set them to position top
	if((activeProjectTop - activeProjectHeight) <= activeTop)
	{
		
		$(".project_rail").each(function()
		{ 
			if($(this).offset().top >= activeTop)
			{	
				$(this).css({"position":"absolute","top":"0","left":"","width":""});
			}
		});
	}
     
	// if this is the first project, set to the top
	if(activeProject == firstProjectID)
	{
		$(firstProjectID+ " .project_rail").css({"position":"absolute","top":"0","left":"","width":""});
	}
	
	// if the active project rail hits the bottom of the project, stick there
	if(activeProjectTop && activeProjectHeight - activeRailHeight + activeProjectTop <= activeTop)
	{
		$(activeProject+ " .project_rail").css({"position":"absolute","top":"","bottom":0,"left":"","width":""});
 
	// if the active project is within our viewport 
	} else if(activeProjectTop && activeProjectTop <= activeTop)
	{

	// if the rail hits the project top, stick to the top

		if(activeRailTop <= activeProjectTop)
		{
			$(activeProject+ " .project_rail").css({"position":"absolute","top":"0","bottom":"","left":"","width":""});
			
			// otherwise, move with the scroll
		} else
		{
			$(activeProject+ " .project_rail").css({"position":"fixed","bottom":"","top":feedHeaderHeight,"left":leftfixed,"width":widthfixed});
		}
	}
}


init();


});
