// --- Glossary floating boxes ---

GlossaryBox = {
	Terms: new Object(),			// Object to hold the terms. Will be populated in the shtml page
	init: function()
	{
		gloss_links = bbcjs.dom.getElementsByClassName( 'glossLink' , 'a' );
		for (i=0; i<gloss_links.length; i++)
		{
			bbcjs.dom.addEventListener(gloss_links[i], 'click', GlossaryBox.clicked, GlossaryBox);
			bbcjs.dom.addEventListener(gloss_links[i], 'mouseover', GlossaryBox.mouseover, GlossaryBox);
			bbcjs.dom.addEventListener(gloss_links[i], 'focus', GlossaryBox.focusIt, GlossaryBox);
			bbcjs.dom.addEventListener(gloss_links[i], 'blur', GlossaryBox.hide, GlossaryBox);
			bbcjs.dom.addEventListener(gloss_links[i], 'mouseout', GlossaryBox.hide, GlossaryBox);
		}
		var glossBox = bbcjs.dom.elem('glossaryBox',{ id: 'glossaryBox' });
		bbcjs.dom.before(bbcjs.dom.first( document.body ),glossBox);
	},
	
	getLinkPos: function(e)
	{
		var pos = {
			x: bbcjs.dom.pageX( e.target ),		
			y: bbcjs.dom.pageY( e.target ) + bbcjs.dom.getHeight( e.target )	// position box below text
		}
		return pos;
	},
	
	// function setting the position of the floating box
	setPos: function(pos)
	{
			bbcjs.dom.setX( $('glossaryBox'), pos.x);	// set x position of floating box
			bbcjs.dom.setY( $('glossaryBox'), pos.y); // set y positoin of floating box
	},
	
	// function to handle mouse pointer hovering over the link
	mouseover: function(e)
	{
		if(e.target.href){
			this.setPos(this.getLinkPos(e));		// position the glossary box close to the link text
			this.show(e);								// show the info box
		}
	},
	
	// function to handle link being selected using tab
	focusIt: function(e)
	{
		if(e.target.href){
			this.setPos(this.getLinkPos(e));		// position the glossary box close to the link text
			this.show(e);								// show the info box
		}
	},
	
	// function to copy info html content and show the floating box
	show: function(e)
	{
		var glossId = e.target.href.split("#")[1]; // get id of the element containing the glossary info for this term from the href attribute
		var glossSubject = $('gt_'+glossId).innerHTML;
		var glossDefinition = bbcjs.dom.next( $('gt_'+glossId) ).innerHTML;
		$('glossaryBox').innerHTML = '<strong>'+ glossSubject +'</strong><p>'+ glossDefinition +'</p>';
		bbcjs.dom.setStyle( $('glossaryBox'), {visibility:'visible'} );		// show the floating box
	},
	hide: function()
	{
		bbcjs.dom.setStyle( $('glossaryBox'), {visibility:'hidden'} );		// hide the floating box
	},
	
	// function to handle a clicked glossary link
	clicked: function(e)
	{
		bbcjs.dom.stopEvent(e);								// disable the link for JS version
	}
};

// initialise the glossary object when the page has loaded
bbcjs.addOnLoadItem( function() { GlossaryBox.init(); });
