var parts = window.location.pathname.split("/");
if (parts.length > 1 && parts[1] == "magnoliaAuthor")
	parts.shift();
var lang = (parts.length > 1 && (parts[1] == "en" || parts[1] == "es"))
	? "/" + parts[1]
	: "";
$.ajaxSetup({async: false});
$.getScript(contextPath + "/docroot/js/glossaryDefinitions" + (lang == "/es" ? "-es" : "") + ".js");
$.ajaxSetup({async: true});

document.getElementsByClassName = function(cl) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for (var i = 0; i < elem.length; i++) {
		var classes = elem[i].className;
		if (myclass.test(classes)) retnode.push(elem[i]);
	}
	return retnode;
};

function dgc(id) {
    return document.getElementsByClassName(id);
}

var currentBubble;

function bubbleOff() {
	var bubbleArray = dgc("bubbleInfo");
	for (i=0; i<bubbleArray.length;i++) {
		if (bubbleArray[i] != currentBubble) {
		var cn = bubbleArray[i].className;
		bubbleArray[i].className = cn.replace("bubbleInfo","bubbleOffInfo");
		}
	}
}

function bubbleOn() {
	var bubbleArray = dgc("bubbleOffInfo");
	for (i=0; i<bubbleArray.length;i++) {
		var cn = bubbleArray[i].className;
		bubbleArray[i].className = cn.replace("bubbleOffInfo","bubbleInfo");
	}
}


var absMiddle;
var popupWidth = 456;
var popupRightOffset = 422;
var popupLeftOffset = 20;

$(document).ready(function(){

	//pageOffSet = document.getElementById("page").offsetLeft;
	pageWidth = document.getElementById("page").offsetWidth;
	winWidth = $(window).width();

	if(winWidth > pageWidth) {
		widthToUse = winWidth;
	} else {
		widthToUse = winWidth;
	}

	$('.glossary').each(function(n) {

		var glossary_index = $(this).text(); // get the glossary term
		var glossary_content = glossaryDefinitions[glossary_index.toLowerCase()]; // getting the glossary content

		var newClassName = "bubbleInfo";
		if(this.className.indexOf("forceLeft")!=-1){
			newClassName += " forceLeft";
		}

		$(this).wrap('<span class="' + newClassName + '"></span>').addClass('trigger').after('<span class="definition"></span>');

		$('<div class="definition_content"><strong>' + glossary_index + '</strong><p>' + glossary_content + '</p></div>').appendTo($(this).siblings(0)).addClass('definition_content'); // inject the glossary content

		$(this).html("<img src='" + contextPath + "/docroot/images/blue_square.gif'>"+ glossary_index);

	});


	$('.bubbleInfo').each(function () {

		/**$(this).css('z-index', '-10');**/
		var offset = $(this).offset();
		offsetLeft = offset.left; // getting the current element's position offset to the left

		absMiddle = widthToUse / 2; // get the middle point

		if (popupWidth > absMiddle) {
			popupRightOffset = Math.floor(popupRightOffset * absMiddle / popupWidth);
			popupLeftOffset = Math.floor(popupLeftOffset * absMiddle / popupWidth);
			popupWidth = absMiddle;
			$(".definition").css("width", popupWidth);
		}

		//alert ('middle = '+absMiddle);
		//alert('offset to the left is '+offsetLeft);

	    // options
	    var distance = 0;
	    var time = 250;
	    var hideDelay = 200;

	    var hideDelayTimer = null;

	    // tracker-
	    var beingShown = false;
	    var shown = false;

	    var trigger = $('.trigger', this);
	    var popup = $('.definition', this).css('opacity', 0);

	    if((offsetLeft > absMiddle) || (this.className.indexOf("forceLeft")!=-1) ) { // debug - for checking which side the current element is located
			leftOrRight = "right";
			popup.css({left: -popupRightOffset});
			$('div', popup).after('<img src="'+contextPath +'/docroot/images/glossary_bottom_right.gif" style="display:block;" width="' + popupWidth + '" height="18" border="0">'); // append the bottom of the glossary image
		} else {
			leftOrRight = "left";
			popup.css({left: -Math.min(offsetLeft, popupLeftOffset)});
			$('div', popup).after('<img src="'+contextPath +'/docroot/images/glossary_bottom.gif" style="display:block;" width="' + popupWidth + '" height="18" border="0">'); // append the bottom of the glossary image
		}
	    //alert(leftOrRight);

	    // set the mouseover and mouseout on both element
	    $([trigger.get(0), popup.get(0)]).mouseover(function () {
	    	//alert(this.parentNode.className);
	    	currentBubble = this.parentNode;
	      // stops the hide event if we move from the trigger to the popup element
	      if (hideDelayTimer) clearTimeout(hideDelayTimer);

	      // don't trigger the animation again if we're being shown, or already visible
	      if (beingShown || shown) {
	        return;
	      } else {
	        beingShown = true;


	        // reset position of popup box
	        popup.css('top', 0-popup.height());

	        popup.css({
	          display: 'block' // brings the popup back in to view
	        })

	        // (we're using chaining on the popup) now animate it's opacity and position
	        .animate({
	          top: '-=' + distance + 'px',
	          opacity: 1
	        }, time, 'swing', function() {
	          // once the animation is complete, set the tracker variables
	          beingShown = false;
	          shown = true;
	        });
          bubbleOff();

	      }
	    }).mouseout(function () {

	      // reset the timer if we get fired again - avoids double animations
	      if (hideDelayTimer) clearTimeout(hideDelayTimer);

	      // store the timer so that it can be cleared in the mouseover if required
	      hideDelayTimer = setTimeout(function () {
	        hideDelayTimer = null;
	        popup.animate({
	          top: '-=' + distance + 'px',
	          opacity: 0
	        }, time, 'swing', function () {
	          // once the animate is complete, set the tracker variables
	          shown = false;
	          // hide the popup entirely after the effect (opacity alone doesn't do the job)
	          popup.css('display', 'none');
	          bubbleOn();

	        });
	      }, hideDelay);

	    });
	  });


});