var cityUrl = "xmlFiles/tnc60cities.xml"; // "file://C:/Projects/YFT/TNCInfo2/tnc60data.xml"
var dataUrl = "xmlFiles/tnc60data.xml"; // "file://C:/Projects/YFT/TNCInfo2/tnc60data.xml"
var cityDoc;
var dataDoc;	// tncdata is referenced in global variable so it is only accessed once
var instDoc;
var variable = new Array();	// stores name of variables in tncdata to use in search
var target = new Array();	// stores target values that determine if provider is a match
var criteria = new Array();	// stores the text of the search criteria to use for output
var matchingRecords = new Array();  // stores indexes of providers satisfying search criteria
var noMatch = "No providers satisfied all of the search criteria";

function showLayer(layer) {
	var s;
	document.getElementById("searchLayer").style.visibility = (layer=="search" ? "visible" : "hidden");
	document.getElementById("resultsLayer").style.visibility = (layer=="results" ? "visible" : "hidden");
	document.getElementById("splashScreen").style.visibility = (layer=="startUp" ?"visible" : "hidden");
	
	// deterimine the font style and border for the search
	// and results tabs
	var sStyle = document.getElementById("searchButton").style
	sStyle.fontWeight = (layer!="search" ? "normal" : "bold");
	sStyle.borderBottomColor = (layer!="search" ? "white" : "#D4D0C8");
	
	var rStyle = document.getElementById("resultsButton").style
	rStyle.fontWeight = (layer!="results" ? "normal" : "bold");
	rStyle.borderBottomColor = (layer!="results" ? "white" : "#D4D0C8");
	
	// on the search page, move the focus off the search button
	// to improve the screen display of the simulated tab
	if (layer=="search") document.getElementById("startNewSearch").focus();
	return false;
}

