// **************************************************************************
// Functions used to read XML file and load page elements for ARI projects.
// **************************************************************************

var xmlDoc;
if (window.ActiveXObject)
{// code for IE
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
}
else if (document.implementation.createDocument)
{// code for Mozilla, Firefox, Opera, etc.
xmlDoc=document.implementation.createDocument("","",null);
}
else
{
alert('Your browser cannot handle this script');
}
xmlDoc.async=false;
xmlDoc.load("app_data/ARI_XML.xml");

var x = xmlDoc.getElementsByTagName("Dynamic_projects");
 
window.onload=init; 

function init() {   
	searchXML();   
}   


function searchXML() {
	if (!xmlDoc) {
		//loadIndex();
		return "";
	}
	// Clear page elements
	document.getElementById("message").innerHTML = "";
	document.getElementById("projectinfo").innerHTML = "";
	
	// get the form field values based on their id
	var searchTerm = document.getElementById("Search_TXT").value;
	var searchYear = document.getElementById("Year_DDL").value;
	var searchFocusArea = document.getElementById("FocusArea_DDL").value;
	
	results = new Array;
	xmlIndex = new Array;
	if (!searchTerm.length > 0 && !searchYear.length > 0 && !searchFocusArea.length > 0) {
			txt = "Enter at least one search criteria.";
			document.getElementById("message").innerHTML = txt;
	} else if (searchTerm.length > 0 && searchTerm.length < 3) {
			txt = "Enter at least three characters.";
			document.getElementById("message").innerHTML = txt;
	} else {
		for (var i=0; i<x.length; i++) {
			var foundTerm = false;
			var foundYear = false;
			var foundFocusArea = false;
			// get the current XML values
			var title = x[i].getElementsByTagName("Title")[0].childNodes[0].nodeValue;
			var abstract = x[i].getElementsByTagName("Abstract")[0].childNodes[0].nodeValue;
			var fiscalyear = x[i].getElementsByTagName("FiscalYear")[0].childNodes[0].nodeValue;
			var focusarea1 = x[i].getElementsByTagName("FocusArea1")[0].childNodes[0].nodeValue;
			var focusarea2 = x[i].getElementsByTagName("FocusArea2")[0].childNodes[0].nodeValue;
			
			// see if the XML entry matches the search term, and (if so) store it in an array
			if (searchTerm.length > 0) {
				var exp = new RegExp(searchTerm,"i");
				if ( title.match(exp) != null) {
					foundTerm = true;
				} else if ( abstract.match(exp) != null) {
					foundTerm = true;
				}
			}
			// see if the XML entry matches the year, and (if so) store it in an array
			if (searchYear.length > 0) {
				var exp = new RegExp(searchYear,"i");
				if ( fiscalyear.match(exp) != null) {
					foundYear = true;
				}
			}
			// see if the XML entry matches the research focus area, and (if so) store it in an array
			if (searchFocusArea.length > 0) {
				var exp = new RegExp(searchFocusArea,"i");
				if ( focusarea1.match(exp) != null) {
					foundFocusArea = true;
				} else if ( focusarea2.match(exp) != null) {
					foundFocusArea = true;
				}
			}
			
			// Add the row if match found for all selected criteria
			var rowMatch = false;
			if (searchYear.length > 0 && searchFocusArea.length > 0 && searchTerm.length > 0) {
				rowMatch = foundYear && foundFocusArea && foundTerm; }
			else if (searchYear.length > 0 && searchFocusArea.length > 0) {
				rowMatch = foundYear && foundFocusArea; }
			else if (searchFocusArea.length > 0 && searchTerm.length > 0) {
				rowMatch = foundFocusArea && foundTerm; }
			else if (searchYear.length > 0 && searchTerm.length > 0) {
				rowMatch = foundYear && foundTerm; }
			else if (searchYear.length > 0) { rowMatch = foundYear; } 
			else if (searchFocusArea.length > 0) { rowMatch = foundFocusArea ;}
			else if (searchTerm.length > 0) { rowMatch = foundTerm; }
			if (rowMatch) {
				results.push(x[i]);
				xmlIndex.push(i);
			}
						
		}
		
		showSearchResults(results, xmlIndex);
	}
}

