$(function () {
    $.fn.mmTooltip = function (options) {
        var $tipContent = $("#mmtooltop-text"), //$('#helper').find("tr:nth-child(2) td:nth-child(2)")
            $tipBody = $("#mmtooltip");//$('#helper');//
        options = jQuery.extend({
                emptySource: false,
                getMessage: function() {
                    return this.attr('rel')
                    //return this.css('content');
                },
                setMessage: function(value) {
                    //this.attr('title', value);
                }
        }, options);
        
        $.showWidget = function(html, x, y) {
            var left, top;
            //.html(html);
            $tipContent.html(html);
            
            left = x - $tipBody.width() / 2;
            top = y + $tipBody.height() / 2;
            if (top < 0) {
                top = 0;
            } else if (top > $(window).height() - $tipBody.height()) {
                top = $(window).height() - $tipBody.height() * 2.5;
            }
            
            $tipBody
                .css({  
                    'left' : (left > 0) ? left : 0, 
                    'top'  : (top > 0) ? top : 0
                })
                .fadeIn(1000);
        }
        
        $.hideWidget = function() { $tipBody.stop(true, true).hide(); }
        
        this.live({
            'mouseenter' : function(event, data){
                var $this = $(this),
                    title = options.getMessage.call($this);
                if (options.emptySource) {
                    $this.data('title', title);
                    options.setMessage.call($this, '');
                }
                if (data) {
                   $.showWidget(title, data.pageX, data.pageY);
                } else {
                    $.showWidget(title, event.clientX, event.clientY);
                }

            },
            'mouseleave' : function(){
                if (options.emptySource) {
                    options.setMessage.call($(this), $(this).data('title'));
                }
                $.hideWidget();
            }
        });
         
        
        return $(this);
    };
    
    $.fn.mmTooltipDestroy = function() {
        return this.die('mouseenter mouseleave');
    }
});
