$(document).ready(function () {
  setup_section_titles();
  display_section_titles();
});

$(window).scroll(function () { 
  display_section_titles();
});

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





// ----------------------------------------
function setup_section_titles() {
  $(".section h1").css("position", "fixed").css("bottom", "17px");
}

// ----------------------------------------
function display_section_titles() {
  var sectionArray = $.makeArray($(".section"));
  
  var window_scroll_top = $(window).scrollTop();
  var window_center = $(window).height()/2;
  window_center = 144;
  
  // sort sections by their relative distance to the center of the window
  sectionArray.sort( function(a, b) { 
    return getDiff(a, window_scroll_top, window_center) > getDiff(b, window_scroll_top, window_center) ? 1 : -1; 
  });
  
  $(".section h1:visible").hide();
  $(sectionArray[0]).children("h1").show();
  
  $(".active").removeClass("active");
  $(sectionArray[0]).addClass("active");
}

// ----------------------------------------
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 minimum of distances of top and bottom of an element
  // to center of the window
  return Math.min( dist_of_top, dist_of_bottom );
}







