var viewWidth = 0;
var viewHeight = 0;
var tooltipWidth = 0;
var tooltipHeight = 0;

function getWidth(){
	var width = 0;
	if( document.documentElement && document.documentElement.clientWidth ) {
		width = document.documentElement.clientWidth;
	} else if( document.body && document.body.clientWidth ) {
		width = document.body.clientWidth;
	}
	return width;
}

function getHeight(){
	var height = 0;
	if( document.documentElement && document.documentElement.clientHeight ) {
		height = document.documentElement.clientHeight;
	} else if( document.body && document.body.clientHeight ) {
		//IE 4 compatible
		height = document.body.clientHeight;
	}
	return height;
}

this.tooltip = function(){	
	xOffset = 20;
	yOffset = 0;		
	$(".tooltiptrigger").hover(function(e){
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		
		viewWidth = getWidth();
		viewHeight = getHeight();

		var theTip = $("#tooltip");
		tooltipWidth = $("#tooltip").width();
		tooltipWidth += parseInt(theTip.css("padding-left"), 10) + parseInt(theTip.css("padding-right"), 10);
		tooltipWidth += parseInt(theTip.css("margin-left"), 10) + parseInt(theTip.css("margin-right"), 10);
		tooltipWidth += parseInt(theTip.css("borderLeftWidth"), 10) + parseInt(theTip.css("borderRightWidth"), 10);
		
		tooltipHeight = $("#tooltip").height();
		tooltipHeight += parseInt(theTip.css("padding-top"), 10) + parseInt(theTip.css("padding-bottom"), 10);
		//tooltipHeight += parseInt(theTip.css("margin-top"), 10) + parseInt(theTip.css("margin-bottom"), 10);
		tooltipHeight += parseInt(theTip.css("borderTopWidth"), 10) + parseInt(theTip.css("borderBottomWidth"), 10);		
		
		var rightEdge = e.clientX + xOffset + tooltipWidth;
		var btEdge = e.clientY - yOffset + tooltipHeight;
			
		var leftVal;
		var topVal;
		if (rightEdge >= viewWidth){
			leftVal = e.pageX - xOffset - tooltipWidth;
		} else {
			leftVal = e.pageX + xOffset;
		}
		if (btEdge >= viewHeight){
			topVal = e.pageY - yOffset - tooltipHeight;
		} else {
			topVal = e.pageY - yOffset;
		}
		
		$("#tooltip")
			.css("top",topVal + "px")
			.css("left",leftVal + "px")
			.css('opacity',0.8)
			.fadeIn("1000");
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });			
};

$('someElement').css('opacity',0.5)

// starting the script on page load
$(document).ready(function(){
	tooltip();
});
