﻿jQuery.fn.extend({
    ToolTip: function(options) {
        var _opt = jQuery.extend({
            delay: 1000,
            toolTipId: 'tool-tip-wrapper',
            maxWidth: 300,
            maxHeight: 300,
            opacity: '1.0',
            offsetX: 0,
            offsetY: 0
        }, options);
        var _o = false;
        var _to, _top, _left, _bottom, _right, _tth, _ttw, _tt;

        var _html = '<div id="' + _opt.toolTipId + '"><table id="tool-tip">';
        _html += '<tr><td id="tip"></td><td class="tr"></td></tr>';
        _html += '<tr><td class="bl"></td><td class="br"></td></tr>';
        _html += '</table></div>';
        jQuery("body").append(_html);

        return this.each(function() {
            if (jQuery.browser.version == '6.0') { return false; }
            var _this = jQuery(this);
            _tt = jQuery("#" + _opt.toolTipId);
            _pw = (document) ? document.body.clientWidth : '0';
            jQuery(this).hover(
                function(evt) {
                    if (!_this.attr('rel')) { return false; }
                    jQuery("#tip").html(_this.attr('rel'));
                    _to = setTimeout(function() { _tt.css({ opacity: _opt.opacity }).fadeIn("slow"); }, _opt.delay)
                    _o = true;
                    _ttw = (_tt.width() > _opt.maxWidth) ? _ttw = _opt.maxWidth : _tt.width();
                    _tth = _tt.height();
                    _tt.css({ width: _ttw + 'px' });
                }, function(evt) {
                    clearTimeout(_to);
                    _o = false;
                    _tt.css({ width: 'auto' }).hide();
                    jQuery("#tip").html('');
                }
            );
            jQuery(this).mousemove(function(evt) {
                _top = (document.documentElement.scrollTop + evt.clientY) + (_opt.offsetY) + 'px';
                _left = (document.documentElement.scrollLeft + evt.clientX) + _opt.offsetX + 'px';
                _right = ((document.documentElement.scrollLeft + evt.clientX) - _ttw) - 5 + 'px';
                _bottom = (document.documentElement.scrollTop + evt.clientY) + 10 + 'px';
                if (!_o) { return; }
                (_tth - evt.clientY > 0) ? _tt.css({ top: _bottom }) : _tt.css({ top: _top });
                ((_pw - (parseInt(_left) + _ttw)) < 50) ? _tt.css({ left: _right }) : _tt.css({ left: _left });
            });
            jQuery(this).click(function(evt) {
                clearTimeout(_to);
                _o = false;
                _tt.css({ width: 'auto' }).hide();
                jQuery("#tip").html('');
            });
        });
    }
});