function initCriteria() {
	// focus forces the splash screen to be displayed
	showLayer("startUp");
	////document.getElementById("splashScreen").focus();

	var ar_ = new Array("","01 - Lubbock area","02 - Abilene area","03-  DFW area",
		"04 - Tyler area","05 - Beaumont area","06 - Houston area","07 - Austin area",
		"08 - San Antonio area","09 - Midland area","10 - El Paso area","11 - Corpus Christi area");
	initSelect("region", ar_, new Array(ar_.length));

	ar_ = new Array("","infant","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18 or older");
	initSelect("age", ar_, new Array(ar_.length));

	ar_ = new Array("","Adoption Services","Assessment Center","Basic Child Care","Child Placing Agency",
		"Emergency Shelter","Foster Family Home (basic)","Foster Group Home (basic)",
		"Habilitative Foster Home","Halfway House","ICF-MR Facility","Institutions Serving the Mentally Retarded",
		"Maternity Home","Physical Health Facility","Psychiatric Hospital","Residential Substance Abuse Treatment",
		"Residential Treatment Center","Therapeutic Camp","Therapeutic Foster Care");
	ax_ = new Array("","typeadopt","typeassess","typebasicc","typechildp","typeemerge","typefoster",
		"typefostea","typehabili","typehalfwa","typeicfmrf","typeinstit","typematern","typephysic",
		"typepsychi","typesubabu","typereside","typetheraa","typetherap");
	initSelect("provider", ar_, ax_);

	ar_ = new Array("","CHAMPUS or CHAMPVA","County Juvenile Probation","Medicaid","Texas Education Agency",
		"Texas Dept. of Family & Protective Services","Texas Youth Commission",
		"Texas Dept. of Mntl. Health & Mntl. Retardation","Donations, Gifts and Grants",
		"Family","Local School Districts","Private Insurance");
	ax_ = new Array("","usuachampu","usuajuveni","usuamedica","usuatexasa","usuatexasd","usuatexase",
		"usuatexasy","usuadonati","usuafamily","usualocals","usuaprivat");
	initSelect("payment", ar_, ax_);

	ar_ = new Array("","American Assn. of Psych. Services for Children","CARF","CHAMPUS or CHAMPVA",
		"Child Welfare League of America","Council on Accreditation","Joint Commission Accreditation Healthcare-O",
		"National Assn. Homes & Services for Children");
	ax_ = new Array("","accraapsa","accrcarf","accrchampu","accrcwla","accrcoa","accrjcaho","accrnahc");
	initSelect("accreditation", ar_, ax_);

	ar_ = new Array("","Checks, Points, Level or Token System","Life Space Interviews","Mechanical Restraints",
		"Natural or Logical Consequences","Personal Restraints","Psychotropic Medication",
		"Restriction of Privileges","Seclusion (locked)","Time-out Room");
	initSelect("behavioral", ar_, new Array(ar_.length));

	ar_ = new Array("Adjustment Disorder","Attention Deficit and/or Hyperactivity","Autism",
		"Conduct Disorder","Depression","Dysthymia","Identity Disorder","Oppositional and/or Defiant disorder",
		"Personality Disorder","Post-Traumatic Stress Disorder","Psychotic and/or Psychotic Features",
		"Substance abuse and/or Dependency");
	initSelect("diagnosis", ar_, new Array(ar_.length));

	ar_ = new Array("","Below 55","56 - 69","70 - 84","Above 85");
	initSelect("iq", ar_, new Array(ar_.length));

	ar_ = new Array("Abusive or cruel to animals","Adjudicated delinquent","Depressed, sad, or withdrawn",
		"Destroys property","Encopretic","Enuretic","History of fire setting",
		"Numerous placements","Physical limitations or disabilities",
		"Physically aggressive with adults","Physically aggressive with peers","Pregnant","Requires behavioral classes",
		"Requires medical or nursing care","Requires medication","Requires on-campus school",
		"Requires special education classes","Runs away","Self-abusive","Sexually abusive or assaultive",
		"Sexually inappropriate behavior","Steals","Substance abuse","Substance dependency",
		"Suicide attempt (current behavior)","Suicide threats");
	initSelect("problem", ar_, new Array(ar_.length));
	
	if (document.implementation && document.implementation.createDocument)
	{
		cityDoc = document.implementation.createDocument("", "", null);
		cityDoc.onload = loadCities;
	}
	else if (window.ActiveXObject)
	{
		cityDoc = new ActiveXObject("Microsoft.XMLDOM");
		cityDoc.onreadystatechange = function () {
			if (cityDoc.readyState == 4) loadCities()
		};
 	}
	cityDoc.load(cityUrl);
	

	// open the xml file for search criteria at beginning of program
	// and leave it open as long as the program is running
	////dataDoc = openXmlFile(dataUrl)
	if (document.implementation && document.implementation.createDocument)
	{
		dataDoc = document.implementation.createDocument("", "", null);
		dataDoc.onload = loadData;
	}
	else if (window.ActiveXObject)
	{
		dataDoc = new ActiveXObject("Microsoft.XMLDOM");
		dataDoc.onreadystatechange = function () {
			if (dataDoc.readyState == 4) loadData()
		};
 	}
	dataDoc.load(dataUrl);
	newSearch();
	showLayer("search");
}
function loadCities() {
	var root = cityDoc.getElementsByTagName('cities');
	document.getElementById("city").options[0] = new Option("", "", false, false);
	for (i = 0; i < root.length; i++) {
		document.getElementById("city").options[i+1] = new Option(root[i].getAttribute("city"),"", false, false);
	}
}
function loadData() {
//	var root = dataDoc.getElementsByTagName('temp');
//	alert(root.length);
}
function loadInst() {
	//var root = instDoc.getElementsByTagName('temp');
	//alert(root.length);
}
function initSelect(selectName, array_, ax_) {
	// assign array elements to select lists
	for (i = 0; i < array_.length; i++) 
		document.getElementById(selectName).options[i] = new Option(array_[i],ax_[i], false, false);
}
function openXmlFile(url) {
    // Use the standard DOM Level 2 technique, if it is supported
    if (document.implementation && document.implementation.createDocument) {
        // Create a new Document object
        var xmldoc = document.implementation.createDocument("", "", null);
        xmldoc.load(url);
    }
    // Otherwise use Microsoft's proprietary API for Internet Explorer
    else if (window.ActiveXObject) { 
        var xmldoc = new ActiveXObject("Microsoft.XMLDOM");   // Create doc.
        xmldoc.async = false
        xmldoc.onreadystatechange = function() {              // Specify onload
            if (xmldoc.readyState == 4) ; //// handler(xmldoc, url);
        }
        xmldoc.load(url);                                     // Start loading!
    }
    return xmldoc;
}

