(function($) {
  jQuery.fn.contextMenu = function ( name, actions, options ) {
    var me = this,
    win = $(window),
    menu = $('<ul id="'+name+'" class="context-menu"></ul>').hide().appendTo('body'),
    activeElement = null, // last clicked element that responds with contextMenu
    hideMenu = function() {
      $('.context-menu:visible').each(function() {
        $(this).trigger("closed");
        $(this).hide();
      });
    },
    default_options = {
      disable_native_context_menu: false,
      leftClick: true
    },
    options = $.extend(default_options, options);

    $(document).bind('click', function(e) {
      hideMenu();
    });

	var clickUser = $(this).attr("rel");
	
    $.each(actions, function(me, itemOptions) {
      var menuItem = $('<li><a rel="'+clickUser+'" href="#">'+me+'</a></li>');

      menuItem.appendTo(menu).bind('click', function(e) {
        itemOptions.click(activeElement);
		return false;
      });
	  
    });

    // fix for ie mouse button bug
    var mouseEvent = 'click';
    if ($.browser.msie && options.leftClick) {
      mouseEvent = 'click';
    } else if ($.browser.msie && !options.leftClick) {
      mouseEvent = 'click';
    }

    return me.bind(mouseEvent, function(e){
      // Hide any existing context menus
      hideMenu();

      var correctButton = ( (options.leftClick && e.button == 0) || (options.leftClick == false && e.button == 2) );
      if ($.browser.msie) correctButton = true;

      if( correctButton ){

        activeElement = $(this); // set clicked element

        if (options.showMenu) {
          options.showMenu.call(menu, activeElement);
        }

        // Bind to the closed event if there is a hideMenu handler specified
        if (options.hideMenu) {
          menu.bind("closed", function() {
            options.hideMenu.call(menu, activeElement);
          });
        }

        menu.css({
          visibility: 'hidden',
          position: 'absolute',
          zIndex: 1000
        });

        // include margin so it can be used to offset from page border.
        var mWidth = menu.outerWidth(true),
          mHeight = menu.outerHeight(true),
          xPos = ((e.pageX - win.scrollLeft()) + mWidth < win.width()) ? e.pageX : e.pageX - mWidth,
          yPos = ((e.pageY - win.scrollTop()) + mHeight < win.height()) ? e.pageY : e.pageY - mHeight;

        menu.show(0, function() {
          $('body').bind('click', hideMenu);
        }).css({
          visibility: 'visible',
          top: yPos + 'px',
          left: xPos + 'px',
          zIndex: 1000
        });

        return false;
      }
    });
  }
})(jQuery);


