// JavaScript Document
// scripts that generate Ebook XML files bases on letter and subject

//Global vars
//-----------
var fld_arr = new Array();
var see_also = new Array();
var nullFlds = [null, 				//[0]
			   		[null, 			//[1][0]
					 null,  		//[1][1]
					 null,  		//[1][2]
					 null,			//[1][3]
					 null], 		//[1][4]
				null, 				//[2]
				null, 				//[3]
					[null, 			//[4][0]	adDate
					 null, 			//[4][1]	adYr
					 null], 		//[4][2]	adMon
				null, 				//[5]
					[null, 			//[6][0]
					 null, 			//[6][1]
					 null], 		//[6][2]
				null,				//[7]
				null,				//[8]
				null, 				//[9]
				null, 				//[10]
				null, 				//[11]
				null, 				//[12]
				null, 				//[13]
				null, 				//[14]
				null,				//[15]
				null,				//[16]
				null,				//[17]
				null,				//[18]
				null				//[19]
			];
	
	
	


//*****************************************************************************************************
// sortByTitle()
// ------------
// sorts the titles by the Title field x[0], in ascending order, regardless of capitalization
//*****************************************************************************************************
function sortByTitle(a, b) {
    var x = a[0].toLowerCase();
    var y = b[0].toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}



//*****************************************************************************************************
// sortBySubHd()
// ------------
// sorts the titles by the Title field x[0], in ascending order, regardless of capitalization
//*****************************************************************************************************
function sortBySubHd(TheArr,u,v,w){

  if(u==undefined){TheArr.sort(Sortsingle);} // this is a simple array, not multi-dimensional, ie, SortIt(TheArr);
  else{TheArr.sort(Sortmulti);}

  function Sortsingle(a,b){

    var swap=0;
    if(isNaN(a-b)){
      if((isNaN(a))&&(isNaN(b))){swap=(b<a)-(a<b);}
      else {swap=(isNaN(a)?1:-1);}
    }
    else {swap=(a-b);}
    return swap;
  }

 function Sortmulti(a,b){
  var swap=0;
    if(isNaN(a[u]-b[u])){
      if((isNaN(a[u]))&&(isNaN(b[u]))){swap=(b[u]<a[u])-(a[u]<b[u]);}
      else{swap=(isNaN(a[u])?1:-1);}
    }
    else{swap=(a[u]-b[u]);}
    if((v==undefined)||(swap!=0)){return swap;}
    else{
      if(isNaN(a[v]-b[v])){
        if((isNaN(a[v]))&&(isNaN(b[v]))){swap=(b[v]<a[v])-(a[v]<b[v]);}
        else{swap=(isNaN(a[v])?1:-1);}
      }
      else{swap=(a[v]-b[v]);}
      if((w==undefined)||(swap!=0)){return swap;}
	} 
 }
}



//*****************************************************************************************************
// checkPrecArt()
// ------------
// returns: title (string)
//
// is passed a title and checks to see whether there is a preceding article. If so, 
// the preceding article is removed and appended to the end of the title. The new title
// is returned.
//*****************************************************************************************************
function checkPrecArt(ttl) {
	//Check the title for preceding A, An, or The
	if (ttl.substr(0,2) == "A ") {
		title = ttl.slice(2) + ', A';
	}
	else if (ttl.substr(0,3) == "An ") {
		title = ttl.slice(3) + ', An';
	}
	else if (ttl.substr(0,4) == "The ") {
		title = ttl.slice(4) + ', The';
	}
	else {
		title = ttl;
	}
	
	return(title);
}	//**checkPrecArt**//



//*****************************************************************************************************
// check_date()
// ------------
// returns: bool
//
// is passed adYr & adMon and checks whether it precedes the current month by 2; 
// if so, TRUE is returned, else FALSE.
//*****************************************************************************************************
function check_date (adYr, adMon) {
//alert('Year: ' + adYr + ', Month: ' + adMon);			
		var today = new Date();

	switch (today.getMonth()+1) {
		case 1:
			if (((today.getFullYear() - adYr == 1) &&
				((adMon == 12) || 
				 (adMon == 11))) 
				||
				((today.getFullYear() == adYr) && 
				 (adMon == 1)))
				return true;
			break;
		case 2:
			if (((today.getFullYear() - adYr == 1) &&
				((adMon == 12))) 
				||
				((today.getFullYear() == adYr) && 
				 ((adMon == 2) || 
				  (adMon == 1))))
				return true;
			break;
		case 3:
			if 	((today.getFullYear() == adYr) && 
				 ((adMon == 3) || 
				  (adMon == 2) || 
				  (adMon == 1)))
				return true;
			break;
		case 4:
			if ((today.getFullYear() == adYr) && 
				 ((adMon == 4) ||
				  (adMon == 3) ||
				  (adMon == 2)))
				return true;
			break;
		case 5:
			if ((today.getFullYear() == adYr) && 
				 ((adMon == 5) ||
				  (adMon == 4) ||
				  (adMon == 3)))
				return true;
			break;
		case 6:
			if ((today.getFullYear() == adYr) && 
				 ((adMon == 6) ||
				  (adMon == 5) ||
				  (adMon == 4)))
				return true;
			break;
		case 7:
			if ((today.getFullYear() == adYr) && 
				 ((adMon == 7) ||
				  (adMon == 6) ||
				  (adMon == 5)))
				return true;
			break;
		case 8:
			if ((today.getFullYear() == adYr) && 
				 ((adMon == 8) ||
				  (adMon == 7) ||
				  (adMon == 6)))
				return true;
			break;
		case 9:
			if ((today.getFullYear() == adYr) && 
				 ((adMon == 9) ||
				  (adMon == 8) ||
				  (adMon == 7)))
				return true;
			break;
		case 10:
			if ((today.getFullYear() == adYr) && 
				 ((adMon == 10) ||
				  (adMon == 9) ||
				  (adMon == 8)))
				return true;
			break;
		case 11:
			if ((today.getFullYear() == adYr) && 
				 ((adMon == 11) ||
				  (adMon == 10) ||
				  (adMon == 9)))
				return true;
			break;
		case 12:
			if ((today.getFullYear() == adYr) && 
				 ((adMon == 12) ||
				  (adMon == 11) ||
				  (adMon == 10)))
				return true;
			break;
	}
	return false;
}	//**check_date**//



//*****************************************************************************************************
// getLangInfoWeb()
// ----------------
// parms: x--array of <item> nodes from WebResources
//        i--current iteration of for loop from 0-x.length
//        ttl_arr--array of titles and associated info pulled from WebResources
//
// for each check to see whether there are any <language> tags (0-3); if so then
// write values to ttl_arr[items][7,8]
//*****************************************************************************************************
function getLangInfoWeb (items, i, ttl_arr, cnt) {
	//Publisher Names and URLs
	lang = items[i].getElementsByTagName("language");
	
	ttl_arr[cnt][7] = new Array();
	//titles can have 0-3 non-English links
	for(j=0; j<lang.length; j++) {
		lVal = lang[j].getElementsByTagName("val");
		lTtl = lang[j].getElementsByTagName("lTitle");
		lURL = lang[j].getElementsByTagName("langURL");

		//how many languages for this resource? and VAL (name of lang)
		ttl_arr[cnt][7][j] = new Array (lVal[0].firstChild.nodeValue);
		ttl_arr[cnt][8] = lang.length;
		
		//if a TITLE is available use it instead of VAL
		if (lTtl[0])
			ttl_arr[cnt][7][j][0] = lTtl[0].firstChild.nodeValue;
		
		//URL (to alternate web page)
		if (lURL[0])
			ttl_arr[cnt][7][j][1] = lURL[0].firstChild.nodeValue;
		else
			ttl_arr[cnt][7][j][1] = "#";
	}
	
}	//**getLangInfoWeb**/