function delay() {
	var startDate = new Date();
	var elapsedTime = 0;
	while (elapsedTime < 2000) {
		var endDate = new Date();
		elapsedTime = endDate.getTime() - startDate.getTime();
	}
}

function newSearch() {
	unselectRadio("sex"); 
//	unselectRadio("male"); 
//	unselectRadio("female"); 
	unselectRadio("serviceLevel");  
	unselectCheck("emergency");
	unselectCheck("slidingFee");
	unselectSelect("age");
	unselectSelect("region");
	unselectSelect("city");
	unselectSelect("provider");
	unselectSelect("accreditation");
	unselectSelect("payment");
	unselectSelect("behavioral");
	unselectSelect("iq");
	unselectSelect("diagnosis");
	unselectSelect("problem");
}
function unselectRadio(elementName) {
	document.getElementById(elementName).checked = false; // none of buttons selected
}
function unselectCheck(elementName) {
	document.getElementById(elementName).checked = false;	
}
function unselectSelect(elementName) {
	var list = document.getElementById(elementName);
	list.selectedIndex = 0;		// scroll the list to the top
	list.selectedIndex = -1;	// unselect all items
}

function search() {
	// only do the search when user is on the page of search criteria
	if (document.getElementById("searchLayer").style.visibility == "visible") {	
		// remove the criteria in the arrays from previous searches
		variable.length = 0;
		target.length = 0;
		criteria.length = 0;
		// clear the fields for displaying search results
		document.getElementById("matches").options.length = 0;
		document.getElementById("individualProviderDetails").value = "";

	    makeOutputTable(dataDoc);
		
		 // show the results layer. must be done before setting focus.
		showLayer('results'); 
		// if any matches were found, set the focus to the list of matches
		// setting the focus enables the user to navigate the list with keyboard arrows
		if (matchingRecords.length  > 0) {
			document.getElementById("matches").focus();	
		}
	}
}
//
// FUNCTIONS FOR CREATING CRITERIA FOR MATCHING
//	
function makeExactCriteria(selectName, varname, label) {
	// used for region and city
	// adds elements to the criteria arrays used to determine which providers meet the user-selected criteria
	// list is the name of the combobox (if nothing was selected, nothing is added)
	// target is the the numeric position of the entry in the list (region or city sorted alphabetically, base 0) 
	var list = document.getElementById(selectName);
	if (list.selectedIndex > 0) {
		variable[variable.length] = varname;	// tncinfo variable name (attribute in the xml file that will be tested for a match)
		target[target.length] = list.selectedIndex;
		criteria[criteria.length] = label + " = " + list.options[list.selectedIndex].text;
	}
}
function makeCheckBoxCriteria(checkboxName, varname, label) {
	var checkbox = document.getElementById(checkboxName);
	if (checkbox.checked == true) {
		variable[variable.length] = varname; 	// tncinfo variable name (attribute in the xml file that will be tested for a match)
		target[target.length] = 1; 				// 1 is equal to true in the tncinfo database
		criteria[criteria.length] = label + " = available"
	}
}
function makeSingleSelectCriteria(selectName, varname, label) {
	// adds one element to the criteria arrays used to determine which providers meet the user-specified criteria
	// selectName is the name of the combobox (if nothing was selected, nothing is added is added to arrays)
	var list = document.getElementById(selectName);
	if (list.selectedIndex > 0) {
		makeCriteria(varname, list.length, list.selectedIndex, label, list.options[list.selectedIndex].text);		
	}
}
function makeMultipleSelectCriteria(selectName, varname, label) {
	// make one entry in search criteria arrays for each list item selected
	var list = document.getElementById(selectName);
	var i, length = list.length;
	
	if (list.selectedIndex == -1) return;	// only iterate list is something is selected
	
	for (i = 0; i < length; i++) {
		if (list[i].selected == true) {
			makeCriteria(varname, length, i, label, list.options[i].text);		
		}
	}
}
function makeRadioButtonCriteria(radioButtonName, varname, label, s) {
	// document.getElementById does not work, so check which
	// radio buttons are passed and use document.form.element syntax
	if (radioButtonName == "sex")
		var radio = document.criteria.gender;
	else
		var radio = document.criteria.svcLevel;
	var i, length = radio.length;
	for (i = 0; i < radio.length; i++) {
		if (radio[i].checked == true) {
			makeCriteria(varname, length, i, label, s[i]);		
			return; // since only one radio button can be marked
		}
	}
}
function makeCriteria(varname, length, selection, label, selectText) {
	// the exponent (power) for raising 2 is based on the length of the list
	// and the position of the selected element in the list 
	// minus 1 since length is base 1 and position is base 0
	variable[variable.length] = varname;		// tncinfo variable name (attribute in the xml file that will be tested for a match)
	var power = length - selection - 1;			
	target[target.length] = Math.pow(2, power);	// integer mask for match
	criteria[criteria.length] = label + " = " + selectText; // criteria text for output
}


