// one global for persistent app variables
var DOT;
require([
	"esri/Map", "esri/views/MapView", "esri/layers/MapImageLayer", "esri/layers/ImageryLayer", "esri/layers/TileLayer", 
	"esri/layers/FeatureLayer", "esri/layers/GraphicsLayer", "esri/rest/support/ImageParameters", 
	"esri/PopupTemplate", "esri/rest/geometryService", "esri/layers/support/MosaicRule", 
	"esri/rest/support/LegendLayer", "esri/rest/locator",  "esri/rest/support/BufferParameters", "esri/rest/support/ProjectParameters", 
	"esri/rest/query", "esri/rest/support/Query", "esri/rest/identify", "esri/rest/support/IdentifyParameters",
	"esri/symbols/SimpleMarkerSymbol", "esri/symbols/PictureMarkerSymbol", 
	"esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleLineSymbol", "esri/symbols/TextSymbol", "esri/symbols/Font",
	"esri/widgets/Legend", "esri/Color", "esri/Graphic", "esri/config",
	"esri/geometry/Point", "esri/geometry/Polyline", "esri/geometry/Polygon", 
	"esri/geometry/Extent", "esri/geometry/support/normalizeUtils", 
	"esri/Basemap", "esri/widgets/BasemapGallery", "esri/widgets/BasemapGallery/support/LocalBasemapsSource", 
	"esri/widgets/Bookmarks", "esri/widgets/Home", "esri/widgets/Locate", "esri/widgets/ScaleBar", "esri/widgets/Popup",
	"esri/widgets/Measurement", "esri/widgets/BasemapToggle", "esri/widgets/Sketch/SketchViewModel", 
	"esri/rest/print", "esri/rest/support/PrintParameters", "esri/rest/support/PrintTemplate",
	"dijit/Menu", "dijit/MenuItem", "dijit/popup", "dijit/MenuSeparator", "esri/widgets/Sketch", 
	"esri/geometry/SpatialReference", "esri/geometry/support/webMercatorUtils",
	"esri/core/reactiveUtils", "esri/geometry/geometryEngine",
	"dojo/parser", "dojo/_base/array", "dojo/promise/all", "dojo/on", 
	"dojo/dom", "dojo/dom-class", "dojo/dom-construct", "dojo/number", "dojo/cookie", "dojo/Deferred", 
	"dojo/data/ItemFileReadStore", "dijit/form/FilteringSelect", "dijit/form/HorizontalSlider",
	"dijit/form/HorizontalRuleLabels", "dijit/layout/BorderContainer", "dijit/layout/ContentPane",
	"dojo/domReady!"
], function(
	Map, MapView, MapImageLayer, ImageryLayer, TileLayer, FeatureLayer, 
	GraphicsLayer, ImageParameters, 
	PopupTemplate,	geometryService, MosaicRule, 
	LegendLayer, locator, BufferParameters, ProjectParameters,
	query, Query, identify, IdentifyParameters,
	SimpleMarkerSymbol, PictureMarkerSymbol, SimpleFillSymbol, SimpleLineSymbol, TextSymbol, Font,
	Legend, Color, Graphic, esriConfig, 
	Point, Polyline, Polygon, 
	Extent, normalizeUtils, 
	Basemap, BasemapGallery, LocalBasemapsSource, 
	Bookmarks, HomeButton, LocateButton, 
	Scalebar, Popup, Measurement, BasemapToggle, SketchViewModel,
	print, PrintParameters, PrintTemplate, 
	Menu, MenuItem, popup, MenuSeparator, Sketch, 
	SpatialReference, webMercatorUtils, reactiveUtils, geometryEngine,
	parser, arrayUtils, all, on,
	dom, domClass, domConstruct, number, cookie, Deferred, 
	ItemFileReadStore, FilteringSelect, HorizontalSlider, HorizontalRuleLabels
) {
	parser.parse();
	DOT = {
		DOTResults	: new Object(),	
		
		initExtent	: null,	
		
		mappoint 	: null,
		
		currentLvl	: null,
		
		planSelected: "",
		
		basemapChanged: false,
		basemapBtnClick: false,
		
		toolActivated: false,
		
		//gPrintTask: new print(),
		gPrintParameters: new PrintParameters(),
		gPrintTemplate: new PrintTemplate(),
		
		legend_layerInfo : {},
		srvlyrFootprints	: new MapImageLayer(services_application.Footprints, {"id": "Footprints", "visible": false}),
		srvlyrImages		: new ImageryLayer(services_application.Images, {"id": "Images", "opacity": 0.7, "visible": false, "useMapImage": true, "noData": 0}),
		srvlyrCounties		: new MapImageLayer({url: services_application.Counties, sublayers: [
		   {
			 id: 6,
			 visible: true
		   }, {
			 id: 7,
			 visible: true
		}]}),
		reflyrHighway		: new MapImageLayer(services_reference.Highway, {"id": "Highway", "visible": false}),
		reflyrGeneral		: new MapImageLayer(services_reference.GeneralRef, {"id": "General", "visible": false}),
		reflyrQuad			: new MapImageLayer(services_reference.Quad, {"id": "Quad", "visible": false}),
		idGraphic 			: new GraphicsLayer({"id": "DOTIDGraphics"}),
		measureGraphic		: new GraphicsLayer({"id": "MeasureGraphics"}),
		textmarkupGraphic	: new GraphicsLayer({"id": "TextmarkupGraphics"}),
		searchGraphic 		: new GraphicsLayer({"id": "SearchGraphics"}),
		geometryGraphic 	: new GraphicsLayer({"id": "GeometryGraphics"}),
		bufferGraphic 		: new GraphicsLayer({"id": "BufferGraphics"}),
		planGraphic 		: new GraphicsLayer({"id": "planGraphics"}),
		shareGraphic 		: new GraphicsLayer({"id": "ShareGraphics"}),
		
		lgdP: new LegendLayer,
		
		ctxMenuForTxtmarkuGraphics	: {},
		txtMarkupSelected 			: {},

		currentAttribute	: "",
		//geometryService 	: new geometryService(services_application.geometry),
		//locatorEsri			: new locator(services_basemap.esri_locator),
				
		/*sms: new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 20, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0,0,255]), 2), new Color([0,0,255,0])),
		sls: new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0,0,255]), 3),
		sfs: new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([0,0,255,0.8]), 3), new Color([0,0,255,0.2])),
		
		sms2: new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_SQUARE, 20, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255,255,0,0.5]), 3), new Color([255,255,0,0.1])),
		sls2: new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255,255,0,0.5]), 5),
		sfs2: new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255,255,0, 0.5]), 3), new Color([255,255,0,0.1])),*/
		
		sfs: {
			type: "simple-fill",
			style: "solid",
			color: [0,0,255,0.2],
			outline: {
				color: [0, 0, 255, 0.8], 
				width: "3px"
			}
		},
		
		markerSymbol		: new PictureMarkerSymbol({
								'url': 'images/picMarker.png',
								'width': 20,
								'height': 20,
								'yoffset': 10
								}),
		layerInfo: [],
		
		DOTClickHandler	: {},
		txtmarkClickHandler	: {},
		
		sketchGeometry	: null,
		searchGeometry	: null,
		bufferGeometry	: null,
		
		init: function() {
			//esriConfig.geometryServiceUrl = DOT.geometryService;
			//esriConfig.defaults.io.corsEnabledServers.push("services.wvgis.wvu.edu");
			
			$("#loadingMap").show();
			
			DOT.objPrint = print;
			DOT.objGeometryService = geometryService;
			DOT.objQuery = query;
			
			DOT.popup = new Popup({
			    fillSymbol: DOT.sfs
			}, domConstruct.create("div"));
			DOT.mapObj = new Map({
				basemap: "streets-vector"
			});
			
			DOT.map = new MapView({
				container: "map",
				map: DOT.mapObj,
				zoom: 7,
				center: [-80.45, 39.00],
				constraints: {
				  maxScale: 300,
				  minScale: 3000000
				}
			});

			DOT.map.popup.watch("selectedFeature", (e) => {
				DOT.map.graphics.removeAll();
				if (e && e.geometry) {
					DOT.map.graphics.add(
					  new Graphic({
						geometry: e.geometry,
						symbol: DOT.sfs
					  })
					);
				}
			});
			
			DOT.map.popup.watch("visible", (e) => {
				if (DOT.map.popup.visible == false) DOT.map.graphics.removeAll();
			});

			// Create the MapView for overview map
			DOT.overviewObj = new Map({
				basemap: "streets-vector"
			});
			DOT.overviewMap = new MapView({
				container: "overviewDiv",
				zoom: 3,
				center: [-80.45, 39.00],
				map: DOT.overviewObj,
				constraints: {
					rotationEnabled: false
				}
			});

			// Remove the default widgets
			DOT.overviewMap.ui.components = [];

			DOT.overviewMap.when(function() {
				DOT.map.when(function() {
					setup();
				});
			});
			
			// Create Basemap Toggle
			DOT.basemapBestLeavesOff = new Basemap({
				id : "IMAGE_BESTLEAVESOFF",
				baseLayers : [new TileLayer({
					url: "https://services.wvgis.wvu.edu/arcgis/rest/services/Imagery_BaseMaps_EarthCover/wv_imagery_WVGISTC_leaf_off_mosaic/MapServer",
					copyright: 'WV Best Leaves Off Imagery by <a href="https://wvgis.wvu.edu">WV GIS Tech Center</a>'
				})],
				title : "WV Best Leaves Off",
				thumbnailUrl : "images/basemap_icon/wvgistc_bestleavesoff.png"
			});
			DOT.basemapToggle = new BasemapToggle({
			  view: DOT.map,
			  nextBasemap: DOT.basemapBestLeavesOff
			}, "basemapToggle");

			function setup() {
			  const extentGraphic = new Graphic({
				geometry: null,
				symbol: {
				  type: "simple-fill",
				  color: [0, 0, 0, 0.5],
				  outline: null
				}
			  }, "basemapToggle");
			  
			  DOT.overviewMap.graphics.add(extentGraphic);

			  //watchUtils.init(DOT.map, "extent", function(extent){
		      reactiveUtils.watch(
				  () => DOT.map.extent,
				  () => {
					// Sync the overview map location
					// whenever the 3d view is stationary
					
					DOT.overviewMap.goTo({
						center: DOT.map.center,
						scale:
						  DOT.map.scale*2*Math.max(DOT.map.width / DOT.overviewMap.width, DOT.map.height / DOT.overviewMap.height)
					}).catch(function(error){
						// ignore goto-interrupted errors
						if (error.name != "view:goto-interrupted"){
						  console.error(error);
						}
					});
					

					extentGraphic.geometry = DOT.map.extent;
				});
			}
			
			DOT.home = new HomeButton({
				view: DOT.map
			}, "homeButton");

		    DOT.geoLocate = new LocateButton({
				view: DOT.map
		    }, "locateButton");

			DOT.scalebar = new Scalebar({
				view: DOT.map,
				style: "ruler"
			}, "scaleBar");
			
			DOT.measurement = new Measurement({
				view: DOT.map,
				areaUnit: "square-feet",
				linearUnit: "us-feet"
			}, "winMeasure");
			
			//DOT.map.infoWindow.resize(350, 270);
			
			DOT.addOpacityControl(DOT.srvlyrImages);
			
			//DOT.srvlyrCounties.setVisibleLayers([6,7]);

			DOT.mapObj.addMany([
				DOT.reflyrQuad,
				DOT.reflyrHighway,
				DOT.reflyrGeneral,
				DOT.srvlyrCounties,
				DOT.srvlyrFootprints,
				DOT.srvlyrImages,
				//DOT.idGraphic,
				DOT.measureGraphic,
				DOT.textmarkupGraphic,
				DOT.geometryGraphic,
				DOT.bufferGraphic,
				DOT.searchGraphic,
				DOT.planGraphic,
				DOT.shareGraphic
			]);
			
			DOT.map.when(DOT.initFunction);
			
			DOT.map.watch("scale", (newValue) => {
				$("#nav_info1").html("Scale - 1: " + Number(newValue.toFixed(0)).toLocaleString());
			});
			DOT.map.watch('updating', function(evt){
				if(evt === true && DOT.toolActivated == false){
					//$("#loadingMap").show();
				}else{
					//$("#loadingMap").hide();
					$(".esriLegendServiceLabel").hide();
				}
			});
			DOT.map.on("pointer-move", (e) => {
				// handle mouse move coordinate
				var mapPoint = DOT.map.toMap({x: e.x, y: e.y});
				var pt = webMercatorUtils.webMercatorToGeographic(mapPoint);
				var str = (pt.y.toFixed(6) + ", " + pt.x.toFixed(6) +")");
				//$("#nav_info").css("display", "block");
				$("#nav_info3").html(str);
				//$("#coordsDisplay").html(str);
			});
			
			/*DOT.map.on("update-start", DOT.updateStartHandler);
			DOT.map.on("update-end", DOT.updateEndHandler);*/
			
			DOT.lgdP.layerId = "Plan Footprints";
			DOT.lgdP.subLayerIds = [0];
		},
		
		
		initFunction: function(){
			
			DOT.initExtent = new Extent(DOT.map.extent);
			
			$("#footerInfo").show();
			$("#idContent").css("height",50);
			$("#idContent").css("top",($(window).height() - 50));
			
			DOT.Bookmark();
			DOT.Measure 	= new Measure().init();
			DOT.TextMarkup	= new TextMarkup().init();
			DOT.ShareLink 	= new ShareLink().init();
			DOT.Printing 	= new Printing().init();
			
			$("#tools .panel").on('hide.bs.collapse', function () {
				$(this).find('.glyphicon-triangle-top').hide();
				$(this).find('.glyphicon-triangle-bottom').show();
			});
			$("#tools .panel").on('show.bs.collapse', function () {
				$(this).find('.glyphicon-triangle-bottom').hide();
				$(this).find('.glyphicon-triangle-top').show();
			});
			
			$("#help .panel").on('hide.bs.collapse', function () {
				$(this).find('.glyphicon-triangle-top').hide();
				$(this).find('.glyphicon-triangle-bottom').show();
			});
			$("#help .panel").on('show.bs.collapse', function () {
				$(this).find('.glyphicon-triangle-bottom').hide();
				$(this).find('.glyphicon-triangle-top').show();
			});
			
			$('#btnClear').click(function() {
				$('#menuBtns').find('.btn-default').removeClass('active');
				$("#LayersPanel").hide(300);
				$("#FilterPanel").hide(300);
				$("#BasemapPanel").hide(300);
				$("#HelpPanel").hide(300);
				$("#ToolsPanel").hide(300);
				$("#ToolsPanel").find('.panel-collapse').collapse('hide');
				//DOT.idGraphic.removeAll();
				DOT.measureGraphic.removeAll();
				DOT.textmarkupGraphic.removeAll();
				DOT.searchGraphic.removeAll();
				DOT.planGraphic.removeAll();

				DOT.shareGraphic.removeAll();
				//DOT.geolocationGraphic.removeAll();
				DOT.geometryGraphic.removeAll();
				DOT.map.graphics.removeAll();
			});
			  
			DOT.DOTClickHandler = DOT.map.on("click", DOT.onPlanClick);
			
			DOT.sketchViewModel = new SketchViewModel({
			  layer: DOT.geometryGraphic,
			  view: DOT.map,
			  pointSymbol: {
				type: "simple-marker",
				style: "circle",
				size: 10,
				color: [255, 255, 255, 0.8],
				outline: {
				  color: [211, 132, 80, 0.7],
				  size: 10
				}
			  },
			  polylineSymbol: {
				type: "simple-line",
				color: [211, 132, 80, 0.7],
				width: 6
			  },
			  polygonSymbol: {
				type: "simple-fill",
				color: [255, 255, 255, 0.8],
				outline: {
				  color: [211, 132, 80, 0.7],
				  size: "10px"
				}
			  },
			  defaultCreateOptions: { hasZ: false }
			});
			
			DOT.sketchViewModel.on(["create"], (event) => {
			  // update the filter every time the user finishes drawing the searchGeometry
			  if (event.state == "complete") {
				DOT.sketchGeometry = event.graphic.geometry;
				updateSearchGeometry();
			  }
			});
			
			function updateSearchGeometry() {
				if (DOT.DOTClickHandler) DOT.DOTClickHandler.remove();
				var bufferSize = document.getElementById("bufferSize").value;
				var bufferUnit = document.getElementById("bufferUnit").value;
				// add a polygon graphic for the bufferSize
				if (DOT.sketchGeometry) {
					if (bufferSize > 0) {
					  DOT.bufferGeometry = geometryEngine.geodesicBuffer(
						DOT.sketchGeometry,
						bufferSize,
						bufferUnit
					  );
					  if (DOT.bufferGraphic.graphics.length === 0) {
						DOT.bufferGraphic.add(
						  new Graphic({
							geometry: DOT.bufferGeometry,
							symbol: DOT.sketchViewModel.polygonSymbol
						  })
						);
					  } else {
						DOT.bufferGraphic.graphics.getItemAt(0).geometry = DOT.bufferGeometry;
					  }
					  DOT.searchGeometry = DOT.bufferGeometry;
					  console.log(DOT.searchGeometry);
					  DOT.geometryQuery(DOT.searchGeometry);
					} else {
					  DOT.bufferGraphic.removeAll();
					  DOT.searchGeometry = DOT.sketchGeometry;
					  DOT.geometryQuery(DOT.searchGeometry);
					}
				}
			};
			
			// draw geometry buttons - use the selected geometry to sktech
			document.getElementById("point-geometry-button").onclick =
			    geometryButtonsClickHandler;
			document.getElementById("line-geometry-button").onclick =
			    geometryButtonsClickHandler;
			document.getElementById("polygon-geometry-button").onclick =
			    geometryButtonsClickHandler;
			document.getElementById("rectangle-geometry-button").onclick =
			    geometryButtonsClickHandler;
			
			function geometryButtonsClickHandler(event) {
				DOT.geometryGraphic.removeAll();
				DOT.bufferGraphic.removeAll();
			    const geometryType = event.target.value;
			    DOT.sketchViewModel.create(geometryType);
			}
			
			/*DOT.textmarkupGraphic.on("mouse-over", function(e) {
	            // We'll use this "selected" graphic to enable editing tools
	            // on this graphic when the user click on one of the tools
	            // listed in the menu.
	            DOT.txtMarkupSelected = e.graphic;
	
	            // Let's bind to the graphic underneath the mouse cursor           
	            ctxMenuForTxtmarkuGraphics.bindDomNode(e.graphic.getDojoShape().getNode());
	        });
	        
			DOT.measureGraphic.on("mouse-over", function(e) {
	            // We'll use this "selected" graphic to enable editing tools
	            // on this graphic when the user click on one of the tools
	            // listed in the menu.
	            DOT.drawSelected = e.graphic;
	
	            // Let's bind to the graphic underneath the mouse cursor           
	            ctxMenuForMeasureGraphics.bindDomNode(e.graphic.getDojoShape().getNode());
			});
			
			DOT.createTxtmarkupGraphicsMenu();
			DOT.createMeasureGraphicsMenu();*/
			
			DOT.createBasemapGallery();
			
			DOT.createLegends();
			
			/*tb = new Draw(DOT.map);
			tb.on("draw-complete", function(e){
				tb.deactivate();
				DOT.doBuffer(e.geometry);
			});*/
			
			$("#nav_info1").css("display","block");
			$("#nav_info1").html("Scale - 1: " + Number(DOT.map.scale.toFixed(0)).toLocaleString());
			$("#nav_info2").css("display","inline-block");
			$("#nav_info2").html("Lat/Long: (");
			$("#nav_info3").css("display","inline-block");
			$("#nav_info3").html("Click on map to capture)");
			
			//util.toggle_basemap();
			
			setTimeout(function(){ DOT.parseURL();}, 500);
		},
		
		createLegends: function() {
			DOT.legend_layerInfo = [
				{layer: DOT.reflyrHighway, title: "Highway"},
				{layer: DOT.reflyrGeneral, title: "General"},
				{layer: DOT.reflyrQuad, title: "Quad"},
			];
			DOT.legendDijit = new Legend({
				view: DOT.map,
				respectLayerVisibility: true,
				layerInfos: DOT.legend_layerInfo
			}, "refLegend");
		},
		
		createBasemapGallery : function (){
			DOT.basemaps = utils.buildBasemap();
			/*var wvBestLayer = new TileLayer({
				url: "https://services.wvgis.wvu.edu/arcgis/rest/services/Imagery_BaseMaps_EarthCover/wv_imagery_WVGISTC_leaf_off_mosaic/MapServer",
				copyright: 'WV Best Leaves Off Imagery by <a href="https://wvgis.wvu.edu">WV GIS Tech Center</a>'
			});

			var wvBestBasemap = new Basemap({
				baseLayers: [wvBestLayer],
				title: "WV Best Leaves Off Imagery",
				id: "wvbest",
				thumbnailUrl: "images/basemap_icon/wvgistc_bestleavesoff.png"
			});*/
			DOT.basemapGallery = new BasemapGallery({
				view: DOT.map,
				container: "basemapGallery",
				source: new LocalBasemapsSource({
					basemaps: DOT.basemaps
					/*basemaps: [
						Basemap.fromId("topo-vector"),
						Basemap.fromId("streets-vector"),
						Basemap.fromId("satellite"),
						Basemap.fromId("hybrid"),
						Basemap.fromId("terrain"),
						Basemap.fromId("dark-gray-vector"),
						Basemap.fromId("gray-vector"),
						wvBestBasemap
					]*/
				})
			});
			/*DOT.basemapGallery = new BasemapGallery({
				showArcGISBasemaps : false,
				basemaps : basemap,
				map :  DOT.map,
				bingMapsKey: 'AugjwLeXzvrq9c69SLNvX_UumfcWsF9XjJ4afKbdK0hA4enIM5FTiXkZ3jysp8bH'
			}, "basemapGallery");
			
			DOT.basemapGallery.startup();	
			DOT.basemapGallery.select("ESRI_STREET");
			
			$(".esriBasemapGalleryNode").on('click', function(){
				basemapSelected = $(this).attr('id');
			});*/
		},
		
        txtmarkClick: function(e) {
			// create context menu for delete graphic
			DOT.createTxtmarkupGraphicsMenu();
			console.log(e.button);
			// when text markup is enabled, if left click, draw new graphic; if right click, show context menu for deletion.
			if (e.button === 0) {
				var txtPoint = e.mapPoint;
				if ($("#chkMarkup").is(':checked')) {
					var rgb_color = utils.hexToRgb($("#textmarkup_color_picker").val().slice(-6));
					/*var txtPtSymbol = new SimpleMarkerSymbol($("#markup_style").val(), $("#markuppt_size_spinner").val(),
										new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([rgb_color.r, rgb_color.g, rgb_color.b]),1 ),
										new Color([rgb_color.r, rgb_color.g, rgb_color.b]));*/
					var txtPtSymbol = {
						type: "simple-marker",  // autocasts as new SimpleMarkerSymbol()
						style: $("#markup_style").val(),
						color: [rgb_color.r, rgb_color.g, rgb_color.b, 0.5],
						size: $("#markuppt_size_spinner").val() + "px",  // pixels
						outline: {  // autocasts as new SimpleLineSymbol()
						color: [rgb_color.r, rgb_color.g, rgb_color.b],
						width: 1  // points
						}
					};						
					var txtgraphic = new Graphic(txtPoint,txtPtSymbol);
					DOT.textmarkupGraphic.add(txtgraphic);
				}
				var rgb_color = utils.hexToRgb($("#textmarkup_color_picker").val().slice(-6));
				var angle = $("#textmarkup_angle_spinner").val();
				var fontsize = $("#textmarkup_size_spinner").val();
				var txtLblSymbol = new TextSymbol($("#txtMarkup_txt").val());
				txtLblSymbol.color = new Color([rgb_color.r, rgb_color.g, rgb_color.b]);
				txtLblSymbol.xoffset = 3;
				txtLblSymbol.yoffset = 3;
				txtLblSymbol.angle = angle;
				txtLblSymbol.font = new Font({size:fontsize, decoration:"underline", style:txtItaclic, weight:txtBold, family:$("#txtMarkup_family").val()});
				if ($("#chkHalo").is(':checked')) {
					var halo_color = utils.hexToRgb($("#halo_color_picker").val().slice(-6));
					txtLblSymbol.haloColor = new Color([halo_color.r, halo_color.g, halo_color.b]);
					txtLblSymbol.haloSize = $("#halo_size_spinner").val();	
				};
				if (txtAlign == "start"){
					//txtLblSymbol.setAlign(TextSymbol.ALIGN_START);
					txtLblSymbol.horizontalAlignment = "left";
				};
				if (txtAlign == "middle"){
					//txtLblSymbol.setAlign(TextSymbol.ALIGN_MIDDLE);
					txtLblSymbol.horizontalAlignment = "center";
				};
				if (txtAlign == "end"){
					//txtLblSymbol.setAlign(TextSymbol.ALIGN_END);
					txtLblSymbol.horizontalAlignment = "right";
				};
				var txtLblGraphic = new Graphic(txtPoint, txtLblSymbol);
				DOT.textmarkupGraphic.add(txtLblGraphic);
			} else if (e.button === 2) {
				DOT.map.hitTest(e).then(function (evt) {
					DOT.getGraphics(evt, e);
				});
			}
        },
		
		// get selected graphic for right click context menu
		getGraphics: function(response, mevent) {
            if (response.results.length) {
              DOT.txtMarkupSelected = response.results.filter(function (result) {
                return result.graphic.layer === DOT.textmarkupGraphic;
              })[0].graphic;
			  console.log(DOT.ctxMenuForTxtmarkuGraphics);
			  popup.open({
                popup: DOT.ctxMenuForTxtmarkuGraphics,
                x: mevent.x,
                y: mevent.y
              });
            } else {
              popup.close(DOT.ctxMenuForTxtmarkuGraphics);
            }
        },
		
		// function to create context menu
		createTxtmarkupGraphicsMenu: function() {
			// Creates right-click context menu for Features
			DOT.ctxMenuForTxtmarkuGraphics = new Menu({});
			DOT.ctxMenuForTxtmarkuGraphics.addChild(new MenuItem({
			  label: "Delete graphic",
			  onClick: function () {
				DOT.textmarkupGraphic.remove(DOT.txtMarkupSelected);
				popup.close(DOT.ctxMenuForTxtmarkuGraphics);
			  }
			}));
			DOT.ctxMenuForTxtmarkuGraphics.startup();
		},
		
		onPlanClick: function(event, pnt){
			if (!DOT.toolActivated) {
				DOT.planSelected = ""
				var centerPlan = false;
				//if (e) centerPlan = true;
				if ($("#map").hasClass('dim')) $("#map").removeClass('dim');
				//DOT.idGraphic.removeAll();
				DOT.planGraphic.removeAll();
				DOT.map.popup.close();
				DOT.map.popup.location = event.mapPoint;
				//DOT.map.infoWindow.hide();
				$("#loadingMap").show();
				$("#opacity_control").hide();
				$("#opacity_slider").hide();
				DOT.srvlyrImages.visible = false;
				$("#zoomIn").unbind("click");
				$("#linkType_plan").prop("disabled", true);
				if ($("#linkType_plan").is(":checked")) $("#linkType_plan").prop("checked", false);
				if (!$("input[name='linkType']").filter(":checked").val()) $("#btnShareLink").prop("disabled", true);
				$("#sharePlan").css("color", "gray");
				//identifyTask = new IdentifyTask(services_application.Footprints);
				var identifyLayers = [0];
				identifyParams = new IdentifyParameters();
				identifyParams.tolerance = 1;
				identifyParams.returnGeometry = true;
				identifyParams.layerIds = identifyLayers;
				//if (e != null) identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_VISIBLE;
				//else identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
				identifyParams.layerOption = IdentifyParameters.LAYER_OPTION_ALL;
				var badParcelLyrDef = [];
				badParcelLyrDef[0] = "CleanParcelID Is Not Null";
				//identifyParams.layerDefinitions = badParcelLyrDef;
				identifyParams.spatialReference = DOT.map.spatialReference;
				identifyParams.width =  DOT.map.width;
				identifyParams.height =  DOT.map.height;
				if (pnt) DOT.mappoint = pnt;
				else if (event) DOT.mappoint = event.mapPoint;
				var pt1 = new Point(DOT.mappoint);
				var pp = new webMercatorUtils.webMercatorToGeographic(pt1);
				var strpp = pp.y.toFixed(6) + ', ' + pp.x.toFixed(6);
				$("#nav_info3").css("display","inline-block");
				$("#nav_info3").html('<a href="https://maps.google.com/maps?q=' + strpp + '" target="_blank">' + strpp + '</a>)');
				
				if (pnt) identifyParams.geometry = pnt;
				else if (event) identifyParams.geometry = event.mapPoint;
				identifyParams.mapExtent =  DOT.map.extent;
				
				//identifyTask.execute(identifyParams).then(function (response) {
				identify.identify(services_application.Footprints, identifyParams).then(function (response) {
					if (response.results.length != 0) {
						$("#loadingMap").hide();
						//DOT.map.infoWindow.show(DOT.mappoint);
						$("#linkType_plan").prop("disabled", false);
						$("#sharePlan").css("color", "black");
						if ($("input[name='linkType']").filter(":checked").val() && $("#btnShareLink").is(":disabled")) $("#btnShareLink").prop("disabled", false);
						return response.results.map(function (result) {
							var feature = result.feature;
							var planTemplate = new PopupTemplate();
							planTemplate.title = "Project ID: {ID}";
							//planTemplate.content=generateInfoContent;
							//function generateInfoContent(feature){
							planTemplate.content=function(){
								var div=document.createElement("div");
								DOT.planSelected = feature.attributes.Name;
								var formatString = "<span style='display:none;' id='prjKeySelected'>" + feature.attributes.Name + "</span><b>Project Key: </b>" + feature.attributes.ProjectKey + "<br><b>Project Title: </b>" + feature.attributes.ProjectTitle;
								if (feature.attributes.FederalProject != "Null") formatString += "<br><b>Federal Project #: </b>" + feature.attributes.FederalProject;
								if (feature.attributes.StateProject != "Null") formatString += "<br><b>State Project #: </b>" + feature.attributes.StateProject;
								if (feature.attributes.County != "Null") formatString += "<br><b>County: </b>" + feature.attributes.County;
								if (feature.attributes.SignSystem != "Null") formatString += "<br><b>Sign System: </b>" + feature.attributes.SignSystem;
								if (feature.attributes.FiscalYear != "Null") formatString += "<br><b>Fiscal Year: </b>" + feature.attributes.FiscalYear;
								if (feature.attributes.RouteNumber != "Null") formatString += "<br><b>Route #: </b>" + feature.attributes.RouteNumber;
								if (feature.attributes.BeginMile != "Null") formatString += "<br><b>Begin Mile: </b>" + feature.attributes.BeginMile;
								if (feature.attributes.BridgeNumbers != "Null") formatString += "<br><b>Bridge Numbers: </b>" + feature.attributes.BridgeNumbers;
								var reportUrl = "https://mapwv.gov/dotplans/ProjectDetails.php?scanID=" + feature.attributes.ID
								formatString += "<br><a target='_blank' href='" + reportUrl + "'>Click Here</a> for More Information";
								//formatString += '<br><a style="cursor:pointer;" onclick="DOT.showImage(\'' + feature.attributes.Name + '\')">Click Here</a> to Show Plan Image';
								formatString += "<br><a style='cursor:pointer;' onclick='DOT.showImage(\"" + feature.attributes.Name + "\")'>Click Here</a> to Show Plan Image";
								div.innerHTML=formatString;
								return div;
							}
							//planTemplate.content=formatString;
							feature.popupTemplate = planTemplate;
							return feature;
						});
					} else {
						$("#loadingMap").hide();
						DOT.map.popup.title = "No Plan found";
					}
				}).then(function(response){
					DOT.map.popup.open({
						features: response,
						//location: event.mapPoint
					});
				});
				//DOT.map.infoWindow.setFeatures([deferred]);
				$(".titleButton.close").on('click', function(){
					if (DOT.srvlyrImages.visible) {
						DOT.srvlyrImages.visible = false;
						$("#opacity_control").hide();
						$("#opacity_slider").hide();
					}
				});
			}
		},
		
		showImage: function(name){
			console.log(name);
			//if (DOT.map.getLayer("map_graphics").graphics[0].geometry) DOT.map.setExtent(DOT.map.getLayer("map_graphics").graphics[0].geometry.getExtent(), true);
			//else if (DOT.planGraphic.graphics[0].geometry) DOT.map.setExtent(DOT.planGraphic.graphics[0].geometry.getExtent(), true);
			var rasterID = [];
			var queryImg      				= new Query();
			//var queryTaskImg  				= new QueryTask(services_application.Images);
			queryImg.where    				= "Name LIKE '%" + name + "%'";
			queryImg.outSpatialReference  	= {wkid:102100}; 
			queryImg.outFields            	= ["*"];
			queryImg.returnGeometry     = true;
		    
			//queryTaskImg.execute(queryImg).then(function(i){
			query.executeQueryJSON(services_application.Images,queryImg).then(function (featureSet) {
				console.log(featureSet);
				if (featureSet.features.length > 0){
					ext = featureSet.features[0].geometry.extent;
					console.log(ext);
					DOT.map.extent = ext;
					var mr = new MosaicRule();
					rasterID.push(featureSet.features[0].attributes.OBJECTID);
					mr.method = "lock-raster";
					mr.lockRasterIds = rasterID;
					DOT.srvlyrImages.mosaicRule = mr;
					//DOT.srvlyrImages.setDefinitionExpression("Name = '" + name + "'");
					//DOT.srvlyrImages.refresh();
					//DOT.map.infoWindow.show(ext.getCenter());
					if (!DOT.srvlyrImages.visible) {
						DOT.srvlyrImages.visible = true;
						$("#opacity_control").show();
						$("#opacity_slider").show();
					}
				}
			});
		},
		
		addOpacityControl: function(layer) {
			var targetElem = dojo.byId("opacity_control");
			var sliderElem = dojo.create("div", {id: "opacity_slider"}, targetElem, "first");
			var opacityControl = new HorizontalSlider({
				name: "slider",
				value: 0.7,
				minimum: 0,
				maximum: 1,
				showButtons: true,
				intermediateChanges: true,
				style: "width: 250px; margin-right: auto; margin-left: auto; border: 2px solid blue; background-color:rgba(255,255,0,0.5);",
				onChange: function(value) {
					layer.opacity = value;
				}
			}, "opacity_slider");
			opacityControl.startup();
			$("#opacity_control").attr('title', 'Drag to change image opacity');
			$("#opacity_control").hide();
			$("#opacity_slider").hide();
		},
		
		getPlanInfo: function(feature) {
			$("#showDetail").show();
			
			// Owner information
			var owner = checkFieldValue(feature.attributes["Owner1"]);	
			if ( feature.attributes.hasOwnProperty("Owner2") ) {
				if ( checkFieldValue(feature.attributes["Owner2"]) != "&nbsp;")
					owner += (' ' + feature.attributes["Owner2"]);
			}
			
			//Legal Description
			var legal = "";
			if ( feature.attributes.hasOwnProperty("LegalDescription1") )
				legal = checkFieldValue(feature.attributes["LegalDescription1"]);
			if ( feature.attributes.hasOwnProperty("LegalDescription2") && checkFieldValue(feature.attributes["LegalDescription2"]) != "&nbsp;" ) {
				legal += ('; ' + feature.attributes["LegalDescription2"]);
			}
			//if ( feature.attributes.hasOwnProperty("LegalDescription3") && checkFieldValue(feature.attributes["LegalDescription3"]) != "&nbsp;" )
				//legal += ('; ' + feature.attributes["LegalDescription3"]);
			
			//Basic Information
			var DOTBasicInfo = "";
			DOTBasicInfo += "<div class='row'><div class='col-sm-4'><b>Project Title:</b></div><div class='col-sm-8' style='padding:0;' id='projectTitleText'>" + feature.attributes["ProjectTitle"] + "</div></div>";
			DOTBasicInfo += "<div class='row'><div class='col-sm-4'><b>Federal Project:</b></div><div class='col-sm-8' style='padding:0;' id='parcelAddrText'>" + feature.attributes["FederalProject"] + "</div></div>";
			DOTBasicInfo += "<div class='row'><div class='col-sm-4'><b>State Project:</b></div><div class='col-sm-8' style='padding:0;'>" + feature.attributes["StateProject"] + "</div></div>";
			DOTBasicInfo += "<div class='row'><div class='col-sm-4'><b>Class Type:</b></div><div class='col-sm-8' style='padding:0;' id='parcelClassText'>" + feature.attributes["PropertyClassDescription"] + "</div></div>";
			$("#DOTInfoText").html(DOTBasicInfo);
		},
		
		doBuffer: function(geometry) {
			//tb.deactivate();
			DOT.DOTClickHandler = DOT.map.on("click", DOT.onPlanClick);
			$(".selectType").css("background-color", "buttonface");
			var symbol;
			switch (geometry.type) {
				case "point":
					//symbol = new SimpleMarkerSymbol(SimpleMarkerSymbol.STYLE_CIRCLE, 8, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([128,128,0]), 2), new Color([255,255,0,0.2]));
					symbol = {type: "simple-marker", style: "circle", color: [255,255,0,0.2], size: "8px", outline: { color: [ 128,128,0 ],width: 2 }};
					break;
				case "polyline": 
					//symbol = new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([255,255,0]), 2);
					symbol = {type: "simple-line", style: "solid", color: [255,255,0,0.2], width: "2px"};
					break;
				case "extent":
					//symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([128,128,0]), 2), new Color([255,255,0,0.2]));
					symbol = {type: "simple-fill", color: [255,255,0,0.2], style: "solid", outline: {color: [128,128,0], width: 2}};
					break;
				case "polygon":
					//symbol = new SimpleFillSymbol(SimpleFillSymbol.STYLE_SOLID, new SimpleLineSymbol(SimpleLineSymbol.STYLE_SOLID, new Color([128,128,0]), 2), new Color([255,255,0,0.2]));
					symbol = {type: "simple-fill", color: [255,255,0,0.2], style: "solid", outline: {color: [128,128,0], width: 2}};
					break;
			}
			var graphic = new Graphic(geometry, symbol);
			DOT.geometryGraphic.add(graphic);
			if (dom.byId("bufferSize").value && dom.byId("bufferSize").value > 0) {
				//setup the buffer parameters
				var params = new BufferParameters();
				params.distances = [dom.byId("bufferSize").value];
				params.outSpatialReference = DOT.map.spatialReference;
				params.geodesic = true;
				params.unit = DOT.objGeometryService[dom.byId("bufferUnit").value];
				//normalize the geometry 

				normalizeUtils.normalizeCentralMeridian([geometry]).then(function(normalizedGeometries){
					var normalizedGeometry = normalizedGeometries[0];
					if (normalizedGeometry.type === "polygon") {
					  //if geometry is a polygon then simplify polygon.  This will make the user drawn polygon topologically correct.
						DOT.objGeometryService.simplify([normalizedGeometry], function(geometries) {
						params.geometries = geometries;
						DOT.objGeometryService.buffer(params, DOT.bufferCompleteHandler);
					  });
					} else {
					  params.geometries = [normalizedGeometry];
					  DOT.objGeometryService.buffer(params, DOT.bufferCompleteHandler);
					}
				});
			} else {
				normalizeUtils.normalizeCentralMeridian([geometry]).then(function(normalizedGeometries){
					/*var symbol = new SimpleFillSymbol(
						SimpleFillSymbol.STYLE_SOLID,
						new SimpleLineSymbol(
							SimpleLineSymbol.STYLE_SOLID,
							new Color([128,128,0,0.4]), 2
						),
						new Color([255,255,0,0.1])
					);*/
					var symbol = {type: "simple-fill", color: [255,255,0,0.1], style: "solid", outline: {color: [128,128,0,0.4], width: 2}};
					var normalizedGeometry = normalizedGeometries[0];
					if (normalizedGeometry.type === "polygon") {
						DOT.objGeometryService.simplify([normalizedGeometry], function(geometries) {
						geometries.forEach(function(geometry) {
							var graphic = new Graphic(geometry, symbol);
							DOT.geometryGraphic.add(graphic);
							DOT.geometryQuery(geometry);
						});
					  });
					} else {
						var graphic = new Graphic(normalizedGeometry, symbol);
						DOT.geometryGraphic.add(graphic);
						DOT.geometryQuery(normalizedGeometry);
					}
				});
			}
		},
		
		bufferCompleteHandler: function(bufferedGeometries) {
			/*var symbol = new SimpleFillSymbol(
				SimpleFillSymbol.STYLE_SOLID,
				new SimpleLineSymbol(
					SimpleLineSymbol.STYLE_SOLID,
					new Color([128,128,0,0.4]), 2
				),
				new Color([255,255,0,0.1])
			);*/
			var symbol = {type: "simple-fill", color: [255,255,0,0.1], style: "solid", outline: {color: [128,128,0,0.4], width: 2}};

			bufferedGeometries.forEach(function(geometry) {
				var graphic = new Graphic(geometry, symbol);
				DOT.geometryGraphic.add(graphic);
				DOT.geometryQuery(geometry);
			});
		},
		
		geometryQuery: function(geometry){
			if (geometry.extent) DOT.map.extent = geometry.extent.expand(2);
			$('#filters').hide();
			$('#searchContent').show();
			$('#searchProgress').show();
			$('#btnParcelReset').show();
			
			DOT.planGraphic.removeAll();
			
			var geomQuery = new Query();
			//var geomQuerytask = new QueryTask(services_application.Footprints+"/0");

			geomQuery.geometry = geometry;
			geomQuery.returnGeometry = true;
			geomQuery.outSpatialReference = DOT.map.spatialReference;
			geomQuery.outFields = ["*"];
			geomQuery.spatialRelationship = Query.SPATIAL_REL_INTERSECTS;
			//geomQuerytask.execute(geomQuery, utils.showPlanResults, function(e){
				//console.log(e);
			//});
			query.executeQueryJSON(services_application.Footprints+"/0",geomQuery).then(utils.showPlanResults);
			DOT.DOTClickHandler = DOT.map.on("click", DOT.onPlanClick);
		},
		
		Bookmark: function() {
			/*var useLocalStorage = supports_local_storage();
			function supports_local_storage() {
				try {
					return 'localStorage' in window && window['localStorage'] !== null;
				} catch( e ) {
					return false;
				}
			}*/
			
			var bookmarks = new Bookmarks({
				view : DOT.map,
				container: "winBookmarks",
				bookmarks : [],
				editingEnabled : true
			});

			// Save new bookmarks in local storage, fall back to a cookie
			// If a cookie is used, it expires after a week
			//dojo.connect(bookmarks, 'onEdit', refreshBookmarks);
			//dojo.connect(bookmarks, 'onRemove', refreshBookmarks);

			// Look for stored bookmarks
			/*var bmJSON;
			if (useLocalStorage) {
				bmJSON = window.localStorage.getItem(storageName);
			} else {
				bmJSON = dojo.cookie(storageName);
			}

			if (bmJSON && bmJSON != 'null') {
				console.log('cookie: ', bmJSON, bmJSON.length);
				var bmarks = dojo.fromJson(bmJSON);
				dojo.forEach(bmarks, function(b) {
					bookmarks.addBookmark(b);
				});
			}

			function refreshBookmarks() {
				if (useLocalStorage) {
					window.localStorage.setItem(storageName, dojo.toJson(bookmarks.toJson()));
				} else {
					var exp = 7;
					// number of days to persist the cookie
					dojo.cookie(storageName, dojo.toJson(bookmarkss.toJson()), {
						expires : exp
					});
				}
			}*/
		},
		
		distanceMeasurement: function() {
			DOT.measurement.activeTool = "distance";

			document.getElementById("btnDistance").classList.add("active");
			document.getElementById("btnArea").classList.remove("active");
		},

		areaMeasurement: function() {
			DOT.measurement.activeTool = "area";
			document.getElementById("btnArea").classList.remove("active");
			document.getElementById("btnDistance").classList.add("active");
		},
  
		  // Clears all measurements
		clearMeasurements: function() {
			document.getElementById("btnArea").classList.remove("active");
			document.getElementById("btnDistance").classList.remove("active");
			DOT.measurement.clear();
		},
		
		parseURL: function(){
			var t = (document.URL).split("?");			//identify possible parameters in the url
			if ( t.length == 1 || (!t[1].trim()) ) {
				utils.startFilter();
				utils.startCheckboxes();
				$("#btnFilter").trigger("click");
				$("#loadingMap").hide();
				return false;
			} else {
				var str = t[1].trim();
				var params1 = str.split("&");				// how many parameters there are
				var wkid=102100, zl=0, px=0, py=0;
				var pl=null, freeTxt=null, cnty=null, ss=null, pTitle=null, pKey=null, fedPrj=null, statePrj=null, rtNo=null, brNo=null;
				var mmin=null, mmax=null, fymin=null, fymax=null;
				var queryShare;
				for (var i=0; i<params1.length; i++){
					var pm = params1[i].split("=");
					if (pm[0].toLowerCase()=="wkid") 			wkid = Number(pm[1]);
					if (pm[0].toLowerCase()=="x") 				px = Number(pm[1]);
					if (pm[0].toLowerCase()=="y") 				py = Number(pm[1]);
					if (pm[0].toLowerCase()=="l") 				zl = Number(pm[1]);
					if (pm[0].toLowerCase()=="name")			pl = pm[1];
					if (pm[0].toLowerCase()=="freetext")		freeTxt = pm[1];
					if (pm[0].toLowerCase()=="county")			cnty = pm[1];
					if (pm[0].toLowerCase()=="signsystem")		ss = pm[1];
					if (pm[0].toLowerCase()=="projecttitle")	pTitle = pm[1];
					if (pm[0].toLowerCase()=="projectkey")		pKey = pm[1];
					if (pm[0].toLowerCase()=="fedproject")		fedPrj = pm[1];
					if (pm[0].toLowerCase()=="stateproject")	statePrj = pm[1];
					if (pm[0].toLowerCase()=="route")			rtNo = pm[1];
					if (pm[0].toLowerCase()=="bridgenumber")	brNo = pm[1];
					if (pm[0].toLowerCase()=="startmile")		mmin = pm[1];
					if (pm[0].toLowerCase()=="endmile")			mmax = pm[1];
					if (pm[0].toLowerCase()=="startyear")		fymin = pm[1];
					if (pm[0].toLowerCase()=="endyear")			fymax = pm[1];
				}
				
				if (pl) DOT.showImage(pl);
				
				if (freeTxt || cnty || ss || pTitle || pKey || fedPrj || statePrj || rtNo || brNo || mmin || mmax || fymin || fymax) {
					
					$('#filters').hide();
					$('#searchContent').show();
					$('#searchProgress').show();
					
					//queryTaskShare = new QueryTask(services_application.Footprints + "/0");
					queryShare = new Query();
					queryShare.returnGeometry = true;
					queryShare.outFields = ["*"];
					queryShare.outSpatialReference = DOT.map.spatialReference;
					
					var fText = "1 = 1";
					
					if (freeTxt) 
						fText += " AND (County LIKE '%" + freeTxt.replace(/_/g, ' ') + "%' OR SignSystem LIKE '%" + freeTxt.replace(/_/g, ' ') + "%' OR CAST(RouteNumber AS varchar(10)) LIKE '%" + freeTxt + "%' OR CAST(BridgeNumbers AS varchar(10)) LIKE '%" + freeTxt + "%' OR ProjectTitle LIKE '%" + freeTxt.replace(/_/g, ' ') + "%' OR ProjectKey LIKE '%" + freeTxt.replace(/_/g, ' ') + "%' OR StateProject LIKE '%" + freeTxt.replace(/_/g, ' ') + "%' OR FederalProject LIKE '%" + freeTxt.replace(/_/g, ' ') + "%')";
					if (cnty && cnty !== "Any")
						fText += " AND County = '" + cnty.replace(/_/g, ' ') + "'";
					if (ss && ss !== "Any")
						fText += " AND SignSystem = '" + ss.replace(/_/g, ' ') + "'";
					if (rtNo)
						fText += " AND RouteNumber LIKE '%" + rtNo + "%'";
					if (brNo)
						fText += " AND BridgeNumbers LIKE '%" + brNo + "%'";
					if (mmin)
						fText += " AND BeginMile >= " + parseInt(mmin);
					if (mmax)
						fText += " AND BeginMile <= " + parseInt(mmax);
					if (fymin)
						fText += " AND FiscalYear >= " + parseInt(fymin);
					if (fymax)
						fText += " AND FiscalYear <= " + parseInt(fymax);
					if (pTitle)
						fText += " AND ProjectTitle LIKE '%" + pTitle.replace(/_/g, ' ') + "%'";
					if (pKey)
						fText += " AND ProjectKey LIKE '%" + pKey.replace(/_/g, ' ') + "%'";
					if (fedPrj)
						fText += " AND FederalProject LIKE '%" + fedPrj.replace(/_/g, ' ') + "%'";
					if (statePrj)
						fText += " AND StateProject LIKE '%" + statePrj.replace(/_/g, ' ') + "%'";
					queryShare.where = fText;
					console.log(queryShare.where);
					//queryTaskShare.execute(queryShare, showPlanResults, function(e){
						//console.log(e);
					//});
					query.executeQueryJSON(services_application.Footprints + "/0",queryShare).then(utils.showPlanResults);
				}
				
				if ( px!=0 && py!=0 ){				// zoom in
					// 4326 is WGS-84, 3857 and 102100 are for web mercator
					if ( wkid != 4326 && wkid != 102100 && wkid != 3857 ){			// if the input point is not in either lat/long or web mercator
						var mapPnt1 = new Point( px, py, new SpatialReference(wkid));
						
						var params = new ProjectParameters();
						params.geometries = [mapPnt1];
						params.outSR = new SpatialReference(102100);
						
						DOT.objGeometryService.project(params, function(pt){
							DOT.map.center = new Point(pt[0]);
							DOT.map.zoom =  zl;
							DOT.shareGraphic.add(new Graphic(new Point(pt[0]),DOT.markerSymbol));
						}, function(e){
				
						});
					} else {
						var mapPnt;
						
						if ( wkid == 4326 )						// if the input point is in lat/long
						{
							mapPnt = geographicToWebMercator(new Point( (0-Math.abs(px)), py, new SpatialReference(wkid)));
						}
						else mapPnt = new Point( px, py, new SpatialReference(wkid));
						DOT.map.zoom =  zl;
						DOT.shareGraphic.add(new Graphic(mapPnt, DOT.markerSymbol));

						DOT.map.center = mapPnt;
						
						//deferred.then(function(){
							//if (zl!=0){
								//DOT.map.setLevel( zl );
								
								//DOT.shareGraphic.add(new esri.Graphic(mapPnt,picSymbol))
							//}
						//});
						
					}
				}
				
				utils.startFilter();
				utils.startCheckboxes();
				//if (!pl) $("#btnFilter").trigger("click");
				$("#loadingMap").hide();
			}
		}
	};
	
	/*$("#show_legend").click(function(e) {
		//$(".esriLegendServiceLabel").hide();
		if ( DOT.legendDijit ){
			if ( $("#refLegend").css("display")=="block" ){
				$("#refLegend").css("display","none");
				$("#show_legend").html("Show Legend");
			} else {
				$("#refLegend").css("display","block");
				$("#show_legend").html("Hide Legend");
			} 	
		} else {
			$("#show_legend").html("Hide Legend");
			
			DOT.legendDijit = new Legend({
				map: DOT.map,
				layerInfos: DOT.legend_layerInfo
			}, "refLegend");
			//DOT.legendDijit.startup();
			
			var deferred = DOT.legendDijit.startup();
			
			deferred.then(function(){
				if ( $("#refLegend").css("display")=="block" ){
					$("#refLegend").css("display","none");
					$("#show_legend").html("Show Legend");
				} else {
					$("#refLegend").css("display","block");
					$("#show_legend").html("Hide Legend");
				}
			});
		}
	});*/
	
	dojo.ready(DOT.init);
});