/*
* jQuery Popup
* Timothy Oliver
*
* A small jQuery plugin that 
* handles the framework to set up
* a popup element on the screen.
*
*/

(function($) {
	var popup = null;
	var popup_content = null;
	
	var pending = false;
	var next = null;
	
	var settings = { 
	
	};
	
	var methods = {
		init: function( html, options)
		{
			//import any settings
			if( options )
				$.extend( settings, options );
			
			//create the popup object raw out of HTML
			if( !popup )
			{
				popup = $('<div id="popup" style="display:none;"><div id="popup_arrow"></div></div>' );
				popup_content = $('<div id="popup_content"></div>' );

				//append it to the document
				$( document.body ).append( popup );
				popup.append( popup_content );
			}
			
			//assign the events to each of the elements
			$(this).each( function() 
			{
				//set mouse over action
				$(this).mouseenter( function()
				{ 
					methods.show.apply( this, [ html ] );
				} );
				
				//set mouse out action
				$(this).mouseleave( function() 
				{ 
					methods.hide.apply( this );
				} );
			} );
		},
		
		show: function( html )
		{ 
			//if pending (ie another element is fading), set this one to appear next
			if( pending )
			{	
				next = this;
				return;
			}
			else
			{
				next = null;	
			}
		
			//set the popup's html first to work out proper dimensions
			popup_content.html( html );
			
			var popup_width = popup.outerWidth();
			var popup_height = popup.outerHeight(true);
			
			//calc the position of the popup
			var this_origin = $(this).offset();
			var this_width = $(this).width();
			
			//calc the target origin of the popup
			var popup_origin = { left: ( this_origin.left+(this_width*0.5) ) - ( popup_width*0.5 ),
									top: ( this_origin.top - popup_height ) };
									
			//position the popup
			popup.css( { left: popup_origin.left+'px', top: popup_origin.top+'px' } );
			
			//show it
			popup.fadeIn( 400 );
		},
		
		hide: function()
		{
			//set pending to stop others from calling show
			pending = true;			
			
			//if the pending element is moused off, cancel
			if( this == next )
				next = null;	

			popup.fadeOut( 400, function() {
				pending = false;
				if( next )
					$(next).trigger('mouseenter');
			} );
		}
	};
	
	$.fn.popup = function( method )
	{
		if ( methods[method] ) {
			return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else {
			return methods.init.apply( this, arguments );
		}	
	}
})(jQuery);
