//Add trim functionality to String object
String.prototype.trim = function (){return this.replace(/^\s*/, "").replace(/\s*$/, "");}

//global variables
var gs_page = 1
var npolist
var gs_totalResults = -1

/*************************************************************************/

function DoGuidestarSearch(bShowWaitMessage)
{
	if(bShowWaitMessage == undefined) bShowWaitMessage = true
	
	//var keywords = "cancer consists education collaborates community grassroots"
	var key = document.getElementById("guidestar_keywords").value
	var org = document.getElementById("guidestar_orgname").value
	var city = document.getElementById("guidestar_city").value
	var st = document.getElementById("guidestar_state").value
	var st2 = document.getElementById("guidestar_state").options[document.getElementById("guidestar_state").selectedIndex].text
	
	if(st.toUpperCase() == "ANY") 
	{
		st = ""
		st2 = ""
	}
	
	DoGuidestarSearchEx(key, org, city, st, st2, bShowWaitMessage)
}

/*************************************************************************/

function DoGuidestarSearchEx(keywords, orgname, city, state, state2, bShowWaitMessage)
{
	if(keywords == "" && orgname == "" && city == "" && state == "")
	{
		alert("Please provide more search criteria to find your nonprofit.")
		document.getElementById("guidestar_content").style.display = "block"
	}
	else
	{
		window.scrollTo(0, 0)
		
		if(bShowWaitMessage)
		{
			document.getElementById("guidestar_loading").style.display = "block"
			document.getElementById("guidestar_content").style.display = "none"
			//Insert pause to allow please wait message to show
			var sCmd = "DoGuidestarSearchExPt2("
			sCmd += "\"" + keywords.replace(/"/gi, "") + "\", "
			sCmd += "\"" + orgname.replace(/"/gi, "") + "\", "
			sCmd += "\"" + city.replace(/"/gi, "") + "\", "
			sCmd += "\"" + state.replace(/"/gi, "") + "\", "
			sCmd += "\"" + state2.replace(/"/gi, "") + "\")"		
			
			setTimeout(sCmd, 1000)
		}
		else
		{
			DoGuidestarSearchExPt2(keywords, orgname, city, state, state2 )		
		}
		
	}
}

/*************************************************************************/

function DoGuidestarSearchExPt2(keywords, orgname, city, state, state2)
{
		var oGS = new GuidestarSearch()	
		
		oGS.SetPageSize(10)
		npolist = oGS.SearchGuidestar(keywords, orgname, city, state, state2, gs_page)
		
		//populate header
		document.getElementById("guidestar_header").innerHTML = formatHeader(oGS, keywords, gs_page)
		
		//populate results
		document.getElementById("guidestar_results").innerHTML = formatResults(keywords)
	
		//populate footer
		document.getElementById("guidestar_footer").innerHTML = formatFooter(oGS, keywords, gs_page)
		
		document.getElementById("guidestar_loading").style.display = "none"
		document.getElementById("guidestar_content").style.display = "block"
}

/*************************************************************************/

function doCleanSearch(kw)
{
	document.getElementById("guidestar_keywords").value = kw	
	DoGuidestarSearchEx(kw, "", "", "")	
}

/*************************************************************************/

function displayPage(newpage) 
{
	gs_page = newpage
	DoGuidestarSearch(false)
}

/*************************************************************************/

function formatHeader(obj, keywords, page)
{
	var totalPages = obj.TotalPages()
	var pageSize = obj.PageSize()
	gs_totalResults = obj.TotalResults()
	var source = obj.Source()
	
	var end = gs_page * pageSize
	var start = end - (pageSize-1)
	if(end > gs_totalResults){end = gs_totalResults}	
	
	var output  = ""	
	var txt = ""

	if(totalPages > 0)
	{	
		txt = "We've found " + formatNumber(gs_totalResults) + " results.<br><br>"
		txt += "They're displayed in groups of " + pageSize + ", with the most relevant results first."
		//txt += " Each group is sorted alphabetically."		
	}
	
	output += "<table width=\"550\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"
	if (txt != "") output += "<tr><td colspan=\"2\" align=\"left\" height=\"20\" valign=\"top\">" + txt + "</td></tr>"	
	output += "<tr><td colspan=\"2\"><img src=\"/Images/spacer.gif\" alt=\"\" width=\"1\" height=\"15\" border=\"0\"></td></tr>"

	if(totalPages > 0)
	{
		output += "<tr><td width=\"50%\" align=\"left\">"
		output += "<table cellpadding=\"0\" cellspacing=\"5\" border=\"0\"><tr>"
		
		if(totalPages > 1)
		{
			output += "<td valign=\"center\" align=\"left\">"
			if(gs_page > 1){output += "<a href=\"javascript:displayPage(" + (parseInt(gs_page) - 1) + ")\" class=\"GSNavLink\" style=\"text-decoration:none;\">&lt;&lt;Prev</a></td>"}
			else{output += "<span style=\"color:#999999\">&lt;&lt;Prev</span></td>"}
		}
		
		output += "<td><img src=\"/Images/spacer.gif\" alt=\"\" width=\"2\" height=\"1\" border=\"0\"></td>"
		output += "<td valign=\"center\" align=\"center\" ><b>Page " + gs_page + " of " + totalPages + "</b></td>"
		output += "<td><img src=\"/Images/spacer.gif\" alt=\"\" width=\"2\" height=\"1\" border=\"0\"></td>"

		if(totalPages > 1)
		{
			output += "<td valign=\"center\" align=\"right\">"			
			if(gs_page < totalPages){output += "<a href=\"javascript:displayPage(" + (parseInt(gs_page) + 1) + ")\" class=\"GSNavLink\" style=\"text-decoration:none;\">Next &gt;&gt;</a></td>"}
			else{output += "<span style=\"color:#999999\">Next &gt;&gt;</span></td>"}
		}
	
		output += "</tr></table></td>"
		output += "<td width=\"50%\" align=\"right\" ><b>Displaying results " + start + " - " + end + "</b></td></tr>"
		output += "<tr><td colspan=\"2\"><img src=\"/Images/spacer.gif\" alt=\"\" width=\"1\" height=\"5\" border=\"0\"></td></tr>"
	}
	
	output += "</table>"

	
	return output
}

/*************************************************************************/

function formatResults(keywords)
{
	var output = ""
	
	if(npolist.length > 0)
	{
		var tmp = typeof(npolist[0])
		if(tmp.toLowerCase() == "object")
		{
			for(count=0; count < npolist.length; count++)
			{
				npo = npolist[count]
		
				var ein = npo.EIN
				var org = npo.OrgName
				var location = npo.City + ", " + npo.State
				var miss = highlightKeywords(keywords, npo.Mission)
				var miss_short = highlightKeywords(keywords, CutWords(npo.Mission, 150, "..."))
				var progs = highlightKeywords(keywords, npo.Programs)
				var progs_short = highlightKeywords(keywords, CutWords(progs, 150, "..."))		
				
				if(output != ""){output += "<br>"}
				
				output += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"550\" class=\"clsFormBox2\">"
				output += "<tr><td class=\"clsFormTopLeft\"><img src=\"/design/1/images/top_left.gif\" class=\"clsFormCornerImage\"></td>"
				output += "<td class=\"clsFormTop\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td>"
				output += "<td class=\"clsFormTopRight\"><img src=\"/design/1/images/top_right.gif\" class=\"clsFormCornerImage\"></td></tr>"
				output += "<tr><td class=\"clsFormLeft\" width=\"6\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td>"
				output += "<td valign=\"top\"><!-- Begin Organization Display -->"
				output += "<table width=\"100%\" cellspacing=\"0\" cellpadding=\"0\" border=\"0\">"
				output += "<tr><td colspan=\"2\"><b><a href=\"javascript:selectNPO('" + count + "');\">" + org + "</a></b><input type=\"hidden\" name=\"FRSId" + ein + "\" value=\"\"></td></tr>"
				output += "<tr><td colspan=\"2\" height=\"4\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"4\"></td></tr>"
				output += "<tr><td colspan=\"2\">"+ location + "<br>EIN: " + ein + "</td></tr>"
				output += "<tr><td colspan=\"2\" height=\"4\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"10\"></td></tr>"
				output += "<tr><td colspan=\"2\">"
				
				if(miss != "")
				{
					output += "<div id=\"divShortMission" + ein + "\" style=\"display:block\"><b>Mission:</b> " + miss_short + "</div>"
					output += "<div id=\"divLongMission" + ein + "\" style=\"display:none\"><b>Mission:</b> " + miss + "</div>"
					if( miss != miss_short) output += "<a id=\"linkMission" + ein + "\" href=\"javascript:toggleText('Mission" + ein + "')\" style=\"font-size:10px;color:#999999\">More >></a>"
				}
				else
				{
					output += "<b>Mission:</b> Not Provided."
				}
					
				output += "</td></tr>"
				output += "<tr><td colspan=\"2\" height=\"4\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"10\"></td></tr>"
				output += "<tr><td colspan=\"2\">"
				
				if(progs != "")
				{
					output += "<div id=\"divShortPrograms" + ein + "\" style=\"display:block\"><b>Programs:</b> " + progs_short + "</div>"
					output += "<div id=\"divLongPrograms" + ein + "\" style=\"display:none\"><b>Programs:</b> " + progs + "</div>"
					if(progs != progs_short) output += "<a id=\"linkPrograms" + ein + "\" href=\"javascript:toggleText('Programs" + ein + "')\" style=\"font-size:10px;color:#999999\">More >></a>"
				}
				else
				{
					output += "<b>Programs:</b> Not Provided."
				}
				output += "</td></tr></table>"
				output += "<!-- End Organization Display --></td>"
				output += "<td class=\"clsFormRight\" width=\"6\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td></tr>"
				output += "<tr><td class=\"clsFormBottomLeft\"><img src=\"/design/1/images/bottom_left.gif\" class=\"clsFormCornerImage\"></td>"
				output += "<td class=\"clsFormBottom\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td>"
				output += "<td class=\"clsFormBottomRight\"><img src=\"/design/1/images/bottom_right.gif\" class=\"clsFormCornerImage\"></td></tr></table>"
			}			
		}
		else
		{
			//There was an error from guidestar
			output += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"550\" class=\"clsFormBox2\">"
			output += "<tr><td class=\"clsFormTopLeft\"><img src=\"/design/1/images/top_left.gif\" class=\"clsFormCornerImage\"></td>"
			output += "<td class=\"clsFormTop\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td>"
			output += "<td class=\"clsFormTopRight\"><img src=\"/design/1/images/top_right.gif\" class=\"clsFormCornerImage\"></td></tr>"
			output += "<tr><td class=\"clsFormLeft\" width=\"6\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td>"
			output += "<td valign=\"top\" align=\"center\"><b>The following error occured while trying to communicate with the Guidestar Search Service:"
			output += "<blockquote style=\"color:Red;font-weight:bold;\">" + npolist[0].replace("###GUIDESTAR ERROR###", "") + "</blockquote>"
			output += "Please try your query again.  If you continue to have problems, please <a href=\"mailto:support@firstgiving.com?subject=Guidestar Error\">let us know</a>."
			output += "</td><td class=\"clsFormRight\" width=\"6\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td></tr>"
			output += "<tr><td class=\"clsFormBottomLeft\"><img src=\"/design/1/images/bottom_left.gif\" class=\"clsFormCornerImage\"></td>"
			output += "<td class=\"clsFormBottom\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td>"
			output += "<td class=\"clsFormBottomRight\"><img src=\"/design/1/images/bottom_right.gif\" class=\"clsFormCornerImage\"></td></tr></table>"		
		}
		
	}
	else
	{
		//there were no results found, 
		var clean = keywords.replace("'", "");
		clean = clean.replace(".", "");
		clean = clean.replace(",", "");
		clean = clean.replace("!", "");
		clean = clean.replace("\"", "");
		
		output += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"550\" class=\"clsFormBox2\">"
		output += "<tr><td class=\"clsFormTopLeft\"><img src=\"/design/1/images/top_left.gif\" class=\"clsFormCornerImage\"></td>"
		output += "<td class=\"clsFormTop\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td>"
		output += "<td class=\"clsFormTopRight\"><img src=\"/design/1/images/top_right.gif\" class=\"clsFormCornerImage\"></td></tr>"
		output += "<tr><td class=\"clsFormLeft\" width=\"6\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td>"
		output += "<td valign=\"top\" class=\"clsAlertMessage\" align=\"center\"><b>There were no nonprofit organizations found that match the specified criteria.</b>"
		
		if (clean != keywords)
		{
			output += "<br><br><b><a href=\"javascript:doCleanSearch('" + clean + "')\">Click here</a> to try your search again without punctuation.</b>"
		}
					
		output += "</td><td class=\"clsFormRight\" width=\"6\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td></tr>"
		output += "<tr><td class=\"clsFormBottomLeft\"><img src=\"/design/1/images/bottom_left.gif\" class=\"clsFormCornerImage\"></td>"
		output += "<td class=\"clsFormBottom\"><img src=\"/images/spacer.gif\" width=\"1\" height=\"1\"></td>"
		output += "<td class=\"clsFormBottomRight\"><img src=\"/design/1/images/bottom_right.gif\" class=\"clsFormCornerImage\"></td></tr></table>"
	}
	
	return output
}

/*************************************************************************/

function formatFooter(obj, keywords, page)
{
	var pageArray = GetPageNumbers(obj, gs_page)
	var totalPages = obj.TotalPages()
	var output  = ""
	
	if(totalPages > 1)
	{
		output += "<table border=\"0\" width=\"550\" cellpadding=\"0\" cellspacing=\"0\"><tr><td>"
		output += "<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" align=\"center\"><tr>"
		output += "<td rowspan=\"3\" align=\"right\" valign=\"top\" ><b>Results Page</b></td>"
		output += "<td rowspan=\"3\"><img src=\"/Images/spacer.gif\" alt=\"\" width=\"5\" height=\"1\" border=\"0\"></td>"
		output += "<td valign=\"top\"><table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr>"
		
		for(pageCount = 0; pageCount < pageArray.length; pageCount++)
		{
			var cpage = pageArray[pageCount]
			var styleClass = (cpage == gs_page) ? "GSNavLinkCurrent" : "GSNavLink"
			
			output += "<td align=\"left\" valign=\"top\" >"
			output += "<a href=\"javascript:displayPage(" + cpage + ")\" class=\"" + styleClass + "\" style=\"text-decoration:none;\">" + cpage + "</a></td>"
			

			if(pageCount < (pageArray.length-1))
			{
				output += "<td><img src=\"/Images/spacer.gif\" alt=\"\" width=\"5\" height=\"1\" border=\"0\"></td>"
			}
		}
		
		output += "</tr></table></td>"
		output += "<td rowspan=\"3\"><img src=\"/Images/spacer.gif\" alt=\"\" width=\"5\" height=\"1\" border=\"0\"></td>"
		output += "<td rowspan=\"3\" align=\"left\" valign=\"top\"><b>of " + totalPages + "</b></td></tr>"
		output += "<tr><td><img src=\"/Images/spacer.gif\" alt=\"\" width=\"1\" height=\"5\" border=\"0\"></td></tr>"
		output += "<tr><td align=\"center\">"
		output += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\"><tr>"
		
		output += "<td align=\"left\" nowrap><a href=\"javascript:displayPage(1)\" class=\"GSNavLink\" style=\"text-decoration:none;\">First</a></td>"
		
		output += "<td align=\"left\" nowrap><img src=\"/Images/spacer.gif\" alt=\"\" width=\"10\" height=\"1\" border=\"0\"></td>"
		
		if(gs_page > 1){output += "<td align=\"left\" nowrap><a href=\"javascript:displayPage(" + (parseInt(gs_page)-1) + ")\" class=\"GSNavLink\" style=\"text-decoration:none;\">&lt;&lt;Prev</a></td>"}
		else{output += "<td align=\"left\" nowrap><span style=\"color:#999999\">&lt;&lt;Prev</span></td>"}
		
		output += "<td align=\"left\" nowrap><img src=\"/Images/spacer.gif\" alt=\"\" width=\"10\" height=\"1\" border=\"0\"></td>"
		
		if(gs_page < totalPages){output += "<td align=\"left\" nowrap><a href=\"javascript:displayPage(" + (parseInt(gs_page)+1) + ")\" class=\"GSNavLink\" style=\"text-decoration:none;\">Next&gt;&gt;</a></td>"}
		else{output += "<td align=\"left\" nowrap><span style=\"color:#999999\">Next &gt;&gt;</span></td>"}
		
		output += "<td align=\"left\" nowrap><img src=\"/Images/spacer.gif\" alt=\"\" width=\"10\" height=\"1\" border=\"0\"></td>"
		
		output += "<td align=\"left\" nowrap><a href=\"javascript:displayPage(" + totalPages + ")\" class=\"GSNavLink\" style=\"text-decoration:none;\">Last</a></td>"
		output += "</tr></table></td></tr></table></td></tr></table>"
	}
	return output
}

/*************************************************************************/

function formatNumber(num)
{
	var sRet = new String(num)
	if (num >= 1000 || num <= -1000) 
	{
		var iStart = sRet.indexOf(".");
		if (iStart < 0)
			iStart = sRet.length;

		iStart -= 3;
		while (iStart >= 1) 
		{
			sRet = sRet.substring(0,iStart) + "," + sRet.substring(iStart,sRet.length)
			iStart -= 3;
		}		
	}
	
	return sRet
}

/*************************************************************************/
function GetPageNumbers(obj, currPage)
{
	var totalPages = obj.TotalPages()
	var seed = 0
	var start = 0
	var finish = 0
	var arrRet = new Array()
	var idx = 0
	
	if(totalPages > 1)
	{
		if(totalPages < 11)
		{
			seed = 1
			start = 2
			finish = totalPages
		}
		else
		{
			seed = currPage - 5
			if(currPage < 6){seed = 0}
			if(currPage >= totalPages-5){seed = totalPages-10}
			
			start = seed + 1
		
			if(currPage >= totalPages-5){finish = totalPages}
			else{finish = seed + 10}
		}
		
		for(pageCount = start; pageCount <= finish; pageCount++)
		{
			arrRet[idx] = pageCount
			idx++
		}
	}	
	return arrRet	
}

/*************************************************************************/

function highlightKeywords(words, text, type)
{
	//array of color values to use for highlights
	backcolors = new Array("#f0e68c", "#b0e0e6", "#dda0dd", "#ffb6c1", "#9acd32", "#ffa500")
	boldcolors = new Array("#5aae42", "#4a307b", "#dda0dd", "#ffb6c1", "#808000", "#ffa500")
	clridx = 0

	//words not to highlight
	noisewords = "AND FOR IF OF THE TO"

	//break up the keywords
	arr = words.split(" ")
	
	for(x=0; x < arr.length; x++)
	{
		word = arr[x].toUpperCase()
		word = word.trim()
		
		if (noisewords.indexOf(word) < 0)
		{
			//convert text to upper case for comparisons
			tmp = text.toUpperCase()
			
			//find first occurance of keyword, and loop until there are no more		
			idx = tmp.indexOf(word, 0)
			
			while(idx >= 0)
			{
				//the end of the word
				idx2 = idx + word.length
				
				//all the string manipulation stuff				
				part1 = text.substring(0, idx)
				part2 = text.substring(idx, idx2)
				part3 = text.substring(idx2)
				
				span1 = "<span style=\"background-color:" + backcolors[clridx] + "\">"
				//span1 = "<span style=\"font-weight:bold;color:" + boldcolors[clridx] + "\">"
				span2 = "</span>"
				
				text = part1 + span1 + part2 + span2 + part3			

				//reset upper case copy to include new span tags
				tmp = text.toUpperCase()
				
				//reset index, adjusting for the length of the added text
				idx = tmp.indexOf(word, (idx2 + (span1.length + span2.length)))
			}
			
			//increment color index
			clridx++
			if(clridx >= backcolors.length) clridx = 0
		}
		
	}
	
	return text
}

/*************************************************************************/

function toggleText(divid)
{
	var objShort = document.getElementById("divShort" + divid);
	var objLong = document.getElementById("divLong" + divid);
	var objLink = document.getElementById("link" + divid);
	
	if(objLong.style.display == "block")
	{
		objShort.style.display = "block";
		objLong.style.display = "none";
		objLink.innerHTML = "More >>"
	}
	
	else
	{
		objShort.style.display = "none";
		objLong.style.display = "block";
		objLink.innerHTML = "<< Less"
	}
}

/*************************************************************************/

function CutWords(sFullText, nLong, sAddWord)
{
	var sReturn, aCountWords
	if(sFullText.length > nLong)
	{
		sReturn = ""
		aCountWords = sFullText.split(" ")
		
		for(z=0; z < aCountWords.length; z++)
		{
			if(sReturn.length <= nLong)
			{
				if(sReturn != ""){sReturn += " "}
				sReturn += aCountWords[z]
			}
		}
		
		return sReturn + sAddWord
	}
	else
	{
		return sFullText
	}
}
