// SOME GLOBAL VARIABLES // need to be changed when moving to different boxes

//for my laptop
//var strBaseURL="localhost";

//for 29
//var strBaseURL="10.2.11.29";


//for production
var strBaseURL="dcatlas.dcgis.dc.gov";

var map = null;
var gmarkers = new Object();
// The allowed region which the whole map must be within
var allowedBounds = null;
var mapExtension;                       //Map extension to add tiled map service
var gOverlays;                          //Add tile layer as a GTileLayerOverlay using mapExtension, (Ownerply)
var dynMapOv = null;                    //Add dynamic layer as map overlay, (Zoning)
//create mapOptions to specify opacity, minResolution, maxResolution when adding to the map.
var mapOptions = { opacity: 1, minResolution: 11, maxResolution: 19 };
var dcbndyply = null;
var identifyTask;                       //idnetify task for extra layer overlays (Zoning, Ownerply)
var identifyTarget;                     //Hold current identify target layer (Zoning, Ownerply)
var identifyEvtListener;                //Identify listner
var overlays;                           //identify result feature highlights
var addlabel; 

function load() {
	if (GBrowserIsCompatible()) 
	{
		try
		{
			map = new GMap2(document.getElementById("map"));
			map.getContainer().style.overflow = "hidden";
			map.addMapType(G_NORMAL_MAP);
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			map.setCenter(new GLatLng(38.897000, -77.02000), 11);
			
			GEvent.addListener(map, "zoomend", function() {
				if (map.getZoom() < 14) {
					if (dynMapOv != null) { map.removeOverlay(dynMapOv); }
					if (strFeature == "dccapital") {document.getElementById("chkOwner").checked = false;}
				}
			}); 
			addDistrictBound();
			if ((strFeature == "dprcapital") || (strFeature == "dccapital"))
			{	
				var geoXml = new GGeoXml("http://dcatlas.dcgis.dc.gov/kmldata/ward2002.kml");
				map.addOverlay(geoXml);
			}
			
			if (strFeature == "dccapital")
			{
			
				//create mapextension class to be used to add/remove results from the map.
				mapExtension = new esri.arcgis.gmaps.MapExtension(map);

				//create custom tile layer
				var tiledmap = new esri.arcgis.gmaps.TiledMapServiceLayer("http://maps.dcgis.dc.gov/DCGIS/rest/services/Basemap-WebMercator/MapServer", mapOptions, addTiledMapAsMaptype);
				
				GEvent.addListener(map, "zoomend", function() {
					if (map.getZoom() < 16) {
						//if (gOverlays != null) { mapExtension.removeFromMap(gOverlays); }
						if (dynMapOv != null) { map.removeOverlay(dynMapOv); addDistrictBound();}
						document.getElementById("chkOwner").checked = false;
					}
				});
			}
			allowedBounds = new GLatLngBounds(new GLatLng(38.75, -77.3), new GLatLng(39.15, -76.8));

			var query="getData.aspx?type=markers&feature=" +strFeature;
			GDownloadUrl(query,  display); 
			
			//chuanyun added July 30, 2009
			correctNav();
		}
		catch(err)
		{
			  txt="We are sorry but an error has occured on this page.\n\n";
			  txt+="Click OK to continue viewing this page,\n";
			  txt+="or Cancel to return to dcgis.dc.gov.\n\n";
			  txt+="Error description: " + err.description;
			  if(!confirm(txt))
			  {
				document.location.href="http://dcgis.dc.gov/";
			  }
        	}
	}
	else
	{ alert ("Sorry, you browser is unable to display the google map."); }

}
//-----------------------------------------------------------------------------------------
// adding DC GIS Map Type.
//-----------------------------------------------------------------------------------------
function addTiledMapAsMaptype(gTileLayer) {
    //Add tile layer as a new GMapType
    var tilelayers = [G_SATELLITE_MAP.getTileLayers()[0], gTileLayer];
    var gMapType = new GMapType(tilelayers, new GMercatorProjection(20), "DCGIS", { errorMessage: "No data available" });

    map.addMapType(gMapType);
    //map.removeMapType(G_NORMAL_MAP);
    map.removeMapType(G_HYBRID_MAP);
    map.removeMapType(G_SATELLITE_MAP);
    map.addMapType(G_HYBRID_MAP);
    map.addMapType(G_SATELLITE_MAP);

    map.setMapType(gMapType);


    //map.enableScrollWheelZoom();
    //callDropdownDB("neighbor");
    //callDropdownDB("mainstreet");
}
//-----------------------------------------------------------------------------------------
// Initialization for adding dynamic map service overlay - Zoning.
//-----------------------------------------------------------------------------------------
function init_addDynamicMap(layerName, box) {
    
        var serviceURL;

        clearResults();
        //clear old custom layer overlay
        if (gOverlays != null) { mapExtension.removeFromMap(gOverlays); }
        if (dynMapOv != null) { map.removeOverlay(dynMapOv); }
        serviceURL = "http://maps.dcgis.dc.gov/DCGIS/rest/services/" + layerName + "/MapServer";

        if (identifyEvtListener != null) { GEvent.removeListener(identifyEvtListener); identifyEvtListener = null; }

        if (box.checked) {
            //document.getElementById("ownership").checked = false;
            if (map.getZoom() >= 16) {
				map.removeOverlay(dcbndyply);
				identifyTask = null;

				dynamicMap = new esri.arcgis.gmaps.DynamicMapServiceLayer(serviceURL, null, 0.75, addDynamicMap);

				if (layerName == "newOwnerPly") {
					identifyTarget = "ownerply";
				} else {
					identifyTarget = "zoning";
				}
				// create an identify task
				identifyTask = new esri.arcgis.gmaps.IdentifyTask(serviceURL);
				// register click event listener for the map
				identifyEvtListener = GEvent.addListener(map, "click", identify);
			} else {
				alert("To improve performance, please first zoom in the map further, then add the layer again.");
				if (box.checked) { box.checked = false; }
			}
        } else {
			addDistrictBound();
		}
    
    
 }
 //-----------------------------------------------------------------------------------------
 // adding dynamic map service overlay - Zoning.
 //-----------------------------------------------------------------------------------------
