﻿(function($) {
    $.fn.tooltip = function(options) {

        var 
		  defaults = {
		      width: '100px'
		  },
		  settings = $.extend({}, defaults, options);

        this.each(function() {
            var $this = $(this);
            var title = this.title;

            if ($this.is('a') && $this.attr('title') != '') {
                this.title = '';
                $this.hover(function(e) {
                    var pos = $(this).offset();

                    // position the popup to the left of the mouse pointer.
                    var leftPos = pos.left - (parseInt(settings.width) + 20);

                    // if that ends up off the screen, position it to the right instead.
                    if (leftPos < 0) {
                        leftPos = pos.left + 50;
                    }

                    // mouse over
                    $('<div id="tooltip" />')
					  .appendTo('body')
					  .html(title)
					  .hide()
					  .css({ top: pos.top, left: leftPos, width: settings.width });

                    var viewableArea = parseInt(document.documentElement.clientHeight);
                    var scrollTop = parseInt($('html,body').scrollTop());
                    var viewablePosBottom = viewableArea + scrollTop;
                    var ttBottom = parseInt(pos.top) + parseInt($('#tooltip').height());
                    
                    if (ttBottom > viewablePosBottom) {
                        $('#tooltip').css({ top: viewablePosBottom - $('#tooltip').height() - 50 });
                    }

                    $('#tooltip').fadeIn(350);

                }, function() {
                    // mouse out
                    $('#tooltip').remove();
                });
            }

        });
        // returns the jQuery object to allow for chainability.
        return this;
    }
})(jQuery);

