/***
 *  Infobox script activates the tooltip functionality of the infobox span tags
 *  created in the BAC editor. 
 */

$(document).ready(function(){
	infoboxEnable();
	
	$(document).on('pfAjaxComplete', function(xhr, ajaxObj, error) {
		//your code here to run when primefaces ajax call complete
		infoboxEnable();
	});

	$(document).ajaxComplete(function( event,request, settings ) {
	   //your code here to run when ajax is complete
		infoboxEnable();
	});
});


$(document).on('click', function(e) {
    if (!$(e.target).closest('.infobox').length) {
       $('.infobox').next('.ttip').remove();
    }
});


function infoboxEnable() {	
	
	$('.infobox').click(function() {	
		
		let topOffset = $(window).scrollTop();

		$('.infobox').next('.ttip').remove();
		// first remove all existing tips.
		$(this).next('.ttip').remove();
		
		let content = $(this).find('.infobox-content:first');
			
		// create the infobox
		$(this).after('<div id="infoboxtip" class="ttip">' + content.html() + '</div>');

		var left = $(this).position().left ;
		var top = $(this).position().top + $(this).height();
		let elem = $("#infoboxtip");

		if(elem) {
			 positionTip(elem, top,left,$(this).offset().left);
		}		
		//galaxy fold has tendency to scoll back to top.
		$(window).scrollTop(topOffset);
		
	});
}

/***
 * Position the infobox to be contained in the window as much as possible
 * @param elem - jquery element to possition
 * @param parentBottom - y co-ord of the bottom edge of the parent element
 * @param parentLeftEdge - x co-ord of the leftmost edge of the parent element
 * @param leftWindowOffset - x co-ord of the leftmost edge of the parent element relative to the window/viewport.
 */
function positionTip(elem, parentBottom, parentLeftEdge, leftWindowOffset) {

	let windowWidth = $(window).width();
	let a = 25; //allowance
	let x = parentLeftEdge;
	let y = parentBottom + 5;
	let w = elem.outerWidth();
	let offset = leftWindowOffset - parentLeftEdge;

	if((x + w + offset) > windowWidth) {

		//offscreen.
		if(w >= windowWidth) {
		  x = 0 - offset; //set to left most if bigger than width of window.
		  elem.css({top: y, left: x, position:'absolute', "width": (windowWidth - a)});
		  elem.find("img").css("max-width" , "100%");
		}else{
			x = windowWidth - w - offset - a;
			elem.css({top: y, left: x, position:'absolute'});
		}
	} else {
		elem.css({top: y, left: (x - a), position:'absolute'});
	}

};