function addDynamicMap(groundov) {
    //Add groundoverlay to map using gmap.addOverlay()
    map.addOverlay(groundov);
    dynMapOv = groundov;
}
//-----------------------------------------------------------------------------------------
// identify function for Ownerply and Zoning.
//-----------------------------------------------------------------------------------------
function identify(overlay, latLng) {
    if ((overlay) && (overlay != dcbndyply)) return;
    // set the identify parameters
    var identifyParameters = new esri.arcgis.gmaps.IdentifyParameters();
    identifyParameters.geometry = latLng; // location where the user clicked on the map
    identifyParameters.tolerance = 2;
    identifyParameters.layerIds = [0];
    identifyParameters.layerOption = "all";
    identifyParameters.bounds = map.getBounds();
    var mapSize = map.getSize();
    identifyParameters.width = mapSize.width;
    identifyParameters.height = mapSize.height;

    // execute the identify operation
    identifyTask.execute(identifyParameters, function(response, error) { // function to be called when the result is available
        // display error message (if any) and return
        if (hasErrorOccurred(error)) return;

        // note that the location where the user clicked on the map (latLng) is visible in this function through closure
        addResultToMap(response, latLng);
    });
}
//-----------------------------------------------------------------------------------------
// add identify function result to map.
//-----------------------------------------------------------------------------------------
function addResultToMap(response, point) {
    // aggregate the result per map service layer
    
    var idResults = response.identifyResults;
    layers = { "0": [] };
    for (var i = 0; i < idResults.length; i++) {
        var result = idResults[i];
        layers[result.layerId].push(result);
    }

    // create and show the info-window with tabs, one for each map service layer
    var tabs = [];
    for (var layerId in layers) {
        var results = layers[layerId];
        
        var count = results.length;
        var label = "", content = "";
        switch (identifyTarget) {
            case "ownerply":
                label = "Owner Polygon";
                content = "<font color=#000000>Total features returned: <b>" + count + "</b></font>";
                if (count == 0) break;
                content += "<table class='identify' border='1'><th>SSL</th><th>Land Area</th><th>Address</th><th>Owner</th>";

                for (var j = 0; j < count; j++) {
                    var attributes = results[j].feature.attributes;
                    //alert(results[j]);
                    content += "<tr>";
                    content += "<td><a href='#' onclick='showFeature(" + layerId + "," + j + ")'>" + attributes["SSL"] + "</a></td>";
                    content += "<td>" + attributes["LANDAREA"] + "</td>";
                    content += "<td>" + attributes["PREMISEADD"] + "</td>";
                    content += "<td>" + attributes["OWNERNAME"] + "</td>";
                    content += "</tr>";
                }
                content += "</table>";
                break;
        }
        tabs.push(new GInfoWindowTab(label, content));
    }
    map.openInfoWindowTabsHtml(point, tabs);
}
//-----------------------------------------------------------------------------------------
// add identify result feature highlight to the map.
//-----------------------------------------------------------------------------------------
function showFeature(layerId, index) {
    mapExtension.removeFromMap(overlays);
    var idResult = layers[layerId][index];
    overlays = mapExtension.addToMap(idResult, { polygonOptions: { clickable: false} });
}
//-----------------------------------------------------------------------------------------
// clear identify result feature highlight on the map.
//-----------------------------------------------------------------------------------------
function clearResults() {
    mapExtension.removeFromMap(overlays);
    
    map.closeInfoWindow();
}
//-----------------------------------------------------------------------------------------
// identify error handling.
//-----------------------------------------------------------------------------------------
function hasErrorOccurred(error) {
    if (error) {
        alert("Error " + error.code + ": " + (error.message || (error.details && error.details.join(" ")) || "Unknown error"));
        return true;
    }
    return false;
}
function display(text, code) { 

    var items=text.split("|"); 
	var eicon = new GIcon();
	if ((strFeature == "dprcapital") || (strFeature == "dccapital")) {
		eicon.image = "http://maps.google.com/mapfiles/kml/pal3/icon56.png";
	} else if (strFeature == "dohpharmacy") {
		eicon.image = "images/Pharmacy.jpg";
	} else if (strFeature == "hotspot") {
		eicon.image = "images/wi-fi.jpg";
	}
	eicon.iconSize = new GSize(16, 16);
	eicon.iconAnchor = new GPoint(6, 20);
	eicon.infoWindowAnchor = new GPoint(5, 1);

	
	
       var mgr = new GMarkerManager(map); 
       
        for (i=0; i<items.length-1; i++) { 
                                   
                var comps=items[i].split(";;"); 
                var lng=comps[0]; 
                var lat=comps[1]; 
                								
				var catName = comps[2];														
				var catAddress = comps[3];	
				var catFeatId = comps[4];
				
				var catURL;
				var catStatus;
				var catWard;
				var agency;	
				var proj_num;	
				//var website;	
				var schoolname;	
				var agencyid;
				var zip;	
				var fee_free;
				var company;
				var email;
				var phone;
				var hours;
				var rpt_new; 
				var h1n1;
				var seasonal;
				
				if (strFeature == "dprcapital") {
					catURL = comps[5];														
					catStatus = comps[6];	
					catWard = comps[7];	
				} else if (strFeature == "dohpharmacy") {
					zip = comps[5];	
					phone = comps[6];	
					h1n1 = comps[7];	
					seasonal = comps[8];
					if ((h1n1=="Y") && (seasonal=="Y")) {
						eicon.image = "images/both.png";
					} else if ((h1n1=="Y") && (seasonal=="N")) {
						eicon.image = "images/h1n1.png";
					} else if ((h1n1=="N") && (seasonal=="Y")) {
						eicon.image = "images/seasonal.png";
					}
					eicon.iconSize = new GSize(18, 18);
				} else if (strFeature == "notary") {
					zip = comps[5];	
					fee_free = comps[6];	
					company = comps[7];	
					//website = comps[8];	
					email = comps[8];	
					phone = comps[9];
					hours = comps[10];
					rpt_new = comps[11];
					if (company!="Self") {
						eicon.image = "http://maps.google.com/mapfiles/kml/pal3/icon63.png";
					} else {
						eicon.image = "http://maps.google.com/mapfiles/kml/pal3/icon56.png";
					}
				} else if (strFeature == "dccapital") {
					catWard = comps[5];	
					agency = comps[6];	
					proj_num = comps[7];	
					//website = comps[8];	
					schoolname = comps[8];	
					agencyid = comps[9];	
					if (trim(agencyid)=="") {agencyid="99999"}
				}			
				
				var ret={};// holds returned caculated values
				var llCoords = SPCStoLL(lng, lat, ret);
				var point = new GLatLng(ret.lat, ret.lon);
				var marker;	
				
				var popuphtml;
				if (strFeature == "notary") {
					popuphtml ='<div id="gmapinfowindow"><table><tr><td><div class="gmaplogo"><img src="images/dcflag.gif" alt="DC Flag Logo" ></img></div></td><td><div class="gmaptitlePopup">'+catName+'</div></td></tr>';
				} else {
					popuphtml ='<div id="gmapinfowindow"><table><tr><td><div class="gmaplogo"><img src="images/dcflag.gif" alt="DC Flag Logo" ></img></div></td><td><div class="gmaptitlePopup">'+catName+'</div></td></tr><tr><td colspan="2"><b>Address</b>: '+catAddress +'</td></tr>';
				}
				if (strFeature == "dprcapital") {
					popuphtml=popuphtml+'<tr><td colspan="2">Status: '+catStatus +'</td></tr>';
					popuphtml=popuphtml+'<tr><td colspan="2">Ward: '+catWard +'</td></tr>';
					popuphtml=popuphtml+'<tr><td colspan="2"><a href="' + catURL + '" target="_blank">Project Details</a></td></tr>';
				}
				if (strFeature == "dohpharmacy") {
					popuphtml=popuphtml+'<tr><td colspan="2">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WASHINGTON, DC '+zip +'</td></tr>';
					popuphtml=popuphtml+'<tr><td colspan="2"><b>Phone</b>: '+phone +'</td></tr>';
				}
				
				
				if (strFeature == "dccapital") {
					popuphtml=popuphtml+'<tr><td colspan="2"><b>Project No</b>: '+proj_num +'</td></tr>';
					popuphtml=popuphtml+'<tr><td colspan="2"><b>Agency</b>: '+agency +'</td></tr>';
					popuphtml=popuphtml+'<tr><td colspan="2"><b>Ward</b>: '+catWard +'</td></tr>';
					//if (schoolname != "") {popuphtml=popuphtml+'<tr><td colspan="2"><b>School</b>: <a href="' + website + '" target="_blank">' + schoolname + '</a></td></tr>';}
					if (schoolname != "") {popuphtml=popuphtml+'<tr><td colspan="2"><b>School</b>: ' + schoolname + '</td></tr>';}
				}
				
				if (strFeature == "notary") {
					if (company!="Self") {
						//popuphtml=popuphtml+'<tr><td colspan="2"><b>Fee or Free</b>: '+fee_free +'</td></tr>';
						popuphtml=popuphtml+'<tr><td colspan="2"><b>Company</b>: '+ company +'</td></tr>';
						popuphtml=popuphtml+'<tr><td colspan="2"><b>Address</b>: '+catAddress +'</td></tr>';
						popuphtml=popuphtml+'<tr><td colspan="2">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WASHINGTON, DC '+zip +'</td></tr>';
						//popuphtml=popuphtml+'<tr><td colspan="2"><b>Repeat or New</b>: ' + rpt_new + '</td></tr>';
					}
					popuphtml=popuphtml+'<tr><td colspan="2"><b>Phone</b>: ' + phone + '</td></tr>';
					popuphtml=popuphtml+'<tr><td colspan="2"><b>Email</b>: '+email +'</td></tr>';
					popuphtml=popuphtml+'<tr><td colspan="2"><b>Hours</b>: ' + hours + '</td></tr>';
				}
				
				
				var atlasurl = 'citizenatlas.dc.gov/atlasapps/reports.aspx?SAR=administrative&ShowX='+lng+'&ShowY='+lat+'&name='+catName+'&QString=';
				
				if ((strFeature == "dprcapital") || (strFeature == "dccapital")) {popuphtml=popuphtml+'<tr><td colspan="2"><a href="http://' + atlasurl + '" target="_blank">Additional Neighborhood Information</a></td></tr></table>';}
				
				if (strFeature != "dccapital") {
					//popuphtml=popuphtml+'</table><br>Get directions: <a href="http://maps.google.com/maps?daddr=' + catAddress + ', WASHINGTON DC' + '" target="_blank">To here</a> - <a href="http://maps.google.com/maps?saddr=' + catAddress + ', WASHINGTON DC' + '" target="_blank">From here</a><BR><div id="start"><input type="text" name="startaddr"><input type="button" name="startGo" value="Go"></div><div id="end"><input type="text" name="endaddraddr"><input type="button" name="endGo" value="Go"></div></div>';
					popuphtml=popuphtml+'</table><b>Get directions:</B> <a href="javascript:Toggle(\'start\')">To here</a> - <a href="javascript:Toggle(\'end\')">From here</a>';
					//destination is the wifi location
					popuphtml=popuphtml+'<div id="start" style="display:none">Start address<input type="text" id="startaddr"><input type="button" value="Go" onclick="javascript:showDirection(\'to\', \'' + catAddress +'\')"></div>';
					//start point is the wifi location
					popuphtml=popuphtml+'<div id="end" style="display:none">End address<input type="text" id="endaddr"><input type="button" value="Go" onclick="javascript:showDirection(\'from\', \'' + catAddress +'\')"></div></div>';
				}
				marker = createMarker(point,catName,catAddress,eicon,lng,lat,catFeatId, popuphtml);
				if (strFeature == "dprcapital") {marker.ward=catWard;}
				if (strFeature == "notary") {marker.pri=(company=="Self");}
				if (strFeature == "dccapital") {
					marker.ward=catWard;
					marker.agency=agencyid;
				}
				if (strFeature == "dohpharmacy") {
					marker.both=((seasonal=="Y") && (h1n1=="Y"));
					marker.h1n1=(h1n1=="Y");
					marker.seasonal=(seasonal=="Y");
				}
				map.addOverlay(marker);
				gmarkers[catFeatId]= marker;
  
        } 
       callDropdownDB(strFeature);

} 