function makeOutputTable(doc) {

	// create the arrays of search criteria
	makeRadioButtonCriteria("sex", "gender", "Sex", new Array("Boy", "Girl"));
	makeRadioButtonCriteria("sex", "gender", "Sex", new Array("Boy", "Girl"));
	
	makeRadioButtonCriteria("serviceLevel", "svl", "Service level", 
							new Array("Basic", "Moderate", "Specialized", "Intense"));

	makeCheckBoxCriteria("emergency", "emer", "Emergency placement");
	makeCheckBoxCriteria("slidingFee", "slidfee", "Sliding fee scale");

	makeExactCriteria("region", "dfpsreg", "DFPS Region");
	makeExactCriteria("city", "citynum", "City");

	makeSingleSelectCriteria("age", "age", "Age");
	makeSingleSelectCriteria("provider", "typfac", "Type of provider");
	makeSingleSelectCriteria("accreditation", "accred", "Accreditation");
	makeSingleSelectCriteria("payment", "payment", "Source of payment or contract");
	makeSingleSelectCriteria("behavioral", "behman", "Behavioral interventions");
	makeSingleSelectCriteria("iq", "iq", "Full-scale IQ");

	makeMultipleSelectCriteria("diagnosis", "diag", "Primary diagnosis");
	makeMultipleSelectCriteria("problem", "prob", "Primary problems and needs");
//	showSearchCriteria();

	var root = dataDoc.getElementsByTagName('temp');
	//alert(root.length);
	
	var isAMatch, crit;
	nMatches = 0;
	matchingRecords.length = 0; // start matching records over with empty array
   	for(var i = 0; i < root.length; i++) {
    	status = "testing provider " + (i+1) + " of " + root.length + "..."
    	var node = root[i];
		var id = node.getAttribute("id");
		var name = node.getAttribute("name");
		var city = node.getAttribute("city");
		var phone = node.getAttribute("telephone");

		// if there are no selection criteria, return all providers
		// if there are selection criteria, start out with false
		// to exclude providers and only include if a match 
		okMatch = (variable.length == 0 ? true : false);
		for(var j = 0; j < variable.length; j++) {
			var providerData= node.getAttribute(variable[j]);
			if (variable[j] == "dfpsreg" || variable[j] == "citynum") {
				// compare the provider data with the requested characteristic
				// to determine whether provider satisfies  search criteria
				// city and region need to be tested for exact match
				// since multiples of city number will also be matched 
				// in binary and
				okMatch = (providerData == target[j] ? true : false);
			}
			else {
				// binary and the provider data with the requested characteristic
				// to determine whether provider satisfies  search criteria
				okMatch = ((providerData&target[j]) == target[j] ? true : false);
			}
			// quit trying for matches on the first non-matching item
			if (okMatch == false) {
				break;
			}
		}

		if (okMatch == true) {
			var matchStr = nMatches + 1;
			if (nMatches + 1 < 100) matchStr = "  " + matchStr 
			if (nMatches + 1 < 10) matchStr = "  " + matchStr 
			document.getElementById("matches").options[nMatches++] = new Option(matchStr + ": " + name + "; " + city + "; " + phone);	
			matchingRecords[matchingRecords.length] = id;
		 }
	}  		 
	if (nMatches == 0) {
		document.getElementById("matches").options[nMatches] = new Option(noMatch);
		document.getElementById("individualProviderDetails").value = ""
	}
	else {
		document.getElementById("matches").options.selectedIndex = 0;
		showDetails();
	}
	document.getElementById("numberOfMatches").value = nMatches + " " + (nMatches==1 ? "match" : "matches");
	status = "Done"; // imitate browser response
}
	