//*****************************************************************************************************
// getSubjHead()
// ------------
// parms: valu1--the subject short-hand name requested by user
//		  *returns: subject long name for display in table
//
// converts the subject heading from the short name used to call the functions to the longer name used
// in the select list that users see.
//*****************************************************************************************************
function getSubjHead(valu1, caller) {
	switch (valu1) {
<!--WEB Subjs-->
		case 'Association': 	return ("Associations &amp; Organizations");
		case 'Trials': 			return ("Clinical Trials");
		case 'Pharm': 			return ("Drugs &amp; Medications");
		case 'Ejournals': 		return ("Electronic Journals");
		case 'Financ': 			return ("Financial Assistance");
		case 'Locator': 		return ("Find a Dentist, Physician, or Specialist");
//		case 'General': 		return ("General Health Guides");
		case 'Government': 		return ("Government Sources");
		case 'Tests': 			return ("Medical Tests");
		case 'NonEnglish': 		return ("Non-English Language Resources");
		case 'Search': 			return ("Finding &amp; Evaluating Web Info");
		case 'Evidence': 		return ("Evidence-Based Medicine");
		case 'Patient':			return ("Patient Education Materials");
		case 'SubjTree':		return ("Full Subject Heading List");

<!--DB Subjs-->
		case 'Dental':			return ("Dentistry");
		case 'Economics': 		return ("Economics &amp; Business");
		case 'Life': 			return ("Environmental &amp; Life Sciences");
//		case 'General':			return ("General Reference");
		case 'Engineering':		return ("Science &amp; Engineering");
		case 'Medicine':		return ("Dentistry &amp; Medicine");
		case 'Social': 			return ("Social Sciences &amp; Humanities");
		case 'Consumer' : 		return ("Consumer Health");
		case 'Patient' :		return ("Patient Education Materials");
		case 'mobileDB' :		return ("Databases with Mobile Support");
		case 'http://webcomm.bcd.tamhsc.edu/library/DBsXML/Consumer' : return ("Databases");

<!--EB Subjs-->
		case 'Alternative': 	if (caller == "DB") 			//called from DB page
									return("Complementary &amp; Alternative Medicine");
								else if (caller == "EB")		//called from EB page
									return("Alternative Medicine");
		case 'BCD_text':		return("BCD Textbooks");
		case 'Biochemistry': 	return("Biochemistry");
		case 'Biotechnology':	return("Biotechnology/Materials");
		case 'Cardiovascular': 	return("Cardiovascular System");
		case 'Communicable':	return("Communicable Diseases");
		case 'Critical':		return("Critical Care Medicine");
		case 'Digestive': 		return("Digestive System");
		case 'Emergency': 		return("Emergency Medicine");
		case 'Endocrine': 		return("Endocrine System");
		case 'Evidence': 		return("Evidence-based Medicine");
		case 'Family': 			return("Family Practice");
		case 'General':			if (caller == "DB") 			//called from DB page
									return("General Reference");
								else if (caller == "EB")		//called from EB page
									return("General Medicine");
								break;
		case 'Geriatrics': 		return("Geriatrics, Gerontology");
		case 'Hemic':			return("Hemic/Lymphatic System");
		case 'Hospitals':		return("Hospitals/Health Facilities");
		case 'Internal': 		return("Internal Medicine");
		case 'Labs':			return("Labs, Tests, Diagnostics");
		case 'Microbiology':	return("Microbiology, Immunology");
		case 'Musculoskeletal':	return("Musuloskelatel System");
		case 'Nervous': 		return("Nervous System");
		case 'Obstetrics': 		return("Obstetrics, Gynecology");
		case 'Otolaryng':		return("Otolaryngology");
		case 'Palliative':		return("Palliative Care");
		case 'Professions':		return("Health Issues/Professions");
		case 'Physical':		return("Physical Therapy");
		case 'Psychiatry': 		return("Psychiatry, Psychology");
		case 'Public':			return("Public Health");
		case 'Radiology':		return("Radiology/Diagnostic Imaging");
		case 'Respiratory': 	return("Respiratory System");
		case 'Systemic':		return("Systemic/Metabolic Disorders");
		case 'Urogenital':		return("Urogenital System");
		case 'http://webcomm.bcd.tamhsc.edu/library/EbooksXML/Consumer' : return ("Ebooks");
		case 'new' : return ("New");
		
<!--EB Provs-->
		case 'Access':			return("Access Medicine");
		case 'Ebsco':			return("Ebsco Ebooks");
		case 'Informa':			return("Informa Healthcare");
		case 'MD':				return("MD Consult");
		case 'Pubmed':			return("Pubmed Bookshelf");
		case 'Science':			return("Science Direct");
		case 'Springer':		return("Springer Link");
		case 'Wiley':			return("Wiley Online Library");

		//for those subject headings that are the same
		default: return (valu1);
	}
}	//**getSubjHead**/



