$.fn.gorePMenu = function() {
  
  this.each(function() {
    
    var root = this, zIndex = 1000;
    var minSubWidth = 100;
    
    function getSubMenu(ele) {
      var idEle = ele.id;
      if (!idEle) return null;
      if (getIdPrefix(idEle) == "sm") {
        return ele;
      } else {
        var idSM = "SM" + getIdSuffix(idEle);
        var sm = $("#" + idSM);
        if (sm.length == 0) return null;
        return sm[0];
      }
    }
    
    function getMenuItem(ele) {
      if (ele.tagName.toLowerCase() != 'td') return null;
      if (getIdPrefix(ele.id).toLowerCase() != "mi") return null;
      return ele;
    }
    
    function getIdPrefix(id) {
      if (id.length < 3) return null;
      return id.substr(0, 2);
    }
    
    function getIdSuffix(id) {
      if (id.length < 3) return null;
      return id.substr(2, id.length - 2);
    }
    
    function isNeedMargin(ele) {
      if (ele == root) return false;
      if (ele == root || $(ele).parent()[0] == root) return false;
      try {
        if (ele.tagName.toLowerCase() == "ul" && $(ele).parent().parent() == root) return false;
      } catch(exc) { return false; }
      return ele.tagName.toLowerCase() == "li";
    }
    
    function hide() {
      var subMenu = getSubMenu(this);
      if (!subMenu) return;
      $.data(subMenu, 'cancelHide', false)
      setTimeout(function() {
        if (!$.data(subMenu, 'cancelHide')) { $(subMenu).hide(); $.data(subMenu, "isVisible", false); } 
      }, 150);
    }
  
    function show() {
      var subMenu = getSubMenu(this);
      if (!subMenu) { return; }
      $.data(subMenu, "cancelHide", true);
      var miObj = getMenuItem(this);
      if (!miObj) { return; }
      if (!$.data(subMenu, "isVisible")) {
        $(subMenu).css({zIndex: ++zIndex}).show();
      }
      $.data(subMenu, "isVisible", true);
      
      var miOffset = $(miObj).offset();
      var miWidth = parseInt($(miObj).css("paddingLeft").replace("px","")) + parseInt($(miObj).css("paddingRight").replace("px","")) + parseInt($(miObj).width());
      if ($(subMenu).hasClass("tSubSub")) {
        $(subMenu).css({left: miOffset.left + miWidth + 1 + "px"}).css({top: miOffset.top + "px"});
        if ($(subMenu).width() < minSubWidth) {
          $(subMenu).width(minSubWidth);
        }
      } else {
        $(subMenu).css({left: miOffset.left + 2 + "px"}).css({top: miOffset.top + 28 + "px"});
        if ($(subMenu).width() < miWidth - 3) {
          $(subMenu).width(miWidth - 3);
        }
      }
    }
    
    $('.tSubMenu,.tdMenuItem', document.body).hover(show, hide);
    
  });
  
};

/*
function ddebSM(act, subMenu) {
  ddeb(act + " " + subMenu.id, $.data(subMenu, 'cancelHide'));
}

function ddeb(name, str) {
  $("#ddeb").append("<br/>\n" + name + " : " + str);
}

*/
