mb_href = null;

function dirname(path) {
  return path.replace(/\\/g,'/').replace(/\/[^\/]*$/, '');
}

function position_overlay(overlay, element, top_offset, left_offset)
{
  var t = element.position();
  var mt = parseInt(element.css('margin-top'));
  var ml = parseInt(element.css('margin-left'));

  if(!top_offset) { top_offset = 0; }
  if(!left_offset) { left_offset = 0; }

  overlay.show();
  overlay.css({
    position: "absolute",
    top: (t.top+mt+top_offset)+"px",
    left: (t.left+ml+left_offset)+"px"
  });
}

function setup_overlay(element_class, overlay, active , overlay_top_offset, overlay_left_offset, active_top_offset, active_left_offset, path_strip)
{
  var overlay_found = false;

  $(element_class).each(function() {
      var mb = $(this);
      var mo = overlay;
      var ma = active;

      var href = mb.parent()[0].href;

      if(!overlay_found) {
	var t_href = href;
	var t_location = document.location.href;

	if(t_href == t_location) {
	  overlay_found = true;
	} else if(path_strip && t_location.length > t_href.length && t_location.indexOf(t_href)== 0) {
	  overlay_found = true;
	}

	if(overlay_found) {
	  position_overlay(ma, mb, active_top_offset, active_left_offset);
	}
      }

      mb.mouseover(function(evt) {
	  var mb = $(this);
	  var href = mb.parent()[0].href;

	  if(href == document.location) {
	    return;
	  }

	  mb_href = mb.parent()[0].href;

	  if(!mb_href) {
	    return;
	  }

	  position_overlay(mo, mb, overlay_top_offset, overlay_left_offset);
          $('a', mo)[0].href = mb_href;
	});

      mo.mouseout(function(evt) {
	  mo.hide();
	  mb_href = null;
	});
    });
}

$(function() {
    setup_overlay('.minibox', $('#minibox_overlay'), $('#minibox_active'), 0, 0, -6, 1);
    setup_overlay('.highlight-box', $('#highlight_overlay'), $('#highlight_active'), -5, -6, -5, -6, 1);
});