//*****************************************************************************************************
// createHTMLfiles()
// ---------------
// parms: field1--indicates what type of value valu1 is (beginLett, subject, resc_type, source, language)
//        valu1--the letter or subject used to locate the appropriate XML file
//        field2--indicates type of 2nd value param
//        valu2--usually a resc_type (Consumer Health, EBs, EJs, etc.)
//
// [1] go through entire XML file (items[]) looking for matching titles/subjects/languages...
//		(whatever is passed in via field/valu params); 
// [2] add matching <item>s to an array (titles[]);
// [3] sort the list; 
// [4] create an array of needed fields (ttlFields[]) for all of those matching titles (titles[])
//		procedure: populateFields()
// [5] process the list to turn it into HTML code; 
//		procedure: processTitlesArray()
//*****************************************************************************************************
function createHTMLfiles (field1, valu1, field2, valu2) {

		var items=XMLfile.getElementsByTagName("item");
		var cnt = 0;								//a count of the items we're adding to titles[]
		var startsWithLettRegExp = /^\D/;
		//array of matching titles
		var ttlInfo = [null, null, -1, null];				//[title, <title> or <alt_title>, index into items[]
		var titles = [ttlInfo];
		var ttlFields = new Array();						//array of fld_arr (see nullFlds for structure)
		var foundsub = false;
		var subHdInfo = [null, -1];
		var subHeads = 	[subHdInfo];						//array of sub-headings and the index into titles of their 1st entry
					
		
//alert(items.length);
	
	caller = document.HTMLoutput.HTMLTrgt.value;
		

	//*** [1] ***//
	//***********//
	// find all matching items
	for (i=0; i<items.length; i++) {
		cont=false; //default value
		
		//first check the resource type of each item to see if it matches what's passed in
		rescT = items[i].getElementsByTagName("resc_type");

		if (field2 == 'resc_type') { 										//if we did pass a resource type, AND
			if ((rescT.length != 0) && (rescT[0].firstChild != null)) {		//if the current item's <resc_type> is not null
				for (j=0; j<rescT.length; j++)								//then, check each <resc_type> against the passed val
					if (rescT[j].firstChild.nodeValue.match(valu2)) {		//if there's a match then continue below
						cont=true;
					}
			}
		}
		else {																//if we didn't pass a resource type
			cont=true;														//then continue below
		}
		
		//get the title (moving any preceding article to the end) and alt_title of each current item
		title  = checkPrecArt(items[i].getElementsByTagName("title")[0].firstChild.nodeValue);
		attl = items[i].getElementsByTagName("alt_title");
		
		if (cont) {
			switch (field1) {
				//find titles by LETTER
				case 'noJava':
				case 'beginLett': 
					//if choosing a letter, then reset the subject category choice
					document.getElementById('EB_Subject').selectedIndex = 0;
					
					//check the first letter of the title after removing any preceding articles
					if (	(valu1 == 'All') ||
							((valu1 == '0to9') && (!startsWithLettRegExp.test(title))) ||
							(valu1 == title.charAt(0).toUpperCase()) ) {
						//*** [2] ***//
						//we have a match so grab this <item> and store it in itemArr[]
						titles[cnt] = [title, 'title', i];
						cnt += 1;							//increase num for the next possible match
					}
					//also check the first letter of the alternative title without preceding article
					if ((attl.length != 0) && (attl[0].firstChild != null)) {
						atitle  = checkPrecArt(items[i].getElementsByTagName("alt_title")[0].firstChild.nodeValue)
						if (	((valu1 == '0to9') && (!startsWithLettRegExp.test(atitle))) ||
								(valu1 == atitle.charAt(0).toUpperCase()) ) {
							//*** [2] ***//
							//we have a match so grab this <item> and store it in itemArr[]
							titles[cnt] = [atitle, 'atitle', i];
							cnt += 1;							//increase num for the next possible match
						}
					}

					break;
					
				//find titles by SUBJECT
				case 'subject':
					//check to see if the current item has a <subject>
					subj = items[i].getElementsByTagName("subject");
					
					if ((subj.length != 0) && (subj[0].firstChild != null)) {
						//items can have 0-8 subjects catagories assigned
						for (k=0; k<subj.length; k++) {
							//if searching for a blank (' ') subject then check that first
							if ((valu1 == ' ') &&  (subj[k].firstChild.nodeValue == ' ')) {
								//*** [2] ***//
								//we have a match so grab this <item> and store it in itemArr[]
								titles[cnt] = [title, 'title', i];
								cnt += 1;							//increase num for the next possible match
							}
							else if ((valu1 != ' ') && (subj[k].firstChild.nodeValue.match(valu1) != null)) {
								//*** [2] ***//
								//we have a match so grab this <item> and store it in itemArr[]
								//see if there is a sub heading ("--"), and then save to titles[] array
								if (subj[k].firstChild.nodeValue.match('--') != null) {
									foundsub = true;
									loc = subj[k].firstChild.nodeValue.indexOf('--');
									subhd = subj[k].firstChild.nodeValue.substring(loc+3);
									if (subhd == valu1) {
									//oops, the subheading is our subject value,
									//so grab the main heading instead and pass that for display
										subhd = subj[k].firstChild.nodeValue.substring(0, loc-1);
									}
									titles[cnt] = [title, 'title', i, subhd];
									cnt += 1;							//increase num for the next possible match
								}
								else {
									titles[cnt] = [title, 'title', i, ''];
									cnt += 1;							//increase num for the next possible match
								}
								
							}
						}
					}
					
					//if there is no subject and we were passed 'empty' as a subject then that's a match!
					//Here we are specifically looking for items with no <subject> at all
					else if (valu1 == 'empty') {
						//*** [2] ***//
						//we have a match so grab this <item> and store it in itemArr[]
						titles[cnt] = [title, 'title', i];
						cnt += 1;							//increase num for the next possible match
					}
					break;
					
				//find NEW titles
				case 'new':
					//does this item have a <date_added> field?
					if (items[i].getElementsByTagName("date_added")[0]) {
						adYr = items[i].getElementsByTagName("year")[0].firstChild.nodeValue;
						
						if (items[i].getElementsByTagName("month")[0]) {
							adMon = items[i].getElementsByTagName("month")[0].firstChild.nodeValue;
							if (check_date(adYr, adMon)) {
								//*** [2] ***//
								//we have a match so grab this <item> and store it in itemArr[]
								titles[cnt] = [title, 'title', i];
								cnt += 1;							//increase num for the next possible match
							}
						}
					}
					break;
					
				//find titles by SOURCE
				case 'source':
					//check to see if the current item has a <source>
					srce = items[i].getElementsByTagName("source");
					
					if ((srce.length != 0) && (srce[0].firstChild != null))
						//items can have 0-3 source catagories assigned
						for (k=0; k<srce.length; k++)
							if (srce[k].firstChild.nodeValue.match(valu1) != null) {
								//*** [2] ***//
								//we have a match so grab this <item> and store it in itemArr[]
								titles[cnt] = [title, 'title', i];
								cnt += 1;							//increase num for the next possible match
							}
					break;
					
				//find titles by sGROUP
				case 'sGroup':
					//check to see if the current item has a <source>
					srce = items[i].getElementsByTagName("sGroup");
					
					if ((srce.length != 0) && (srce[0].firstChild != null))
						//items can have 0-3 source catagories assigned
						for (k=0; k<srce.length; k++)
							if (srce[k].firstChild.nodeValue.match(valu1) != null) {
								//*** [2] ***//
								//we have a match so grab this <item> and store it in itemArr[]
								titles[cnt] = [title, 'title', i];
								cnt += 1;							//increase num for the next possible match
							}
					break;
					
				//find titles by RESOURCE TYPE
				case 'resc_type':
					//check to see if the current item has a <resc_type>
					rescT = items[i].getElementsByTagName("resc_type");
					
					if ((rescT.length != 0) && (rescT[0].firstChild != null))
						//items can have 0-4 rescource types assigned
						for (k=0; k<rescT.length; k++) {
							if (rescT[k].firstChild.nodeValue.match(valu1)) {
								//*** [2] ***//
								//we have a match so grab this <item> and store it in itemArr[]
								titles[cnt] = [title, 'title', i];
								cnt += 1;							//increase num for the next possible match
							}
						}
					break;
					
				//find titles by LANGUAGE
				case 'language':
					//check to see if the current item has a <language>
					lang = items[i].getElementsByTagName("language");
					
					if ((lang.length != 0) && (lang[0].firstChild != null)) {
						//*** [2] ***//
						//if there is a language field then there is a non-English element to the resource,
						//so grab this <item> and store it in itemArr[]
						titles[cnt] = [title, 'title', i];
						cnt += 1;							//increase num for the next possible match
					}
					break;
					
				//find EBooks marked as BCD Textbooks
				case 'BCD_text': 
					//check to see if the current item has a <bcd_text>
					BCD_text = items[i].getElementsByTagName("BCD_text");
					
					if (BCD_text.length != 0) {
						//*** [2] ***//
						//we have a match so grab this <item> and store it in itemArr[]
						titles[cnt] = [title, 'title', i];
						cnt += 1;							//increase num for the next possible match
					}
					break;
					
				//find titles by PUBLISHER::NAME
				case 'provider':
					//publisher and name are both required fields so we'll always have at least one of each
					//however, we may have more than one, so make sure to check for multiples
					names = items[i].getElementsByTagName("name");
					
					for (k=0; k<names.length; k++) {
						if (names[k].firstChild.nodeValue.match(valu1) != null) {
							//*** [2] ***//
							//we have a match so grab this <item> and store it in itemArr[]
							titles[cnt] = [title, 'title', i];
							cnt += 1;							//increase num for the next possible match
						}
					}
					break;

				//find DBs with MOBILE support
				case 'mobile': 
					//check to see if the current item has a <mobile>
					mobile = items[i].getElementsByTagName("mobile");
					
					if (mobile.length != 0) {
						//*** [2] ***//
						//we have a match so grab this <item> and store it in itemArr[]
						titles[cnt] = [title, 'title', i];
						cnt += 1;							//increase num for the next possible match
					}
					break;		
			}
		}
	}

	//if any titles were found then sort them and move them into another array from which to generate HTML
	if (cnt > 0) {
		//*** [3] ***//
		//***********//
		//now sort the array and send it off to be turned into HTML
		//if a sub-heading was encoutered earlier then sort first by sub-heading, then by title
		if (foundsub) {
			sortBySubHd(titles,3,0);
			
			//go through the newly sorted titles to and get values of the subheads and how many titles for each
			subHeads[0] = [titles[0][3], 0];
			subCnt = 1;
			for (j=0; j<titles.length-1; j++) {
				//get the first entry
				if (titles[j][3] != titles[j+1][3]) {
					subHeads[subCnt] = [titles[j+1][3], j+1];
					subCnt++;
				}
			}
		}
		
		//otherwise sort by title
		else {
			titles.sort(sortByTitle);
			subHeads = null;
		}

		//check the list for any duplicate titles
		//step through the array of titles comparing each one with it's predecesor
		//show an alert when there's a match
		for (j=1; j<titles.length; j++) {
			if (titles[j][0] == titles[j-1][0]) {
				alert("Duplicate Title: " + titles[j][0]);
			}
		}

		
		//*** [4] ***//
		//***********//
		//go through the list of titles and grab the needed fields from the associated items[]
		//store them in an arra of fld_arr[]s
		
		//first zero out our global arry of related subjects for SEE ALSOs below
		see_also = [];
		
		for (x=0; x<titles.length; x++) {
			index = titles[x][2];
			
			ttlFields[x] = populateFields(items[index], caller, titles[x][1]);
			//             --------------

		
			//SEE ALSOs
			//For Subject pages we want to provide a list of SEE ALSO subjects
			//This is a list of any other <subject>s used in addition to the one that
			//matched our passed-in <subject> used to create our list of titles
//Cindy didn't like this
//			if ((caller ==  'EB') && (field1 == 'subject'))
//				populateSeeAlso(items[index], valu1);
//alert(ttlFields[x]["ttl"]);
		}
//alert(see_also);

	}
	else {	//cnt <= 0; i.e. no titles
		titles.length = 0;
		subHeads = null;
	}
alert(titles.length);


	//*** [5] ***//
	//***********//
	//process the array and turn its items into html code (if there's something in the array)
	document.HTMLoutput.HTMLCode.value = processTitlesArray(ttlFields, field1, valu1, caller, subHeads);
	//                                   ------------------

	//set the name of the file to be written to (the file name is of the form <dir/name>
	if (field1 == 'noJava')
		document.HTMLoutput.HTMLFile.value = caller + '/noJava.html';
	else
		document.HTMLoutput.HTMLFile.value = caller + '/' + valu1 + '.html';

}	//**createHTMLfiles**/



