
// POPULATE COUNTY PULLDOWN LIST

function initCntyCoord(){ 

var pulldown =""
pulldown += '<h2 class="title">West Virginia National Register Interactive Map</h2>'
pulldown += '<select name="selectCounty" id="selectCounty" size="1" style="font-size: 8pt" onchange="setcounty(this.value);"><option selected name="Select a county">Select a county</option>'
for (var i=0; i<55; i++){
		countyinfo = cntyCoord[i].split("|");
		pulldown += '<option value="'+cntyCoord[i]+'">'+countyinfo[0]+'</option>'
		 
	}
pulldown += '</select>'
document.getElementById("places").innerHTML = pulldown
}


// MASTER MAP FUNCTION.  
// Loads County points from countycity.js.  Loads SHPO point data past a certain zoom or based upon URL string declaration.
function load() { 

    if (GBrowserIsCompatible()) {

	
			// Read URL for variables so map can be directed to auto-click
			//  ZOOM TO COUNTY: http://url.com/kmlviewer.html?c=Monongalia
			//  ZOOM TO POINT WITHIN COUNTY: http://url.com/kmlviewer.html?c=Brown Building
			currentid=false
			clicked =false
			id ="";
			index = -1;
			url = ""
			var query = location.search.substring(1);
			var pairs = query.split("&");
			for (var i=0; i<pairs.length; i++) {
					// break each pair at the first "=" to obtain the argname and value
					var pos = pairs[i].indexOf("=");
					var argname = pairs[i].substring(0,pos).toLowerCase();
					var value = pairs[i].substring(pos+1).toLowerCase();
					// process each possible argname  -  use unescape() if theres any chance of spaces
					if (argname == "c") {url = unescape(value);}
					if (argname == "id") {id = unescape(value);}
					if (argname == "marker") {index = parseFloat(value);}
		      }
			
			//DECLARE ALL OTHER VARIABLES
			bounds = new GLatLngBounds();
			sidebar_title=""
			sidebar_table=[];
			gmarkers = []
			gpolys = []
			idmarkers = [];
			active = []
			inactive = []
			placemarks = []
			countysidebar = []
			countymarker =[]
			countyset = []
			countysetarr = []
		
			var options = {
				showOnLoad : true
			};
    
			//DECLARE MAP
			var map = new GMap2(document.getElementById("map"), {googleBarOptions: options});
			themap = map
			map.setCenter(new GLatLng(38.9476105,-80.152943),7); 
			
			//DECLARE MAP LAYERS		
			//WV SAMB orthophotos layer 	
			var copycol = new GCopyrightCollection("");
			var tileWVSAMB= new GTileLayer(copycol,1,18);
			tileWVSAMB.myBuild=1;
			tileWVSAMB.myMercZoomLevel=2;
			tileWVSAMB.myLayers='WV_SAMB_orthophotos_2003_utm83_2ft';
			tileWVSAMB.myFormat='image/png';
			tileWVSAMB.myBaseURL='http://www.mapwv.gov/wmsconnector/com.esri.wms.Esrimap?SERVICENAME=WV_SAMB_Orthophotos_2003_UTM83';
			tileWVSAMB.getTileUrl=CustomGetTileUrl;	
			
			//WV Topo layer	
			var tileTSDrg= new GTileLayer(copycol,1,18);
			tileTSDrg.myBuild=1;
			tileTSDrg.myMercZoomLevel=2;
			tileTSDrg.myLayers='WV_topomap_DRG_24k_utma83';
			tileTSDrg.myFormat='image/png';
			tileTSDrg.myBaseURL='http://www.mapwv.gov/wmsconnector/com.esri.wms.Esrimap?SERVICENAME=WV_Topomap_DRG_24K_UTM83';
			tileTSDrg.getTileUrl=CustomGetTileUrl;
						
			//Layer arrays -- formatted as arrays to handle hybrid layers
			var layerNewHybrid=[tileWVSAMB,G_HYBRID_MAP.getTileLayers()[1]];
			var samb = [tileWVSAMB]
			var topo = [tileTSDrg]
			
			//Layer declaration
			var MapNewHybrid = new GMapType(layerNewHybrid, G_SATELLITE_MAP.getProjection(), "Hybrid ", G_SATELLITE_MAP);
			var mapAerial = new GMapType(samb, G_SATELLITE_MAP.getProjection(), "Aerial", G_SATELLITE_MAP);
			var mapTopo = new GMapType(topo, G_NORMAL_MAP.getProjection(), "Topo", G_SATELLITE_MAP);
			var mapTerrain = new GMapType(G_PHYSICAL_MAP.getTileLayers(), G_PHYSICAL_MAP.getProjection(), "Terrain", G_SATELLITE_MAP);
			
			//prevent default google map buttons
			map.getMapTypes().length = 0;
			
			//Add layers and controls to map
			map.addMapType(MapNewHybrid);
			map.addMapType(mapAerial);
			map.addMapType(mapTopo);
			map.addMapType(mapTerrain);
			map.setMapType(MapNewHybrid);
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());
			//Add GoogleBar on bottom -- search control
			map.addControl(new GScaleControl(),
			new GControlPosition(G_ANCHOR_BOTTOM_LEFT,new GSize(0,32))); 
			map.enableGoogleBar()
			
			//Declare custom point makrer
			var bluepin = new GIcon(); 
			bluepin.image = 'images/blue.png';
			bluepin.shadow = 'images/shadow.png';
			bluepin.transparent = 'images/blank_trans.png';
			bluepin.iconSize = new GSize(32, 32);
			bluepin.shadowSize = new GSize(59, 32);
			bluepin.iconAnchor = new GPoint(15, 32);
			bluepin.infoWindowAnchor = new GPoint(16, 1);
			
			//Declare custom county makrer
			var county = new GIcon(); 
			county.image = 'images/blue-circle.png';
			county.shadow = '';
			county.transparent = 'images/blank_trans.png';
			county.iconSize = new GSize(32, 19);
			county.shadowSize = new GSize(59, 32);
			county.iconAnchor = new GPoint(15, 0);
			county.infoWindowAnchor = new GPoint(16, 1);
			
			//Declare markers within custom marker array
			customIcons = [];
			customIcons["bluepin"] = bluepin	
			customIcons["county"] = county
			
			
			//Read county javascript file upon page load and display county points.  
			// "cntyCoord" variable declared in "countycity.js"
				readJS(cntyCoord)
				jsactive = true
			

		
			//Zoom to county if specified in url
			if (url) {
				for (var i=0; i<55; i++){
				countyinfo = cntyCoord[i].split("|");
				if (countyinfo[0].toLowerCase() == url) {
					setcounty(cntyCoord[i])
					parsecounty()
					countyactive = countyinfo[0]
					}
				}									
			}
					
			// Change point layer depending on zoom level.  Under Zoom 10 show counties.  Above Zoom 10, show point locations.		
			GEvent.addListener(map, "moveend", function() {
					
					if (themap.getZoom() <= 10) {
						if (!jsactive)
						{
							clearMap()
							readJS(cntyCoord)
							jsactive = true
						}
					}
					else if (themap.getZoom() > 10) {
						parsecounty()
					}
	
				})
				
				

			
			// display a warning if the browser was not compatible
				 
		} else {
		  alert("Sorry, the Google Maps API is not compatible with this browser");
		}		
	}
	
	
	
