
function rptGeog(geog, username, modlist)
{
  window.event.cancelBubble = true;
	
    //This variable will be the new innerHTML of the geography div.  This was 
    //used instead of just directly setting the geography repeatedly because 
    //IE corrects any unfinished tags after innerHTML is set.
    //var strNewGeogHTML = "";
    //
    //(This was commented out due to necessity of having generated HTML create
    //DOM objects and running tests against those objects.  The solution became
    //to just embed the innerHTML into a string.)  --AJN 20050803
   
    var RegionPattern = /^region/
    var CountyPattern = /^county/
    var GoverningPattern = /Governing/
    var fGeogPlurals = function(geoglevel){
        var retval = '';
        if(geoglevel=='provider') retval = "agencies";
        if(geoglevel.match(GoverningPattern) != null) retval = "regions";
        if(geoglevel.match(CountyPattern) != null) retval = "counties";
        return retval;
    }

    //var isTester = isIn(username.toLowerCase(), new Array("alex","petel", "toni_k", "wredefa", "beckgrant", "kowalsc", "mitchjj"));

    //Create radio-generating string for later use (in two places)
    var chk1, chk2, strGoverningFundOptions, strAggregationCheck1, strAggregationCheck2, strAggregationCheck3;
    var bHaveAggregationCheck = (geog.value=='provider') && !document.getElementById("DisallowMultipleGeographySelections");
   
        if(document.forms(0).UserLevel.value == "County"){
        	chk1 = " checked='checked'";
        	chk2 = "";
        } else {
        	chk1 = "";
        	chk2 = " checked='checked'";
        }
 	
	//Display this only for governing region/county.  Could be denied, like on Detox reports.
        strGoverningFundOptions = ((geog.value.match(GoverningPattern) != null) && (document.getElementById('showConstrainGovCounty'))) ? 
              "<div class='MainText' style='margin-left:1em;'>\n"
        	+ "<input type='radio' name='FundSource' id='radfundtype1' value='CCS'  style='background-color:transparent;'" + chk1 + " /><label for='radfundtype1' style='font-size:0.8em;'>County Community Services (CCS) only</label><br/>\n"
        	+ "<input type='radio' name='FundSource' id='radfundtype2' value='ALL'  style='background-color:transparent;'" + chk2 + " /><label for='radfundtype2' style='font-size:0.8em;'>All fund sources</label><br/>\n"
        	+ "</div>\n" : "";
 
	if(bHaveAggregationCheck){
		strAggregationCheck2 = "";//"<input type='checkbox' name='aggregatereport' value='y' id='chkmultpage' style='background-color:transparent;'/><label for='chkmultpage' style='font-size:0.8em;'>Create one report for all selected " + fGeogPlurals(geog.value);
	} else {
	    strAggregationCheck2 = "";
	}
    
    strAggregationCheck1 = "<div class='MainText' style='margin-left:1em; display:none;' id='AggregationContainer'>";
    strAggregationCheck3 = "";//" <span class='Notes'>(Default is one report for each selection)</span></div>";
    
    
    //Begin generating the select boxes based off of geography selection
    if (geog.value.match(RegionPattern) != null) {
      geography.innerHTML = "<br/><select name='levelid' size='6' style='margin-left:1em;' onchange='ToggleAggregationCheck()'>" +
                            "  <option value='1'>Region 1</option>" +
                            "  <option value='2'>Region 2</option>" +
                            "  <option value='3'>Region 3</option>" +
                            "  <option value='4'>Region 4</option>" +
                            "  <option value='5'>Region 5</option>" +
                            "  <option value='6'>Region 6</option>" +
                            "</select>";
      if(bHaveAggregationCheck){
	      document.getElementById('levelid').multiple = 'yes';
	      geography.innerHTML = [
              "<table><tr><td>",
              geography.innerHTML,
              "</td><td>",
              strAggregationCheck1,
              strAggregationCheck2,
              strAggregationCheck3,
              "</td></tr></table>",
              "<p class='Notes'>Note:  Shift+click or Ctrl+click to select multiple values.</p>"
          ].join('\n');
          
      }
      geography.innerHTML += strGoverningFundOptions;
      geolbl.outerHTML="<div class='header' ID=geolbl>Select Region: </div>";
    }
    else if (geog.value.match(CountyPattern) != null||geog.value == 'provider') {
        if (geog.value.match(CountyPattern) != null) {
          GeogValue = 'county';
          varid = 'X138';
        }
        else {
          GeogValue = 'provider';
          varid = 'X97';
        }

	// Load XML 
	var xml = new ActiveXObject("Microsoft.XMLDOM")
	xml.async = false
	xml.load("metadata/userMeta/" + username + "_" + varid + ".xml")

	if (geog.value=='provider'){
	var oNodes = xml.selectNodes("xml/rs:data/z:row");
	listlen=oNodes.length;
	var prefil=modlist.split("~");
	
	
				    for (i=0; i<listlen; i++)
				    {
				       oNode = oNodes.nextNode;
					//loop through all modalities selected on form
					match=0;
					
					for (j=0; j<prefil.length; j++){
						//strip trailing and leading spaces
						xmlfil=oNode.attributes(3).text.replace(/\s+/g,"");
						slctfil = prefil[j].replace(/\s+/g,"");
						
						if(xmlfil.indexOf(slctfil) >= 0)
						{
							match=1;
							break;  //found a match so exit loop
						} 
						//no match and end of loop, remove the node	
					}
						if(match==0){
							var objRoot = xml.documentElement; 
							currNode = objRoot.childNodes.item(1);
							oldChild = currNode.removeChild(currNode.childNodes.item(i));
							listlen=listlen-1;
							i=i-1;	
						}
				    }	
	}



	// Load XSL
	var xsl = new ActiveXObject("Microsoft.XMLDOM")
	xsl.async = false
	xsl.load("Reports/rptgeog.xsl")

	// Transform
	geography.innerHTML = xml.transformNode(xsl);
	geolbl.outerHTML="<div class='header' ID=geolbl>Select " + GeogValue + ": </div>";
	if(document.getElementById('selLevelId').options.length > 0){
		// If a Provider's agency has no associated modalities, the
		// agency won't be displayed in the list.  If a Provider has no
		// agencies with modalities, an error pops up here.  (Discovered
		// with a test account by Alex (20050708); not likely to occur
		// with an actual user.)
		document.getElementById('selLevelId').options[0].selected = true;	//Select first entry in list by default
		
		

		if(document.getElementById('selLevelId').options.length > 1 && bHaveAggregationCheck){
			document.getElementById('selLevelId').multiple = 'yes';
	        geography.innerHTML = [
                "<table><tr><td>",
                geography.innerHTML,
                "</td><td>",
                strAggregationCheck1,
                strAggregationCheck2,
                strAggregationCheck3,
                "</td></tr></table>",
                "<p class='Notes'>Note:  Shift+click or Ctrl+click to select multiple values.</p>"
            ].join('\n');
		}

		geography.innerHTML += strGoverningFundOptions;
	} else {
		//There were no agencies/counties available with this modality; note it.
		
		strNoneDesc = "No data available for this " + GeogValue + ".";
		document.getElementById('selLevelId').options[0] = new Option(strNoneDesc, 'none', false, false);
		document.getElementById('selLevelId').disabled = true;
		
	}
	
	//allvar='';	
	//  for (var i=0; i<document.forms[1].levelid.length; i++) {
	 // 	allvar=allvar+ "'" + document.forms[1].levelid.options[i].value + "',";	
	 //   } 

	 //   if(document.forms[1].levelid.length>1){
	//		var indexCounter;
	//		document.forms[1].levelid.options[document.forms[1].levelid.length] = new Option();
			
	//			for (indexCounter = document.forms[1].levelid.length-1; indexCounter > 0; indexCounter--)
	//			{
	//			      document.forms[1].levelid.options[indexCounter].text = document.forms[1].levelid.options[indexCounter - 1].text;
	//			      document.forms[1].levelid.options[indexCounter].value = document.forms[1].levelid.options[indexCounter - 1].value;
	//			}
	//			document.forms[1].levelid.options[0] = new Option('All Facilities', allvar.substring(0,allvar.length-1));
	//			document.forms[1].levelid.options[0].selected=true;						
	//		}
  		
	}
    else {
        //We have no match; we are either looking at the Statewide choice or a facility choice in the Opiate Substitution report.
        geography.innerHTML = "";
        geolbl.outerHTML="<div ID=geolbl></div>";
    }
}

