(function($)
{
  //
  // plugin definition
  //
  $.fn.glossaryToolTip = function(options) 
  {

    // build options
    var opts = $.extend({}, $.fn.glossaryToolTip.defaults, options);

    // iterate and reformat each matched element
    return this.each(function() 
    {
      var $this = $(this);

      $this.data('glossaryToolTip.opts', opts);
	  // initialize your elements here
      
      $this.bind('mouseover.glossaryToolTip', showToolTip);      
    });

  };


  //
  // define private functions 
  //
	function showToolTip(ev)
	{
		var $this = $(this);
		
		// create tooltip with loading indicator
		var opts	 = $this.data('glossaryToolTip.opts')
		var $tooltip = $(opts.wrap_pre + opts.indicator + opts.wrap_post);
		
		// position tooltip
		$tooltip.css('position', opts.position);		
		$tooltip.css('left',(ev.pageX + opts.offsetX) + 'px');
		$tooltip.css('top', (ev.pageY + opts.offsetY) + 'px');
		
		// removal function
		$tooltip.glossaryToolTip_remove	= function()
		{
			$tooltip.remove();
			$(this).unbind('mouseout.glossaryToolTip');
		};
		
		// bind mouse out event
		if (opts.use_timeout)
		{
			window.setTimeout($tooltip.glossaryToolTip_remove, opts.timeout);
		}
		else
		{
			$this.bind('mouseout.glossaryToolTip', $tooltip.glossaryToolTip_remove);
		}			
		
		$('.glossarytooltip_d1').hide()
		$('body').append($tooltip);
		$('.alpha-image').ifixpng();
	
		// retreive glossary term description via ajax
		$.get(
			this.href, 
			function(data)
			{
				var json = eval(data);
				var content = '<' + opts.result_headline_type + '>' + json.headline + '</' + opts.result_headline_type + '>' + json.content;			
				$('.indicator-glossary', $tooltip).replaceWith(content);
			},
			'text'
		);
	}
	
  //
  // define and expose public functions
  // carefull : $(this) means $.fn.<pluginname>, not an HTML element here 
  //
  $.fn.glossaryToolTip.destroy	=	
  function() 
  {
  };
 
  //
  // plugin defaults
  //
  $.fn.glossaryToolTip.defaults = 
  {
  	blocking				:	'true',
  	wrap_pre				: 	'<div class = "glossarytooltip_d1 alpha-image"><div class = "glossarytooltip_d2">',
  	wrap_post				:	'</div></div>',
  	indicator				:   '<div class="indicator-glossary"><p>Glossareintrag wird geladen ...</p></div>',
  	result_headline_type	:	'h2',
  	offsetX					:	-30,
  	offsetY					:	10,
  	position				:	'absolute',
  	timeout					: 	10000,
  	use_timeout				:   false
  };
	
})(jQuery);