//Determines what KML (.xml) files to load (or unload) based upon map extent.  
function parsecounty() {

		//Clear map of county points
		if (jsactive == true)
		{
		clearMap()
		jsactive = false
		}
		var dir = 'kml/'  // THE DIRECTORY OF THE XML FILES
		
		// Loop through and extract values within county array (cntyCoord).  
		for (var i=0; i<cntyCoord.length; i++) {
			var countyarr = cntyCoord[i].split("|");
			var countyboundsarr = countyarr[3].split(",");
			var thebounds = new GLatLngBounds(new GLatLng(parseFloat(countyboundsarr[0]), parseFloat(countyboundsarr[1])), new GLatLng(parseFloat(countyboundsarr[2]), parseFloat(countyboundsarr[3])))
			
			// if the current county is outside current map extent
			if (!thebounds.intersects(themap.getBounds())) {
				//if the map has been declared as active...
				if (active[countyarr[0]] && countysetarr[countyarr[0]]) {
					//if the key in each child element is equal to the current county, remove the marker.
					for (key in countysetarr[countyarr[0]]) {
							if (key.indexOf(countyarr[0]) != -1) {
						
								themap.removeOverlay( countysetarr[countyarr[0]][key] );
							}
						}
					
					//if the key in each child element is equal to the current county, remove sidebar entry
					for (key in sidebar_table) {
						if (key.indexOf(countyarr[0]) != -1) {
							sidebar_table[key] = ""
							}
						}
					
					// remove county from all working arrays	
					active[countyarr[0]] = ""
					countysetarr[countyarr[0]] = ""
					// redraw the sidebar
					printSidebar()
				}
				
			// if the current county is INSIDE current map extent				
			} else {
				// if county has not already been loaded (delcared active)
				if (!active[countyarr[0]]) {
					readXML(dir+countyarr[4],countyarr[0])
					//if polygon layer is declared
					if (countyarr[5]) {
						readXML(dir+countyarr[5],countyarr[0])
					}
					active[countyarr[0]] = countyarr[0]	
				
				}	
			}
		}
	}