function Toggle(thediv) { 
	document.getElementById("start").style.display = "none"; 
	document.getElementById("end").style.display = "none"; 
	document.getElementById(thediv).style.display = "block"; 
}  

function showDirection(whichdir, theaddr) { 
	var anotherloc;
	if (whichdir=="from") {
		anotherloc=document.getElementById("endaddr").value + ", WASHINGTON DC";
		window.open("http://maps.google.com/maps?saddr=" + theaddr + ", WASHINGTON DC&daddr=" + anotherloc);
	} else {
		anotherloc=document.getElementById("startaddr").value + ", WASHINGTON DC";
		window.open("http://maps.google.com/maps?daddr=" + theaddr + ", WASHINGTON DC&saddr=" + anotherloc);
	}
}  

function newupdateMarkerVis()
{
	for (gm in gmarkers){gmarkers[gm].hide();}
	var ddl;
	var value;
	if ((strFeature == "dprcapital") || (strFeature == "dccapital")) {
		ddl = document.getElementById("ddlWards");
	} else if ((strFeature == "notary") || (strFeature == "dohpharmacy")) {
		ddl = document.getElementById("ddlTypes");
	}
	value = ddl.options[ddl.selectedIndex].value;
	if (strFeature == "dccapital") {
		var ddl2 = document.getElementById("ddlAgency");
		var value2 = ddl2.options[ddl2.selectedIndex].value;
		for (gm in gmarkers) {
			if ((value==0) && (value2==0)) {
				gmarkers[gm].show();
			} else if ((value==0) && (value2!=0)) {
				if (gmarkers[gm].agency == value2) {gmarkers[gm].show();}
			} else if ((value!=0) && (value2==0)) {
				if (gmarkers[gm].ward == value) {gmarkers[gm].show();}
			} else if ((value!=0) && (value2!=0)) {
				if ((gmarkers[gm].ward == value) && (gmarkers[gm].agency == value2)) {gmarkers[gm].show();} 
			}
		}
	} else if (strFeature == "dprcapital") {
		for (gm in gmarkers) {
			if (value==0) {
				gmarkers[gm].show();
			} else {
				if (gmarkers[gm].ward == value) {gmarkers[gm].show();} 
			}
		}
	} else if (strFeature == "notary") {
		for (gm in gmarkers) {
			if (value==0) {
				gmarkers[gm].show();
			} else if (value==1) {
				if (!gmarkers[gm].pri) {gmarkers[gm].show();} 
			} else if (value==2) {
				if (gmarkers[gm].pri) {gmarkers[gm].show();} 
			}
		}
	} else if (strFeature == "dohpharmacy") {
		for (gm in gmarkers) {
			if (value==0) {
				gmarkers[gm].show();
			} else if (value==1) {
				if (gmarkers[gm].seasonal) {gmarkers[gm].show();} 
			} else if (value==2) {
				if (gmarkers[gm].h1n1) {gmarkers[gm].show();} 
			}
		}
	}
	
}
function createMarker(point,catName,catAddress,eicon,refX,refY,id,popuphtml)
{
	var marker = new GMarker(point, { title: catName, icon: eicon });

	
	
	GEvent.addListener(marker, 'click', function() 
	{
		map.setCenter(marker.getLatLng(), 16);
        map.openInfoWindowHtml(marker.getLatLng(), popuphtml, {maxWidth:300, maxHeight:300}); 
		var ctrl; 
		var ctrl2;
		if (strFeature == "hotspot") {
			ctrl = document.getElementById("ddlTargetHotSpots"); 
		} else if (strFeature == "dprcapital") {
			ctrl = document.getElementById("ddlTargetSpeProjs"); 
		} else if (strFeature == "dohpharmacy") {
			ctrl = document.getElementById("ddlTargetPharmacy"); 
		} else if (strFeature == "notary") {
			ctrl = document.getElementById("ddlTargetNotaries");
		} else if (strFeature == "dccapital") {
			ctrl = document.getElementById("ddlTargetDCCapitals"); 
		}
		
		if ((strFeature == "dprcapital")) {
			ctrl2 = document.getElementById("ddlWards");
			for(var j = 0; j < ctrl2.options.length; j++) // cycle through the object list 
			{ 
				if (ctrl2.options[j].value != -999) {
					var comp=ctrl2.options[j].value;  
					if(comp == marker.ward){ 
						ctrl2.options[j].selected=true; 
					//addPrecinctBound(id);
					}
				}
			}
		}
		
		for(var i = 0; i < ctrl.options.length; i++) // cycle through the object list 
		{ 
			if (ctrl.options[i].value != -999) {
				var comps=ctrl.options[i].value.split(":");  
				if(comps[2] == id){ 
					ctrl.options[i].selected=true; 
					//addPrecinctBound(id);
				}
			}
		}
	});
	
	return marker;
}

