/*
 * JTip v2
 * Originally by Cody Lindley (http://www.codylindley.com)
 * Version 2 by Thomas Reynolds
 * Under an Attribution, Share Alike License
 * JTip is built on top of the very light weight jquery library.
 */
(function($) {
  // Add option defaults
  $.jTip = {
    options: { 
      position: 'vertical',
      distance: 15
    }
  };

  // Public method
  $.fn.jTip = function(options) {
    var settings = $.extend($.jTip.options, options || {});
    return this.each(function() {
      // Insert into DOM so we can calculate size    
      var jTipDiv = $("<div class='jTip' style='display: none;' />");
      $('body').append(jTipDiv);

      var elem     = $(this).css('cursor', 'pointer'),
          title    = settings.title || elem.attr('title') || elem.attr('name') || "&nbsp;";

      jTipDiv.html('<span>' + title + '</span>');
      elem.hover(function() {
        var fromLeft = parseInt(elem.offset().left + (elem.width() / 2) - (jTipDiv.width() / 2)),
            fromTop  = parseInt(elem.offset().top + (elem.height() / 2) + settings.distance),
            hasRoom  = fromLeft + jTipDiv.width() - $(window).width() + 15;

        if (hasRoom > 0) {
          fromLeft -= hasRoom;
          var arrowOffset = (parseInt(jTipDiv.width() / 2) + hasRoom - 5)  + 'px';
        } else
          var arrowOffset = '50%';

        jTipDiv.css({ 'background-position': arrowOffset + ' 0' })
               .css({ left: fromLeft, top: fromTop }).show(); 
      }, function() {jTipDiv.hide();});
    });
  }
})(jQuery);