var mTermsDictionaryWords = new Array();
var mTermsDictionaryDefinitions = new Array();
var mTermsDictionaryOffsetX = 20;
var mTermsDictionaryOffsetY = -20;

$( function() {
	$.get( "Terms-Dictionary.xml", "", Init );
});

function Init( iData )
{
	var words = iData.getElementsByTagName( "word" );
	var definitions = iData.getElementsByTagName( "definition" );
	
	for ( var index = 0; index < words.length; index++ )
	{
		mTermsDictionaryWords[ index ] = words[ index ].firstChild.data.toLowerCase();
		mTermsDictionaryDefinitions[ index ] = definitions[ index ].firstChild.data;
	}
	
	InitWords();
	InitPopup();
}


function InitWords()
{
	var text = $( "#Main" ).html();

	for ( var index = 0; index < mTermsDictionaryWords.length; index++ )
	{
		var pattern = new RegExp( "(<p.*?)([\\s\">])(" + mTermsDictionaryWords[ index ] + ")([\\s.,;:?!\">])(.*/p>)", "gi" );
		text = text.replace( pattern, "$1$2#@$3@#$4$5" );
		//var pattern = new RegExp( "([\\s\">])(" + mTermsDictionaryWords[ index ] + ")([\\s.,;:?!\"<])", "gi" );
		//text = text.replace( pattern, "$1#@$2@#$3" );
	}
	
	text = text.replace( /#@/g, "<dfn>" );
	text = text.replace( /@#/g, "</dfn>" );

	$( "#Main" ).html( text );
}


function InitPopup()
{
	$( "body" ).append( "<div id=\"TermsDictionaryPopup\"></div>" );
	$( "#TermsDictionaryPopup" ).hide();
	$( "dfn" ).mouseover( ShowPopup );
	$( "dfn" ).mouseout( HidePopup );
	$( "dfn" ).mousemove( MovePopup );
}


function ShowPopup( iEvent )
{
	$( "#TermsDictionaryPopup" ).html( GetDefinition( iEvent.target.innerHTML ) );
	$( "#TermsDictionaryPopup" ).css( "left", ( iEvent.pageX + mTermsDictionaryOffsetX ) + "px" );
	$( "#TermsDictionaryPopup" ).css( "top", ( iEvent.pageY + mTermsDictionaryOffsetY ) + "px" );
	$( "#TermsDictionaryPopup" ).fadeIn();
	
}


function HidePopup()
{
	$( "#TermsDictionaryPopup" ).html( "" );
	$( "#TermsDictionaryPopup" ).hide();
}


function MovePopup( iEvent )
{
	$( "#TermsDictionaryPopup" ).css( "left", ( iEvent.pageX + mTermsDictionaryOffsetX ) + "px" );
	$( "#TermsDictionaryPopup" ).css( "top", ( iEvent.pageY + mTermsDictionaryOffsetY ) + "px" );
}


function GetDefinition( iWord )
{
	for ( var index = 0; index < mTermsDictionaryWords.length; index++ )
	{
		if ( mTermsDictionaryWords[ index ] == iWord.toLowerCase() )
		{
			return mTermsDictionaryDefinitions[ index ];
		}
	}
	
	return "";
}