/*
 * ContextMenu - jQuery plugin for right-click context menus
 *
 * Author: Chris Domigan
 * Contributors: Dan G. Switzer, II
 * Parts of this plugin are inspired by Joern Zaefferer's Tooltip plugin
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Version: r2
 * Date: 16 July 2007
 *
 * For documentation visit http://www.trendskitchens.co.nz/jquery/contextmenu/
 *
 */

(function($) {

 	var menu, shadow, trigger, content, hash, currentTarget, autohide, sizeadded;
  var defaults = {
    menuStyle: {
      listStyle: 'none',
      padding: '1px',
      margin: '0px',
      backgroundColor: '#fff',
      border: '1px solid #999',
      width: '100px'
    },
    itemStyle: {
      margin: '0px',
      color: '#000',
      display: 'block',
      cursor: 'pointer',
      padding: '3px',
      border: '1px solid #fff',
      backgroundColor: 'transparent'
    },
    itemHoverStyle: {
      border: '1px solid #0a246a',
      backgroundColor: '#b6bdd2'
    },
    eventPosX: 'pageX',
    eventPosY: 'pageY',
    shadow : true,
    onContextMenu: null,
    onShowMenu: null,
	// DRP: trigger option
	trigger: 'contextmenu',
	// DRP: direction option. 'up' to open menu upwards
	direction: 'down',
	// FZ: direction option. 'right' to open menu to right
	xdirection: 'right',
	timeout: true,
	//FZ: autohide, click away to hide
	autohide: true,
	closeicon: false
 	};

  $.fn.contextMenu = function(id, options) {
    if (!menu) {                                  // Create singleton menu
		menu = $('<div id="jqContextMenu"></div>')
			.hide()
			.css({position:'absolute', zIndex:'500'})
			.appendTo('body')
			.bind('click', function(e) {
				e.stopPropagation();
			});
    }
    if (!shadow) {
      shadow = $('<div></div>')
                 .css({backgroundColor:'#000',position:'absolute',opacity:0.3,zIndex:499})
                 .appendTo('body')
                 .hide();
    }
	options = options || [];
    hash = hash || [];
    hash.push({
      id : id,
      menuStyle: $.extend({}, defaults.menuStyle, options.menuStyle || {}),
      itemStyle: $.extend({}, defaults.itemStyle, options.itemStyle || {}),
      itemHoverStyle: $.extend({}, defaults.itemHoverStyle, options.itemHoverStyle || {}),
      bindings: options.bindings || {},
      shadow: options.shadow || options.shadow === false ? options.shadow : defaults.shadow,
      onContextMenu: options.onContextMenu || defaults.onContextMenu,
      onShowMenu: options.onShowMenu || defaults.onShowMenu,
      eventPosX: options.eventPosX || defaults.eventPosX,
      eventPosY: options.eventPosY || defaults.eventPosY,
	  // DRP: trigger option
	  trigger: options.trigger || defaults.trigger,
	  // DRP: direction option
	  direction: options.direction || defaults.direction,
	  // FZ: direction option on x-axis
	  xdirection: options.xdirection || defaults.xdirection,
	  // FZ: mouseout timeout.
	  timeout: options.timeout || defaults.timeout,
	  // FZ: autohide 
	  autohide: options.autohide || defaults.autohide,
	  // FZ: autohide
	  closeicon: options.closeicon || defaults.closeicon
    });
	autohide = options.autohide || defaults.autohide;

    var index = hash.length - 1;
	// DRP: trigger option
    $(this).bind(hash[index].trigger, function(e) {
      // Check if onContextMenu() defined
      var bShowContext = (!!hash[index].onContextMenu) ? hash[index].onContextMenu(e) : true;
      if (bShowContext) display(index, this, e, options);
      return false;
    });

	if(options.event && !$.browser.msie) {
		//for all non-ie browser. the event need to be triggered onclick
		setTimeout(function() {	display(index, this, options.event, options); }, 1);
	}
    return this;
  };

  function display(index, trigger, e, options) {
    var cur = hash[index];
    content = $('#'+cur.id).find('ul:first').clone(true);

	//FZ-MOD
	var icon;
	if(options.closeicon)
		icon = $('#'+cur.id).find('a.dialogClose').clone();

    content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
      function() {
		// DRP: added noHover for non-menu items
        $(this).not('.noHover').css(cur.itemHoverStyle);
      },
      function(){
        $(this).css(cur.itemStyle);
      }
    ).find('img').css({verticalAlign:'middle',paddingRight:'2px'});

    // Send the content to the menu
	//FZ-MOD
	menu.html(""); //clean up first
	if(options.closeicon)
		menu.append(icon);
    menu.append(content);

    // if there's an onShowMenu, run it now -- must run after content has been added
		// if you try to alter the content variable before the menu.html(), IE6 has issues
		// updating the content
    if (!!cur.onShowMenu) menu = cur.onShowMenu(e, menu, cur);

    $.each(cur.bindings, function(id, func) {
      $('#'+id, menu).bind('click', function(e) {
	    hide();
        func(trigger, currentTarget);
      });
    });
	// DRP: direction option, and handle event position of 0,0 which indicates enter was pressed rather than a mouse click
	var offset = {
		top: e[cur.eventPosY],
		left: e[cur.eventPosX]
	}

	if (offset.top == 0 && offset.left == 0)
		offset = $(trigger).offset();
	
	//FZ-MOD
	offset.top -= options.direction == 'up' ? menu.height() : 0;
	offset.left -= options.xdirection == 'left' ? menu.width() : 0;
	
	if(menu.height() > 200) {
		menu.find('ul').height(200).css("overflow-y", "scroll");
		if(cur.closeicon) {
			menu.find('a.dialogClose').css('right', '20');
		}
	}

	if(cur.closeicon && !sizeadded) {
		menu.width(menu.width() + 45);
		sizeadded = true;
		//ajust the size we added for closeicon
		offset.left -= 45;
	}

	menu.css(offset).show();
	if (cur.shadow) shadow.css({width:menu.width(),height:menu.height(),left:offset.left+3,top:offset.top+3}).show();

    $(document).one('click', hide);
	
	//FZ-MOD
	if(cur.timeout == true) {
		// DRP: Track mouse so that once it enters the extents of the menu, it will disappear after the mouse has left it after a period of time
		menu.one("mouseover", function() {
			var mouseIn = true;
			menu.mouseover(function() {
				mouseIn = true;
			});
			menu.mouseout(function() {
				mouseIn = false;
				setTimeout(function() {
					if (!mouseIn) {
						menu.hide();
						shadow.hide();
					}
				}, 4000);
			});
		});
	}
	
	// DRP: Remove focus from element so that enter key doesn't cause a click event, with coordinates of 0,0 which would 
	//   cause the menu to appear in upper left corner of screen
	$(document).focus(null);

	//extra click verify
	$j(document).bind("click", function() {
		if(menu.is(':visible'))
			hide();
	});
  }

  function hide() {
	//FZ-MOD. make sure when there is popup, the click won't trigger hide event
	var simplemodal = $('#simplemodal-container');
	if(simplemodal.length == 0 || !simplemodal.is(':visible')) {
		menu.hide();
		shadow.hide();
	}
  }

  // Apply defaults
  $.contextMenu = {
    defaults : function(userDefaults) {
      $.each(userDefaults, function(i, val) {
        if (typeof val == 'object' && defaults[i]) {
          $.extend(defaults[i], val);
        }
        else defaults[i] = val;
      });
    }
  };

})(jQuery);

$j(function() {
  $j('div.contextMenu').hide();
});