$(document).ready(function () {
	//Don't display popups on iPhone
	if (!(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i))) {
		$('.nt[title]').attr('nicetitle', function() { return $(this).attr('title'); }).
			removeAttr('title').
			mouseover(showNiceTitle).
			mousemove(showNiceTitle).		
			mouseout(hideNiceTitle).
			focus(showNiceTitle).
			blur(hideNiceTitle);

		var f = function(e) { e.stopPropagation(); };
			
		$('.ntno').mousemove(f).mouseover(f);
	
		$('body').attr('ntID', 1);
	}
});

function findPosition( oLink ) {
  if( oLink.offsetParent ) {
    for( var posX = 0, posY = 0; oLink.offsetParent; oLink = oLink.offsetParent ) {
      posX += oLink.offsetLeft;
      posY += oLink.offsetTop;
    }
    return [ posX, posY ];
  } else {
    return [ oLink.x, oLink.y ];
  }
};

var ntJaxTimeout = false;

function showNiceTitle(e) {
    hideNiceTitle();

    w = 40;
	ww = window.innerWidth;
	wh = window.innerHeight;
    mx = e.clientX;
	sx = window.scrollX;
	my = e.clientY;
	sy = window.scrollY;
    
	var item = this;
	
	style = '';
	if (mx > (ww/2)) style += 'right: ' + (ww-mx+5) + 'px; ';
	else style += 'left: ' + (mx+15) + 'px; ';
	if (my > (wh/2)) style += 'bottom: ' + (wh-my+5) + 'px; ';
	else style += 'top: ' + (my+15) + 'px; ';

	var url = $(this).attr('data-ajaxtip');
	var myID;
	
	if ($(item).attr('nicetitleid')) {
		myID = $(item).attr('nicetitleid');
		$('#' + myID).attr('style', style).show();
	} else {
		var ntID = $('body').attr('ntID');
		$('body').attr('ntID', parseInt(ntID)+1);
		
		myID = 'nicetitle' + ntID;
		
		$(item).attr('nicetitleid', myID);

	    nicetitle = '<div class="nicetitle" id="' + myID + '" style="' + style + '">' + $(this).attr('nicetitle');
	
		$(this).removeAttr('nicetitle');
    
		//Prepare to display embedded ajax data for title
		if (url) {
			//Write placeholder div with loading image
			nicetitle += '<br /><div class="jax"><img src="/images/tipload.gif" alt="Loading..."></div>';

		}
	
		if ($(item).attr('loadbar')) nicetitle += $(item).attr('loadbar');
		nicetitle += '</div>';
	    $("body").append(nicetitle);
	}
	
	if (url)
		ntJaxTimeout = setTimeout(function() {
			$(item).removeAttr('data-ajaxtip');
			$('#' + myID + ' .jax').load(url);
		}, 100);
};

function hideNiceTitle(e) {
	clearTimeout(ntJaxTimeout);
	$('.nicetitle').hide();
};