//Loads county layer from javascript array
function readJS(dataarray) {
		for (var i=0; i<dataarray.length; i++) {
		var countyinfo = dataarray[i].split("|");
		var countycoord = new GLatLng(parseFloat(countyinfo[2]),parseFloat(countyinfo[1]))
		var marker = createMarker(countycoord,countyinfo[0],countyinfo[0],i,"county")
		countymarker[i] = marker
		themap.addOverlay(countymarker[i]);
		}
		printSidebar()
		}

 
 //Loads SHPO point layer from KML file.
 function readXML(url,countyname) {
	  //AJAX Call
	  var request = GXmlHttp.create();
	  request.open("GET", url, true);
	  request.onreadystatechange = function() {
			if (request.readyState == 4) {
				var xmlDoc = GXml.parse(request.responseText);
				var docname = xmlDoc.documentElement.getElementsByTagName("name");
				var placemarks = xmlDoc.documentElement.getElementsByTagName("Placemark");
				if (sidebar_title=="") {
				//Add a title within the sidebar
				//sidebar_title  += '<h3 class="title">' + GXml.value(docname[0]) +  '</h3>'
				 }
				
				for (var i = 0; i < placemarks.length; i++) {
						var name=GXml.value(placemarks[i].getElementsByTagName("name")[0]);
						var coords=GXml.value(placemarks[i].getElementsByTagName("coordinates")[0]);
						var path = coords.split(" ");
						
						//unique marker ID that maintains trailing zeros
						var lab = coords.split(",");
						var regEx2 = /[0]+$/;
						var label  = lab[1].replace(regEx2,'')
						
						var desc=GXml.value(placemarks[i].getElementsByTagName("description")[0]);
						
						var refStart = desc.indexOf("REFNUM") + 61 + 6; //61 characters plus 6 letters of "REFNUM"
						var refEnd = desc.indexOf("<", refStart);
						
									
						var countyStart = desc.indexOf("<b>COUNTY") + 61 + 9; //61 characters plus 9 letters of "<b>COUNTY"
						var countyEnd = desc.indexOf("<", countyStart);
						var pointInfo  = new Array (desc.substring(refStart, refEnd), desc.substring(countyStart,countyEnd) );
						var pdfURL = "http://www.wvculture.org/shpo/nr/pdf/" + pointInfo[1].toLowerCase() + "/" + pointInfo[0].toString() + ".pdf"
				
					
						
						
						desc = '<div id="attributes">' + desc + '</div>'
					
						  
						  // Is this the polyline?
						  if (path.length > 2) {
									var points = [];
									for (var p=0; p<path.length-1; p++) {
									   var bits = path[p].split(",");
									   var point = new GLatLng(parseFloat(bits[1]),parseFloat(bits[0]));
									   points.push(point)          
									   if (p==0) {
									  // /*  start point */
									  //Create sidebar entry for just one vertex of the polygon
									  createSidebar(name,label,"poly", desc, countyname)
									  desc += '<div id="infoBubbleLinks"><img src="images/ajax-loader.gif"> Searching for links...'
									   }
									   if (p==path.length-2) {
										// /*  end point */
									   }
									}
									
									// Create polygon marker object
									var poly = createPoly(themap,points,name,desc,label,countyname,pointInfo);
									themap.addOverlay(poly);
									
									//If marker is declared in URL, click the polygon
									if (name.toLowerCase() == id && !clicked) 
									  {
										polyclick(label)
										clicked = true
									  }
									  
							// Not a polygon, the feature is a point		  
							} else {
								var bits = path[0].split(",");
								var point = new GLatLng(parseFloat(bits[1]),parseFloat(bits[0]));
								
								// Create point marker object -- sidebar entry is created within this function
								var marker = createMarker(point,name,desc,label,"point",countyname,pointInfo);
								themap.addOverlay(marker);
							}
								//If marker is declared in URL, click the point	  
								if (name.toLowerCase() == id && !clicked) 
								  {
									myclick(label)
									clicked = true
								  }
				}
				
				// Draw the sidebar after all points have been delcared
				printSidebar()
				
					  

			}

		}
		
		//Add all county points to own array element so they may be later removed
		countysetarr[countyname] = countyset
		
		//close ajax call
		request.send(null);

}