function showSearchResults(results, xmlIndex) {
	var output = "";	
	var currProj = "";
	var lastProj = "";
		
	if (results.length > 0) {		
		// if there are any results, put them in the "searchresults" div
		//output += "<p><strong>Click a Title below to view project details:</strong></p>";
		output += "<table class='courseinfo'>\n";
		output += "<tr>";
		output += "<th>Project Number</th>";
		output += "<th>Title</th>";
		output += "<th>Project Director</th>";
		output += "<th>Year</th>";	
		output += "</tr>\n";
		for (var i=0; i<results.length; i++) { 
		  currProj = results[i].getElementsByTagName("ARINumber")[0].childNodes[0].nodeValue;
			// Add the row if its a different project number (XML data repeats project info for each Coinv or Collab)
			if (currProj != lastProj) {
				lastProj = currProj;
				output += "<tr>";
				output += "<td>";
				output += results[i].getElementsByTagName("ARINumber")[0].childNodes[0].nodeValue;
				output += "</td>";
				output += "<td><a href='#project' onclick='showProjectInfo(" + xmlIndex[i] + ")' title='View project details'>";
				output += results[i].getElementsByTagName("Title")[0].childNodes[0].nodeValue;
				output += "</a></td>";
				output += "<td>";
				output += results[i].getElementsByTagName("LastName")[0].childNodes[0].nodeValue;
				output += "</td>";
				output += "<td>";
				output += getYearText(results[i].getElementsByTagName("FiscalYear")[0].childNodes[0].nodeValue);
				output += "</td>";
				output += "</tr>";
			}
		}
		output +="</table>\n";
	} else {
		// else tell the user no matches were found
		output = "<p><strong>Sorry, no matches were found.</strong></p>";
	}
	document.getElementById("searchresults").innerHTML = output;
}

function showProjectInfo(i) {
	arinumber = "";
	fiscalyear = "";
	title = "";
	abstract = "";
	fname = "";
	mi = "";
	lname = "";
	phd = "";
	totalFunding = "";
	matchFund = "";
	focusArea1 = "";
	focusArea2 = "";
	focusAreas = "";
	coinv_fname = "";
	coinv_mname = "";
	coinv_lname = "";
	coinv_phd = "";
	coinv = "";
	collab_fname = "";
	collab_mname = "";
	collab_lname = "";
	collab_phd = "";
	collabs = "";
	projectRows = new Array;

	arinumber = (x[i].getElementsByTagName("ARINumber")[0].childNodes[0].nodeValue);
	fiscalyear = (x[i].getElementsByTagName("FiscalYear")[0].childNodes[0].nodeValue);
	title = (x[i].getElementsByTagName("Title")[0].childNodes[0].nodeValue);
	abstract = (x[i].getElementsByTagName("Abstract")[0].childNodes[0].nodeValue);
	if( x[i].getElementsByTagName("FirstName")[0] ) 
		fname = (x[i].getElementsByTagName("FirstName")[0].childNodes[0].nodeValue);
	if( x[i].getElementsByTagName("MiddleInitial")[0] ) 
		mi = (x[i].getElementsByTagName("MiddleInitial")[0].childNodes[0].nodeValue);
	if( x[i].getElementsByTagName("LastName")[0] ) 
		lname = (x[i].getElementsByTagName("LastName")[0].childNodes[0].nodeValue);
	if( x[i].getElementsByTagName("PhD")[0] ) 
		phd = (x[i].getElementsByTagName("PhD")[0].childNodes[0].nodeValue);
	if( x[i].getElementsByTagName("AriTotalFunding")[0] ) 
		totalFunding = (x[i].getElementsByTagName("AriTotalFunding")[0].childNodes[0].nodeValue);
	if( x[i].getElementsByTagName("MatchingFunds")[0] ) 
		matchFund = (x[i].getElementsByTagName("MatchingFunds")[0].childNodes[0].nodeValue);
	if( x[i].getElementsByTagName("FocusArea1")[0] ) 
		focusArea1 = (x[i].getElementsByTagName("FocusArea1")[0].childNodes[0].nodeValue);
	if( x[i].getElementsByTagName("FocusArea2")[0] ) 
		focusArea2 = (x[i].getElementsByTagName("FocusArea2")[0].childNodes[0].nodeValue);
	// Get all rows for this project (project info is repeated in XML data for each coinvestigator or collaborator)
	projectRows = getRowsByARInumber(arinumber);
	// Get all coinvestigators for this project
	for (var i=0; i<projectRows.length; i++) {
		if( projectRows[i].getElementsByTagName("Coinv_FirstName")[0] ) 
			coinv_fname = (projectRows[i].getElementsByTagName("Coinv_FirstName")[0].childNodes[0].nodeValue);
		if( projectRows[i].getElementsByTagName("Coinv_MiddleName")[0] ) 
			coinv_mname = (projectRows[i].getElementsByTagName("Coinv_MiddleName")[0].childNodes[0].nodeValue);
		if( projectRows[i].getElementsByTagName("Coinv_LastName")[0] ) 
			coinv_lname = (projectRows[i].getElementsByTagName("Coinv_LastName")[0].childNodes[0].nodeValue);
		if( projectRows[i].getElementsByTagName("Coinv_PHD")[0] ) 
			coinv_phd = (projectRows[i].getElementsByTagName("Coinv_PHD")[0].childNodes[0].nodeValue);
		if (coinv_lname.length > 0 && coinv.indexOf(coinv_lname) == -1 ) {		// Add the name if it wasn't already added (dups in XML)
		  if (coinv.length > 0) { coinv += " <br>" }
			coinv += coinv_fname+" "+coinv_mname+" "+coinv_lname+((coinv_phd.length > 0) ? ", "+coinv_phd : "");
		}
	}
	// Get all collaborators for this project
	for (var i=0; i<projectRows.length; i++) {
		if( projectRows[i].getElementsByTagName("CollabCoop_FirstName")[0] ) 
			collab_fname = (projectRows[i].getElementsByTagName("CollabCoop_FirstName")[0].childNodes[0].nodeValue);
		if( projectRows[i].getElementsByTagName("CollabCoop_MiddleName")[0] ) 
			collab_mname = (projectRows[i].getElementsByTagName("CollabCoop_MiddleName")[0].childNodes[0].nodeValue);
		if( projectRows[i].getElementsByTagName("CollabCoop_LastName")[0] ) 
			collab_lname = (projectRows[i].getElementsByTagName("CollabCoop_LastName")[0].childNodes[0].nodeValue);
		if( projectRows[i].getElementsByTagName("CollabCoop_PHD")[0] ) 
			collab_phd = (projectRows[i].getElementsByTagName("CollabCoop_PHD")[0].childNodes[0].nodeValue);
		if (collab_lname.length > 0 && collabs.indexOf(collab_lname) == -1 ) {		// Add the name if it wasn't already added (dups in XML)
		  if (collabs.length > 0) { collabs += " <br>" }
			collabs += collab_fname+" "+collab_mname+" "+collab_lname+((collab_phd.length > 0) ? ", "+collab_phd : "");
		}
	}

	// Build string containing focus areas
	focusAreas = focusArea1;
	if (focusArea2.length > 0 && focusArea2 != "None") { focusAreas += ", " + focusArea2; }
	// Display text for empty fields
	if (coinv == "") { coinv = "None"; }
	if (collabs == "") { collabs = "None"; }
	if (matchFund == "") { matchFund = "Match Not Required"; }

// Build HTML output
	txt = "<h3>"+title+"</h3>";
	txt += "<table title=\"Project Information\" >";
	txt += "<tr><th scope=\"row\">Project Number</th><td>"+arinumber+"</td></tr>";
	txt += "<tr><th scope=\"row\">Fiscal Year</th><td>"+getYearText(fiscalyear)+"</td></tr>";
	txt += "<tr><th scope=\"row\">Research Focus Area</th><td>"+focusAreas+"</td></tr>";
	txt += "<tr><th scope=\"row\">Project Director</th><td>"+fname+" "+mi+" "+lname+((phd.length > 0) ? ", "+phd : "")+"</td></tr>";
	txt += "<tr><th scope=\"row\">Coinvestigators</th><td>"+coinv+"</td></tr>";
	txt += "<tr><th scope=\"row\">Collaborators/Cooperators</th><td>"+collabs+"</td></tr>";
	txt += "<tr><th scope=\"row\">ARI Total Funding</th><td>"+formatCurrency(totalFunding)+"</td></tr>";
	txt += "<tr><th scope=\"row\">Matching Funds</th><td>"+formatCurrency(matchFund)+"</td></tr>";
	txt += "</table>";
	txt += "<p><strong>Abstract</strong><br/>"+abstract+"</p>";
	txt += "<a href=\"#search\">Back to Search Results</a>";
	document.getElementById("projectinfo").innerHTML = txt;
	
	// Jump to project detail display area
	//window.location.hash="project"; 
}