//*****************************************************************************************************
// populateFields()
// ------------
// returns: array of fields from item
//
// parms: 	mItem--the item that was matched on from the array of items
//			caller--EB, DB, SG
//			alt--'title' for <title> or 'atitle' for <alt_title>
//
// populates the fields from the <item>s in question; ebooks are different from databases and subject
// guides
//*****************************************************************************************************
function populateFields (mItem, caller, alt) {
	FieldsArray = new Array();
	numPubs = 1;	//default value
	
	//before beginning we have to consider the possibility of more than one provider for EBooks
	//in this case we want to gather the information for all providers listed
	if (caller=='EB') {
		pubs = mItem.getElementsByTagName("publisher");
		numPubs = pubs.length;
	}
		
	//COMMON fields that are in all resource type XSDs
	//------
	
	// TITLE
	//check whether we're getting 
	if (alt == 'title') {
		if (mItem.getElementsByTagName("title")[0])
			FieldsArray["ttl"] = checkPrecArt(mItem.getElementsByTagName("title")[0].firstChild.nodeValue);
		else alert("Missing title");
	}
	else {
		if (mItem.getElementsByTagName("alt_title")[0])
			FieldsArray["ttl"] = checkPrecArt(mItem.getElementsByTagName("alt_title")[0].firstChild.nodeValue);
		else alert("Missing title");
	}


	//PUBLISHER/PROVIDER info
	//URL & NAME are required, so they will always be there for all providers
	url = mItem.getElementsByTagName("URL");
	if (url[0]) {
		FieldsArray["url"] = new Array();
		for (a=0; a<numPubs; a++) {
			FieldsArray["url"][a] = url[a].firstChild.nodeValue;
		}
//alert('URL: ' + FieldsArray["url"]);
	}
	
	pName = mItem.getElementsByTagName("name");
	if (pName[0]) {
		FieldsArray["prvName"] = new Array();
		for (a=0; a<numPubs; a++) {
			FieldsArray["prvName"][a] = pName[a].firstChild.nodeValue;
		}
	}
	
	//AboutURL is optional, so if not there then indicate blank field with a '#'
	aUrl = mItem.getElementsByTagName("aboutURL");
	FieldsArray["about"] = new Array();
	if (aUrl[0]) {
		for (a=0; a<numPubs; a++) {
			FieldsArray["about"][a] = aUrl[a].firstChild.nodeValue;
			//aboutURL is optional so make sure it's not empty or missing
			if (FieldsArray["about"][a] == ' ')	//a possible indicator that the aboutURL is empty
				FieldsArray["about"][a] = '#';
		}
	}
	else {
		for (a=0; a<numPubs; a++) {
			FieldsArray["about"][a] = '#';
		}
	}
//alert(FieldsArray["url"]);

		
	//SUBJECTs
	subjs = mItem.getElementsByTagName("subject");
	if (subjs[0]) {
		FieldsArray["subject"] = new Array();
		for (a=0;a<subjs.length;a++) {
			FieldsArray["subject"][a] = subjs[a].firstChild.nodeValue;
		}
	}
	
	//NOTES
	if (mItem.getElementsByTagName("notes")[0])
		FieldsArray["notes"] = mItem.getElementsByTagName("notes")[0].firstChild.nodeValue;
			
	//DESCRiption
	if (mItem.getElementsByTagName("descr")[0])
		FieldsArray["descr"]	= mItem.getElementsByTagName("descr")[0].firstChild.nodeValue;
			
	//DATE_ADDED
	if (mItem.getElementsByTagName("year")[0]) {
		FieldsArray["adYr"]  = mItem.getElementsByTagName("year")[0].firstChild.nodeValue;
		if (mItem.getElementsByTagName("month")[0]) {
			FieldsArray["adDate"] = true;
			FieldsArray["adMon"] = mItem.getElementsByTagName("month")[0].firstChild.nodeValue;
		}
		else {
			FieldsArray["adDate"] = false;
			alert("add_date missing a MONTH");
		}
	}
	else {
		FieldsArray["adDate"] = false;
		if (mItem.getElementsByTagName("month")[0]) {
			alert("add_date missing a YEAR");
		}
	}
	

	//EBOOKS specific fields
	//------
	if (caller=='EB') {
		//PUBLISHER info
		//All these fields are optional, so we need to check each publisher block separately for values,
		//if something's not there then indicate blank field with a '#'
		
		publ = mItem.getElementsByTagName("publisher");
		FieldsArray["pub_edtn"] = new Array();
		FieldsArray["pub_date"] = new Array();
		FieldsArray["language"] = new Array();
		FieldsArray["free"] = new Array();
		FieldsArray["limit"] = new Array();
		for (q=0; q<publ.length; q++) {
			//EDITION
			edtn = publ[q].getElementsByTagName("edition");
			if (edtn[0])
				FieldsArray["pub_edtn"][q] = edtn[0].firstChild.nodeValue;
			else
				FieldsArray["pub_edtn"][q] = '#';
//alert(FieldsArray["ttl"] + ', ' + 'pub_edtn[' + q + ']: ' + FieldsArray["pub_edtn"][q]);
			
			//PUB DATE
			pdate = publ[q].getElementsByTagName("pubdate");
			if (pdate[0])
				FieldsArray["pub_date"][q] = pdate[0].firstChild.nodeValue;
			else
				FieldsArray["pub_date"][q] = '#';
		
			//LANGUAGE
			lang = publ[q].getElementsByTagName("language");
			if (lang[0])
				FieldsArray["language"][q] = lang[0].firstChild.nodeValue;
			else
				FieldsArray["language"][q] = '#';
			
			//FREE
			fr = publ[q].getElementsByTagName("Free");
			if (fr[0])
				FieldsArray["free"][q] = true;
			else
				FieldsArray["free"][q] = false;

			//LIMITed to BCD or BUMC?
			lim = publ[q].getElementsByTagName("limit");
			if (lim[0])
				FieldsArray["limit"][q] = lim[0].firstChild.nodeValue;
			else
				FieldsArray["limit"][q] = '#';
		}


		//EDITors/AUTHors
		edats = mItem.getElementsByTagName("editauth");
		if (edats[0]) {
			FieldsArray["editauth"] = new Array();
			for (a=0;a<edats.length;a++) {
				//get the LAST name only
				FieldsArray["editauth"][a] = edats[a].firstChild.nodeValue.split(",",1);
			}
		}
		
		//SERIES
		if (mItem.getElementsByTagName("series")[0])
			FieldsArray["series"]	= mItem.getElementsByTagName("series")[0].firstChild.nodeValue;

		//LANGUAGE
		//unlike with DBs and SGs, there is only one <laguage> field (part of <publisher>)
		if (mItem.getElementsByTagName("language")[0]) {
			FieldsArray["lang"] = new Array();
			FieldsArray["lang"][0] = new Array();
			FieldsArray["lang"][0]["lVal"]	= mItem.getElementsByTagName("language")[0].firstChild.nodeValue;
			FieldsArray["lang"][0]["lTtl"]	= mItem.getElementsByTagName("language")[0].firstChild.nodeValue;
			FieldsArray["lang"][0]["lUrl"]	= '#';
		}
	}
	
	
	//DATABASE specific fields
	//--------
	else if (caller=='DB') {
		//DATE_RANGE
		if (mItem.getElementsByTagName("dateRange")[0]) {
			FieldsArray["dateRng"] = mItem.getElementsByTagName("dateRange")[0].firstChild.nodeValue;
		}
		else FieldsArray["dateRng"] = null;
//alert(FieldsArray["dateRng"]);

		//LIMITed to BCD or BUMC?
		if (mItem.getElementsByTagName("limit")[0])
			FieldsArray["limit"] = mItem.getElementsByTagName("limit")[0].firstChild.nodeValue;

		//CONTENT
		if (mItem.getElementsByTagName("content")[0])
			FieldsArray["content"] = mItem.getElementsByTagName("content")[0].firstChild.nodeValue;

		//RESorCe TYPE
		if (mItem.getElementsByTagName("resc_type")[0])
			FieldsArray["resc_type"] = mItem.getElementsByTagName("resc_type")[0].firstChild.nodeValue;
		
		//AVAILability
		if (mItem.getElementsByTagName("avail")[0])
			FieldsArray["avail"] = mItem.getElementsByTagName("avail")[0].firstChild.nodeValue;

		//FREE?
		FieldsArray["free"] = new Array();
		if (mItem.getElementsByTagName("source")[0]) {
			if (mItem.getElementsByTagName("source")[0].firstChild.nodeValue == "Free") {
				FieldsArray["free"][0] = true;
			}
			else
				FieldsArray["free"][0] = false;
		}
		else
			FieldsArray["free"][0] = false;

		//LANGUAGEs
		langs = mItem.getElementsByTagName("language");
		if (langs[0]) {
			FieldsArray["language"] = new Array();
			for (a=0;a<langs.length;a++) {
				FieldsArray["language"][a] = new Array();

				//The value of the language, i.e. 'Spanish', 'French', etc (required field)
				FieldsArray["language"][a]["lVal"] = langs[a].getElementsByTagName("val")[0].firstChild.nodeValue;
				
				//The Title of the page in the non-english language
				if (langs[a].getElementsByTagName("lTitle")[0])
					FieldsArray["language"][a]["lTtl"] = langs[a].getElementsByTagName("lTitle")[0].firstChild.nodeValue;
				else FieldsArray["language"][a]["lTtl"] = FieldsArray["language"][a]["lVal"];
				
				//The URL to the page in non-english, if available
				if (langs[a].getElementsByTagName("langURL")[0])
					FieldsArray["language"][a]["lUrl"] = langs[a].getElementsByTagName("langURL")[0].firstChild.nodeValue;
				else FieldsArray["language"][a]["lUrl"] = '#';
//alert ('lang[' + a + ']["lUrl"]: ' + FieldsArray["lang"][a]["lUrl"]);
			}
		}
		
		//MOBILE
		mob = mItem.getElementsByTagName("mobile");
		if (mob[0]) {
			FieldsArray["mobile"] = true;
			//does the site have a web-optimized page? y=true, else false
			mobPg = mItem.getElementsByTagName("mWeb")[0].firstChild.nodeValue;
			if ((mobPg = 'y') || (mobPg = 'Y')) 
				FieldsArray["mWeb"]  = true;
			else FieldsArray["mWeb"]  = false;
			
			//if there is an app, what is the URL for more information or download
			if (mItem.getElementsByTagName("appURL")[0]) 
				FieldsArray["appURL"] = mItem.getElementsByTagName("appURL")[0].firstChild.nodeValue;
			else 
				FieldsArray["appURL"] = '#';
				
			//are there any notes concerning the app?
			if (mItem.getElementsByTagName("appNote")[0]) 
				FieldsArray["appNote"] = mItem.getElementsByTagName("appNote")[0].firstChild.nodeValue;
			else 
				FieldsArray["appNote"] = '#';
		}
		else FieldsArray["mobile"] = false;
	}
	
	
	//SUBJECT GUIDE specific fields
	//-------------
	else if (caller=='SG') {
		//DATE_RANGE
		if (mItem.getElementsByTagName("dateRange")[0]) {
			FieldsArray["dateRng"] = mItem.getElementsByTagName("dateRange")[0].firstChild.nodeValue;
		}
		else FieldsArray["dateRng"] = null;

		//LIMITed to BCD or BUMC?
		if (mItem.getElementsByTagName("limit")[0])
			FieldsArray["limit"] = mItem.getElementsByTagName("limit")[0].firstChild.nodeValue;

		//RESorCe TYPE
		if (mItem.getElementsByTagName("resc_type")[0])
			FieldsArray["resc_type"] = mItem.getElementsByTagName("resc_type")[0].firstChild.nodeValue;

		//AVAILability
		if (mItem.getElementsByTagName("avail")[0]) {
			FieldsArray["avail"] = mItem.getElementsByTagName("avail")[0].firstChild.nodeValue;
		//FREE?
			if (FieldsArray["avail"] == "Free")
				FieldsArray["free"] = true;
		}

		//LANGUAGEs
		langs = mItem.getElementsByTagName("language");

		if (langs[0]) {
			FieldsArray["lang"] = new Array();
			for (a=0;a<langs.length;a++) {
				FieldsArray["lang"][a] = new Array();

				//The value of the language, i.e. 'Spanish', 'French', etc (required field)
				FieldsArray["lang"][a]["lVal"] = langs[a].getElementsByTagName("val")[0].firstChild.nodeValue;
				
				//The Title of the page in the non-english language
				if (langs[a].getElementsByTagName("lTitle")[0])
					FieldsArray["lang"][a]["lTtl"] = langs[a].getElementsByTagName("lTitle")[0].firstChild.nodeValue;
				else FieldsArray["lang"][a]["lTtl"] = FieldsArray["lang"][a]["lVal"];
				
				//The URL to the page in non-english, if available
				if (langs[a].getElementsByTagName("langURL")[0])
					FieldsArray["lang"][a]["lUrl"] = langs[a].getElementsByTagName("langURL")[0].firstChild.nodeValue;
				else FieldsArray["lang"][a]["lUrl"] = '#';
//alert ('lang[' + a + ']["lUrl"]: ' + FieldsArray["lang"][a]["lUrl"]);
			}
		}
	}


//alert(FieldsArray);
	return(FieldsArray);
	
}	//**populateFields**/



