//
//	tootip jquery plugin
//	(c) revolweb 2011
//	@ picios
//	version 2.0
//	modified: 2011.10.14
//

function _calculateRwTooltipPosition(e, tooltip, tip, o) {
	_left = e.pageX+o.offsetX;
	_top = e.pageY+o.offsetY;
						
	_controllX = $(window).width() - e.clientX - tip.width();
	_controllY = $(window).height() - e.clientY - tip.height();

	if (_controllY<0) {
		_top = _top - tip.height() - 4*o.offsetY;
	}
						
	if (_controllX<0) {
		_left = _left - tip.width() - 4*o.offsetX;
	}

	tooltip.css({  
		left: _left,
		top: _top
	});
}

(function($){
 
    $.fn.extend({
         
        //pass the options variable to the function
        rwTooltip: function(options) {
 
            //Set the default values, use comma to separate the settings, example:
            var defaults = {
                showDelay: 300,
                offsetX : 10,
                offsetY : 10,
                followTheCursor : true,
                fadeIn : false
            }
                 
            var options =  $.extend(defaults, options);
            
            var tip = null;
			$("body").prepend("<div id=\"rwTooltip\"></div>");
			var tooltip = $("#rwTooltip");
 
            return this.each(function() {
                var o = options;
                var obj = $(this);
                
                obj.bind('mouseenter', function (e) {
						
					$(this).attr("title","");
					$(this).children().attr("title","");
						
					tip = $(this).find('.tip:first-child');	
						
					if (tip == undefined || tip.html() == null) {
						tip = $(this).next(".tip");
					}
						
					if (tip != undefined && tip.html() != null) {
						tooltip.html(tip.html());
						if (o.fadeIn != true) {
							_ticking = setTimeout(function() {	tooltip.show() }, o.showDelay);
						} else {
							tooltip.fadeIn();
						}
						_calculateRwTooltipPosition(e, tooltip, tip, o);
					}
				}).bind('mouseleave', function (e) {
					
					if (o.fadeIn != true) {
						clearTimeout(_ticking);
						tooltip.hide(); //Hide tooltip
					} else {
						tooltip.hide();
					}
				}).mousemove(function(e) {
					
					if (o.followTheCursor == true) {
						if (tip == undefined || tip == null) {
							return false;
						}
						_calculateRwTooltipPosition(e, tooltip, tip, o);
						
					}	// following the cursor
				});
            });
        }
    });
     
})(jQuery);