function getRowsByARInumber(searchARINumber) {
	// Get all rows in the xml data with the specified ARI number.
	rows = new Array;
	for (var i=0; i<x.length; i++) {
		var arinumber = x[i].getElementsByTagName("ARINumber")[0].childNodes[0].nodeValue;
		// see if the XML entry matches the search term, and (if so) store it in an array
		var exp = new RegExp(searchARINumber,"i");
		if ( arinumber.match(exp) != null) {
			rows.push(x[i]);
		}
	}
	return rows;
}

function formatCurrency(strValue) {
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);
	if(isNaN(dblValue)) { return strValue; }	// Return original value if blank or not a number
	
	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
		
}

function getYearText(xmlFiscalYear) {
	var str = xmlFiscalYear.toString();
	if (str.length == 1) {
			year = "200" + str;
	} else if (str.length == 2) {
			year = "20" + str;
	} else {
			year = str;
	}
	return year;
}

function isNumeric(text) {
	var sValidChars = "0123456789.";
	var bIsNumber=true;
	var currentChar;
	for (i = 0; i < text.length && bIsNumber == true; i++) { 
		currentChar = text.charAt(i); 
		if (sValidChars.indexOf(currentChar) == -1) {
			 bIsNumber = false;
		}
	}
	return bIsNumber;
}

function limitString(originalStr, charLimit) {
	var trimmedStr  = "";
	trimmedStr = originalStr.substring(0, charLimit);
	trimmedStr += "... ";
	return trimmedStr;
}