// Create sidebar.  Change link declaration depending on point type
function createSidebar(name,i,type,html,countyname) {
		if (type == "poly") {
				// store county and point name info in array key
				sidebar_table[name+i+countyname]  = '<li class="poly"><a href="javascript:polyclick(' + i + ',\'poly\')" onmouseover="polycolor(\'#de5446\','+i+')" onmouseout="polycolor(\'#6181e0\','+i+')">' + name + '</a></li>';
					}
					
		if (type == "point") {
				// store county and point name info in array key
				sidebar_table[name+i+countyname]  = '<li class="listpin"><a href="javascript:myclick(' + i + ',\'point\')" onmouseover="gmarkers['+i+'].setImage(\'images/red.png\')" onmouseout="gmarkers['+i+'].setImage(\'images/blue.png\')" class="listmarker">' + name + '</a></li>';
			}
	   if (type == "county") {
			 sidebar_table[name]  = '<li class="listcounty"><a href="javascript:myclick(' + i + ',\'county\')" onmouseover="GEvent.trigger(gmarkers['+i+'],\'click\');gmarkers['+i+'].setImage(\'images/red-circle.png\')" onmouseout="gmarkers['+i+'].setImage(\'images/blue-circle.png\')" class="listmarker">' + name + ' County</a></li>';
		}
}

//Resort sidebar alphabetically, and print.
function printSidebar() {
		array = sidebar_table;
		var sidebar_print=''
		keys = new Array();
		for(k in array) {
			keys.push(k);
		}
		keys.sort( function (a, b){return (a > b) - (a < b);} );
		
		sidebar_print += '<div class="listcontainer"><ul class="list">'
		for (var i = 0; i < keys.length; i++) {
			sidebar_print += array[keys[i]];
		}
		sidebar_print += '</ul></div>'

	   document.getElementById("sidebar").innerHTML = sidebar_title + sidebar_print ;
	   
}

//Clear all variables, features, and sidebar
function clearMap() {
	sidebar_title=""
	loaded = ""
	sidebar_table=[];
	gmarkers = []
	gpolys = []
	idmarkers = [];
	countymarker =[]
	countyset = []
	countypointnames = []
	countysetarr = []
	active = []
	placemarks = []
	countymarker =[]
	themap.clearOverlays();
	document.getElementById("sidebar").innerHTML = "" ;
}