//*****************************************************************************************************
// populateSeeAlso()
// ---------------
// returns: <nothing>--populates Global see_also array
//
// parms: 	mItem--the item that was matched on from the array of items
//			valu1--indicates what type of value valu1 is (beginLett, subject, resc_type, source, language)
//
// populates the Global see_also array with subjects other that the one passed in valu1;
// creates a list of all other the <sbujects> used in our list of titles;
// used to create a See Also list on Subject based pages
//*****************************************************************************************************
function populateSeeAlso (mItem, valu1) {
		var newSubj = true;
	
	subjs = mItem.getElementsByTagName("subject");
//alert("valu1: " + valu1);
	for (a=0;a<subjs.length;a++) {
//alert("subjs[a]: " + subjs[a].firstChild.nodeValue);
		if ((valu1 == ' ') || (subjs[a].firstChild.nodeValue.match(valu1) != null)) {
			//if the subject matches what was passed in, then don't save it to see_also[]
			//BUT, we only want to set this here if it's the first subject heading listed,
			//otherwise, we'll leave the value of newSubj to whatever was set by the values
			//before it.
			if (a == 0) {
				newSubj = false;
//alert("no add 1");
			}
		}

		else {
			//first loop through see_also[] to see if our current <subject> is already saved there
			if (see_also.length > 0) {
				for (b=0;b<see_also.length;b++) {
//alert(subjs[a].firstChild.nodeValue + ' : ' + see_also[b]);
					if (see_also[b] == subjs[a].firstChild.nodeValue) {
						newSubj = false;
//alert("no add 2");
					}
				}
			}
			
			//if the subject is not already there, then put it in see_also[]
			if (newSubj) {
//alert("add: " + subjs[a].firstChild.nodeValue);
				see_also[see_also.length] = subjs[a].firstChild.nodeValue;
			}
		}
		//rest newSubj for the next iteration of the FOR loop above
		newSubj = true;
	}
//alert('see_also: ' + see_also);
}	//**populateSeeAlso**//