//ToggleAggregationCheck: displays or hides the aggregation checkbox for region, county or provider selection.
//This function runs as the onChange event of selLevelId and levelid.
function ToggleAggregationCheck(){
	//This container may not be there (for initial testing purposes)
	if(document.getElementById('AggregationContainer')){
		var bmult;
		if(document.getElementById('levelid')){
			bmult = CountSelections(document.getElementById('levelid')) > 1;
		}
		if(document.getElementById('selLevelId')){
			bmult = CountSelections(document.getElementById('selLevelId')) > 1;
		}
        	
		document.getElementById('AggregationContainer').style.display = bmult ? 'block' : 'none';
	}
}

// This function is used by the standard reports to set a UserCounties hidden var to be a list
// of all the countied to which the user has access;
// Curtis Mack Feb 10 2005

function CountyFilter(){ 
   var main=open('','MainWin');
   var xmlDoc = new ActiveXObject("microsoft.xmldom");
   var Values = "";
   xmlDoc.async = false;
   xmlDoc.load("metadata/userMeta/" + document.forms(0).UserName.value + "_" + "X138" + ".xml");
  var oNodes = xmlDoc.selectNodes("xml/rs:data/z:row");	
    for (i=0; i<oNodes.length; i++)
    {
       oNode = oNodes.nextNode;
       if (oNode != null) 
       {  
          if (Values != "") {Values = Values + "~"}
          Values = Values + oNode.getAttribute("ValLabel");
       }
    }
    document.forms(0).UserCounties.value = Values;     		
}

function setParms() {
    document.forms(0).AF.value = AdditionalFilters
    document.forms(0).SF.value = SubFilters
}
