var obj = null;
var willhide = null;

$(document).ready(function(){
  
  var headers = $("#HM_Head img");
  
  /* activate the navigation submenus */
  var x_offset = 0;	// initial pixel shift from left edge of window
  var y_offset = 0;
  $("ul.HM_Menu").each(function setupHM_Menu(n) {
	// align dropdown list with header
	hoverMenu = $(this);
    hoverMenu.css('position','absolute');
	hoverMenu.css('width','150px');
    hoverMenu.css('top', y_offset+'px');
    hoverMenu.css('left', x_offset+'px');
    x_offset = x_offset + headers[n].width; // Get position from image, set offset for next item

	// group submenu and header by common ID
    unid = 'HM_Menu'+(n+1);
    hoverMenu.addClass(unid); //for hover targets, must use class rather than id
    headers[n].id = unid;

	hoverMenu.hover(function submenuOver(){
		if(willhide) clearTimeout(willhide);
	}, function submenuOut() {
		willhide = setTimeout(function() {
		  obj.hide();
		  obj = null;
    	}, 500);     // delay (ms)
	});

  });

  /* top-level hover menu behavior */
  headers.hover(function headerOn() {
    this.src = toggleHN(this.src, 'on'); // change image
	if(willhide) clearTimeout(willhide);
  	if (obj) {   // and hide visible submenu
		obj.hide();
		obj = null;
  	}
    if (this.id) { // show corresponding submenu
      obj = $('ul.'+this.id);  // IMPORTANT: selecting by class,
                               // since id doesn't seem to work.
	  obj.show();
    }
  }, function headerOut() {
    this.src = toggleHN(this.src, 'off');
    if (obj) {
      willhide = setTimeout(function() {
        obj.hide();
	    obj = null;
      }, 800);     // delay (ms)
    }
  });

});

/* Top-Menu elements change color on mouseover */
/* TODO: pre-load hover images before rather than after page renders, or use css-sprites */
function toggleHN(img_src, hov_status) {
  re = /HN[R]?(\w+\.gif)/ ; // specific (legacy) filename requirements
  if (hov_status == 'on') {
    img_name = img_src.replace( re, "HNR$1");
  } else if (hov_status == 'off') {
    img_name = img_src.replace( re, "HN$1");
    // TODO: test for 'HNOxxx.gif', if we wish to use this script below site root
  }
  return img_name;
}
