// Expand matched elements to fill all available vertical space in container
//  (or the document body if container not specified)
// Limitations:
// - if called on two elements in the same container, the first element handled
//   gets all the available height
// - may have issues with non-pixel heights (percentages, ems, etc)
(function($){
var _resize_pending = null;
$.fn.heightexpand = function(container){
  if (!container) container = document.body;
  this.each(function(){ // operate separately on each item to be expanded
	var height = 0;
	for (var e = this; e != container; e = e.parentNode)
		$(e).siblings(":not(script)").each(function(){
			var _ = $(this);
			// only tally elements in normal flow
			if (!(   /absolute|fixed/.test(_.css('position'))
			      || /none/.test(_.css('display')) ))
			{
				var _height = _.outerHeight();
				if (_height) height += parseInt(_height);
			}
		});
	clientheight = $(window).height();
	if (clientheight > 0)
		$(this).height(clientheight - height + "px");
  });
  // keep expanded heights current with changes to browser
  var _these = this;
  // the resize event can be flaky on some browsers; this works around
  $(window).one('resize', function(){
	if (_resize_pending) clearTimeout(_resize_pending);
	_resize_pending = setTimeout(function(){ _these.heightexpand() }, 10);
  });
};
})(jQuery);
