function makeTag(pStr, sKey, sTag){
	var outStr = pStr;
	var i, build, openTag;

	//first parse for headings
	build = outStr.split(sKey);
	openTag = true;
	outStr = build[0];
	for(i=1; i < build.length; i++)
	{
		if (openTag) {
			outStr = outStr + "<" + sTag + ">" + build[i];
			openTag = false;
		}
		else {
			outStr = outStr + "</" + sTag + ">" + build[i];
			openTag = true;
		}
	}
	return outStr;
}

function parseFormat(s){
	var inStr = s;

	//first parse for headings
	inStr = makeTag(inStr, "*h*", "h2");

	//first parse for paragraphs
	inStr = makeTag(inStr, "*p*", "p");

	// parse for bold
	inStr = makeTag(inStr, "*b*", "strong");
	
	// parse for italics
	inStr = makeTag(inStr, "*i*", "em");
				
	return inStr;
}

function showToolTip(e){
	
	var screenWidth;
	if ($.browser.msie)
		screenWidth = document.body.offsetWidth;
	else
		screenWidth = window.innerWidth;
	var tipWidth = document.getElementById('tooltip').offsetWidth;
	var mouseLimit = screenWidth - tipWidth - 20; // 20 pixels for the scrollbar
	var mousePosX = e.pageX + 10;
	mousePosX = mousePosX > mouseLimit ? mouseLimit : mousePosX;
	var mousePosY = e.pageY + 15;
	$("#tooltip").css({left: mousePosX + "px", top: mousePosY + "px"});
	$("#tooltip").show();			
}

function hideToolTip(){
	if ($("#tooltip").is(":visible"))
	$("#tooltip").hide();
}

$(document).ready(function(){
	$("<div id='tooltip'><p>This is the tool tip for the individual grants.</p></div>").appendTo("body");
	// Hide the tooltip div
	$("#tooltip").hide();
	$(".toggle").each(function(){
		$(this).attr("count", $(this).children("a").children("span").text());
	});
	
	//Hide the extra links
	$(".other").hide();
	makeSameHeight();
	
	//set up the tooltips as an extra property of the hyperlink
	$(".featured a").each(function(index,domElem){
		$(this).attr("tooltext", parseFormat($(this).attr("title")));
		$(this).attr("title", "");
	});
	
	//Slide up/down to hide/reveal the list.
	$(".toggle").click(function(e){
		
		//console.log(e);
		
		var otherList = $(this).parents().children("ul.other");
		if($(otherList).is(":hidden"))
		{
			$(otherList).slideDown("slow");
			$(this).html('<a href="#">show less...</a>').css({cursor: "pointer"});
		}
		else
		{
			$(otherList).slideUp("slow");
			$(this).html('<a href="#">show ' + $(this).attr("count") +  ' more...</a>').css({cursor: "pointer"});
		}
		return false;
	});
	
	$(".featured a").mouseover(function(e){
		var ttText = $(this).attr("tooltext");
		$("#tooltip").html(ttText);
		showToolTip(e);
	});
	
	$(".featured a").mouseout(function(e){
		hideToolTip();
	});
	
	$(".featured a").mousemove(function(e){
		showToolTip(e);
	});
});
