/*
 * 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;
  var defaults = {
    menuStyle: {
      listStyle: 'none',
      padding: '0px',
      margin: '0px',
      backgroundColor: 'transparent',
      border: '0px solid #999',
      width: '100%',
      height: '48px'
    },
    itemStyle: {
      float: 'left',
      margin: '0px',
      color: '#000',
      display: 'block',
      cursor: 'pointer',
      padding: '0 5px 0 0',
      border: '0px solid #fff',
      backgroundColor: 'transparent'
    },
    itemHoverStyle: {
      border: '0px solid #0a246a',
      backgroundColor: 'transparent'
    },
    eventPosX: 'pageX',
    eventPosY: 'pageY',
    shadow : false,
    onContextMenu: null,
    onShowMenu: null,
    onBindingDraw: null
 	};

  $.fn.contextMenu = function(id, options) {
    if (!menu) {    
          // Create singleton menu
          menu = $('<div id="jqContextMenu" class="adminContextMenu">'+
					  '<div class="adminContextMenuLeft">' + 
					  	'<div class="adminContextMenuRight">' +
					  		'<div class="adminContextMenuMiddle">'+
					  			'<div id="jqContextMenuBody" class="adminContextMenuBody">'+
					  			'</div>'+
					  		'</div>'+
					  		'<div class="adminContextMenuClose" id="jqContextMenu_close" onclick="$(\'#jqContextMenu\').hide()"></div>'+
					  	'</div>'+
					  '</div>'+
					'</div>')
               .hide()
               .css({position:'absolute', zIndex:'1010'})
               .appendTo('body')
               .bind('click', function(e) {
                 e.stopPropagation();
               });
    }
    if (!shadow) {
      shadow = $('<div></div>')
                 .css({backgroundColor:'#000',position:'absolute',opacity:0.2,zIndex:499})
                 .appendTo('body')
                 .hide();
    }
    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,
      onBindingDraw: options.onBindingDraw || defaults.onBindingDraw,
      eventPosX: options.eventPosX || defaults.eventPosX,
      eventPosY: options.eventPosY || defaults.eventPosY
    });

    var index = hash.length - 1;
    $(this).bind('contextmenu', 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;
    });
    return this;
  };

  function display(index, trigger, e, options) {
    var cur = hash[index];
    content = $('#'+cur.id).find('ul:first').clone(true);
    content.css(cur.menuStyle).find('li').css(cur.itemStyle).hover(
      function() {
        $(this).css(cur.itemHoverStyle);
      },
      function(){
        $(this).css(cur.itemStyle);
      }
    ).find('img').css({verticalAlign:'middle',paddingRight:'0px'});

    // Send the content to the menu    
   // menu.html(content);
    $('#jqContextMenuBody', menu).html(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) {
    	var result = cur.onShowMenu(e, menu);
    	if(result === false) return false;
    	menu = result;
    }
    	
    $('li', menu).hide();
    
    $.each(cur.bindings, function(id, func) {
    	if (!!cur.onBindingDraw) func = cur.onBindingDraw(e, id, func);
    	if(func != false) {
	    	$('#'+id, menu).show();
	    	$('#'+id, menu).find(':first-child').show();
			$('#'+id, menu).bind('click', function(e) {
				if(id != 'editInPlace') hide();
				func(trigger, currentTarget, menu);
			});
    	}
    });

    var m_left = e[cur.eventPosX];
    var m_top = e[cur.eventPosY]-45;
    if(m_top < 0) m_top = 0; // if the box is above the page
    var sm_left = e.pageX+2;
    var sm_top = e.pageY-123;
    
    menu.css({'left': m_left,'top': m_top}).show();
    if (cur.shadow) shadow.css({ width: menu.width(), height: menu.height(), left: sm_left, top: sm_top}).show();
    $(document).one('click', hide);
  }

  function hide() {
    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);

$(function() {
  $('div.contextMenu').hide();
});