var prevTooltip;
// Main function to retrieve mouse x-y pos.s
function getWindowWidth() {
    if(window.innerWidth) {
        return window.innerWidth;
    } 
    return document.body.clientWidth
}


// Detect if the browser is IE or not.
// If it is not IE, we assume that the browser is NS.
var IE = document.all?true:false;
var IE7 = navigator.appVersion.match(/MSIE 7\.0/i) == 'MSIE 7.0'?true:false;

// If NS -- that is, !IE -- then set up for mouse capture
if (!IE) document.captureEvents(Event.MOUSEMOVE);

function mouseX(e) {
	var tempX = 0;
	if (IE) { // grab the x-y pos.s if browser is IE
    	if(IE7) {
			tempX = event.clientX + document.documentElement.scrollLeft;
    	}
    	else {
    		tempX = event.clientX + document.body.scrollLeft;
    	}
  	} else {  // grab the x-y pos.s if browser is NS
    	tempX = e.pageX
  	}  
  	if (tempX < 0){tempX = 0}
    return tempX;
}

function mouseY(e) {
	var tempY = 0;	
	if (IE) { // grab the x-y pos.s if browser is IE
		if(IE7) {
			tempY = event.clientY + document.documentElement.scrollTop;
		}
		else {
			tempY = event.clientY + document.body.scrollTop;
		}
		
	} else {  // grab the x-y pos.s if browser is NS
		tempY = e.pageY
	}
	// catch possible negative values in NS4
	if (tempY < 0){tempY = 0}  
	return tempY; 
}


function tooltip(e, element, o) {
    var windowWidth = getWindowWidth();

    o = document.getElementById(o);
    
    if(prevTooltip && prevTooltip != o) {
        prevTooltip.style.visibility = 'hidden';
    }

    if(o.style.visibility == 'visible') {

        o.style.visibility = 'hidden';
        element.onmousemove = "";
    } else {
    
        if(o.offsetWidth) {
            ew = o.offsetWidth;
        } else if(o.clip.width) {
            ew = o.clip.width;
        }
    
        y = mouseY(e) + 22;
        x = mouseX(e) + 15;
        
        if (x < 2) {
            x = 2;
        } else if(x + ew > windowWidth) {
            x = windowWidth - ew - 4;
        }
        
        o.style.left = x + 'px';
        o.style.top = y + 'px';    
        
        o.style.visibility = 'visible';
        
        prevTooltip = o;
        document.getElementById(element).onmousemove = moveTooltip;
    }
}

function moveTooltip(e) {
	var windowWidth = getWindowWidth();
	o = prevTooltip;
	if(o.offsetWidth) {
            ew = o.offsetWidth;
        } else if(o.clip.width) {
            ew = o.clip.width;
        }
    
        y = mouseY(e) + 22;
        x = mouseX(e) + 15;
        
        if (x < 2) {
            x = 2;
        } else if(x + ew > windowWidth) {
            x = windowWidth - ew - 4;
        }
        
        o.style.left = x + 'px';
        o.style.top = y + 'px';
}
