$(document).ready(function () {
  remove_focus_borders();
  setup_section_titles();
  display_section_titles();
  $('.media').media();
  normalize_images();
});

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

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

// ----------------------------------------
function normalize_images() {
  var maxH = 0;
  $(".normalize").each(function(){
    var h = $(this).height();
    maxH = Math.max(maxH, h);
  });
  
  $(".normalize").each(function(){
    $(this).height(maxH);
  });
}

// ----------------------------------------
function init_contributor(e, id) {
  var full_id = "contributor_"+id+"_detail";
  
  // if this view of contributor already exists
  if( $(e).next().attr("id") == full_id ) {
  //   // hide it
    $('#'+full_id).toggle();
  } else {
  //   // remove the other case
    $('#'+full_id).remove();
    $(e).after("<span id='"+full_id+"' class='contributor_detail' />");
    // $(e).next().html("Loading&hellip;");    
  }
}

// ----------------------------------------
// remove focus borders in Firefox
function remove_focus_borders() {
	$("a").each( function() {
		$(this).bind("focus", function() { $(this).blur(); });
	});
}

// ----------------------------------------
function setup_section_titles() {
  $("h1").css("position", "fixed").css("top", "10px");
}

// ----------------------------------------
function display_section_titles() {
  var sectionArray = $.makeArray($(".section"));
  
  var window_scroll_top = $(window).scrollTop();
  var window_center = $(window).height()/2;
  window_center = 100;
  
  // 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 );
}