//*****************************************************************************************************
// processTitlesArray()
// ------------
// returns: result_text (string)
//
// parms: ttlFields[]--array of fields for each <item> in the specific XML file
//		  field1--
//		  valu1--
//		  caller--EB/DB/SG?
//		  subHeads[]--array of sub-headings if any exist, if not then is null
//
// writes one long string to result_text which is then written into document.XMLoutput.HTMLCode.value 
// (in function createHTMLfiles())
// results structure is a table with a green header that includes search value and # of results;
//
// first write header,
// then if title has only one publisher write the row for the title
//		more info icon, free icon?, url, title, new icon?, more info box 
//			(with title, authors, publisher name, edition & pubdate)
//			if title had a preceding article before sorting put it back when writing title
//	else if title has multiple publishers write the row with publisher URLs after title
//			include other information and articles too
//*****************************************************************************************************
// move FREE to here
// need getAuth() or equivalent?
// need getPrvdInfo() separate or move here?
//*****************************************************************************************************
function processTitlesArray (ttlFields, field1, valu1, caller, subHeads) {
		var startsWithLettRegExp = /^\D/;
//alert ("processTitlesArray");
//alert(ttlFields);
	
	//init result_text
	result_text = '';
	
	//For the EB and DB pages, clicking all should reveal the jumpstart to links within the list
	//hiddenJumpTo & alphalooopAll are in DB-head & EB-head.html
	//hiddenIMapsTab is in SG_/DB_/EB_XML.php
	result_text += '<script type="text/javascript">document.getElementById("hiddenIMapsTab").style.visibility="visible";';
	if (valu1 == 'All') {
		if ((caller == 'DB') || (caller == 'EB')) {
			result_text += 'document.getElementById("hiddenJumpTo").style.visibility="visible";document.getElementById("alphaloopAll").style.borderBottom="none";';
		}
	}
	else 
		//hide hiddenJumpTo & alphaloopAll
		result_text += 'document.getElementById("alphaloopAll").style.borderBottom="1px solid #000033";';
	result_text += '</script>';
	
		//how many items are in this result file?
		result_text += '<table width="100%" cellspacing="0" cellpadding="0" border="0">';
		result_text += '<tr><td class="ItemsNum" width="100%" align="right" colspan="2">Number of items found: <b>' + (ttlFields.length) + '</b></td></tr>';

		//for pages based on a subject heading, if there are any sub-headings then we want to create a list of
		//links to books marks at the top
		if (subHeads != null) {
			result_text += '<tr><td colspan="2"><font color="#003333"><b>Sub-topics: </b></font></td></tr>'
			for (k=0; k<subHeads.length; k++) {
				if (subHeads[k][0] == '') 
					result_text += '<tr><td style="padding-left:12px; font-family:Arial, Helvetica, sans-serif; font-size:10pt"><a href="#General">General</a></td></tr>';
				else
					result_text += '<tr><td style="padding-left:12px; font-family:Arial, Helvetica, sans-serif; font-size:10pt"><a href="#' + subHeads[k][0] + '">' + subHeads[k][0] + '</a></td></tr>';
			}
		}
	
	
	for (i=0; i<ttlFields.length; i++) {
		//set vars to fld_arr[] values
		ttl			= ttlFields[i]["ttl"];												//All
		attl		= ttlFields[i]["attl"];												//EB
		prov		= ttlFields[i]["prov"];												//All
			prvName		= ttlFields[i]["prvName"];											//All
			url			= ttlFields[i]["url"];											//All
			about		= ttlFields[i]["about"];											//DB, Wb
			pub_edtn	= ttlFields[i]["pub_edtn"];											//EB
			pub_date	= ttlFields[i]["pub_date"];											//EB
		editauth	= ttlFields[i]["editauth"];												//EB
		dateRng		= ttlFields[i]["dateRng"];												//All (EB:pub date, DB/Wb:date-range)
		free		= ttlFields[i]["free"];												//All
		adDate		= ttlFields[i]["adDate"];												//All		(in check_date())
			adYr		= ttlFields[i]["adYr"];											//All
			adMon		= ttlFields[i]["adMon"];											//All
		notes		= ttlFields[i]["notes"];												//All
		lang		= ttlFields[i]["lang"];												//All
		subj		= ttlFields[i]["subj"];												//All
		notes		= ttlFields[i]["notes"];												//All
		descr		= ttlFields[i]["descr"];												//DB, Wb
		resctyp		= ttlFields[i]["resc_type"];											//DB, Wb
		series		= ttlFields[i]["series"];												//EB
		limit		= ttlFields[i]["limit"];												//DB, EB
		content		= ttlFields[i]["content"];												//DB
		avail		= ttlFields[i]["avail"];												//Wb
		mobile		= ttlFields[i]["mobile"];											//DB
		mWeb		= ttlFields[i]["mWeb"];												//DB
		mApp		= ttlFields[i]["appURL"];											//DB
		mNote		= ttlFields[i]["appNote"];											//DB
			
		//put section header rows based on first letter of title when showing All
		if (valu1 == "All") {
			if (i==0) {
				if ((caller == 'DB') || (caller == 'SG')) {
					result_text += '<tr><td>&nbsp;</td></tr>';
					result_text += '<tr class="TableHeader"><td colspan="2"><a class="EbooksLink">A</a></td></tr>';
				}
				//some Ebooks have titles that start with numbers, dontchaknow
				else if (caller == 'EB') {
					result_text += '<tr><td>&nbsp;</td></tr>';
					result_text += '<tr class="TableHeader"><td colspan="2"><a class="EbooksLink">0 to 9</a></td></tr>';
				}
			}
			else if ((startsWithLettRegExp.test(ttl.toString())) && (ttl.toString().charAt(0) != ttlFields[i-1]["ttl"].toString().charAt(0))) {  //the first letter of the title has changed
				result_text += '<tr><td>&nbsp;</td></tr>';
				
				//The title's first character and check it
				firstChar = ttl.toString().charAt(0);
				if (firstChar == ' ')
					alert(ttl.toString() + ' has a preceding blank space');
				else
					//make a bookmark for each Letter
					result_text += '<tr class="TableHeader"><td><a class="EbooksLink" name="' + firstChar + '">' + firstChar + '</a></td>';
				
				result_text += '<td align="right"><a href="#top">top<img src="http://bcd.tamhsc.edu/library/img/web/misc/return_arrow_bw.gif" height="20px" width="20px" border="0" alt="Return to top of page." align="texttop" title="Return to top of page."></a></td></tr>';
			}
		}
		
		//When there are sub-headings available then this is a subject list and we need to 
		//display header rows based on the sub-headings available
		if (subHeads != null) {
			//loop throught the subHeads array and see if this title (ttlFields[1]) 
			//is the begin of a new sub-head (subHeads[k][1])
			for (k=0; k<subHeads.length; k++) {
				if (i == subHeads[k][1]) {
					//if so the print the sub-heading
					result_text += '<tr><td>&nbsp;</td></tr>';
					if (subHeads[k][0] == '') 
						result_text += '<tr class="TableHeader"><td colspan="2"><a class="EbooksLink" name="General">General</a></td></tr>';
					else {
						result_text += '<tr class="TableHeader"><td><a class="EbooksLink" name="' + subHeads[k][0] + '">' + subHeads[k][0] + '</a></td>';
						result_text += '<td align="right"><a href="#top">top<img src="http://bcd.tamhsc.edu/library/img/web/misc/return_arrow_bw.gif" height="20px" width="20px" border="0" alt="Return to top of page." align="texttop" title="Return to top of page."></a></td></tr>';
					}

				}
			}
		}

		statusMsg = "Resource Info";
		statusBlnk = "";
		
		//base the info note numbering on a system with the caller id (EB/DB/SG) as a prefix
		callId = caller + i;
		
		resultId = "infoNote" + callId;
		tableRowId = "resultRow" + callId;
		infoBoxId = "infoBox" + callId;
		infoBoxClass = "DB_info_box";
		infoBoxId_str = "'infoBox" + callId + "'";
		infoBoxClass_str = "'DB_info_box'";

		result_text += '<tr><td class="TableRow" colspan="2" id="' + tableRowId + '">';
			//INFO-more icon and event action
			//For the ALL page don't include info, because it slows everything down
			if (valu1 == "All")
				result_text += '<img align="texttop" src="http://bcd.tamhsc.edu/library/img/web/buttons_bars/info.gif" alt="Provided through ' + prvName.toString() + '" title="Provided through ' + prvName.toString() + '"> ';
			else 
				result_text += '<a href="javascript:void(0);" onClick="showHide_DBs(' + infoBoxId_str + ',' + infoBoxClass_str +');return false;" style="cursor:help"><img align="texttop" src="http://bcd.tamhsc.edu/library/img/web/misc/info-more.gif" id="' + resultId + '" title="More info"  onMouseOver="window.status=statusMsg; return true" onMouseOut="window.status=statusBlnk;"/></a> ';

			//MOBILE?
			if (mobile) {
				result_text += ' <img src="http://bcd.tamhsc.edu/library/img/web/misc/pda-icon.gif" align="absmiddle" alt="new" title="new"/>';
			}
		
			//TITLE, FREE, URL, & LIMIT
			//-------------------------
			//there are two possibilities for displaying a title and it's accompanying info (free icon URL and limit)
			// 1) if there are mutliple providers (more than one prvName), then display title followed by
			//    free icon(s) (if appropriate), hyperlinked provider names and limit (bcd only?)
			// 2) if there is only one provider then display free icon (if appropriate), hyperlinked title and limit
			if (prvName.length > 1) {
				//TITLE
				result_text += ttl.toString() + '&nbsp;' + '&nbsp;';

				for (z=0; z<prvName.length; z++) {
					//FREE?
					if (free[z])
						result_text += '<img align="texttop" src="http://bcd.tamhsc.edu/library/img/web/buttons_bars/FreeStar.gif" alt="Free"> ';
					
					//URL
					result_text += '(<a class="Results" href="' + url[z].toString() + '">' + prvName[z].toString() + '</a>)&nbsp;';
					
					//LIMIT
					if (limit[z] != '#')
						result_text += '<font color="red"><i>' + limit[z].toString() + '</i></font>&nbsp;&nbsp;';
				}
			}
			
			else {
				//FREE?
				if (free[0])
					result_text += '<img align="texttop" src="http://bcd.tamhsc.edu/library/img/web/buttons_bars/FreeStar.gif" alt="Free"> ';
				else if (avail == 'Mix')
					result_text += '<img align="texttop" src="http://bcd.tamhsc.edu/library/img/web/misc/Half_FreeStar.gif" alt="For Free &amp; For Fee content available"> ';
				
				//URL
				result_text += '<a class="Results" href="' + url.toString() + '">';
				
				//TITLE
				result_text += ttl.toString() + '</a>';

				//LIMIT
				if (limit)
					if (limit[0] != '#')
						result_text += '&nbsp;&nbsp;&nbsp;<font color="red"><i>' + limit.toString() + '</i></font>';
			}
			
			//NEW?
			if (adDate) {
				if (check_date(adYr, adMon)) {
					result_text += ' <img src="http://bcd.tamhsc.edu/library/img/web/misc/new.gif" align="absmiddle" alt="new" title="new"/>';
				}
			}
			
			
			//the LIMIT code got moved to above for EBs, but works for DBs too
			//LIMITed avail? If item in only avail. at BCD, etc.
//			if (limit)
//				if (limit == 'BCD only')
//					result_text += ' <font color="red"><i>BCD only</i></font>';
//				else if (limit == 'BUMC only')
//					result_text += ' <font color="red"><i>BUMC only</i></font>';
			
			
			//if MULTIPLE LANGUAGEs, then create links to them too
			if (lang) {
				if (lang.length > 0) {
					//start a new line and indent in a bit
					result_text += '<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
					if (lang.length == 1) {
						lUrl		= lang[0]["lUrl"];
						lTtl		= lang[0]["lTtl"];
						
						if (lUrl == '#')
							result_text += ' (' + lTtl.toString() + ')';
						else
							result_text += ' (<a class="Results" href="' + lUrl.toString() + '">' + lTtl.toString() + '</a>)';
					}
	
					else {
						result_text += '(';
						for (j=0; j<lang.length; j++) {
							lUrl		= lang[j]["lUrl"];
							lTtl		= lang[j]["lTtl"];
						
							if (lUrl == '#')
								result_text += ' (' + lTtl.toString() + ')';
							else {
								result_text += '<a class="Results" href="' + lUrl.toString() + '">' + lTtl.toString() + '</a>';
								//separate entries with a "|"
								if (j<(lang.length-1))
									result_text += ' | ';
							}
						}
						result_text += ')';
					}
				}
			}
			
			//new divs for additional info slidedown box
			//don't do this for the ALL page
			if (valu1 != 'All') {
				
				//create this Info box for EBOOKS
				//                         ------
				if (caller == 'EB') {
					result_text += '<div id="' + infoBoxId + '" class="' + infoBoxClass +'" style="display:none">';
						result_text += '<center>';
							result_text += '<table width="90%" cellpadding="0" cellspacing="0" style="font-size:1.2em">';
								
								//EDITOR/AUTHOR last names
								if (editauth) {
									if (editauth.length > 0) {
										result_text += '<tr><td colspan="2"><b>(';
										//a title may have 0-4 editors/authors
										for (k=0; k<editauth.length; k++) {
											result_text += editauth[k];
											if (k == editauth.length-1) {break}
											result_text += ', ';
										}
										result_text += ')</b></td></tr>';
									}
								}
								
								//if there is more than one provider for this resource we want to display the info
								//for each provider separtely
									//EB: for now (033010) this only applies to EB info (pubname, abouturl, edition, pubdate)
									//
								
								for (y=0; y<prvName.length; y++) {
									//SERIES info
									if (series) {
									result_text += '<tr>';
										result_text += '<td valign="top">Series: </td>';
										result_text += '<td style="border-bottom:solid 1px #000000">[' + series.toString() + ']</td>';
									result_text += '</tr>';
									}
									
									//DATE RANGE info
									if (dateRng != null) {
									result_text += '<tr>';
										result_text += '<td style="border-bottom:solid 1px #000000" valign="top"><b>Date Range: </b></td>';
										result_text += '<td style="border-bottom:solid 1px #000000">[' + dateRng.toString() + ']</td>';
									result_text += '</tr>';
									}
									
									//PUBLISHER's NAME & ABOUT URL
									result_text += '<tr>';
										result_text += '<td width="20%" style="border-bottom:solid 1px #000000" valign="top"><b>Provider: </b></td>';
										if (about[y] == '#')
											result_text += '<td width="80%" style="border-bottom:solid 1px #000000">' + prvName[y].toString() + '</td>';
										else
											result_text += '<td width="80%" style="border-bottom:solid 1px #000000">' + prvName[y].toString() + ' (<a href="' + about.toString() + '" alt="Provider info" title="Provider info"><b>About</b></a>)</td>';
									result_text += '</tr>';
									
									//CONTENT
									if(content) {
									result_text += '<tr>';
										result_text += '<td style="border-bottom:solid 1px #000000" valign="top"><b>Content: </b></td>';
										result_text += '<td style="border-bottom:solid 1px #000000">' + content.toString() + '</td>';
									result_text += '</tr>';
									}
									
									//DESCR
									if(descr) {
									result_text += '<tr>';
										result_text += '<td style="border-bottom:solid 1px #000000" valign="top"><b>Description: </b></td>';
										result_text += '<td style="border-bottom:solid 1px #000000">' + descr.toString() + '</td>';
									result_text += '</tr>';
									}
									
									//EDITION
									if (pub_edtn[y] != '#') {
									result_text += '<tr>';
										result_text += '<td valign="top" align="right" style="padding-right:6px">Edition: </td>';
										result_text += '<td style="border-bottom:solid 1px #000000">' + pub_edtn[y].toString() + '</td>';
									result_text += '</tr>';
									}
									
									//PUBDATE
									if (pub_date[y] != '#') {
									result_text += '<tr>';
										result_text += '<td valign="top" align="right" style="padding-right:6px">Year: </td>';
										result_text += '<td style="border-bottom:solid 1px #000000">' + pub_date[y].toString() + '</td>';
									result_text += '</tr>';
									}
			
									//NOTES
									if (notes) {
									result_text += '<tr>';
										result_text += '<td style="border-bottom:solid 1px #000000" valign="top"><font color="#FF3300"><b>Note: </b></font></td>';
										result_text += '<td style="border-bottom:solid 1px #000000">' + notes.toString() + '</td>';
									result_text += '</tr>';
									}
									
									//LINE - have a separating line between entries if multiple providers
									if (y < prvName.length-1) {
										result_text += '<tr><td colspan="2" style="border-bottom:solid 2px #000000">&nbsp;</td></tr>'
									}
								}
							result_text += '</table>';
						result_text += '</center>';
					result_text += '</div>';
				}
				
				//create this Info box for DATABASES
				//                         ---------
				if (caller == 'DB') {
					result_text += '<div id="' + infoBoxId + '" class="' + infoBoxClass +'" style="display:none">';
						result_text += '<center>';
							result_text += '<table width="90%" cellpadding="0" cellspacing="0" style="font-size:1.2em">';
								
								//if there is more than one provider for this resource we want to display the info
								//for each provider separtely
									//EB: for now (033010) this only applies to EB info (pubname, abouturl, edition, pubdate)
									//
								
								for (y=0; y<prvName.length; y++) {
									//DATE RANGE info
									if (dateRng != null) {
									result_text += '<tr>';
										result_text += '<td style="border-bottom:solid 1px #000000" valign="top"><b>Date Range: </b></td>';
										result_text += '<td style="border-bottom:solid 1px #000000">[' + dateRng.toString() + ']</td>';
									result_text += '</tr>';
									}
									
									//PUBLISHER's NAME & ABOUT URL
									result_text += '<tr>';
										result_text += '<td width="20%" style="border-bottom:solid 1px #000000" valign="top"><b>Provider: </b></td>';
										if (about[y] == '#')
											result_text += '<td width="80%" style="border-bottom:solid 1px #000000">' + prvName[y].toString() + '</td>';
										else
											result_text += '<td width="80%" style="border-bottom:solid 1px #000000">' + prvName[y].toString() + ' (<a href="' + about.toString() + '" alt="Provider info" title="Provider info"><b>About</b></a>)</td>';
									result_text += '</tr>';
									
									//CONTENT
									if(content) {
									result_text += '<tr>';
										result_text += '<td style="border-bottom:solid 1px #000000" valign="top"><b>Content: </b></td>';
										result_text += '<td style="border-bottom:solid 1px #000000">' + content.toString() + '</td>';
									result_text += '</tr>';
									}
									
									//DESCR
									if(descr) {
									result_text += '<tr>';
										result_text += '<td style="border-bottom:solid 1px #000000" valign="top"><b>Description: </b></td>';
										result_text += '<td style="border-bottom:solid 1px #000000">' + descr.toString() + '</td>';
									result_text += '</tr>';
									}
									
									//NOTES
									if (notes) {
									result_text += '<tr>';
										result_text += '<td style="border-bottom:solid 1px #000000" valign="top"><font color="#FF3300"><b>Note: </b></font></td>';
										result_text += '<td style="border-bottom:solid 1px #000000">' + notes.toString() + '</td>';
									result_text += '</tr>';
									}
									
									//LINE - have a separating line between entries if multiple providers
									//MOBILE
									if (mobile) {
									result_text += '<tr>';
										result_text += '<td style="border-bottom:solid 1px #000000" valign="top"><b>Mobile Support: </b></td>';
										if (mWeb)
											result_text += '<td style="border-bottom:solid 1px #000000">This site is optimized for mobile devices.<br/>';
										if (mApp != '#')
											result_text += 'A mobile app is available. For information or to download, please see: <a href="' + mApp.toString() + '" target="_blank" alt="opens new window" title="opens new window">' + mApp.toString() + '</a><br/>';
										if (mNote != '#')
											result_text += '<font color="red"><b>Note: </b></font>' + mNote.toString();
											
									result_text += '</td></tr>';
									}
									
									if (y < prvName.length-1) {
										result_text += '<tr><td colspan="2" style="border-bottom:solid 2px #000000">&nbsp;</td></tr>'
									}
								}
							result_text += '</table>';
						result_text += '</center>';
					result_text += '</div>';
				}
			}
	
		result_text += '</td></tr>';
	}
	
	//if this is a subject list that has some entries, then process see_also[] (global) to include this list as well
	//PUTTING THIS ON HOLD -- Cindy didn't like it
	//if ((ttlFields.length > 0) && (field1 == 'subject')) {
	//	processSeeAlsoArray(valu1);
	//}
	
	if (valu1 == "Ejournals")
		result_text += '<tr><td class="TableRow"><a href="http://linkresolver.tamu.edu:9003/bhsl/az/default?param_perform_value=locate">Search</a> or <a href="http://linkresolver.tamu.edu:9003/bhsl/azlist/default?perform=searchCategories">Browse</a> our Ejournals page for more titles.</td></tr>';
	else if (valu1 == "EB")
		result_text += '<tr><td class="TableRow">See BHSL&rsquo;s <a href="http://webcomm.bcd.tamhsc.edu/library/EbooksXML/Ebooks_XML.html">Ebooks page</a> for more titles.</td></tr>';

result_text += "</table>";
	
	return (result_text);
}	//**processTitlesArray**//