//Create point marker
function createMarker(point,name,html,i,layer,countyname,pointInfo) {
	
	
	//show icons and HTML bubble for county points
	if (layer == "county") {
	
		var marker = new GMarker(point, customIcons["county"]);
		createSidebar(name, i, "county", html, countyname)
		html = '<a href="javascript:myclick('+i+',\'county\')">Show all locations around<h2>'+html+' County</h2>';
		
		GEvent.addListener(marker, "click", function() {
		  marker.openInfoWindowHtml(html);
		  marker.setImage("images/red-circle.png");
		  
	
		});
	
		GEvent.addListener(marker, "mouseover", function() {
		  marker.setImage("images/red-circle.png");
		});
		GEvent.addListener(marker, "mouseout", function() {
		  marker.setImage("images/blue-circle.png");
		})	
	

	//show icons and HTML bubble for SHPO points	
	} else {
		var marker = new GMarker(point, customIcons["bluepin"]);
		createSidebar(name, i, "point", html, countyname)
		html += '<div id="infoBubbleLinks"><img src="images/ajax-loader.gif"> Searching for links...'
		
		GEvent.addListener(marker, "click", function() {
		
		  marker.openInfoWindowHtml(html);
		  marker.setImage("images/red.png");
		  validurls = []
		  fetchurl = "fetchlinks.php?id=" + pointInfo[0] + "&county=" + pointInfo[1].toLowerCase()
		  
		  		GDownloadUrl(fetchurl, function(data, responseCode) {
				 if(responseCode == 200) {
					validurls = data.split('|')
					setTimeout("updateWindow(validurls)",500)
				
				}
				
			});
			
						



						
		
			});
		  
		  
		
	
		GEvent.addListener(marker, "mouseover", function() {
		  marker.setImage("images/red.png");
		});
		GEvent.addListener(marker, "mouseout", function() {
		  marker.setImage("images/blue.png");
		});
	
	}
	
	// array of all markers
	gmarkers[i] = marker;
	// array of markers for one county -- county name in key, adds i variable to keep key unique
	countyset[countyname+i] = marker
	// array of markers for URL parse
	idmarkers[name.toLowerCase()] = marker;			
	i++;
	
	return marker;
 }
  
 function updateWindow(array) {
 
				if (array.length > 0) {
				
				document.getElementById("infoBubbleLinks").innerHTML = ''
				for (var i = 0; i < array.length; i++) {
				if (array[i]) {
				var f_ext = array[i].match(/(.{3}$)/)[1];
				
				if (f_ext == 'pdf') {
						var image = '<img src="images/pdficon.gif">'
					} else if (f_ext == 'jpg' || f_ext == 'tif') {
						var image = '<img src="images/jpeg_icon.jpg">'
					} else {
						var image = ''
					}
				document.getElementById("infoBubbleLinks").innerHTML += image + '<a href="' +array[i] +'" target="_blank" id="infoBubbleLinksText">View ' + f_ext + "</a>"
				}
				else {
				document.getElementById("infoBubbleLinks").innerHTML = 'No links found'
				}
 }
 }
 }
  
  
//Create polygon  
function createPoly(map,points,name,html,i,countyname,pointInfo) {
	var poly = new GPolygon(points, '#7070cc', 3, .5, '#6181e0', .5)
  
	GEvent.addListener(poly, "click", function() {
		map.openInfoWindowHtml(poly.getBounds().getCenter(),html);
		
		  fetchurl = "fetchlinks.php?id=" + pointInfo[0] + "&county=" + pointInfo[1].toLowerCase()
		  
		  		GDownloadUrl(fetchurl, function(data, responseCode) {
				 if(responseCode == 200) {
					validurls = data.split('|')
					setTimeout("updateWindow(validurls)",500)
				
				}
				
			});
		
		
	});
	
	GEvent.addListener(poly, "mouseover", function() {
	poly.color = "#de5446";
	poly.redraw(true); 
	})	
	
	GEvent.addListener(poly, "mouseout", function() {
	poly.color = "#6181e0";
	poly.redraw(true); 
	})	
	
	// array of polygons for one county
	countyset[countyname+i] = poly
	// array of polygons for one county
	gpolys[i] = poly;
	idmarkers[name.toLowerCase()] = poly;
	
	i++
	
	return poly;
  
 }
  

// Declare polygon color for mouseover/mouseout
function polycolor(color,i) {
			gpolys[i].color = color;
			gpolys[i].redraw(true); 
}


// Event when polygon is clicked
function polyclick(i) {
	  themap.setCenter(gpolys[i].getBounds().getCenter(),16)
		GEvent.trigger(gpolys[i],"click");
}
  
  
// Event when sidebar county item is hovered over
function myhover(i,html) {
	var html = '<a href="javascript:myclick('+i+',\'county\')">Show all locations around<h2>'+html+' County</h2>'
	  gmarkers[i].openInfoWindowHtml(html);
	   GEvent.trigger(gmarkers[i],"click");
}
	
	
// Event when point is clicked 
function myclick(i,type) {
  
		if (type=="county") {
		themap.setCenter(gmarkers[i].getPoint(),11)
		} else {
	  
		if (themap.getCurrentMapType().getName() == "Terrain")
			  {
			  themap.setCenter(gmarkers[i].getPoint(),15)
				  GEvent.trigger(gmarkers[i],"click")
			  } 
	  else {
	   themap.setCenter(gmarkers[i].getPoint(),17)
		GEvent.trigger(gmarkers[i],"click")
		}
	  
	  
	  }
  }
  
 // Zoom to county when chosen in pulldown.
function setcounty(coords) {
  
	var coordsplit = new Array;
	coordsplit = coords.split("|");
	themap.setCenter(new GLatLng(parseFloat(coordsplit[2]),parseFloat(coordsplit[1])), 11);
	thecounty=coordsplit[0]
	
 }
  