function callDropdownDB(feature)
{		
		var value;
		if (strFeature == "hotspot"){
			var query="getData.aspx?type=markers&value=-1&feature="+feature; 
		} else if (strFeature == "dprcapital") {
			var ddl = document.getElementById("ddlWards");
			value = ddl.options[ddl.selectedIndex].value;
			var query="getData.aspx?type=markers&feature="+feature+ "&value="+value;
		} else if (strFeature == "notary") {
			var ddl = document.getElementById("ddlTypes");
			value = ddl.options[ddl.selectedIndex].value;
			var query="getData.aspx?type=markers&feature="+feature+ "&value="+value;
		} else if (strFeature == "dohpharmacy") {
			var ddl = document.getElementById("ddlTypes");
			value = ddl.options[ddl.selectedIndex].value;
			var query="getData.aspx?type=markers&feature="+feature+ "&value="+value;
		} else if (strFeature == "dccapital") {
			var ddl = document.getElementById("ddlWards");
			var value1 = ddl.options[ddl.selectedIndex].value;
			var ddl2 = document.getElementById("ddlAgency");
			var value2 = ddl2.options[ddl2.selectedIndex].value;
			value = value1+"/"+value2;
			var query="getData.aspx?type=markers&feature="+feature+ "&value="+value;
		}
		
	    //if (value != 0) {addWardBound(value);}
		
		GDownloadUrl(query,  setList); 
		if ((strFeature == "dprcapital") && (value == 0)) {clearSelection();}
		//var valuearray=value.split("/");
		
		if ((strFeature == "dccapital")) {clearSelection();}
		

}
function clearSelection() {
	
	map.setCenter(new GLatLng(38.897000, -77.02000), 11);
	
}
function setList(text,code)
{
	map.closeInfoWindow();	
	if ((strFeature == "dprcapital") || (strFeature == "dccapital") || (strFeature == "notary") || (strFeature == "dohpharmacy")) {newupdateMarkerVis();}
	var items=text.split("|");
	var ctrl;
	if (strFeature == "hotspot") {
		ctrl = document.getElementById("ddlTargetHotSpots"); 
	} else if (strFeature == "dohpharmacy") {
		ctrl = document.getElementById("ddlTargetPharmacy");
	} else if (strFeature == "notary") {
		ctrl = document.getElementById("ddlTargetNotaries"); 
	} else if (strFeature == "dprcapital") {
		ctrl = document.getElementById("ddlTargetSpeProjs"); 
	} else if (strFeature == "dccapital") {
		ctrl = document.getElementById("ddlTargetDCCapitals");
	}
	ctrl.innerHTML = '';
	var defaultvalue = document.createElement('option');
	defaultvalue.value = "-999";
	if (strFeature == "hotspot") {
		defaultvalue.text="Select a Wi-Fi hot spot from this list"; 
	} else if (strFeature == "dohpharmacy") {
		defaultvalue.text="Select a pharmacy from this list";
	} else if (strFeature == "notary") {
		defaultvalue.text="Select a notary public location from this list"; 
	} else if (strFeature == "dprcapital") {
		defaultvalue.text="Select a capital project from this list"; 
	} else if (strFeature == "dccapital") {
		defaultvalue.text="Select a capital project from this list"; 
	}

	ctrl.options.add(defaultvalue);
	
	for (i=0; i<items.length-1; i++) { 
                var comps=items[i].split(";;"); 
                var lng=comps[0]; 
                var lat=comps[1]; 							
				var name = comps[2];							
				var address = comps[3];
				var id = comps[4];	
				var schoolname;
				var agencyid;
				var company;
				if (strFeature == "notary") {company=comps[7];}	
				if (strFeature == "dccapital") {schoolname = comps[9];agencyid = comps[10];}	
				var catId = lng + ":" + lat + ":" + id;	
				
				// Create a new <OPTION> node.
				var htmlCode = document.createElement('option');
				// Add the new <OPTION> node to our <SELECT> drop list
				ctrl.options.add(htmlCode);
				// Set the <OPTION> display text and value;
								
				if ((strFeature == "dccapital") && (agencyid=="")) {
					if (schoolname=="") {
						htmlCode.text = trim(name);
					} else {
						htmlCode.text = trim(name) + " - " + trim(schoolname);
					}
				} else if (strFeature == "notary") {
					if (company!="Self") {
						htmlCode.text = trim(name) + " - " + trim(address) + " - " + trim(company);
					} else {
						htmlCode.text = trim(name) + " - " + trim(address);
					}
				} else {
					if (address=="") {
						htmlCode.text = trim(name);
					} else {
						htmlCode.text = trim(name) + " - " + trim(address);
					}
				}
				htmlCode.value = catId;  
				
        } 
}