//*****************************************************************************************************
// processSeeAlsoArray()
// -------------------
// returns: none
//
// parms:	valu1 -- 
//
// If there's anything in the global see_also array, then sort it and turn it into a list of links 
// into related subject pages.
// appends the links formatted into on row of a table to result_text which is then written into  
// document.XMLoutput.HTMLCode.value (in function createHTMLfiles())
//
//*****************************************************************************************************
function processSeeAlsoArray(valu1) {
	if (see_also.length > 0) {
		//sort the array
		see_also.sort();
		
		//begin the next row of the table
		result_text += '<tr><td>&nbsp;</td></tr><tr><td class="TableRow" colspan="2"><div style="height:16px; width:95px; background-color:#99CC99"><font color="#000000" size="larger">See Also:&nbsp;</font>&nbsp;<img src="http://bcd.tamhsc.edu/library/img/web/misc/question.gif" align="absbottom" height="16" width="16" title="Some of the resources on this page also use the subject headings below." alt="Some of the resources on this page also use the subject headings below."/></div><table width="90%" cellpadding="0" cellspacing="0">'
		
		for (a=0;a<see_also.length;a++) {
			//form the basic URL used to link to the other subject pages
			url = 'http://webcomm.bcd.tamhsc.edu/library/EB/EB_XML.php?pg=';
			val = see_also[a].split(/\W/, 1); 		//grabs the first word of the <subject> string
			
			url += val;
			
			//if there's a sub-heading, then add a # string to the URL to go straight to 
			//the correct part of the page
			if (see_also[a].match(' -- ') != null) {
				loc = see_also[a].indexOf(' -- ') + 4;
				url += '#' + see_also[a].slice(loc);
			}
			
			//write the link to the results
			result_text += '<tr><td style="padding-left:12px; font-family:Arial, Helvetica, sans-serif; font-size:10pt"><a href="' + url + '">' + see_also[a] + '</a></td></tr>';
		}
		
		//close up the table and rows
		result_text += '</table></td></tr>';
	}
}	//**processSeeAlsoArray**//