function showDetails() {
	
	// load the individual provider file and create
	// the detail document when file is loaded
	var pick = document.getElementById("matches").selectedIndex;   	
   	var fname = "0000" + matchingRecords[pick];
   	var len = fname.length;
   	fname = "inst" + fname.substring(fname.length - 4, fname.length );
	var instUrl = "xmlFiles/" + fname + ".xml"
	if (document.implementation && document.implementation.createDocument)
	{
		instDoc = document.implementation.createDocument("", "", null);
		instDoc.onload = createDetail;
	}
	else if (window.ActiveXObject)
	{
		instDoc = new ActiveXObject("Microsoft.XMLDOM");
		instDoc.onreadystatechange = function () {
			if (instDoc.readyState == 4) createDetail()
		};
 	}
	instDoc.load(instUrl);
}

function createDetail() {
	var root = instDoc.getElementsByTagName('temp');

	var name = root[0].getAttribute("name");
	var address = root[0].getAttribute("address");
	var city = root[0].getAttribute("city");
	var state = root[0].getAttribute("state");
	var zipcode = root[0].getAttribute("zipcode");
	var region = root[0].getAttribute("region");
	var phone = root[0].getAttribute("telephone");
	var tollfree = root[0].getAttribute("tollfree");
	if (tollfree != "") tollfree = "Toll Free Number: " + tollfree + "\n"
	var contact = root[0].getAttribute("contactper");
	// age and sex
	var bAge = root[0].getAttribute("boysage");
	var gAge = root[0].getAttribute("girlsage");
	bAge = (bAge == "" ? "" : "   - Boys in the age range from " + bAge + "\n") ;
	gAge = (gAge == "" ? "" : "   - Girls in the age range from " + gAge + "\n");
	var whoServed = "";
	if (bAge != "" || gAge != "") {
		whoServed = "\nChildren served:\n" + bAge  + gAge;
	}

	var svl = "";
	var rad = document.getElementById("serviceLevel");
	if (root[0].getAttribute("levelbasic") == "true") svl = svl + "   - Basic" + "\n";
	if (root[0].getAttribute("levelmoder") == "true") svl = svl + "   - Moderate" + "\n";
	if (root[0].getAttribute("levelspec")  == "true") svl = svl + "   - Specialized" + "\n";
	if (root[0].getAttribute("levelinten") == "true") svl = svl + "   - Intense" + "\n";
	if (svl != "") {
		svl = "\n" + "Service levels:" + "\n" + svl 
	}

	var cap = (root[0].getAttribute("licensedma") == "" ? "" : "Licensed maximum capacity: " + root[0].getAttribute("licensedma") + "\n");
	var geo = (root[0].getAttribute("geograarea") == "" ? "" : "Geographic area served: " + root[0].getAttribute("geograarea") + "\n");
	var capgeo= "";
	if (cap != "" || geo != "") {
		capgeo= "\n" + cap + geo;
	}
	
	var emer = "\nSame day emergency placement:\n   - " 
		+ capitalize((root[0].getAttribute("sameyes") == "true" ? "" : "not ") + "available\n");
	var slid = "\nSliding fee scale based on ability to pay:\n   -  " 
		+ capitalize((root[0].getAttribute("slidyes") == "true" ? "" : "not ") + "available\n");
	var emerslid = "";
	if (emer != "" || slid != "") {
		emerslid = "\n" + capitalize(emer) + capitalize(slid);
	}
	
	
	// State Agency License or Certification
	var label_ = new Array("Texas Department of Family and Protective Services","Texas Youth Commission",
		"Texas Department of Mental Health and Mental Retardation",	"Texas Commission on Alcohol and Drug Abuse",
		"Texas Department of Health");
	var vname_ = new Array("stattexasd","stattexasy","stattexasa","stattexasc","stattexasb");
	var license = characteristicsFromArrays("State agency license or certification:", 
						  vname_, label_, "statother", root[0]);

	// Legal Description of Provider
	var label_ = new Array("Incorporated, private for profit","Legal Incorporated, private not for profit","Not incorporated","Public");
	var vname_ = new Array("descincorp","descincora","descnotinc","descpublic");
	var provDescription = characteristicsFromArrays("Legal description of provider:", vname_, label_, "", root[0]);

	// Description of Physical Setting
	var label_ = new Array("Secure or locked setting","Open setting with secure unit","Open setting");
	var vname_ = new Array("descsecure","descopense","descopensa");
	var physSetting = characteristicsFromArrays("Descripton of physical setting:", vname_, label_, "descothera", root[0]);

	// Type of Educational Services
	var label_ = new Array("On–site public schools",	"On–site private schools","Off–site public schools",	"Off–site private schools");
	var vname_ = new Array("typeonsite","typeonsita","typeoffsit","typeoffsia");
	var educSettings = characteristicsFromArrays("School settings available:", vname_, label_, "", root[0]);

	// TYPE OF EDUCATIONAL OPPORTUNITIES
	var label_ = new Array("Special education classes","Special behavior classes","Vocational or trade classes",
		"Academic tutoring","Independent living skills classes","Summer school","Work–study program","Substance abuse education");
	var vname_ = new Array("educspecia","educspecib","educvocati","educacadem","educindepe","educsummer","educworkst","educsubsta");
	var educOpportunties = characteristicsFromArrays("Educational services available:", vname_, label_, "educother", root[0]);
	
	// TYPE OF THERAPEUTIC INTERVENTIONS
	var label_ = new Array("Individual therapy or counseling","Group therapy","Family therapy",
		"Milieu therapy","Therapeutic recreation","Diagnosis and assessment","Substance abuse treatment",
		"12–step drug and alcohol program");
	var vname_ = new Array("typeindivi","typegroupt","typefamily","typemilieu",
		"typetherpe","typediagno","typesubsta","type12step");
	var typeTher = characteristicsFromArrays("Therapeutic services available:", vname_, label_, "typeotherb", root[0]);

	
	var_ = new Array("adjustnot","attenot","autinot","condnot","depresnot","dystnot",
		"idennot","opponot","persnot","postnot","psycnot","subsabnot");
	var diagNot = notAccepted("Children with the following diagnosis not served:", document.getElementById("diagnosis"), var_, root[0]);
	
	var_ = new Array("abusnot","adjunot","deprnot","destnot","enconot","enurnot","histnot",
		"numenot","physnotab","physnot",
		"physnotaa","pregnot","requnotac","requnot","requnotaa","requnotad","requnotab",
		"runsnot","selfnot","sexunot","sexunotaa","steanot","subsnot","subsnotaa","suicnot","suicnotaa");
	var probNot = notAccepted("Children with the following behaviors not served:", document.getElementById("problem"), var_, root[0]);
	
	
	document.getElementById("individualProviderDetails").value = name + "\n" 
		+ address + "\n" 
		+ city + ", " + state + " " + zipcode + "\n\n"
		+ "Telephone: " + phone + "\n" + tollfree 
		+ "Contact person: " + contact + "\n" 
		+ capgeo
		+ whoServed 
		+ svl
		+ characteristics("Type of provider:", document.getElementById("provider"), "typeother", root[0])
		+ characteristics("Accredited by:", document.getElementById("accreditation"), "accrother", root[0])
		+ emer
		+ characteristics("Accepts payment from or contracts with:", document.getElementById("payment"),  "", root[0])
		+ slid
		+ license
		+ provDescription 
		+ physSetting 
		+ educSettings 
		+ educOpportunties 
		+ typeTher
		+ diagNot
		+ probNot
	
}
function notAccepted(lead, list, v_, dataNode) {
	var t = "";
	for (var i=0; i < v_.length; i++) {
		if (dataNode.getAttribute(v_[i]) == "true") {
			t = t + "   - " + list.options[i].text+ "\n";
		}
	}
	return (t != "" ? "\n" + lead + "\n" + t : "");
}
function characteristics(lead, list, other, dataNode) {
	var t = "";
	for (var i=0; i < list.length; i++) {
		if (list[i].value.length != 0) {
			if (dataNode.getAttribute(list[i].value) == "true") {
				t = t + "   - " + list.options[i].text+ "\n";
			}
		}
	}
	if (other != "") {
		var oth = dataNode.getAttribute(other);
		if (oth != "") {
			t = t + "   - " + oth + "\n";
		}
	}
	return (t != "" ? "\n" + lead + "\n" + t : "");
}
function characteristicsFromArrays(lead, v_, l_, other, dataNode) {
	var t = "";
	for (var i=0; i < v_.length; i++) {
		if (dataNode.getAttribute(v_[i]) == "true") {
			t = t + "   - " + l_[i] + "\n";
		}
	}
//	alert(other);
	if (other != "") {
		var oth = dataNode.getAttribute(other);
		if (oth != "") {
			t = t + "   - " + oth + "\n";
		}
	}
	return (t != "" ? "\n" + lead + "\n" + t : "");
}
function capitalize(c) {
	if (c.length == 0) return c;
	if (c.length == 1) {
		return c.toUpperCase(); }
	else {
		return c.substring(0, 1).toUpperCase() + c.substring(1, c.length);
	}
}
function showSearchCriteria() {
	for (var i = 0; i < target.length; i++) {
		alert(variable[i] + " : " + target[i]);
	}
}
function printWindow(content) {
	if (content == "printDetails" && document.getElementById("matches").options[0].text == noMatch) {
		alert(noMatch);
		return;
	}

	//printWin = window.open("TNCInfo Output", "smallwin", "width=600,height=350,resizable=yes,menubar=yes,scrollbars=yes,top=yes,toolbar=no");
	printWin = window.open("", "smallwin", "width=600,height=350,resizable=yes,menubar=yes,scrollbars=yes,top=yes,toolbar=no");
	var d = printWin.document.open("text/html");

	d.write("<html><head><title>TNCInfo Placement Finder Results</title>");
	d.write("<style type='text/css'>.style1 {font-family: 'Times New Roman', Times, serif; font-size: 14pt}");
	d.write(".style2 {font-family: 'Times New Roman', Times, serif; font-size: 10pt}</style>");
	d.write("</head><body>");
	

	var matchList =  document.getElementById("matches");
	if (content=="printDetails") {
		if (document.getElementById("matches").options[0] == noMatch) {
			d.write("<p class='style1'>" + "No providers matched the search criteria");
		}
		else {
			var s = document.getElementById("individualProviderDetails").value;
			var details = s.split("\n");
			d.write("<p class='style1'>" + details[0] + "</p>");
		
			d.write("<p class='style2'>");
			for (var i=1; i<details.length;i++) {
				d.write(details[i] + "<br>");
			}
			d.write("</p>");
		}
	}
	
	if (content=="printList") {
		var dt = new Date();
		if (criteria.length == 0) {
			d.write("<p class='style1'>" + "Providers in TNCInfo Placement Locator (" + dt.toLocaleDateString() + ")" + "</p>");			
		}
		else {
			d.write("<p class='style1'>" + "TNCInfo Placement Search on " + dt.toLocaleDateString() + ", using the criteria:" + "</p>");
			d.write("<ul class='style2'>");
			for (var i=0; i < criteria.length; i++) {
				d.write("<li>" + criteria[i] + "</li>");
			}
			d.write("</ul>");
		} 
		if (criteria.length > 0) {
			d.write("<p class='style1'>" + "The following providers satisfied the search criteria:" + "</p>");
		}
		d.write("<p class='style2'>");
		for (var i =0; i < matchList.length; i++) {
			d.write(matchList.options[i].text + "<br>");
		} 	
		d.write("</p>");
	}
	d.write("</body></html>");
	d.close();
	
	printWin.focus(); // to force the print window to display on top of browser
}