function addDistrictBound()
{
	
	GDownloadUrl("data/DCBndyPly_Gen.kml", function(data) {
		var xml = GXml.parse(data);
		var placemarks = xml.documentElement.getElementsByTagName("Placemark");

		var count = 0;
		for(var i=0; i<placemarks.length; i++){

			var name = placemarks[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;

			var coordinates;
			coordinates = placemarks[i].getElementsByTagName("coordinates")[0].childNodes[0].nodeValue;

			coordinates = coordinates.trim();

			for(var chunk=1;  chunk<placemarks[i].getElementsByTagName("coordinates")[0].childNodes.length;chunk++){
				 coordinates+=placemarks[i].getElementsByTagName("coordinates")[0].childNodes[chunk].nodeValue;
			}

			coordinates = coordinates.split(" ");

			for(var j=0; j<coordinates.length;j++){
					coordinates[j] = coordinates[j].split(",");
			}
			
			if(coordinates.length > 1){
				var points = new Array();
				for(var j=0; j<coordinates.length; j++)
				{
					if(coordinates[j].length == 3)
					{	
						points.push(new  GLatLng(parseFloat(coordinates[j][1]),parseFloat(coordinates[j][0])));	
					}
					else if(coordinates[j].length == 4)
					{	
						points.push(new  GLatLng(parseFloat(coordinates[j][2]),parseFloat(coordinates[j][1])));	
					}
				}
				dcbndyply = new GPolygon(points, "#FF0000", 2, 0.8, "#FF0000",0)
				map.addOverlay(dcbndyply);				
			}
			else
			{
				continue;
			}								
		}		
        });  
}
// If the map position is out of range, move it back
function checkBounds() {
// Perform the check and return if OK
	if (allowedBounds.contains(map.getCenter())) {
		return;
	}
	else
	{
		// It`s not OK, so find the nearest allowed point and move there
		var C = map.getCenter();
		var X = C.lng();
		var Y = C.lat();

		var AmaxX = allowedBounds.getNorthEast().lng();
		var AmaxY = allowedBounds.getNorthEast().lat();
		var AminX = allowedBounds.getSouthWest().lng();
		var AminY = allowedBounds.getSouthWest().lat();

		if (X < AminX) {X = AminX;}
		if (X > AmaxX) {X = AmaxX;}
		if (Y < AminY) {Y = AminY;}
		if (Y > AmaxY) {Y = AmaxY;}
		//alert ("Restricting "+Y+" "+X);
		map.setCenter(new GLatLng(Y,X));
	}
}

String.prototype.trim = function () 
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
function recentermap() {
	map.setCenter(new GLatLng(38.897000, -77.02000), 11);
}


function createSimpleMarker(point,title, addressicon,lat,lon,address,refX,refY)
{
	var marker = new GMarker(point, { title: title, icon: addressicon }); 	
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(title);
	});
	
	return marker;
}

