// find all items with class glossary, attach event 
$(document).ready(function() {
		addGlossaryActions('.glossary');
});

function addGlossaryActions( selector ) {
	$(selector).each(function(index) {
		var classParts = $(this).attr("class").split(" ");
		for (var i=0; i < classParts.length; i++) {
			if (classParts[i].substring(0,7) == "itemid_") {
				var actualId = classParts[i].substring(7);
				$("#glossaryLookupBox").bind("mouseover", function(event) {
						if ( $("#glossaryLookupBox").css('opacity') >= .5 ) { 
							$("#glossaryLookupBox").stop().show().css( {'opacity':1} );
						} else {
							hideGlossaryItem(0);
						}
				} );
				$("#glossaryLookupBoxClose").bind("click", function(event) {
						hideGlossaryItem(0);
				} );
				$("#glossaryLookupBox").bind("mouseout", function(event) {
						hideGlossaryItem(500);
				} );
				$(this).bind("mouseover", {glossaryItemId: actualId}, function(event) {
					hideGlossaryItem(0);
					showGlossaryItem(event.data.glossaryItemId);
					positionGlossaryItem(this);
				} );
				$(this).bind("click", {glossaryItemId: actualId}, function(event) {
					hideGlossaryItem(0);
					showGlossaryItem(event.data.glossaryItemId,true);
					positionGlossaryItem(this);
				} );				
				$(this).bind("mouseout", {glossaryItemId: actualId}, function(event) {
					hideGlossaryItem(500);
				} );
			}
		}
	});
}

function positionGlossaryItem(node) {
	var $this = $(node);
	var pos = $this.offset();
	var width = $this.width();
	var height = $this.height();
	var right = $(document).width();
	var boxWidth = $("#glossaryLookupBox").width();
	
	var maxLeft = right - boxWidth - 5;
	var minLeft = 5;
	var calculatedLeft = pos.left + (width/2) - (boxWidth/2);
	
	$("#glossaryLookupBox").css({
		"left": Math.min( maxLeft, Math.max( minLeft, calculatedLeft  ) ) + "px",
		"top": (pos.top + height) + "px"
	});
}

function showGlossaryItem(glossaryItemNodeId,instant) {
	$("#glossaryLookupBox").stop();
	$("#glossaryLookupBoxContent").html('<img src="/extension/lbbc/design/lbbc_user/images/loading.gif" alt="Glossary definition loading" />');
	
	if ( !instant ) {
	//	$("#glossaryLookupBox").delay(750);
	}
	
	$("#glossaryLookupBox").fadeIn(250,function(){
			$("#glossaryLookupBox").css( {'opacity':1} );
	});
	//alert("/layout/set/json/content/view/json/"+glossaryItemNodeId);
	$.ajax({
		url: "/layout/set/json/content/view/json/"+glossaryItemNodeId,
		type: 'get',
		cache: true,
		dataType: 'html',
		success: function(data) {
		
			// trim data, take out anything after <!--
			var indexOfComment = data.indexOf("<!--");
			if (indexOfComment > 0) {
				data = data.substring(0, indexOfComment);
			}
			$("#glossaryLookupBoxContent").html(data);
		}			
	});
}

function hideGlossaryItem(speed) {
	$("#glossaryLookupBox").stop();
	$("#glossaryLookupBox").fadeOut(speed);
};

