﻿(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();
                    // mouse over
                    $('<div id="tooltip" />')
					  .appendTo('body')
					  .html(title)
					  .hide()
					  .css({
					      top: pos.top,
					      left: pos.left - (parseInt(settings.width) + 20),
					      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,
                            left: pos.left - (parseInt(settings.width) + 20),
                            width: settings.width
                        });
                    }

                    $('#tooltip').fadeIn(350);

                }, function() {
                    // mouse out
                    $('#tooltip').remove();
                });
            }

        });
        // returns the jQuery object to allow for chainability.
        return this;
    }
})(jQuery);