function reportWindow(url)
{
	window.open(url);
}

function showTarget()
    {
		var ctrl;
		if (strFeature == "hotspot") {
			ctrl = document.getElementById("ddlTargetHotSpots"); 
		} else if (strFeature == "dprcapital") {
			ctrl = document.getElementById("ddlTargetSpeProjs"); 
		} else if (strFeature == "dohpharmacy") {
			ctrl = document.getElementById("ddlTargetPharmacy"); 
		} else if (strFeature == "notary") {
			ctrl = document.getElementById("ddlTargetNotaries"); 
		} else if (strFeature == "dccapital") {
			ctrl = document.getElementById("ddlTargetDCCapitals"); 
		}
         var featureXY = ctrl[ctrl.selectedIndex].value;
         if(featureXY != "-999")
         {
			//lng + ":" + lat + ":" + id
			var paras = featureXY.split(":");
			var featureX=paras[0];
			var featureY=paras[1];
			var ret={};// holds returned caculated values
			var llCoords = SPCStoLL(featureX, featureY, ret);
			//var point = new GLatLng(ret.lat, ret.lon);
			//map.setCenter(new GLatLng(ret.lat,ret.lon), 15);
			GEvent.trigger(gmarkers[paras[2]], "click");

		}
		
}
// Removes leading whitespaces
		function LTrim( value ) 
		{
			var re = /\s*((\S+\s*)*)/;
			return value.replace(re, "$1");
		}

		// Removes ending whitespaces
		function RTrim( value ) 
		{
			var re = /((\s*\S+)*)\s*/;
			return value.replace(re, "$1");
		}

		// Removes leading and ending whitespaces
		function trim( value ) 
		{
			return LTrim(RTrim(value));
		}

		function IsNumeric(sText)
		{
			var ValidChars = "0123456789.";
			var IsNumber=true;
			var Char;

		for (var i = 0; i < sText.length && IsNumber == true; i++) 
				{ 
					Char = sText.charAt(i); 
					if (ValidChars.indexOf(Char) == -1) 
			{
				IsNumber = false;
			}
				}

				return IsNumber;
			
		}

	   
		// Function to load the customer selection data into the <SELECT> drop list control
		function verifyAddress()
		{
			var xmlHttpObj = CreateXmlHttpRequestObject();
			if (xmlHttpObj)
			{
				//var eleAddress = document.getElementById("address_txtAddress");
				var eleAddress = document.getElementById("txtAddress");
				var strAddress = eleAddress.value;
				if(strAddress.length < 3) 
				{
					return;
				}
				
				// We want this request asynchronous
				xmlHttpObj.open("POST","http://" + strBaseURL +"/wsProxy/proxy_LocVerifier.asmx/findLocation_all", true);

				xmlHttpObj.onreadystatechange = function()
				{
					if ( xmlHttpObj.readyState == READYSTATE_COMPLETE )
					{
						if(xmlHttpObj.status == HTTPSTATUS_OK)
						{
							//var ctrl = document.getElementById("address_ddlAddresses");
							var ctrl = document.getElementById("ddlAddresses");
							var doc = xmlHttpObj.responseXML;
							var nodesType = doc.getElementsByTagName("sourceOperation");
							var queryType = nodesType[0].childNodes[0].nodeValue;
							switch(queryType)
							{
								case "DC Place":
									//var nodesName1 = doc.getElementsByTagName("FULLADDRESS");
									var nodesName1 = doc.getElementsByTagName("ALIASNAME");
									var nodesX = doc.getElementsByTagName("XCOORD");
									var nodesY = doc.getElementsByTagName("YCOORD");
									break;
								case "DC Intersection":
									var nodesName1 = doc.getElementsByTagName("FULLINTERSECTION");
									//var nodesName2 = doc.getElementsByTagName("FULLSTREET2DISPLAY");
									var nodesX = doc.getElementsByTagName("REFX");
									var nodesY = doc.getElementsByTagName("REFY");
									break;
									
								case "DC Address":  //case "DC AID":
									var nodesName1 = doc.getElementsByTagName("FULLADDRESS");
									//var nodesName2 = doc.getElementsByTagName("ALIASNAME");
									var nodesX = doc.getElementsByTagName("XCOORD");
									var nodesY = doc.getElementsByTagName("YCOORD");
									break;
								
								case "DC Block":
								case "DC Block Address":
									var nodesName1 = doc.getElementsByTagName("FULLBLOCK");
									//var nodesName2 = doc.getElementsByTagName("ALIASNAME");
									var nodesX = doc.getElementsByTagName("CENTROIDX");
									var nodesY = doc.getElementsByTagName("CENTROIDY");
									break;
								
								default : break;
								
							}
							//clear first
							ctrl.options.length = 0;
							var catName;
							var catId;
							var htmlCode;
							
							if(! nodesName1) return;
							
							if(nodesName1.length == 0)
							{
								//alert("No match found, please try another address.");
								var nomatchvalue = document.createElement('option');
								nomatchvalue.value = "-999";
								nomatchvalue.text = "No match found, please correct your address and type again.";
																						
								ctrl.options.add(nomatchvalue);
								return;
							}
							else
							{
								var aryOptions = new Array();
								for (var i=0; i < nodesName1.length; i++)
								{
									var catName = nodesName1[i].childNodes[0].nodeValue;
									var catId = "showX="+nodesX[i].childNodes[0].nodeValue+"&showY="+nodesY[i].childNodes[0].nodeValue+"&Name="+catName;
									aryOptions[i] = catName + "::" + catId;
									
								}
								aryOptions.sort();
								var iLoc;
								for(i=0; i < aryOptions.length; i++)
								{
									var htmlCode = document.createElement('option');
									ctrl.options.add(htmlCode);
									catName = aryOptions[i];
									iLoc = catName.indexOf("::");
									htmlCode.text = catName.substring(0, iLoc);
									htmlCode.value = catName.substring(iLoc+2);
									if  ((aryOptions.length==1) && (strFeature == "dprcapital")) htmlCode.selected=true;   
								}
							}
						}
						else
						{
							var fault = xmlHttpObj.responseText;
							alert("Error happened: " + fault);
						}
					}
				}
	            
				xmlHttpObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
				xmlHttpObj.setRequestHeader("SOAPAction", "str");
				// Execute the request        
				//alert(strAddress);    
				xmlHttpObj.send("str="+ strAddress);
			}
		}
	    
	   
		function showAddress()
		{
				//alert("hello");
				//var addr = document.getElementById("address_ddlAddresses");
				if (gmarkers[99999] != null) map.removeOverlay(gmarkers[99999]);
				//if (addlabel != null) map.removeOverlay(addlabel);
				
				var addr = document.getElementById("ddlAddresses");
				var selectValues = "";
				var x;
				var y;
				var htmlcode;
				for(var i=0; i < addr.options.length; i++)
				{
					selectValues += addr.options[i].value + ":";
					if(addr.options[i].selected)
					{
						var addrID = addr.options[addr.selectedIndex].value;
						var paras = addrID.split("&");
						x = paras[0].substring(paras[0].indexOf("=")+1);
						y = paras[1].substring(paras[1].indexOf("=")+1);

						
					
						selectValues += i + ":";
					}
				}
				
				if(selectValues.length > 0)
				{
					selectValues = selectValues.substring(0, selectValues.length -1);
				}
				
				
							
				var addressicon = new GIcon();
				addressicon.image = "images/blu-blanksmall.png";
				addressicon.iconSize = new GSize(16, 16);
				addressicon.iconAnchor = new GPoint(6, 20);
				addressicon.infoWindowAnchor = new GPoint(5, 1);
				
				var ret={};// holds returned caculated values
				var llCoords = SPCStoLL(x, y, ret);
				var point = new GLatLng(ret.lat, ret.lon);
				var marker = createSimpleMarker(point,addr.options[addr.selectedIndex].text,addressicon,ret.lat,ret.lon,htmlcode,x,y);
				gmarkers[99999]= marker;
				map.addOverlay(marker);	
				
				//var label = new ELabel(new GLatLng(marker.lat,marker.lng), "<div style='background-color:#ccccff;font-weight:bold;border:1px solid black'><font color='black'>" + addr.options[addr.selectedIndex].text + "</font></div>", null, new GSize(-3, 20), 80, false);
				//map.addOverlay(label);
				
				var bounds = new GLatLngBounds();
				bounds.extend(marker.getPoint());
				map.setCenter(marker.getPoint(), 15);
				GEvent.trigger(gmarkers[99999], "click");
					
				if (strFeature == "dohpharmacy") {
					var query="getData.aspx?type=nearest&x="+x+"&y="+y+"&feature=" + strFeature;
					GDownloadUrl(query,  function(text,code){
	
						if (text!="") {
							var ids=text.split(",");
							//GEvent.trigger(gmarkers[id], "click");
							var id;
							for (gm in gmarkers){gmarkers[gm].hide();}
							gmarkers[99999].show();
							for(var j=0; j<ids.length;j++){
								id=parseInt(ids[j]);
								gmarkers[id].show();
								bounds.extend(gmarkers[id].getPoint());
							}
							//bounds.extend(gmarkers[id].getPoint());
							map.setZoom(map.getBoundsZoomLevel(bounds));
							map.setCenter(bounds.getCenter());
						}
					
					
					});
				}
				
				
	
	}
