(function() {

	jQuery.fn.flyout = function(o) {

		jQuery(this).each( function() {

			var el = jQuery(this);
			var flyout = jQuery(this).find('.flyout');

			$(el).hoverIntent({

				sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
				interval: 150, // number = milliseconds for onMouseOver polling interval
				timeout: 200, // number = milliseconds delay before onMouseOut

				over: function() {

					var f = $(el).find('.flyout');

					// Hide all flyouts
					$('.flyout').hide();

					// Min-width/height fix
					if( o.minWidth ) if( $(f).outerWidth() > o.minWidth ) $(f).height(o.minWidth);
					if( o.minHeight ) if( $(f).outerHeight() > o.minHeight ) $(f).height(o.minHeight);


					var x = $(this).offset().left + $(this).outerWidth();
					var y = $(this).offset().top;

					if( o.x_offset ) x = x + parseInt(o.x_offset);
					if( o.y_offset ) y = y + parseInt(o.y_offset);

					// Keep within viewport
					if( (y + $(flyout).outerHeight()) > ($(window).height() + $(window).scrollTop()) ) {
						y = ($(window).height() + $(window).scrollTop()) - $(flyout).outerHeight();
					}

					if( (x + $(flyout).outerWidth()) > ($(window).width() + $(window).scrollLeft()) ) {
						x = ($(window).width() + $(window).scrollLeft()) - $(flyout).outerWidth();
					}

					if( x < 0 ) x = 0;
					if( y < 0 ) y = 0;

					$(f).css({
						position: 'absolute',
						zIndex: 9999,
						left: x + 'px',
						top: y + 'px'
					}).show();

				},

				out: function() {

					$(this).find('.flyout').hide();

				}

			});

			// Hide flyout on selection
			$(el).find('A').click( function() {
				// Hide all flyouts
				$('.flyout').hide();
			});

		});

		return jQuery(this);

	}

})();

