﻿(function($) {
	jQuery.fn.balloon = function(text, options) {
		var opt = $.extend({
			offsetX: 0,
			offsetY: 0,
			position: 'top' // {'top', -'left', -'right', 'bottom'}
		}, options);
		return this.each(function(idx) {
			this.balloonOn = function() {

				var $this = $(this);
				if (!$this.is(':visible'))
					return;
				if (typeof $this.data('balloon-box') == 'object') {
					// if there's already a popup, remove it before creating a new one.
					this.balloonOff();
				}

				var $b = $('<div class="balloon"><div class="blnText">' + text + '</div><div class="blnPt"></div></div>');
				$('body').append($b);
				$this.addClass('bt-active').data('balloon-box', $b);
				var p = $this.offset();
				$g = $b.find('.blnPt');

				var bH = $b.outerHeight();
				var bW = $b.outerWidth();
				var oW = $this.outerWidth();
				var gW = $g.outerWidth();
				var wMrg = 8; // margins
				var x = 1 / 3;
				var s = opt.offsetX >= 0 ? 1 : -1;
				var s1 = opt.offsetX >= 0 ? 0 : 1;
				var s2 = 1 - s1;
				var x1 = (s1 * (1 - x) + x * (1 - s1));
				var x2 = (s2 * (1 - x) + x * (1 - s2));

				// calc how much ballon can move to eah side
				var maxOffX = bW * x1 + oW * x2 - gW - wMrg;
				var offX = opt.offsetX < -maxOffX ? -maxOffX : opt.offsetX > maxOffX ? offX = maxOffX : opt.offsetX;

				// calc where to put pointer element
				var c = offX / maxOffX;
				var gOffX = -c * (bW - gW) * x1;
				if (gOffX > 0)
					$g.addClass('R');

				$g.css("left", gOffX + (bW - gW) * x + s * wMrg);
				if (opt.position == 'bottom') {
					$b.css("top", p.top + $this.outerHeight() + opt.offsetY); //ok
					$b.addClass('btm');
				}
				else {
					$b.css("top", p.top - bH + opt.offsetY); //ok
				}
				$b.css("left", p.left + offX + (oW - bW) * x);
				$b.show();

			};

			this.balloonOff = function() {
				$this = $(this);
				$b = $(this).data('balloon-box');
				$b.hide().parent().remove($b);

				$this.removeClass('bt-active').removeData('balloon-box');
			};
		});
	};

	/**
	* A convenience function to run btOn() (if available)
	* for each selected item
	*/
	jQuery.fn.balloonOn = function() {
		return this.each(function(index) {
			if (jQuery.isFunction(this.balloonOn)) {
				this.balloonOn();
			}
		});
	}; // </ $().btOn() >

	/**
	* 
	* A convenience function to run btOff() (if available)
	* for each selected item
	*/
	jQuery.fn.balloonOff = function() {
		return this.each(function(index) {
			if (jQuery.isFunction(this.balloonOff)) {
				this.balloonOff();
			}
		});
	};

}
)(jQuery);