//*****************************************************************************************************
// createSubjTreeFile()
// --------------------
// create a file that contains a current subject list tree.
//*****************************************************************************************************
function createSubjTreeFile() {
		var heads=XMLfile.getElementsByTagName("head");
		var tree = new Array;
//alert(heads.length);

	// *** 1 ***//
	//**********//
	//loop through the list of <head> and build an array of main- and sub-headings
	for (x=0;x<heads.length;x++) {
		//grab all of the main headers and loop through to create links
		main = heads[x].getElementsByTagName("main");

		//find any sub-headings for this main heading
		subs = heads[x].getElementsByTagName("sub");

		tree[x] = [main[0].firstChild.nodeValue, new Array];
		tree[x][1].length = 0;		//set the length of the new subarray to 0

		//write the sub-headings to the array associated with the main heading
		if (subs.length > 0) {
			for (y=0;y<subs.length;y++) {
				tree[x][1][y] = subs[y].firstChild.nodeValue;
			}
		}
	}
alert(tree);

	//*** 2 ***//
	//*********//
	//now create a list of links to the pages/chapters for each main/sub heading
	caller = document.HTMLoutput.HTMLTrgt.value;
	document.HTMLoutput.HTMLFile.value = caller + '/SubjTree.html';
	
	//init result_text
	result_text = '';
	
	//start the results table
	result_text += '<script type="text/javascript">document.getElementById("hiddenIMapsTab").style.visibility="visible";document.getElementById("alphaloopAll").style.borderBottom="1px solid #000033";</script><table width="100%" cellspacing="0" cellpadding="0" border="0"><tr><td>';

	//put the results in a bullted-list
	result_text += '<ul type="disc">';
	for (a=0;a<tree.length;a++) {
		//for the Health Issues/Professions heading the value should be Professions
		//for all others it's just the first full word in the heading as it is in the menu
		if (tree[a][0] == "Health Issues/Professions")
			heading = "Professions";
		else
			heading = tree[a][0].split(/\W/, 1);
		
		result_text += '<li><a href="http://webcomm.bcd.tamhsc.edu/library/EB/EB_XML.php?pg=' + heading + '">' + tree[a][0] + '</a></li>';

		//check for any sub-headings and display those in another indented list
		if (tree[a][1].length > 0) {
			result_text += '<ul type="circle">';

			for (b=0;b<tree[a][1].length;b++) {
				result_text += '<li><a href="http://webcomm.bcd.tamhsc.edu/library/EB/EB_XML.php?pg=' + heading + '#' + tree[a][1][b] + '">' + tree[a][1][b] + '</a></li>';
			}
			result_text += '</ul>';
		}
	}
	result_text += '</ul></td></tr></table>';	
	
	document.HTMLoutput.HTMLCode.value = result_text;
}	//**createSubjTreeFile**//



//*****************************************************************************************************
// makePOSTRequest() & alertContents()
// ---------------     -------------
// code copied from http://www.captain.at/howto-ajax-form-post-request.php from to use with 
// createAllHTML().
//*****************************************************************************************************
var http_request = false;
function makePOSTRequest(url, parameters) {
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
	 http_request = new XMLHttpRequest();
	 if (http_request.overrideMimeType) {
		// set type accordingly to anticipated content type
		//http_request.overrideMimeType('text/xml');
		http_request.overrideMimeType('text/html');
	 }
  } else if (window.ActiveXObject) { // IE
	 try {
		http_request = new ActiveXObject("Msxml2.XMLHTTP");
	 } catch (e) {
		try {
		   http_request = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {}
	 }
  }
  if (!http_request) {
	 alert('Cannot create XMLHTTP instance');
	 return false;
  }
  
  http_request.onreadystatechange = alertContents;
  http_request.open('POST', url, true);
  http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http_request.setRequestHeader("Content-length", parameters.length);
  http_request.setRequestHeader("Connection", "close");
  http_request.send(parameters);
}

function alertContents() {
  if (http_request.readyState == 4) {
	 if (http_request.status == 200) {
		//alert(http_request.responseText);
		result = http_request.responseText;
		document.getElementById('displayEbookResults').innerHTML = result;            
	 } else {
		alert('There was a problem with the request.');
	 }
  }
}


//*****************************************************************************************************
// createAllHTML()
// -------------
// Steps through all the letters of the alphabet and all subjects available to the specified caller
// to create .html files for all values.
//*****************************************************************************************************
function createAllHTML() {
	var alphaList = new Array ('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0to9');

	for (a=0; a<3; a++) {
		//create the HTML code
alert(a + ', ' + alphaList[a]);
		createHTMLfiles('beginLett', alphaList[a]);
		//now create the HTML file with PHP
		poststr = "HTMLFile=" + encodeURI(document.HTMLoutput.HTMLFile.value) +
                  "&HTMLTrgt=" + encodeURI(document.HTMLoutput.HTMLTrgt.value) + 
				  "&HTMLCode=" + encodeURI(document.HTMLoutput.HTMLCode.value);
//alert(poststr);
		makePOSTRequest('http://webcomm.bcd.tamhsc.edu/library/HTMLCreate.php', poststr);
	}
	
}



   
   


