/** *******************************************************
 * Generate a tooltip
 */
var tt = {
	/**
	 * init the tooltip
	 * @param	jQuery $ele jQuery object of the elements that need an tooltip
	 */
	init: function(ele){
		ele.live('mouseover', tt.tipOver);
		ele.live('mouseout', tt.tipOut);
		
		if(!$("#tip")[0]){
			var tip = '<span id="tip"></span>';
			$("body").append(tip);
			$("#tip").hide();
			
			this.winWidth = $(window).width(); // curr window width
			this.pad = parseInt($("#tip").css('padding-left'),10) + parseInt($("#tip").css('padding-right'),10); // tooltip padding
			this.text = '';
		}
		
		$(window).resize(function(){
			tt.winWidth = $(window).width();
		});
	},
	/**
	 * hover of tooltip
	 * @param	jQuery $e	the mouseover event
	 */
	tipOver: function(e){
				
		var _tip = $("#tip");
		_tip.hide();
		tt.text = '';
		_tip.html('');
		_tip.removeClass('tip-event');
				
		if($(this).attr("title") !== "" && typeof($(this).attr("title")) !== 'undefined'){ // check if title attr present and not empty
			_tip.append($(this).attr("title"));
			tt.text = $(this).attr("title"); // save current attr
			$(this).attr("title", ""); // remove current attr
		}else{
			if($(this).attr("alt") !== "" && typeof($(this).attr("alt")) !== 'undefined'){ // check if alt attr present and not empty
				_tip.append($(this).attr("alt"));
				tt.text = $(this).attr("alt"); // save current attr
				$(this).attr("alt", ""); // remove current attr
			}else{
				if($(this).find('.tip')[0]){ // check if hover is on event
					text = $(this).find('.tip').clone();
					_tip.addClass('tip-event').append(text);
					_tip.find('.tip>li:last').addClass('last');
				}else{
					return false;
				}
			}
		}
		
		_tip.show();
		_tip.css({
			'width': _tip.width(),
			'display': 'block'
		});
		
		// while the mouse is in mouvement
		$(this).mousemove(function(e){
			_tip.css({
				'top': e.pageY + 20,
				'left': e.pageX - _tip.width()/2,
				'right': 'auto'
			});
								
			// if gets ouside to the right
			if((parseInt(_tip.css("left"),10) + _tip.width()) + tt.pad >= (tt.winWidth - 1)){
				_tip.css({
					'left': 'auto',
					'right': '5px',
					'left': 'auto'
				});
			}
			// if get outside to left
			if(parseInt(_tip.css("left"),10) <= 0){
				_tip.css("left", 1);
			}
			
		});		
	},
	/**
	 * hover out of tooltip
	 */
	tipOut: function(){
		if(tt.text !== ''){ // reset the starting attributes to the element
			$(this).attr("title", tt.text);
			$(this).attr("alt", tt.text);
		}
		$("#tip").width('auto').text('').hide();
	}
};
