(function ($) {
  $.fn.infoBox = function () {
    return this.each(function () {
      var infoBox = $(this),
          content = infoBox.find('.content'),
          arrow   = infoBox.find('.arrow'),
          spaceY = infoBox.offset().top,
          infoBoxHeight = infoBox.height(),
          protrusionY, offsetTop, contentHeight, contentWidth;

      if (infoBox.data('initialized.infobox') === true) {
        return;
      }

      infoBox.data('initialized.infobox', true);

      content.css({'display': 'block', 'visibility': 'hidden'});

      contentHeight = content.height();
      contentWidth  = content.outerWidth();
      protrusionY   = Math.round(contentHeight / 2)

      if (protrusionY > spaceY) { // not enough space at the top for the infobox content
        offsetTop = Math.round((spaceY * -1) + (contentHeight / 2));
      } else {
        offsetTop = Math.round(((contentHeight / 2) * -1) + (infoBoxHeight / 2));
      }

      arrow.css({
        'top': Math.round((offsetTop * -1) - ((arrow.height() /2) - (infoBoxHeight / 2)))
      })

      content.css({
        'display': '',
        'visibility': '',
        'top': offsetTop,
        'right': (contentWidth + 5) * -1
      });

      infoBox.bind('mouseover.infobox', function () {
        content.css({'display': 'block'});
      });

      infoBox.bind('mouseout.infobox', function () {
        content.css({'display': ''});
      })
    });
  }
})(jQuery);
