/**
 * jQuery brTip plugin
 * This jQuery plugin was inspired and based on various other plugins of tooltip, but this is better =)
 * @name jquery-brtip-1.1.js
 * @author Gabriel Sobrinho - gabriel.sobrinho@gmail.com
 */

(function($){
	$.fn.tooltip = function(opts){
		opts = $.extend({
			fadeIn: '',
			fadeOut: '',
			toShow: 100,
			toHide: 500,
			opacity: 0.8,
			top: -1,
			left: 15,
			title: null,
			minLength:null,
			box: null,
			delayToShow: null,
			delayToHide: null,
			txt: ''
		}, opts);
		function _clearTimes(){clearTimeout(opts.delayToShow); clearTimeout(opts.delayToHide);}
		function _create(){
			_clearTimes();
			if (!opts || !opts.box){
				opts.box = $('<div class="tootltip_box"><div class="tootltip_content">&nbsp;</div></div>').appendTo('body');
				opts.box.css('opacity', opts.opacity);
			};
			opts.box.find('div.tootltip_content').html(opts.txt);
			opts.delayToShow = setTimeout(function(){opts.box.fadeIn(opts.fadeIn);}, opts.toShow);}
		function _hide(){opts.delayToHide = setTimeout(function(){opts.box.fadeOut(opts.fadeOut);}, opts.toHide);}
		function _setPos(top, left){
			if (opts && opts.box){
				opts.box.css({
					top: top + opts.top,
					left: left + opts.left
				});
			}else{setTimeout(function(){_setPos(top, left);}, 100);}
		}
		return this.each(function(){
			var self = $(this);
			if(opts.minLength=='' || self.attr('title').length <  opts.minLength){return;}
			self
				.mouseover(function(){
					opts.txt = self.attr('title');
					self.attr('title', '');
					_create();
				})
				.mouseout(function(){
					self.attr('title', opts.txt);
					opts.txt = '';
					_hide();
				})
				.mousemove(function(e){
					var w = parseInt((screen.availWidth)/2), p = '';
					e.pageX>w ? p = parseInt((e.pageX)-260) : p = e.pageX;
					_setPos(e.pageY, p);
				})
		});
	};
}(jQuery));