$(document).ready(function () {
	/*
	
			DISPLAY META WHEN SCROLLING
			Behaviours and scripts inspired, taken and re-aranged 
			from the really nice work of Tomas Celizna for http://formsofinquiry.com
			Inspiration also comes from the mesmerising InfiniteScroll Plugin
	
			Yes.
			And then i took it;)
			Not really changed it at all.
			Just took the h1 out of the span, what is not nice coding.
			loving it. blessings.
			
	*/
	$('#tile_container').html($("#main_title").html());
	display_section_titles();	
	$('#auto_menu a').click(function(){	
			var destination = $('#to_'+$(this).attr('id'));	
			if (destination.length >0){
				$.scrollTo(destination,{axis:'y', duration:500, queue:false, offset: {left:0, top:-16}, onAfter: function() {}});
				return false;				
			} 			
			return false;			
	});
});
$(window).scroll(function(){ 
  display_section_titles();
});
$(window).resize(function () { 
  display_section_titles();
});
function display_section_titles(){
  var sectionArray = $.makeArray($(".postWrapper .page_paragraph"));  
  var window_scroll_top = $(window).scrollTop();
  var window_center = $(window).height()/2;
  window_center = 200;
  sectionArray.sort( function(a, b) { 
    return getDiff(a, window_scroll_top, window_center)>getDiff(b, window_scroll_top, window_center)?1:-1; 
  });
  $('#tile_container').html($(sectionArray[0]).children(".meta").html());
}
function getDiff(item, window_scroll_top, window_center){
  var item_viewportoffset_top=$(item).offset().top-window_scroll_top;
  var dist_of_top=Math.abs(item_viewportoffset_top-window_center);
  var dist_of_bottom=Math.abs(item_viewportoffset_top+$(item).height()-window_center);
  return Math.min( dist_of_top, dist_of_bottom);
}