function showAll() {
	var eleAddress = document.getElementById("txtAddress");
	eleAddress.value='';
	var addr = document.getElementById("ddlAddresses");
	addr.options.length = 0;
	for (gm in gmarkers){gmarkers[gm].show();}
	if (gmarkers[99999]) gmarkers[99999].hide();
	map.closeInfoWindow();
	map.setCenter(new GLatLng(38.897000, -77.02000), 11);
}
//chuanyun added July 30. 2009
function correctNav()
{
	//href="http://octo.dc.gov/octo/cwp/view,a,3,q,579547,octoNav,|32777|,.asp"   class="navtax">Employment<br>  Opportunities</A>
	//href="http://octo.dc.gov/octo/cwp/view,a,1302,q,579820,octoNav,|32782|,.asp"   class="navtax">Policies, Guidelines, &<br>  Procedures
	//href="http://octo.dc.gov/octo/cwp/view,A,1301,Q,606616,octoNav,|32782|,.asp"   class="navtax">Program Management<br>  Standards
	//href="http://octo.dc.gov/octo/cwp/view,a,1301,q,604425,octoNav,|32782|,.asp"   class="navtax">Web Standards<br>  and Style</A>
	//href="http://dc.gov/contact/index.htm?octoNav=|"   class="navtax"><FONT FACE='verdana'><b>ONLINE SERVICE<br>  REQUESTS</b>
	
	for(var i=0; i < document.links.length; i++)
	{
		if("http://octo.dc.gov/octo/cwp/view,a,3,q,579547,octoNav,%7C32777%7C,.asp" === document.links[i].href)
		{
			document.links[i].innerHTML = "Employment<br>&nbsp;&nbsp;Opportunities";
		}
		else if("http://dcop.dc.gov/dcop/cwp/view.asp?a=1222&q=530365&dcopnav=|31656|&dohNav=|33110|" === document.links[i].href)
		{
			document.links[i].innerHTML = "Employment<br>&nbsp;&nbsp;Opportunities";
		}
		else if("http://doh.dc.gov/doh/cwp/view,a,1371,q,581507,dohNav_GID,1787,dohNav,%7C33120%7C,.asp" === document.links[i].href)
		{
			document.links[i].innerHTML = "Health&nbsp;Care&nbsp;for&nbsp;Uninsured&nbsp;<br>&nbsp;Immunization";
		}
		else if("http://doh.dc.gov/doh/cwp/view,a,1371,q,581955,dohNav_GID,1787,dohNav,%7C33120%7C,.asp" === document.links[i].href)
		{
			document.links[i].innerHTML = "Birth,&nbsp;Death&nbsp;Certificates";
		}
		else if("http://hrla.doh.dc.gov/hrla/site/default.asp?dohNav=|33120|" === document.links[i].href)
		{
			document.links[i].innerHTML = "Health Regulation and<br>&nbsp;LicensingLicensing";
		}
		else if("http://octo.dc.gov/octo/cwp/view,a,1302,q,579820,octoNav,%7C32782%7C,.asp" === document.links[i].href)
		{
			document.links[i].innerHTML = "Policies, Guidelines, <br>&nbsp;&nbsp;Procedures";
		}
		else if("http://octo.dc.gov/octo/cwp/view,A,1301,Q,606616,octoNav,%7C32782%7C,.asp" === document.links[i].href)
		{
			document.links[i].innerHTML = "Program Management<br>&nbsp;&nbsp;Standards";
		}
		else if("http://octo.dc.gov/octo/cwp/view,a,1301,q,604425,octoNav,%7C32782%7C,.asp" === document.links[i].href)
		{
			document.links[i].innerHTML = "Web Standards<br>&nbsp;&nbsp;and Style";
		}
		else if("http://dc.gov/contact/index.htm?octoNav=|" === document.links[i].href)
		{
			document.links[i].innerHTML = "<FONT FACE='verdana'><b>ONLINE SERVICE<br>&nbsp;&nbsp;REQUESTS</b>";
		}
		else if("http://hpla.doh.dc.gov/" === document.links[i].href)
		{
			document.links[i].innerHTML = "Professional&nbsp;Licensing";
		}
		else if("http://doh.dc.gov/doh/cwp/view,a,3,q,573086,dohNav_GID,1802,dohNav,%7C33200%7C,.asp" === document.links[i].href)
		{
			document.links[i].innerHTML = "Administrations<br>&nbsp;& Offices";
		}
		else if("http://doh.dc.gov/doh/cwp/view,a,1370,q,574808,dohNav_GID,1787,dohNav,%7C33139%7C,.asp" === document.links[i].href)
		{
			document.links[i].innerHTML = "Health&nbsp;Phone&nbsp;Numbers";
		}
		
	}
		
}

