/*
 * @(#)jquery.xlt.hoverBox-1.2.js		1.00 11/09/30
 *
 * Copyright (c) 2011 SG Büromedien GmbH
 * Märkischer Ring 120, 58097 Hagen, Deutschland
 * All rights reserved.
 * 
 * @author		Marcus Holtgräwe
 * @version		1.2 06 Oct 2011
 */

(function($) {
	$.fn.hoverBox = function(value) {
		if ((value === undefined) || (typeof value == 'object')) {
			$.fn.hoverBox.defaults = {
				width : '300px',
				left: '0px',
				top: '0px'
			};
			
			$.fn.hoverBox.options = $.extend({}, $.fn.hoverBox.defaults, value || {});
			var options = $.fn.hoverBox.options;
			
			var markup =
				'<div class="arrow-up"></div> \
				<div class="top-content-wrapper"> \
					<div class="drop-shadow-top-right"></div> \
				</div> \
				<div class="drop-shadow-right"> \
					<div class="content"></div> \
				</div> \
				<div class="drop-shadow-bottom-left"></div> \
				<div class="drop-shadow-bottom-right"></div> \
				<div class="drop-shadow-bottom"></div>';
			$(this).html(markup).hide().addClass('hover-box hover-box-visible');
			$(this).css('position', 'absolute');
			$('.content', this).css('width', options.width);
			
			var box$ = $(this);
			$('*').mouseover(function() {
				var elem$ = $(this).closest('.hover-box-visible');
				if (elem$.length <= 0) {
					hide.call(box$);
				}
				return false;
			});
			
			var trigger$ = options.trigger;
			trigger$.addClass('hover-box-visible');
			$('*', trigger$).mouseenter(
				function() {
					if (box$.find(':visible').length <= 0) {
						show.call(box$);
					}
					return false;
				}
			);
			
		} else if (typeof value == 'string') {			
			switch (value) {
				case 'show':
					show.call(this);
					break;
					
				case 'hide':
					hide();
					break;
					
				case 'content':
					if (arguments.length == 2) {
						var content = arguments[1] || '';
						$('.content *', this).remove();
						$('.content', this).append(content);
					}
					break;
			}
		}
		
		return this;
		
		function show() {
			var options = $.fn.hoverBox.options;
			var top = options.position.top;
			var scrollTop = parseInt($(document).scrollTop());
			
			if (top < scrollTop) {
				var x = $(window).width();
				x -= $(this).parent().outerWidth();
				x -= $(this).parent().offset().left;
				$('.arrow-up', this).hide();
				$(this).css({ top: scrollTop, right: -x });
			} else {
				$('.arrow-up', this).show();
				$(this).css(options.position);//.fadeIn('normal');
			}
			
			$(this).fadeIn('normal');
		}
		
		function hide() {
			// UGLY HACK using try ... catch to prevent an exception in IE
			// and TypeError: Cannot read property 'defaultView' of undefinded
			try {
				$(this).fadeOut('fast');
			} catch (ignore) {}
		}
	};
})(jQuery);
