var uc={
	config: {
		shiftZoom: false
	},
	mode: 'default',
	apiBase: 'http://gisapps.co.union.nc.us/ws/rest/v2/',
	ctrlKey: false,
	map: null,
	iw: new google.maps.InfoWindow({maxWidth:444,zIndex:100}),
	ac: null,
	maxResults: 200,
	streetView: null,
	searchDistance: 10,
	isIPad: navigator.userAgent.match(/iPad/i),
	fallbackSelectableLayer: {
		datasource: 'parcels',
		name: 'Parcels',
		layerType: 'polygon',
		overlayMap: null,
		fields: '&fields=gid,acctno,owner1,owner2,address,x(ST_PointOnSurface(transform(the_geom,4326)))+as+lon,y(ST_PointOnSurface(transform(the_geom,4326)))+as+lat,st_asgeojson(transform(simplify(the_geom,1),4326),6)+AS+geojson',
		tFields: '&fields=t.gid,t.acctno,t.owner1,t.owner2,t.address,x(ST_PointOnSurface(transform(t.the_geom,4326)))+as+lon,y(ST_PointOnSurface(transform(t.the_geom,4326)))+as+lat,st_asgeojson(transform(simplify(t.the_geom,1),4326),6)+AS+geojson',
		short_desc1:{
			pre: '<a class="result-info" href="javascript:void(0);" title="Click for Feature Info">',
			field:'acctno',
			post: '</a>'
		},
		short_desc2: {
			pre: '',
			field: 'owner1',
			post: ''
		}
	},
	selectableLayers: [],
	styles: {
		marker: {
			normal: function(){
				return {
					icon: 'images/markers/yellow.png'
				};
			},
			highlight: function(){
				return {
					icon: 'images/markers/red.png'
				};
			}
		},
		polyline: {
			normal: function(){
				return {
					strokeColor:'#FF0000',
					strokeOpacity:0.75,
					strokeWeight:5
				};
			},
			highlight: function(){
				return {
					strokeColor:'#FFFF00',
					strokeWeight:7
				};
			}
		},
		polygon: {
			normal: function(){
				return {
					strokeColor: "#FF7800",
					strokeOpacity: 1,
					strokeWeight: 2,
					fillColor: "#46461F",
					fillOpacity: 0.25
				};
			},
			highlight: function(){
				return{
					fillOpacity:0.75
				};
			}
		}
	},
	polygons: {
		items: [],
		removeAll: function(){
			$.each(this.items, function(i, n){
				n.polygon.setMap(null);
			});
			this.items=[];
		}
	},
	lines:{
		items:[],
		removeAll: function(){
			$.each(this.items,function(i,n){
				n.polyline.setMap(null);
			});
		}
	},
	markers: {
		items:[],
		removeAll: function(){
			$.each(this.items,function(i,n){
				n.setMap(null);
			});
			this.items=[];
		}
	},
	measure:{
		ll_line: new google.maps.MVCArray(),
		ll_poly: new google.maps.MVCArray(),
		markers:[],
		line:null,
		poly:null
	},
	overlayMaps:[
		{
			name:'FEMA Flood Zones', 
			visible:false,
			legend:'images/legend/flood-zones.png', 
			config:{ 
				getTileUrl: function(coord, zoom){
					return 'http://gisapps.co.union.nc.us:8080/geoserver/gwc/service/gmaps?layers=uc%3Afema_flood_zones&zoom=' + zoom + '&x=' + coord.x + '&y=' + coord.y + '&format=image/png8';
				},tileSize: new google.maps.Size(256,256),
				isPng:true,
				opacity:0.5
			},
			selectableLayers: [
				{
					datasource: 'fema_flood_zones',
					name: 'FEMA Flood Zones',
					layerType: 'polygon',
					overlayMap: 'FEMA Flood Zones',
					fields: '&fields=gid,label,\'\'+as+nada,st_asgeojson(transform(the_geom,4326))+AS+geojson',
					tFields: '&fields=t.gid,t.label,\'\'+as+nada,st_asgeojson(transform(t.the_geom,4326))+AS+geojson',
					short_desc1:{
						pre: 'Flood Zone Type: ',
						field:'label',
						post: ''
					},
					short_desc2: {
						pre: '',
						field: 'nada',
						post: ''
					}
				}
			]
		},{
			name:'Municipalities', 
			visible:false,
			legend:'images/legend/municipal.png', 
			config:{ 
				getTileUrl: function(coord, zoom){
					return 'http://gisapps.co.union.nc.us:8080/geoserver/gwc/service/gmaps?layers=uc%3Amunicipalities&zoom=' + zoom + '&x=' + coord.x + '&y=' + coord.y + '&format=image/png8';
				},tileSize: new google.maps.Size(256,256),
				isPng:true,
				opacity:0.5
			},
			selectableLayers: [
				{
					datasource: 'municipalities',
					name: 'Municipalities',
					layerType: 'polygon',
					overlayMap: 'Municipalities',
					fields: '&fields=gid,name,\'\'+as+nada,st_asgeojson(transform(the_geom,4326))+AS+geojson',
					tFields: '&fields=t.gid,t.name,\'\'+as+nada,st_asgeojson(transform(t.the_geom,4326))+AS+geojson',
					short_desc1:{
						pre: 'Municipality: ',
						field:'name',
						post: ''
					},
					short_desc2: {
						pre: '',
						field: 'nada',
						post: ''
					}
				}
			]
		},{
			name:'Subdivisions', 
			visible:false,
			legend:'images/legend/subdivisions.png', 
			config:{ 
				getTileUrl: function(coord, zoom){
					return 'http://gisapps.co.union.nc.us:8080/geoserver/gwc/service/gmaps?layers=uc%3Asubdivisions&zoom=' + zoom + '&x=' + coord.x + '&y=' + coord.y + '&format=image/png8';
				},tileSize: new google.maps.Size(256,256),
				isPng:true,
				opacity:1
			},
			selectableLayers: [
				{
					datasource: 'subdivisions',
					name: 'Subdivisions',
					layerType: 'polygon',
					overlayMap: 'Subdivisions',
					fields: '&fields=gid,name,\'\'+as+nada,st_asgeojson(transform(the_geom,4326))+AS+geojson',
					tFields: '&fields=t.gid,t.name,\'\'+as+nada,st_asgeojson(transform(t.the_geom,4326))+AS+geojson',
					short_desc1:{
						pre: 'Subdivision: ',
						field:'name',
						post: ''
					},
					short_desc2: {
						pre: '',
						field: 'nada',
						post: ''
					}
				}
			]
		},{
			name:'Water', 
			visible:false,
			legend:'images/legend/water.png', 
			config:{ 
				getTileUrl: function(coord, zoom){
					return 'http://gisapps.co.union.nc.us:8080/geoserver/gwc/service/gmaps?layers=wtr_base&zoom=' + zoom + '&x=' + coord.x + '&y=' + coord.y + '&format=image/png8';
				},tileSize: new google.maps.Size(256,256),
				isPng:true,
				opacity:1
			},
			selectableLayers: [
				{
					datasource: 'wtr_hydrant',
					name: 'Fire Hydrant',
					layerType: 'point',
					overlayMap: 'Water',
					fields: '&fields=gid,\'\'+as+nada,x(transform(the_geom,4326))+as+lon,y(transform(the_geom,4326))+as+lat,st_asgeojson(transform(the_geom,4326))+AS+geojson',
					tFields: '&fields=t.gid,\'\'+as+nada,x(transform(t.the_geom,4326))+as+lon,y(transform(t.the_geom,4326))+as+lat,st_asgeojson(transform(t.the_geom,4326))+AS+geojson',
					short_desc1:{
						pre: '',
						field:'nada',
						post: 'Fire Hydrant'
					},
					short_desc2: {
						pre: '',
						field: 'nada',
						post: ''
					}
				},{
					datasource: 'wtr_main',
					name: 'Water Main',
					layerType: 'line',
					overlayMap: 'Water',
					fields: '&fields=gid,round(diameter,0)+as+pipe_dia,material,st_asgeojson(transform(the_geom,4326))+AS+geojson',
					tFields: '&fields=t.gid,round(t.diameter,0)+as+pipe_dia,t.material,st_asgeojson(transform(t.the_geom,4326))+AS+geojson',
					short_desc1:{
						pre: '',
						field:'pipe_dia',
						post: '" Water Main'
					},
					short_desc2: {
						pre: 'Material: ',
						field: 'material',
						post: ' '
					}
				}
			]
		},{
			name:'Sewer', 
			visible:false,
			legend:'images/legend/sewer.png', 
			config:{ 
				getTileUrl: function(coord, zoom){
					return 'http://gisapps.co.union.nc.us:8080/geoserver/gwc/service/gmaps?layers=swr_base&zoom=' + zoom + '&x=' + coord.x + '&y=' + coord.y + '&format=image/png8';
				},tileSize: new google.maps.Size(256,256),
				isPng:true,
				opacity:1
			},
			selectableLayers: [
				{
					datasource: 'swr_mh',
					name: 'Man Hole',
					layerType: 'point',
					overlayMap: 'Sewer',
					fields: '&fields=gid,round(mh_dia,0)+as+mh_dia,\'\'+as+nada,wwtp,x(transform(the_geom,4326))+as+lon,y(transform(the_geom,4326))+as+lat,st_asgeojson(transform(the_geom,4326))+AS+geojson',
					tFields: '&fields=t.gid,round(t.mh_dia,0)+as+mh_dia,\'\'+as+nada,t.wwtp,x(transform(t.the_geom,4326))+as+lon,y(transform(t.the_geom,4326))+as+lat,st_asgeojson(transform(t.the_geom,4326))+AS+geojson',
					short_desc1:{
						pre: '',
						field:'nada',
						post: 'Man Hole'
					},
					short_desc2: {
						pre: 'Flows to ',
						field: 'wwtp',
						post: ' WWTP'
					}
				},{
					datasource: 'swr_gravity',
					name: 'Gravity Sewer',
					layerType: 'line',
					overlayMap: 'Sewer',
					fields: '&fields=gid,round(pipe_dia,0)+as+pipe_dia,wwtp,st_asgeojson(transform(the_geom,4326))+AS+geojson',
					tFields: '&fields=t.gid,round(t.pipe_dia,0)+as+pipe_dia,t.wwtp,st_asgeojson(transform(t.the_geom,4326))+AS+geojson',
					short_desc1:{
						pre: '',
						field:'pipe_dia',
						post: '" Gravity Sewer'
					},
					short_desc2: {
						pre: 'Flows to: ',
						field: 'wwtp',
						post: ' WWTP'
					}
				},{
					datasource: 'swr_fm',
					name: 'Force Sewer',
					layerType: 'line',
					overlayMap: 'Sewer',
					fields: '&fields=gid,round(fm_dia,0)+as+pipe_dia,wwtp,st_asgeojson(transform(the_geom,4326))+AS+geojson',
					tFields: '&fields=t.gid,round(t.fm_dia,0)+as+pipe_dia,t.wwtp,st_asgeojson(transform(t.the_geom,4326))+AS+geojson',
					short_desc1:{
						pre: '',
						field:'pipe_dia',
						post: '" Force Sewer'
					},
					short_desc2: {
						pre: 'Flows to: ',
						field: 'wwtp',
						post: ' WWTP'
					}
				}
			]
		},{
			name:'Parcels', 
			visible:false,
			legend:'images/legend/parcels.png', 
			config:{ 
				getTileUrl: function(coord, zoom){
					return 'http://gisapps.co.union.nc.us:8080/geoserver/gwc/service/gmaps?layers=uc%3Aparcels&zoom=' + zoom + '&x=' + coord.x + '&y=' + coord.y + '&format=image/png8';
				},tileSize: new google.maps.Size(256,256),
				isPng:true,
				opacity:1
			}
		}
	],
	baseMaps:[
		{
			name: "Union",
			alt: "Union Base Map",
			getTileUrl: function(coord, zoom){
				return 'http://gisapps.co.union.nc.us:8080/geoserver/gwc/service/gmaps?layers=Basemap&zoom=' + zoom + '&x=' + coord.x + '&y=' + coord.y + '&format=image/png8';
			},
			tileSize: new google.maps.Size(256,256),
			isPng: true,
			maxZoom: 18,
			minZoom: 9
		},{
			name: "OSM",
			alt: "OpenStreetMap",
			credits: 'Tiles Courtesy of <a href="http://www.mapquest.com/" target="_blank">MapQuest</a>',
			getTileUrl: function(coord, zoom){
				var subdomains = ["otile1", "otile2", "otile3", "otile4"];
				var subdomain = subdomains[(coord.x + coord.y) % subdomains.length];
				return "http://" + subdomain + ".mqcdn.com/tiles/1.0.0/osm/" + zoom + "/" + coord.x + "/" + coord.y + ".png";
			},
			tileSize: new google.maps.Size(256,256),
			isPng: true,
			maxZoom: 18,
			minZoom: 9
		}
	],
	infoWindows:{
		items:[],
		removeAll: function(){
			$.each(this.items,function(i,n){
				n.close();
			});
			this.items=[];
		}
	},
	selectedFeatures: {
		items:[],
		remove:function(gid){
			var feat=this.getFeatureRef(gid);
			if (feat){
				feat[feat.gType].setMap(null);
				this.items.splice(feat.index,1);
				$('#tr-'+gid).remove();
				FormatResults();
			}
		},
		zoomTo: function (gid){
			var feat = this.getFeatureRef(gid);
			if (feat){
				if (feat.gType=="marker"){
					uc.map.setCenter(feat.marker.getPosition());
					uc.map.setZoom(17);
				}else{
					uc.map.fitBounds(feat[feat.gType].Bounds());
				}
			}
		},
		showIW:function(gid,LL){
			$.getJSON(uc.apiBase + "cm_iw.ashx?gid=" + gid + "&callback=?", function(data){
				uc.iw.setContent(data.content);
				uc.iw.open(uc.map, new google.maps.Marker({
					position: LL
				}));
				$("ul.tabs").tabs("div.panes > div");
			});
		},
		showStreetView:function(gid){
			var feat = this.getFeatureRef(gid);
			var svService = new google.maps.StreetViewService();
			svService.getPanoramaByLocation(feat.LL,150,function(svData,svStatus){
				if(svStatus=='OK'){
					var center = uc.map.getCenter();
					$('#map').css('height','50%');
					$('#street-view').show();
					google.maps.event.trigger(uc.map,'resize');
					uc.map.setCenter(center);
					uc.streetView.setVisible(true);
					uc.streetView.setPosition(svData.location.latLng);
					uc.streetView.setPov({heading:computeAngle(feat.LL,svData.location.latLng),pitch:0,zoom:1});
				}else{
					Message('Sorry! No Street View is available for this feature.');
				}
			});
		},
		getFeatureRef:function(gid){
			var feat;
			$.each(this.items,function(i,n){
				if(n.gid==gid){
					feat=n;
					feat.index=i;
					return false;
				}
			});
			return feat;
		},
		removeAll:function(){
			$.each(this.items,function(i,n){
				n[n.gType].setMap(null);
			});
			this.items=[];
		},
		highlight:function(gid){
			var feat=this.getFeatureRef(gid);
			feat[feat.gType].setOptions(uc.styles[feat.gType].highlight());
			$('#tr-'+gid).addClass('trhighlight');
		},
		highlightRestore:function(gid){
			var feat=this.getFeatureRef(gid);
			feat[feat.gType].setOptions(uc.styles[feat.gType].normal());
			$('#tr-'+gid).removeClass('trhighlight');
		},
		getAllBounds:function(){
			var bounds = new google.maps.LatLngBounds();
			$.each(this.items,function(i,n){
				if (n.gType=="marker"){
					bounds.extend(n.marker.getPosition());
				}else{
					bounds.union(n[n.gType].Bounds());
				}
			});
			return bounds;
		},
		promptBuffer:function(id,fromDatasource){
			$('.row-buffer').remove();
			var options = '';
			$.each(uc.selectableLayers,function(i,n){
				options += '<option value="' + i + '">' + n.name + '</option>';
			});
			options += '<option value="parcels">Parcels</option>';
			var html='<tr class="row-buffer"><td colspan="4">Select <select id="buffer-layer">' + options + '</select> within <input id="buffer-distance" type="text" value="100"> feet</td><td><input id="buffer-go" type="button" onclick="uc.selectedFeatures.performBuffer(\''+fromDatasource+'\',\''+id+'\',$(\'#buffer-layer\').val(),$(\'#buffer-distance\').val());" value="Go" /></td></tr>';
			$(html).insertAfter('#tr-'+id);	
		},
		performBuffer:function(fromDatasource,id,toDatasource,distance){
			if (parseInt(distance)>500){
				Message('Distance must be less than 500 ft.');
				return;
			}
			getFeatures(toDatasource,'buffer', fromDatasource + ':' + id, null, true, distance);
		}
	},
	initialExtent:new google.maps.LatLngBounds(new google.maps.LatLng(34.814008,-80.840281),new google.maps.LatLng(35.208409,-80.2772061)),
	eventMapClickYes:function(evt){
		var event = google.maps.event.addListener(uc.map, 'click', function(evt){
			if (uc.mode == 'default') {
				getFeatures((uc.selectableLayers.length ? 0 : 'parcels'),'click', null, {
					x: evt.latLng.lng(),
					y: evt.latLng.lat()
				}, false);
			}else{
				measureAdd(evt.latLng);
			}
    	});
		return event;
	},
	eventMapClickNo:function(evt){
		var event = google.maps.event.addListener(uc.map, 'click', function(evt){
			if (uc.mode == 'default') {
				Message('Zoom in closer to select features.');
			}else{
				measureAdd(evt.latLng);
			}
          });
          return event;
	}
};
$(document).ready(function(){
	uc.layout = $('body').layout({
		applyDefaultStyles: false,
		south: {
			size: 20,
			closable: false
		},
		west: {
			size: 350,
			spacing_open: uc.isIPad ? 20 : 15,
			spacing_closed: uc.isIPad ? 20 : 15,
			closable: true
		},
		north: {
			size: 80,
			closable: false
		},
		east: {
			size: 0,
			closable: false
		},
		center: {
			onresize: function(){
				var center = uc.map.getCenter();
				google.maps.event.trigger(uc.map,'resize');
				uc.map.setCenter(center);
			}
		}
	});
    uc.map = new google.maps.Map(document.getElementById("map"), {
        zoom: 10,
        center: new google.maps.LatLng(35.04, -80.557),
		streetViewControl: false,
		draggableCursor: "pointer"
    });
	uc.streetView = new google.maps.StreetViewPanorama(document.getElementById('street-view'),{
		enableCloseButton: true,
		addressControl: false
	});
	uc.map.setStreetView(uc.streetView);
	google.maps.event.addListener(uc.streetView,'closeclick',function(){
		var center = uc.map.getCenter();
		$('#street-view').hide();
		$('#map').css('height','100%');
		google.maps.event.trigger(uc.map,'resize');
		uc.map.setCenter(center);
	});
	var baseHolder = []; 
    $.each(uc.baseMaps, function(index){
    	uc.map.mapTypes.set(this.name, new google.maps.ImageMapType(this));
    	baseHolder.push(this.name);
	});
	uc.map.setOptions({
		mapTypeId: "Union",
		mapTypeControlOptions: {
	 		mapTypeIds: [
				google.maps.MapTypeId.ROADMAP,
				google.maps.MapTypeId.TERRAIN,
				google.maps.MapTypeId.SATELLITE,
				google.maps.MapTypeId.HYBRID
			].concat(baseHolder)
		}
	});
	google.maps.event.addListener(uc.map, "zoom_changed", function(){
		//uc.searchDistance = Math.pow(0.0009, (20 - uc.map.getZoom()));
		if (uc.map.getZoom()>=14 || uc.selectableLayers.length){
			if (uc.mapClick) google.maps.event.removeListener(uc.mapClick);
			uc.mapClick=null;
			uc.mapClick=uc.eventMapClickYes();
		}else{
			if (uc.mapClick) google.maps.event.removeListener(uc.mapClick);
			uc.mapClick = uc.eventMapClickNo();
		}
	});
	google.maps.event.addListener(uc.map, "maptypeid_changed", function(){
		$("#basemap-credits").html(uc.map.getMapTypeId() == "OSM" ? 'Tiles Courtesy of <a href="http://www.mapquest.com/" target="_blank">MapQuest</a>' : "");
	});
	uc.map.controls[google.maps.ControlPosition.BOTTOM_RIGHT].push($("<div id='basemap-credits'></div>")[0]);
	uc.ac = $('#text-search').autocomplete({
		serviceUrl:uc.apiBase+'ac_all.ashx?callback=?',
		minChars: 4,
		maxHeight: 400,
		width: 430,
		deferRequestBy: 100,
		noCache: true,
		onSelect: function(value,data){ProcessACResults(value,data);}
	});
	$('#text-search').click(function(){
		$(this).focus();
		$(this).select();
	}).focus(function(){
		$('#search-options').show();
	}).blur(function(){
		$('#search-options').hide();
	}).keyup(function(event){
		var val=$(this).val();
		if (event.keyCode==13){
			if (val.substring(0,1)=="0"){
				getFeatures('parcels','attribute','acctno=\'' + val + '\'',null,true);
			}else if ($('#last-search').val().length){
				ProcessACResults($('#last-search').val().split(',')[0],$('#last-search').val().split(',')[1]);
			}
		}
    });
	$('#map-options .map-option input').click(function(){
		switch($(this).attr('id')){
			case "check-latlon":
				if ($(this).attr('checked')){
					uc.map_mouseout = google.maps.event.addListener(uc.map,'mouseout',function(){
						$('.ui-layout-south div.right').hide();
					});
					uc.map_mouseover = google.maps.event.addListener(uc.map,'mouseover',function(){
						$('.ui-layout-south div.right').show();
					});
					uc.map_mousemove = google.maps.event.addListener(uc.map,'mousemove',function(evt){
						$('#latitude').text(evt.latLng.lat().toFixed(5));
						$('#longitude').text(evt.latLng.lng().toFixed(5));
					});
				}else{
					if (uc.map_mouseout) google.maps.event.removeListener(uc.map_mouseout);
					if (uc.map_mouseover) google.maps.event.removeListener(uc.map_mouseover);
					if (uc.map_mousemove) google.maps.event.removeListener(uc.map_mousemove);
					$('.ui-layout-south div.right').hide();
				}
				break;
			case "check-limit":
				uc.maxResults = $(this).attr('checked') ? 1000 : 200;
				break;
			case "check-shift-zoom":
				if ($(this).attr('checked')){
					if (uc.config.shiftZoom){
						uc.map.enableKeyDragZoom({
							boxStyle:{border: "2px solid #FF7800",backgroundColor: "#46461F",opacity: 0.5}
						});
						return;
					}
					$.getScript("script/keydragzoom_packed.js", function(){
						uc.config.shiftZoom = true;
						uc.map.enableKeyDragZoom({
							boxStyle:{border: "2px solid #FF7800",backgroundColor: "#46461F",opacity: 0.5}
						});
					});
				}else{
					if (uc.config.shiftZoom)
						uc.map.disableKeyDragZoom();
				}
		}
	}).removeAttr('checked');
	var overlayMapCount = 0;
	$.each(uc.overlayMaps,function(i,n){
		overlayMapCount++;
		uc.map.overlayMapTypes.push(null);
		if (n.visible){
			uc.map.overlayMapTypes.setAt(i,new google.maps.ImageMapType(n.config));
			$.each(n.selectableLayers,function(j,o){
				uc.selectableLayers.push(o);
			});
		}
		$('#layers').append('<div class="legend-item"><div class="div3"><img src="'+n.legend+'" class="rounded5" /></div><div class="selector"><input type="checkbox" id="overlayMaps-'+i+'" class="layer" ' + (n.visible ? 'checked="checked"' : '') + '/><label for="overlayMaps-'+i+'">'+n.name+'</label></div><div class="slider" id="slider-'+i+'" style="display:'+(n.visible ? 'block' : 'none')+';"></div><div id="opacity-'+i+'" style="display:'+(n.visible ? 'block' : 'none')+';">Opacity:&nbsp;<span id="opacity-label-'+i+'">'+n.config.opacity*100+'</span>%</div><div class="clearit"></div></div>');
		if (overlayMapCount==3){
			$('#layers').append('<div class="clearit"></div>');
			overlayMapCount = 0;
		}
		$('#slider-'+i).slider({
			step: 5,
			value: n.config.opacity*100,
			slide: function (evt,ui){
				$('#opacity-label-'+i).text(ui.value);
			},
			stop: function (evt,ui){
				changeOverlayOpacity(i,ui.value);
			}
		});
	});
	$('#map-layers .layer').click(function(){
		var collection = $(this).attr('id').split('-')[0];
		var layerID = parseInt($(this).attr('id').split('-')[1]);
		if ($(this).attr('checked')){
			if (collection=="overlayMaps"){
				uc.map.overlayMapTypes.setAt(layerID,new google.maps.ImageMapType(uc.overlayMaps[layerID].config));
				$('#slider-'+layerID+',#opacity-'+layerID).show();
				
				if (uc.overlayMaps[layerID].selectableLayers)
					$.each(uc.overlayMaps[layerID].selectableLayers,function(i,n){
						uc.selectableLayers.push(n);
					});

				
			}else if (collection=="kmlLayers" || collection=="googleLayers"){
				sw[collection][layerID].layer.setMap(uc.map);
			}
		}else{
			if (collection=="overlayMaps"){
				if (uc.map.overlayMapTypes.getLength()>0){
					uc.map.overlayMapTypes.setAt(layerID,null);
					$('#slider-'+layerID+',#opacity-'+layerID).hide();
					
					var removeThese = [];
					$.each(uc.selectableLayers,function(i,n){
						if (!n.overlayMap)
							return;
						if (n.overlayMap==uc.overlayMaps[layerID].name)
							removeThese.push(i);
					});
					uc.selectableLayers.splice(removeThese.min(),removeThese.length);

					
				}
			}else if (collection=="kmlLayers" || collection=="googleLayers"){
				sw[collection][layerID].layer.setMap(null);
			}
		}
	});
	$(document).bind('keydown',function(e){
		if (!uc.ctrlKey) {
			var code = e.keyCode ? e.keyCode : e.which;
			if (code == 17) {
				uc.ctrlKey = true;
			}
		}
	}).bind('keyup',function(e){
		var code = e.keyCode ? e.keyCode : e.which;
		if (code == 17) {
			uc.ctrlKey = false;
		}
	});
	$('#a-full-extent').click(function(){
		uc.map.fitBounds(uc.initialExtent);
	});
	$('#a-start-over').click(function(){
		ResetMap();
		var mapSizeChanged = false;
		if (uc.layout.state.west.isClosed){
			uc.layout.open('west');
			mapSizeChanged = true;
		}
		if ($('#street-view').is(':visible')){
			$('#street-view').hide();
			$('#map').css('height','100%');
			mapSizeChanged = true;
		}
		if (mapSizeChanged)
			google.maps.event.trigger(uc.map,'resize');
		uc.map.fitBounds(uc.initialExtent);
		uc.streetView.setVisible(false);
		uc.map.setMapTypeId("Union");
	});
	$('#a-clear-map').click(function(){
		ResetMap();
	});
	$('#a-options[rel],#a-layers[rel],#a-about[rel]').overlay({
		expose:{
			color: '#333',
			opacity: 0.4
		},closeOnClick:false
	});
	$('#a-measure').click(function(){
		ResetMap();
		uc.mode='measure';
		uc.map.setOptions({
			draggableCursor:'crosshair'
		});
		$('#results-content').html($('#measure-container').html());
	});
	$('#a-link-map').click(function(){
		var center = uc.map.getCenter();
		$('#link-map-url').val('http://gisapps.co.union.nc.us/community-mapper/?lat=' + center.lat() + '&lng=' + center.lng() + '&zoom=' + uc.map.getZoom() + '&basemap=' + uc.map.getMapTypeId());
		$('#link-map-mailto').attr('href','mailto:someone@example.com?Subject=Map%20Link&Body=Click%20the%20link%20to%20see%20my%20shared%20map:%20' + escape('http://gisapps.co.union.nc.us/community-mapper/?lat=' + center.lat() + '&lng=' + center.lng() + '&zoom=' + uc.map.getZoom()));
		$('#link-map').show();
	});
	$('#link-map-close-a').click(function(){
		$('#link-map').hide();
	});
	$('#results-content').html($('#no-results-container').html());
	if (getUrlParam("lat") && getUrlParam("lng") && getUrlParam("zoom")){
		uc.map.setCenter(new google.maps.LatLng(parseFloat(getUrlParam("lat")), parseFloat(getUrlParam("lng"))));
		uc.map.setZoom(parseInt(getUrlParam("zoom")));
		if (getUrlParam("basemap")){
			if ($.inArray(getUrlParam("basemap"), uc.map.mapTypeControlOptions.mapTypeIds) > -1){
				setTimeout(function(){
					uc.map.setMapTypeId(getUrlParam("basemap"));
				},1500);
			}
		}
	}else{
		uc.map.fitBounds(uc.initialExtent);
	}
	/* jQuery.live() */
	$('#zoom-all-results').live('click',function(){
		uc.map.fitBounds(uc.selectedFeatures.getAllBounds());
	});
	$('.result-zoom').live('click',function(){
		uc.selectedFeatures.zoomTo($(this).parent('td').parent('tr').attr('id').split('-')[1]);
	});
	$('.result-buffer').live('click',function(){
		uc.selectedFeatures.promptBuffer($(this).parent('td').parent('tr').attr('id').split('-')[1],$(this).parent('td').parent('tr').attr('datasource'));
	});
	$('.result-sv').live('click',function(){
		uc.selectedFeatures.showStreetView($(this).parent('td').parent('tr').attr('id').split('-')[1]);
	});
	$('.result-info').live('click',function(){
		var feat = uc.selectedFeatures.getFeatureRef($(this).parent('td').parent('tr').attr('id').split('-')[1]);
		if (feat) uc.selectedFeatures.showIW(feat.gid,new google.maps.LatLng(feat.lat,feat.lon));
	});
	$('.remove-a').live('click',function(){
		uc.selectedFeatures.remove($(this).parent('td').parent('tr').attr('id').split('-')[1]);
	});
	/* End jQuery.live() */
	if (uc.isIPad){
		$("#ipad-zooms").show();
		alignIPadZooms();
	}
	$(".ipad-zooms-button > img").click(function(){
		uc.map.setZoom(uc.map.getZoom() + parseInt($(this).attr('id')));
	});
	$(window).resize(function(){
		if (uc.isIPad)
			alignIPadZooms();
	});
});
function ProcessACResults(value,data){
	measureDone();
	$('#last-search').val(value+','+data);
	$('#text-search').blur();
	$('#text-search').val($.trim(value.split(':')[1]));
	var dataParts=data.split(":");
	switch (dataParts[0]){
		case "0":/* Address */
			var url=uc.apiBase+'geo_featureoverlay.ashx?from_geotable=address_points&to_geotable=parcels&fields=t.gid&parameters=f.gid='+dataParts[2]+'&format=json';
			$.getJSON(url+'&callback=?',function(data){
				if (data.rows.length){
					getFeatures('parcels','attribute','gid=' + data.rows[0].gid,null,true);
				}
			});
			break;
		case "1":/* Intersection */
			ShowFacility(dataParts[2].split(",")[0],dataParts[2].split(",")[1],'images/markers/intersection.png','<h4>'+value+'</h4>',true);
			break;
		case "2":/* Subdivision */
			var url = uc.apiBase+'geo_attributequery.ashx?geotable=subdivisions&fields=gid,name,st_asgeojson(transform(the_geom,4326))+as+geojson&parameters=gid='+dataParts[2]+'&order=&limit=1&format=geojson';
			$.getJSON(url+'&callback=?',function(data){
				if (data.rows.length){
					var thisSub=data.rows[0];
					ResetMap();
					geojson2GMaps(thisSub,{strokeColor: "#46461F",strokeOpacity: 1,strokeWeight: 2,fillColor: "#46461F",fillOpacity: 0.25});
					thisSub.polygon.setMap(uc.map);
					uc.polygons.items.push(thisSub);
					uc.map.fitBounds(thisSub.polygon.Bounds());
				}
			});
			break;
		case "3":/* Road - Parcels along road*/
			$.getJSON(uc.apiBase+'geo_featureoverlay.ashx?from_geotable=address_points&to_geotable=parcels&fields=t.gid&parameters='+ encodeURIComponent('f.name=\''+dataParts[2]) +'\'&format=json&callback=?',function(data){
				if (data.rows.length){
					var gids='';
					$.each(data.rows,function(i,n){
						gids+=n.gid+',';
					});
					gids=gids.slice(0,gids.length-1);
					getFeatures('parcels','attribute','gid IN ('+ gids + ')',null,true);
				}
			});
			break;
		case "4": case "5": case "6":/* Schools */
			ShowFacility(dataParts[2].split(',')[0],dataParts[2].split(',')[1],'images/markers/school.png','<h4>'+value+'</h4>',true);
			break;
		case "7": /* Parcel Owner */
			getFeatures('parcels','attribute','owner1=\'' + escape(dataParts[2].replace(/'/g, "''")) + '\'',null,true);
			break;
		case "8": /* Parcels in Subdivision */
			getFeatures('parcels','geometrySub','f.gid=' + dataParts[2],null,true);
			break;
		case "9": /* Road - Show road */
			var url = uc.apiBase+'geo_attributequery.ashx?geotable=roads&fields=display,st_asgeojson(transform(st_simplify(the_geom,5),4326))+as+geojson&parameters=road_name=\''+dataParts[2]+'\'&order=&limit=&format=geojson';
			$.getJSON(url+'&callback=?',function(data){
				if (data.rows.length){
					ResetMap();
					var bounds = new google.maps.LatLngBounds();
					$.each(data.rows,function(i,n){
						geojson2GMaps(n,{clickable:false,strokeColor:'#46461F',strokeOpacity:0.5,strokeWeight:7});
						n.polyline.setMap(uc.map);
						uc.lines.items.push(n);
						bounds.union(n.polyline.Bounds());
					});
					uc.map.fitBounds(bounds);
				}
			});
			break;
	}
}
function ShowFacility(lat,lon,icon,iwContent,zoomTo){
	var LL = new google.maps.LatLng(lat,lon);
	var marker = new google.maps.Marker({
		icon: icon,
		position: LL,
		map: uc.map
	});
	uc.markers.items.push(marker);
	if (zoomTo) {
		uc.map.setCenter(LL);
		uc.map.setZoom(17);
	}
	if (iwContent.length > 0) {
		var iw=new google.maps.InfoWindow({
			content: iwContent,
			zIndex: uc.iw.getZIndex()+Math.round(100*Math.random())
		});
		listener = google.maps.event.addListener(marker,'click',function(){
			iw.open(uc.map,marker);
		});
		uc.infoWindows.items.push(iw);
		iw.open(uc.map,marker);
	}
}
function getFeatures(datasource, searchType, searchParams, geom, zoomTo, distance){
	measureDone();
	$('#text-search').blur();
	var append = uc.ctrlKey;
	if (!append)
		ResetMap();
	$('#results-content').hide();$('#results-loading').show();
	
	var selectableLayer;
	
	var index = datasource;
	if (!isNaN(index)){
		selectableLayer = uc.selectableLayers[index];
	}else{
		$.each(uc.selectableLayers,function(i,n){
			if (n.datasource==datasource)
				selectableLayer = n;
		});
		if (!selectableLayer)
			selectableLayer = uc.fallbackSelectableLayer;
	}
	
    var url = '';
	switch (searchType) {
        case 'attribute':
			var params = '&parameters=' + searchParams;
            url += uc.apiBase + 'geo_attributequery.ashx?geotable=' + selectableLayer.datasource + selectableLayer.fields + params + '&limit='+uc.maxResults+'&format=geojson&order=';
            break;
        case 'geometryPoint': case 'click':
			if (selectableLayer.layerType=='polygon'){
				url += uc.apiBase + 'geo_pointoverlay.ashx?x=' + geom.x + '&y=' + geom.y + '&srid=4326&geotable=' + selectableLayer.datasource + selectableLayer.fields + '&parameters=&format=geojson';
			}else{
				url += uc.apiBase + 'geo_bufferpoint.ashx?x=' + geom.x + '&y=' + geom.y + '&srid=4326&geotable=' + selectableLayer.datasource + selectableLayer.fields + '&parameters=&distance=0.0001&order=&limit=100&format=geojson';
            }
			break;
		case 'geometrySub':
			url += uc.apiBase + 'geo_centroidoverlay.ashx?from_geotable=subdivisions&to_geotable=' + selectableLayer.datasource + selectableLayer.tFields + '&parameters=' + searchParams + '&format=geojson&limit='+uc.maxResults;
			break;
		case 'buffer':
			var fromLayer = searchParams.split(':')[0];
			var fromId = searchParams.split(':')[1];
			url += uc.apiBase + 'geo_bufferfeature.ashx?from_geotable='+fromLayer+'&to_geotable='+selectableLayer.datasource+selectableLayer.tFields+',st_asgeojson(transform(simplify(Buffer(simplify(f.the_geom,2),'+distance+'),1),4326))+as+search_geom&parameters=f.gid='+fromId+'&distance='+distance+'&limit=&format=geojson';
			break;
    }
    $.getJSON(url+'&callback=?', function(data){
		var html='';
		var count = data.rows.length;
        if (count > 0) {
            if (!append) {
				html += '<div class="results-count"><span id="count-results"></span>&nbsp;result' + (count > 1 ? 's' : '') + ' <a id="zoom-all-results" href="javascript:void(0);" title="View all features"><img src="images/zoom.png" alt="View all features" title="View all features" /></a></div>';
				if (selectableLayer.datasource=="parcels")
					html += '<div class="results-links">Download as <a href="javascript:void(0);" onclick="ParcelExport(\'kml\');">KML</a> <span>(google earth)</span>, <a href="javascript:void(0);" onclick="ParcelExport(\'csv\');">CSV</a> <span>(excel)</span></div>';
				if (count==200)
					html += '<div class="results-200">Results are initially limited to 200 records. Change this by selecting "Options" above.</div>';
				html += '<table class="tbl-results"><tbody>';
			}
            $.each(data.rows, function(i, n){
				if (n.acctno && data.rows[0].acctno)
					if (i>0 && n.acctno == data.rows[0].acctno)
						return false;
				n.datasource = selectableLayer.datasource;
				if (n.lat && n.lon)
					n.LL = new google.maps.LatLng(n.lat,n.lon);
				geojson2GMaps(n);
				n[n.gType].setMap(uc.map);
				google.maps.event.addListener(n[n.gType],'mouseover',function(evt){
					$('#tr-'+n.gid).trigger('mouseover');
				});
				google.maps.event.addListener(n[n.gType],'mouseout',function(evt){
					$('#tr-'+n.gid).trigger('mouseout');
				});
				google.maps.event.addListener(n[n.gType],'click',function(evt){
					uc.selectedFeatures.showIW(n.gid,n.LL);
				});
				html += '<tr id="tr-' + n.gid +'" datasource="' + n.datasource + '"><td><a class="result-zoom" href="javascript:void(0);" title="Zoom to Feature"><img src="images/zoom.png" alt="Zoom to Feature" /></a></td><td><a class="result-buffer" href="javascript:void(0);" title="Buffer Feature"><img src="images/buffer.png" alt="buffer icon" title="Buffer Feature" /></a></td><td>' + (n.LL ? '<a class="result-sv" href="javascript:void(0);" title="Show Google Street View if available"><img src="images/street-view-logo.png" title="Show Google Street View if available" /></a>' : '') + '</td><td>' + selectableLayer.short_desc1.pre + n[selectableLayer.short_desc1.field] + (n.address ? '&nbsp;-&nbsp;'+n.address : '') + selectableLayer.short_desc1.post + '<br />' + selectableLayer.short_desc2.pre + n[selectableLayer.short_desc2.field] + selectableLayer.short_desc2.post + '</td><td class="remove"><a class="remove-a" href="javascript:void(0);"><img src="images/x.png" alt="Remove this Feature" title="Remove this Feature" /></a></td></tr>';
				uc.selectedFeatures.items.push(n);
            });
            if (!append) html += '</tbody></table>';
			if (zoomTo && !append) uc.map.fitBounds(uc.selectedFeatures.getAllBounds());
			if (searchType=='click' && selectableLayer.layerType=="polygon" && !uc.isIPad)
				setTimeout(function(){
					google.maps.event.trigger(data.rows[0][data.rows[0].gType],'mouseover');
				},50);
			if ($('#street-view').is(':visible'))
				uc.selectedFeatures.showStreetView(data.rows[0].gid);
        }else {
            if (!append)
				html+=$('#no-results-container').html();
			if (searchType=="click"){
				if(!isNaN(index)){
					if (index+1<uc.selectableLayers.length){
						getFeatures(index+1,searchType,searchParams,geom,zoomTo,distance);
					}else{
						getFeatures('parcels',searchType,searchParams,geom,zoomTo,distance);
					}
				}else{
					$('#results-loading').hide();
					$('#results-content').html($('#no-results-container').html()).show();
				}
			}else{
				Message('Sorry, No features found');
			}
        }
		if (append){
			$('.tbl-results').append(html);
		}else{
			$('#results-content').html(html);
		}
		FormatResults();
		if (distance && data.rows.length){
			if (data.rows[0].search_geom){
				var vector = {};
				vector.geojson = data.rows[0].search_geom;
				vector.geojson.type = "LineString";
				vector.geojson.coordinates = vector.geojson.coordinates[0];
				geojson2GMaps(vector,{
					strokeOpacity: 0.75,
					strokeColor: '#FF0000',
					strokeWeight: 2,
					clickable:false
				});
				vector.polyline.setMap(uc.map);
				uc.lines.items.push(vector);
			}
		}
		$('.tbl-results tbody tr').hover(function(){
			$(this).children('td:last').children('a').show();
			uc.selectedFeatures.highlight($(this).attr('id').split("-")[1]);
		},function(){
			$(this).children('td:last').children('a').hide();
			uc.selectedFeatures.highlightRestore($(this).attr('id').split("-")[1]);
		});
		$('#results-content').show();$('#results-loading').hide();
    });
}
function FormatResults(){
	$('#count-results').text(uc.selectedFeatures.items.length);
	$('.tbl-results tbody tr').removeClass('treven');
	$('.tbl-results tbody tr:even').addClass('treven');
	$('.tbl-results tbody tr:first td').addClass('trfirst');
}
function geojson2GMaps(feat,options){
	switch (feat.geojson.type){
		case "Point":
			feat.gType = "marker";
			var opts = (options ? options : uc.styles.marker.normal());
			opts.position = new google.maps.LatLng(feat.geojson.coordinates[1],feat.geojson.coordinates[0]);
			feat.marker = new google.maps.Marker(opts);
			break;
		case "LineString":
			feat.gType = "polyline";
			var opts = (options ? options : uc.styles.polyline.normal());
			var path = [];
			$.each(feat.geojson.coordinates,function(i,n){
				var ll = new google.maps.LatLng(n[1],n[0]);
				path.push(ll);
			});
			opts.path = path;
			feat.polyline = new google.maps.Polyline(opts);
			break;
		case "MultiLineString":
			feat.gType = "polyline";
			var opts = (options ? options : uc.styles.polyline.normal());
			var path = [];
			$.each(feat.geojson.coordinates[0],function(i,n){
				var ll = new google.maps.LatLng(n[1],n[0]);
				path.push(ll);
			});
			opts.path = path;
			feat.polyline = new google.maps.Polyline(opts);
			break;
		case "Polygon":
			feat.gType = "polygon";
			var opts = (options ? options : uc.styles.polygon.normal());
			var paths = [];
			$.each(feat.geojson.coordinates,function(i,n){
				var path=[];
				$.each(n,function(j,o){
					var ll = new google.maps.LatLng(o[1],o[0]);
					path.push(ll)
				});
				paths.push(path);
			});
			opts.paths = paths;
			feat.polygon = new google.maps.Polygon(opts);
			break;
		case "MultiPolygon":
			feat.gType = "polygon";
			var opts = (options ? options : uc.styles.polygon.normal());
			var paths = [];
			$.each(feat.geojson.coordinates,function(i,n){
				$.each(n,function(j,o){
					var path=[];
					$.each(o,function(k,p){
						var ll = new google.maps.LatLng(p[1],p[0]);
						path.push(ll);
					});
					paths.push(path);
				});
			});
			opts.paths = paths;
			feat.polygon = new google.maps.Polygon(opts);
			break;
	}
}
function ResetMap(){
	measureDone();
	$('#results-content').html($('#no-results-container').html());
	uc.iw.close();
	uc.selectedFeatures.removeAll();
	uc.markers.removeAll();
	uc.infoWindows.removeAll();
	uc.polygons.removeAll();
	uc.lines.removeAll();
}
function Tab2(gid){
	if ($('#tb2-ajaxdone').val()==0) {
		$('#tb2-ajaxdone').val(1);
		var parcel = uc.selectedFeatures.getFeatureRef(gid);
		/* Fire */
		$.getJSON(uc.apiBase+'geo_pointoverlay.ashx?x=' + parcel.lon + '&y=' + parcel.lat + '&srid=4326&geotable=fire_districts&fields=dist_id,dist_name,type&parameters=&format=json&callback=?', function(data){
			if (data.rows.length > 0) {
				$('#tb2-fire-district').html(data.rows[0].dist_name);
				$.getJSON(uc.apiBase+'geo_attributequery.ashx?geotable=fire_stations&fields=station_na,station_nu,x(transform(the_geom,4326))+AS+lon,y(transform(the_geom,4326))+AS+lat&parameters=dist_id=' + data.rows[0].dist_id + '&order=station_nu&limit=&format=json&callback=?', function(data){
					var html = '';
					$.each(data.rows, function(i, n){
						html += '<div><a href="javascript:void(0);" onclick="ShowFacility(' + parseFloat(n.lat) + ',' + parseFloat(n.lon) + ',\'images/markers/fire.png\',\'' + n.station_na + ' #' + n.station_nu + '\',true);">' + n.station_na + ' #' + n.station_nu + '</a></div>';
					});
					html = html.slice(0, html.length - 2);
					$('#tb2-fire-stations').html(html);
				});
			}
		});
		/* Polling Place */
		$.getJSON(uc.apiBase + 'geo_pointoverlay.ashx?x=' + parcel.lon + '&y=' + parcel.lat + '&srid=4326&geotable=boe_precinct_districts&fields=dist_num&parameters=&format=json&callback=?',function(data){
			if (data.rows.length >0){
				var distnum = data.rows[0].dist_num;
				$('#tb2-voting-precinct').text(distnum);
				$.getJSON(uc.apiBase + 'geo_attributequery.ashx?geotable=boe_polling_places&fields=name,address,city_st_zi,x(transform(the_geom,4326))+as+lon,y(transform(the_geom,4326))+as+lat&parameters=precinct_n=\'' + distnum + '\'&order=&limit=&format=json&callback=?',function(data){
	    			var html = '<a href="javascript:void(0);" onclick="ShowFacility(' + parseFloat(data.rows[0].lat) + ',' + parseFloat(data.rows[0].lon) + ',\'images/markers/vote.gif\',\'Precinct ' + distnum + ' - ' + data.rows[0].name + '\',true);">'+data.rows[0].name+'</a>';
	    			$('#tb2-voting-pollingplace').html(html);
    			});
			}
        });
		/* Schools */
		$.getJSON(uc.apiBase+'geo_attributequery.ashx?fields=s.school_type,s.school_name,s.school_name_full,x(transform(s.the_geom,4326))+AS+x,y(transform(s.the_geom,4326))+AS+y&geotable=elem_att+e,mid_high_att+mh,schools+s&parameters=st_within(transform(GeometryFromText(\'POINT('+parcel.lon+' '+parcel.lat+')\',4326),2264),e.the_geom)AND+st_within(transform(GeometryFromText(\'POINT('+parcel.lon+' '+parcel.lat+')\',4326),2264),mh.the_geom)+AND+(e.e_school_id=s.school_id+OR+mh.mid_school_id=s.school_id+OR+mh.high_school_id=s.school_id)&format=json&limit=&order=&callback=?',function(data){
            if (data.rows.length) {
                $.each(data.rows,function(i,n){
                    $('#tb2-schools-'+n.school_type).html('<a href="javascript:void(0);" onclick="ShowFacility(' + parseFloat(n.y) + ',' + parseFloat(n.x) + ',\'images/markers/school.png\',\''+n.school_name_full+'\',true);">' + n.school_name + '</a>');
                });
            }
        });
	}
}
function Tab3(gid){
	if ($('#tb3-ajaxdone').val()==0){
		$('#tb3-ajaxdone').val(1);
		var parcel = uc.selectedFeatures.getFeatureRef(gid);
		$.each([
			{geotable:"libraries",field:"name",count:"2",marker:"images/markers/library.png",div:"tb3-libraries"},
			{geotable:"parks",field:"park_name",count:"3",marker:"images/markers/park.png",div:"tb3-parks"},
			{geotable:"collection_sites",field:"name",count:"1",marker:"images/markers/recycle.png",div:"tb3-trashrecycle"}
		],function(i,n){
			$.getJSON(uc.apiBase + 'geo_bufferpoint.ashx?x=' + parcel.lon + '&y=' + parcel.lat + '&srid=4326&geotable='+n.geotable+'&fields='+n.field+',x(transform(the_geom,4326))+as+lon,y(transform(the_geom,4326))+as+lat&parameters=&distance=150000&order=&limit='+n.count+'&format=json&callback=?',function(data){
				var html='';
				if (data.rows.length>0){
   		        	$.each(data.rows,function(j,o){
						html += '<div>'+(data.rows.length>1 ? ((j+1)+'.&nbsp;'): '') +'<a href="javascript:void(0);" onclick="javascript:ShowFacility(' + parseFloat(o.lat) + ',' + parseFloat(o.lon) + ',\''+n.marker+'\',\'' + o[n.field] + '\',true);">'+o[n.field]+'</a></div>';
					});
   		    	}else{
   		        	html += 'None';
   		    	}
   		    	$('#'+n.div).html(html);
			});
		});
		$.getJSON('http://maps.co.mecklenburg.nc.us/rest/v2/ws_geo_bufferpoint.php?x=' + parcel.lon + '&y=' + parcel.lat + '&srid=4326&geotable=cats_park_and_ride&fields=name,x(transform(the_geom,4326))+as+lon,y(transform(the_geom,4326))+as+lat&parameters=&distance=150000&order=&limit=1&format=json&callback=?',function(data){
			var html = '';
			if (data.total_rows>0){
				$.each(data.rows,function(i,n){
					o = n.row;
					html += '<div><a href="javascript:void(0);" onclick="javascript:ShowFacility(' + parseFloat(o.lat) + ',' + parseFloat(o.lon) + ',\'images/markers/bus.png\',\'' + o.name + '\',true);">'+o.name+'</a></div>';
				});
			}else{
				html += 'None';
			}
			$('#tb3-cats').html(html);
		});
		$.getJSON(uc.apiBase + 'ext_walkscore.ashx?x='+ parcel.lon + '&y='+ parcel.lat+'&srid=4326&callback=?',function(data){
			if (data.status==1){
				$('#tb3-walkscore-a').attr('href',data.ws_link).html('<img src="'+data.logo_url+'" alt="Walk Score" />');
				$('#tb3-walkscore-score').text(data.walkscore);
				$('#tb3-walkscore-description').text(data.description);
			}else{
				$('#tb3-walkscore').html('<a href="http://www.walkscore.com" target="_blank">Get Score</a>');
			}
		});
	}
}
function Tab4(gid){
	if ($('#tb4-ajaxdone').val() == 0) {
		$('#tb4-ajaxdone').val(1);
		var parcel = uc.selectedFeatures.getFeatureRef(gid);
		/* Soils, Flood Zones */
		$.each([
			{to_geotable:"soils",field:"t.dsl_name",div:"tb4-enviro-soils"},
			{to_geotable:"fema_flood_zones",field:"t.label",div:"tb4-enviro-floodzones"}
		],function(i,n){
			$.getJSON(uc.apiBase+'geo_featureoverlay.ashx?from_geotable=parcels&to_geotable='+n.to_geotable+'&fields=distinct('+n.field+')&parameters=f.gid='+parcel.gid+'&format=json&callback=?',function(data){
				var html='';
				if (data.rows.length){
					$.each(data.rows,function(j,o){
						html+=o[n.field.split('.')[1]]+', ';
					});
					html = html.slice(0, html.length - 2);
				}else{
					html+='None';
				}
				$('#'+n.div).html(html);
			});
		});
		/* DFIRM Panel, Water Supply Watershed, River Basin */
		$.each([
			{geotable:"fema_flood_zones_grid",field:"panel",div:"tb4-enviro-dfirm"},
			{geotable:"water_supply_watersheds",field:"name",div:"tb4-enviro-wsws"},
			{geotable:"river_basins",field:"name",div:"tb4-enviro-basin"}
		],function(i,n){
			$.getJSON(uc.apiBase+'geo_pointoverlay.ashx?x='+parcel.lon+'&y='+parcel.lat+'&srid=4326&geotable='+n.geotable+'&fields='+n.field+'&parameters=&format=json&callback=?',function(data){
				$('#'+n.div).html(data.rows.length ? data.rows[0][n.field] : 'None');
			});
		});
	}
}
function ParcelExport(format){
	var gids='';
	$.each(uc.selectedFeatures.items,function(i,n){
		gids+=n.gid+',';
	});
	gids=gids.slice(0,gids.length-1);
	if (gids.length) window.open(uc.apiBase+'geo_parcelexport.ashx?gids='+gids+'&format='+format+'&random='+Math.random());
}
function Message(html){
	$('#message').html(html).show().css({
		'top':($('#right-content').height()/2)-($('#message').height()/2)+'px',
		'left':($('#right-content').width()/2)-($('#message').width()/2)+'px',
		'filter':'alpha(Opacity=85)'
	});
	setTimeout(function(){
		$('#message').fadeOut(2000);
	},2000);
}
function measureAdd(ll){
	var marker = new google.maps.Marker({
		map: uc.map,
		position: ll,
		draggable: true,
		raiseOnDrag: false,
		title: 'Drag me to change shape',
		icon: new google.maps.MarkerImage('images/markers/measure-vertex.png',new google.maps.Size(9,9), new google.maps.Point(0,0), new google.maps.Point(5,5))
	});
	var count = uc.measure.ll_line.push(ll);
	uc.measure.ll_poly.push(ll);
	var llIndex = count-1;
	google.maps.event.addListener(marker,'dragend',function(evt){
		if (uc.measure.ll_line.getLength()>2)
			measureCalc();
	});
	google.maps.event.addListener(marker,'mouseover',function(evt){
		marker.setIcon(new google.maps.MarkerImage('images/markers/measure-vertex-hover.png',new google.maps.Size(15,15), new google.maps.Point(0,0), new google.maps.Point(8,8)));
	});
	google.maps.event.addListener(marker,'mouseout',function(evt){
		marker.setIcon(new google.maps.MarkerImage('images/markers/measure-vertex.png',new google.maps.Size(9,9), new google.maps.Point(0,0), new google.maps.Point(5,5)));
	});
	google.maps.event.addListener(marker,'drag',function(evt){
		uc.measure.ll_line.setAt(llIndex,evt.latLng);
		uc.measure.ll_poly.setAt(llIndex,evt.latLng);
	});
	uc.measure.markers.push(marker);
	if (uc.measure.ll_line.getLength()>1){
		if (!uc.measure.line){
			uc.measure.line = new google.maps.Polyline({
				map:uc.map,
				clickable:false,
				strokeColor:'#FF0000',
				strokeOpacity:0.5,
				strokeWeight:3,
				path:uc.measure.ll_line
			});
		}
		if (uc.measure.ll_poly.getLength()>2){
			if (!uc.measure.poly){
				uc.measure.poly = new google.maps.Polygon({
					clickable:false,
					map:uc.map,
					fillOpacity:0.25,
					strokeOpacity:0,
					paths:uc.measure.ll_poly
				});
			}
		}
	}
	if (count>2)
		measureCalc();
}
function measureReset(){
	if (uc.measure.poly) {
		uc.measure.poly.setMap(null);
		uc.measure.poly = null;
	}
	if (uc.measure.line) {
		uc.measure.line.setMap(null);
		uc.measure.line = null;
	}
	//while (uc.measure.ll.getLength()>0) uc.measure.ll.pop();
	uc.measure.ll_line.clear();
	uc.measure.ll_poly.clear();
	for (i=0;i<uc.measure.markers.length;i++){
		uc.measure.markers[i].setMap(null);
	}
	$('#measure span').text('0');
}
function measureDone(){
	measureReset();
	uc.mode = 'default';
	uc.map.setOptions({
		draggableCursor: 'pointer'
	});
}
function measureCalc(){
	var length_met = google.maps.geometry.spherical.computeLength(uc.measure.line.getPath());
	var area_met = google.maps.geometry.spherical.computeArea(uc.measure.poly.getPath());
	var length = length_met*3.2808399;
	var area = area_met*10.7639104;
	$('#measure-area-sqft').text(addCommas(area.toFixed(0)));
	$('#measure-area-sqmi').text(addCommas((area/27878400).toFixed(1)));
	$('#measure-area-acres').text(addCommas((area/43560).toFixed(3)));
	$('#measure-length-feet').text(addCommas(length.toFixed(0)));
	$('#measure-length-meters').text(addCommas(length_met.toFixed(1)));
	$('#measure-length-miles').text(addCommas((length/5280).toFixed(3)));
}
function changeOverlayOpacity(layer,value){
	var opts = uc.overlayMaps[layer].config;
	opts.opacity = value/100;
	uc.map.overlayMapTypes.setAt(layer,null);
	uc.map.overlayMapTypes.setAt(layer,new google.maps.ImageMapType(opts));
}
function alignIPadZooms(){
	setTimeout(function(){
		var height = $('#right-content').height();
		$('#ipad-zooms').css('margin-top',((height/2)-52) + 'px');
	},200);
}
Array.prototype.min = function(){
	var min = this[0];
	var len = this.length;
	for (var i = 1; i < len; i++) if (this[i] < min) min = this[i];
	return min;
}
function addCommas(nStr){nStr += '';x = nStr.split('.');x1 = x[0];x2 = x.length > 1 ? '.' + x[1] : '';	var rgx = /(\d+)(\d{3})/;while (rgx.test(x1)) {	x1 = x1.replace(rgx, '$1' + ',' + '$2');}return x1 + x2;}
function computeAngle(endLatLng, startLatLng){var DEGREE_PER_RADIAN = 57.2957795;var RADIAN_PER_DEGREE = 0.017453;var dlat = endLatLng.lat() - startLatLng.lat();var dlng = endLatLng.lng() - startLatLng.lng();var yaw = Math.atan2(dlng * Math.cos(endLatLng.lat() * RADIAN_PER_DEGREE), dlat) * DEGREE_PER_RADIAN;return wrapAngle(yaw);}
function wrapAngle(angle){if (angle >= 360){angle -= 360;}else if (angle < 0) {angle += 360;}return angle;}
/* Extend Google Maps Vectors */
google.maps.Polygon.prototype.Bounds = function() {
	var bounds = new google.maps.LatLngBounds();
		for (var i=0; i < this.getPath().getLength(); i++) {
			bounds.extend(this.getPath().getAt(i));
		}
	return bounds;
}
google.maps.Polyline.prototype.Bounds = google.maps.Polygon.prototype.Bounds;
function getUrlParam(name){
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}
