require([
	"dojo/dom", 
	"dojo/query",
	'dojox/grid/DataGrid', 
	'dojo/data/ItemFileWriteStore',
	"dojo/_base/array",
	"dojo/promise/all",
	"dojo/on",
	"esri/Basemap",
	"esri/Color", 
	"esri/Graphic",
	"esri/geometry/Circle",
	"esri/geometry/geometryEngine",
	"esri/views/MapView",
	"esri/layers/MapImageLayer", 
	"esri/layers/TileLayer", 
	"esri/request",
	"esri/widgets/Popup",
	"esri/widgets/BasemapGallery",
	"esri/symbols/SimpleMarkerSymbol", "esri/symbols/PictureMarkerSymbol", 
	"esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleLineSymbol",
	"esri/rest/find", "esri/rest/support/FindParameters",
	"esri/rest/query", "esri/rest/support/Query",
	"esri/rest/identify", "esri/rest/support/IdentifyParameters",
	"esri/rest/support/ProjectParameters", "esri/rest/support/BufferParameters",  "esri/rest/geometryService"
], function (dom, query, arrayUtils, all, on, DataGrid, ItemFileWriteStore, Basemap, Color, Graphic, Circle, geometryEngine, MapView, MapImageLayer, TileLayer, esriRequest, Popup, BasemapGallery, SimpleMarkerSymbol, PictureMarkerSymbol, SimpleFillSymbol, SimpleLineSymbol, find, FindParameters, query, Query, identify, IdentifyParameters, ProjectParameters, BufferParameters, geometryService) 
{
	utils = new function(){
		this.compare = function(a,b){
		  if (a.attributes.ID){
			if (a.attributes.ID < b.attributes.ID)
				return -1;
			if (a.attributes.ID > b.attributes.ID)
				return 1;
			return 0;
		  }
		}

		this.hexToRgb = function(hex) {
			// Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
			var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
			hex = hex.replace(shorthandRegex, function(m, r, g, b) {
				return r + r + g + g + b + b;
			});

			var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
			return result ? {
				r: parseInt(result[1], 16),
				g: parseInt(result[2], 16),
				b: parseInt(result[3], 16)
			} : null;
		}

		this.openNav = function(sideId) {
			$('#menuBtns').find('.btn-default').removeClass('activeBtn');
			var menuId = sideId + "Panel";
			var btnId = "btn" + sideId;
			if (menuId == "BasemapPanel") DOT.basemapBtnClick = true;
			if (menuId == "LayersPanel") {
				$("#sliderHighway").on("input", function(){
					DOT.reflyrHighway.opacity = this.value;
					$("#showHighwayOpacity").val(this.value);
				});
				$("#sliderGeneral").on("input", function(){
					DOT.reflyrGeneral.opacity = this.value;
					$("#showGeneralOpacity").val(this.value);
				});
				$("#sliderQuad").on("input", function(){
					DOT.reflyrQuad.opacity = this.value;
					$("#showQuadOpacity").val(this.value);
				});
			}
			if (!$("#" + menuId).is(':visible')) {
				$("#" + btnId).addClass('activeBtn');
				$("#LayersPanel").hide(300);
				$("#FilterPanel").hide(300);
				$("#BasemapPanel").hide(300);
				$("#HelpPanel").hide();
				$("#ToolsPanel").hide(300);
				var menuHeight = $(window).height() - 260;
				if (menuHeight < 480) menuHeight = 480;
				else if (menuHeight > 720) menuHeight = 720;
				$("#" + menuId).css("height", menuHeight);
				var maxHeight = menuHeight - 43;
				var filterHeight = menuHeight - 225;
				$("#resultsTable").css("max-height", filterHeight);
				$("#" + menuId + " .panel-body").css("max-height", maxHeight);
				$("#" + menuId).show(300);
			} else {
				$("#" + menuId).hide(300);
			}
		}
		this.closeToolPanel = function() {
			$("#ToolsPanel").find('.panel-collapse').collapse('hide');
			$("#ToolsPanel").hide(300);
			$('#btnTools').removeClass('activeBtn');
		}
		this.closeHelpPanel = function() {
			$("#HelpPanel").find('.panel-collapse').collapse('hide');
			$("#HelpPanel").hide(300);
			$('#btnHelp').removeClass('activeBtn');
			
		}
		this.closeFilterPanel = function() {
			//if ($('input[type=radio][name=locType]:checked').val() == "city") $("#selectListLocation").val("citynull");
			//if ($('input[type=radio][name=locType]:checked').val() == "county") $("#selectListLocation").val("cntynull");
			//$("#selectListHArea").val("hareanull");
			//$("#selectListFArea").val("fareanull");
			$("#everywhere").prop("checked", true);
			$("#selectListLocation").find('option').remove();
			$("#selectListLocation").css("display","none");
			$("#FilterPanel").find('.panel-collapse').collapse('hide');
			$('.list-group.checked-list-box .list-group-item').each(function () {
				var $widget = $(this),
				color = ($widget.data('color') ? $widget.data('color') : "selected"),
				style = ($widget.data('style') == "button" ? "btn-" : "list-group-item-"),
				settings = {
					on: {
						icon: 'glyphicon glyphicon-check'
					},
					off: {
						icon: 'glyphicon glyphicon-unchecked'
					}
				};
				$widget.data('state', "off");
				$widget.find('.state-icon')
					.removeClass()
					.addClass('state-icon ' + settings[$widget.data('state')].icon);
				$widget.removeClass(style + color + ' active');
			});
			DOT.searchGraphic.removeAll();
			$('#FilterPanel').hide(300);
			$("#filters").show();
			$("#btnApply").show();
			$("#btnClearInput").show();
			$("#btnReset").hide();
			$("#searchContent").hide();
			$('#btnFilter').removeClass('activeBtn');
		}
		this.toggle_visibility = function(id, parentId) {
			var e = document.getElementById(id);
			var ee = document.getElementById(parentId);
			//e.style.display = ((e.style.display!='none') ? 'none' : 'block');
			if (e.style.display == "none"){
				e.style.display = "block";
				ee.getElementsByClassName("glyphicon-plus")[0].style.display = "none";
				ee.getElementsByClassName("glyphicon-minus")[0].style.display = "block";
			} else {
				e.style.display = "none";
				ee.getElementsByClassName("glyphicon-plus")[0].style.display = "block";
				ee.getElementsByClassName("glyphicon-minus")[0].style.display = "none";
			}
		}
		this.trimWhitespaceAndMixedcase = function(str) {
			// remove all the whitespaces, tabs, returns, and line breaks.
			var trim1 = /^\s+|\s+$/g;
			if (str) {
				var str = str.replace(trim1, "");

				// remove the leading and ending whitespace, remove extra whitespaces in the middle
				var trim2 = /\s{2,}/g;
				var str2 = str.replace(trim2, " ");

				return str2;
			} 
			else
			{
				return "";
			}
		}

		this.checkFieldValue = function(fldVal) {
			if ( fldVal && fldVal!=undefined && (fldVal+"").trim().length>0 && (fldVal+"").toLowerCase()!="null"  )
				return fldVal;
			else
				return "&nbsp;";
		}

		this.checkFieldValue2 = function(fldVal) {
			if ( fldVal && fldVal!=undefined && (fldVal+"").trim().length>0 && (fldVal+"").toLowerCase()!="null"  )
				return fldVal;
			else
				return "";
		}

		this.formatFldVal_Num = function(fldVal) {
			if ( fldVal && fldVal!=undefined && (fldVal+"").trim().length>0 && (fldVal+"").toLowerCase()!="null" && fldVal != 0 )
				return fldVal.toLocaleString();
			else
				return "&nbsp;";
		}

		this.leadingZeros = function(str, n) {
			var s = str+"";
			while ( s.length < n ) s = "0" + s;
			return s;
		}

		this.leadingWhitespace = function(str, n) {
		  var s = str + "";
		  while (s.length < n)
		  s = " " + s;
		  return s;
		}

		this.formatFldVal_dollar = function(fldVal) {
			if ( fldVal && fldVal!=undefined && (fldVal+"").trim().length>0 && (fldVal+"").toLowerCase()!="null" && fldVal != 0 )
				return "$"+fldVal.toLocaleString();
			else
				return "&nbsp;";
			
		}

		this.startCheckboxes = function(){
			
			$("#chkFootprint").click(function(e) {
				e.stopPropagation();
				if (this.checked){
					$(this).prop('checked', true);
					DOT.srvlyrFootprints.visible = true;
				} else {
					$(this).prop('checked', false);
					DOT.srvlyrFootprints.visible = false;
				}
			});
			
			$("#chkHighway").click(function(e) {
				e.stopPropagation();
				if (this.checked){
					$(this).prop('checked', true);
					$("#setHighwayOpacity").show();
					$("#sliderHighway").removeAttr("disabled");
					DOT.reflyrHighway.visible = true;
				} else {
					$(this).prop('checked', false);
					$("#setHighwayOpacity").hide();
					$("#sliderHighway").attr("disabled", true);
					DOT.reflyrHighway.visible = false;
				}
			});
			
			$("#chkGeneral").click(function(e) {
				e.stopPropagation();
				if (this.checked){
					$(this).prop('checked', true);
					$("#setGeneralOpacity").show();
					$("#sliderGeneral").removeAttr("disabled");
					DOT.reflyrGeneral.visible = true;
				} else {
					$(this).prop('checked', false);
					$("#setGeneralOpacity").hide();
					$("#sliderGeneral").attr("disabled", true);
					DOT.reflyrGeneral.visible = false;
				}
			});
			
			$("#chkQuad").click(function(e) {
				e.stopPropagation();
				if (this.checked){
					$(this).prop('checked', true);
					$("#setQuadOpacity").show();
					$("#sliderQuad").removeAttr("disabled");
					DOT.reflyrQuad.visible = true;
				} else {
					$(this).prop('checked', false);
					$("#setQuadOpacity").hide();
					$("#sliderQuad").attr("disabled", true);
					DOT.reflyrQuad.visible = false;
				}
			});
		}

		this.startFilter = function(){
			//$("#searchInput").val("");
			$("#county_list").append(cntyOptions);
			$("#sign_list").append(signOptions);
			
			/*$("#county_list").change(function(){
				var cntySelected = $("#county_list").val();
				if (cntySelected != "cntyAll") {
					quickZoom(cntySelected, 3, "NAME");
					DOT.planGraphic.remove();
				}
			});*/
			
			$("#btnSearch").click(function() {
				utils.searchPlan();
			});
			
			$("#btnClearInput").click(function() {
				$('#filterOptions input').each(function(){
					$(this).val('');
				});
				$('#filterOptions select').each(function(){
					$(this).find('option:first').prop('selected', true);
				});
			});
			
			/*$("#form").submit(function(event) {
				console.log(1);
				event.preventDefault();
				searchPlan();
			});*/
			
			$('#btnReset').click(function() {
				$("#filters").show();
				$("#btnSearch").show();
				$("#btnReset").hide();
				$("#searchContent").hide();
				$("#searchInput").val("");
				
				$("#plan_search_results").find("tbody")
										   .remove()
										   .end();
				$('#resultsTableHead').hide();
				$("#planTotalReturns").hide();
				DOT.searchGraphic.removeAll();
				DOT.planGraphic.removeAll();
				DOT.geometryGraphic.removeAll();
				DOT.bufferGraphic.removeAll();
			});
			
			$('#btnClearGeometry').click(function(){
				$(".selectType").css("background-color", "buttonface");
				DOT.geometryGraphic.removeAll();
				DOT.bufferGraphic.removeAll();
				DOT.searchGraphic.removeAll();
				if (tb) {
					tb.deactivate();
					DOT.DOTClickHandler = DOT.map.on("click", DOT.onPlanClick);
				}
			});

			$(".selectType").click(function() {
				DOT.geometryGraphic.removeAll();
				DOT.bufferGraphic.removeAll();
				DOT.searchGraphic.removeAll();
				
				if (DOT.DOTClickHandler) DOT.DOTClickHandler.remove();
				geomType = this.id;
				$("#" + geomType).css("background-color", "#B4B4B4");
				if (tb) tb.activate(geomType);
			});
		};

		this.quickZoom = function(srchTxt, lyrId, fldName) {
			var quickzoomQT;
			//if (lyrId == 1) quickzoomQT = new QueryTask(services_application.Task_zoom + "1");
			//else if (lyrId == 3) quickzoomQT = new QueryTask(services_application.Task_zoom + "3");
			
			var quickzoomQuery = new Query();
			quickzoomQuery.returnGeometry = true;
			quickzoomQuery.outFields = ["*"];
			quickzoomQuery.where = fldName + " = '" + srchTxt + "'";
			if (lyrId == 1) {
				query.executeQueryJSON(services_application.Task_zoom + "1",quickzoomQuery).then(function (featureSet) {
					var geo1 = featureSet.features[0].geometry;

					DOT.map.Extent = geo1.Extent.expand(1.5);
				});
			} else if (lyrId == 3) {
				query.executeQueryJSON(services_application.Task_zoom + "3",quickzoomQuery).then(function (featureSet) {
					var geo1 = featureSet.features[0].geometry;

					DOT.map.Extent = geo1.Extent.expand(1.5);
				});
			}
		}

		this.searchPlan = function(){
			$('#filters').hide();
			$('#searchContent').show();
			$('#searchProgress').show();
			
			DOT.planGraphic.removeAll();
			
			var filterText = "1 = 1";
			var querySearch = new Query();
			//var querytask = new QueryTask(services_application.Footprints+"/0");
			querySearch.returnGeometry = true;
			querySearch.outSpatialReference = DOT.map.spatialReference;
			querySearch.outFields = ["*"];
			
			if ($("#county_list").val() && $("#county_list").val() != "cntyAll")
				filterText += " AND County = '" + $("#county_list").val() + "'";
			if ($("#sign_list").val() && $("#sign_list").val() != "signAll")
				filterText += " AND SignSystem = '" + $("#sign_list").val() + "'";
			if ($("#searchRtNo").val() && $("#searchRtNo").val() != "")
				//filterText += " AND RouteNumber LIKE '%" + $("#searchRtNo").val() + "%'";
				filterText += " AND RouteNumber = " + $("#searchRtNo").val();
			if ($("#searchBrNo").val() && $("#searchBrNo").val() != "")
				filterText += " AND BridgeNumbers LIKE '%" + $("#searchBrNo").val() + "%'";
			if ($("#searchMileStart").val() && $("#searchMileStart").val() != "")
				filterText += " AND BeginMile >= " + parseInt($("#searchMileStart").val());
			if (($("#searchMileEnd").val() && $("#searchMileEnd").val() != ""))
				filterText += " AND BeginMile <= " + parseInt($("#searchMileEnd").val());
			if ($("#searchFYStart").val() && $("#searchFYStart").val() != "")
				filterText += " AND FiscalYear >= " + parseInt($("#searchFYStart").val());
			if (($("#searchFYEnd").val() && $("#searchFYEnd").val() != ""))
				filterText += " AND FiscalYear <= " + parseInt($("#searchFYEnd").val());
			if ($("#prjTitleSearch").val() && $("#prjTitleSearch").val() != "")
				filterText += " AND ProjectTitle LIKE '%" + $("#prjTitleSearch").val() + "%'";
			if ($("#prjKeySearch").val() && $("#prjKeySearch").val() != "")
				filterText += " AND ProjectKey LIKE '%" + $("#prjKeySearch").val() + "%'";
			if ($("#fedPrjSearch").val() && $("#fedPrjSearch").val() != "")
				filterText += " AND FederalProject LIKE '%" + $("#fedPrjSearch").val() + "%'";
			if ($("#statePrjSearch").val() && $("#statePrjSearch").val() != "")
				filterText += " AND StateProject LIKE '%" + $("#statePrjSearch").val() + "%'";
			
			querySearch.where = filterText;
			console.log(filterText);
			//querytask.execute(query).then(function (response) {
				//utils.showPlanResults(response);
			//});
			query.executeQueryJSON(services_application.Footprints+"/0",querySearch).then(function (featureSet) {
				utils.showPlanResults(featureSet);
			});
		}

		this.onKeyPress = function(e) {
			var chCode = ('charCode' in e) ? e.charCode : e.keyCode;
			return (chCode >= 48 && chCode <= 57);
		}

		this.showPlanResults = function(results){
			$('#searchProgress').hide();
			$("#planTotalReturns").show();
			$("#btnReset").show();
			var plans = new Array();
			var resultIDs = [];
			if ( results.hasOwnProperty("features") )
				plans = results.features;
			else
				plans = results;
			console.log(plans.length);
			searchresultPlan = plans;
			/*var symbol = new esri.symbol.SimpleFillSymbol(
							esri.symbol.SimpleFillSymbol.STYLE_SOLID,
							new esri.symbol.SimpleLineSymbol( esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([0, 0, 255, 0.5]), 2),
							new esri.Color([0, 0, 255, 0.1])
						);*/
			$("#plan_search_results").find("tbody")
									.remove()
									.end();
			var $str = $('<tbody>');
			if (plans.length == 0) {
				 $("#planTotalReturns").html("No plan was found. Please try a different search criteria.");
			} else {
				if (plans.length >= 1000) window.alert("Due to system limits, only the first 1,000 matching records are shown. Please try a more specified criteria for better accuracy.");
				//$("#planTotalReturns").html("<b>" + plans.length + "</b> plan(s) found. Click on a record to zoom in and view its detailed info.");
				$('#resultsTableHead').show();
				$("#plan_search_results").append($str);

				var iiiddd = Math.ceil(Math.random()*100000);
				
				//var querytask_plan = new QueryTask(services_application.Footprints+"/0"); 
				var query_plan = new Query();

				query_plan.returnGeometry = true;
				query_plan.outSpatialReference = DOT.map.spatialReference;
				query_plan.outFields = ["*"];
				
				plans.sort(function(a,b){
					if (a.attributes["ID"] < b.attributes["ID"]) return -1;
					else if (a.attributes["ID"] > b.attributes["ID"]) return 1;
					return 0;
				});
				var shpGeometries = [];
				for (var i=0; i<plans.length; i++) {
					var planResult = 'planResult_' + iiiddd + '_' + i;
					var planResultWarning = 'planResultWarning_' + iiiddd + '_' + i;
					var planNoGeometry = 'planNoGeometry_' + iiiddd  + '_' + i + '_close';
					
					var planGeom = plans[i].geometry;
					var symbol1 = {
						type: "simple-fill",
						style: "none",
						outline: {
							color: [255, 255, 0, 1], 
							width: "3px"
						}
					};
					var o = new Object();
					if (plans[i].hasOwnProperty("feature")){
						o = plans[i].feature.attributes;
					} else {
						o = plans[i].attributes;
					}
					var prjID = "";
					if (utils.checkFieldValue(o.ID) != "&nbsp;") prjID = o.ID;
					
					var prjKey = "&nbsp;";
					if (utils.checkFieldValue(o.ProjectKey) != "&nbsp;") prjKey = o.ProjectKey;
					
					var prjTitle = "&nbsp;";
					if (utils.checkFieldValue(o.ProjectTitle) != "&nbsp;") prjTitle = o.ProjectTitle;
					
					var prjCounty = "&nbsp;";
					if (utils.checkFieldValue(o.County) != "&nbsp;") prjCounty = o.County;
					
					if (resultIDs.indexOf(prjID) < 0) {
						resultIDs.push(prjID);
						DOT.searchGraphic.add(new Graphic(planGeom, symbol1));
						if (prjID != 2276) shpGeometries.push(planGeom);
						
						$str = ('<tr id="' + planResult + '"><td style="padding-left: 0px; padding-right: 0px; font-style: italic;">' + prjID + '</td><td style="padding-left: 0px; padding-right: 0px;"><span id="planSearchRestult_' + iiiddd + '">' + prjKey + '</span></td><td style="padding-left: 0px; padding-right: 0px;">' + prjCounty + '</td></tr>');
						$("#plan_search_results").append($str);
						
						$str = $('<tr id="' + planResultWarning + '" style="display: none;"><td colspan="4">' + 
							'<div class="bg-warning text-warning" style="font-size: 12px;"><a id="' + planNoGeometry + '" class="close" aria-label="close" style="padding-right: 5px; font-size: 18px; opacity: 0.5;">&times;</a><strong>Warning!</strong> This plan has no corresponding geometry available.</div>' +
							'</td></tr>');
						$("#plan_search_results").append($str);

						$('#' + planNoGeometry).on('click', function(e){
							e.stopPropagation();
							
							var a= this.id.split("_");
							$("#planResultWarning_" + a[1] + "_" + a[2]).css("display", "none");
							
						});
						$("#" + planResult).on('mouseover', function(event) {
							//DOT.planGraphic.remove();
							var a= this.id.split("_");
							var ii = a[2];
							
							var warning11 = 'planResultWarning_' + a[1] + '_' + a[2];
							
							var o222;
							
							if (searchresultPlan[ii].hasOwnProperty("feature")){
								o222 = searchresultPlan[ii].feature;
							}
							else {
								o222 = searchresultPlan[ii];
							}
							
							//DOT.map.setExtent(new esri.geometry.Polygon(o222.geometry).getExtent());
							
							query_plan.where = "ID =" + o222.attributes.ID;
							//querytask_plan.execute(query_plan).then(function (response) {
							query.executeQueryJSON(services_application.Footprints+"/0",query_plan).then(function (featureSet) {
								if (featureSet.features.length > 0) {
									DOT.planGraphic.removeAll();
									var geom1 = featureSet.features[0].geometry;
									
									var symbol2 = {
										type: "simple-fill",
										style: "none",
										outline: {
											color: [0, 0, 255, 1], 
											width: "3px"
										}
									};
									
									DOT.planGraphic.add(new Graphic(geom1, symbol2));
								}
							});
							/*function(e){
								console.log(e);
								$("#" + warning11).css("display", "table-row");
								//alert("This plan has no corresponding geometry available.");
							});*/
						});
						
						$("#" + planResult).on('mouseout', function(event) {
							DOT.planGraphic.removeAll();
						});
						
						$("#" + planResult).on('click', function(event) {
							DOT.planGraphic.removeAll();
							var a= this.id.split("_");
							var ii = a[2];
							
							var warning11 = 'planResultWarning_' + a[1] + '_' + a[2];
							
							var o222;
							
							if (searchresultPlan[ii].hasOwnProperty("feature")){
								o222 = searchresultPlan[ii].feature;
							}
							else {
								o222 = searchresultPlan[ii];
							}
							console.log(o222);
							query_plan.where = "ID =" + o222.attributes.ID;
							//querytask_plan.execute(query_plan).then(function (response) {
							query.executeQueryJSON(services_application.Footprints+"/0",query_plan).then(function (featureSet) {
								if (featureSet.features.length > 0) {
									/*var geom1 = r.features[0].geometry;
									var deferred = DOT.map.setExtent(geom1.getExtent().expand(2));
									deferred.then(function(){
										DOT.geometryService.labelPoints([geom1], function(labelPoints) {
											var labelPt = labelPoints[0];
											DOT.onPlanClick(null, labelPt);
										});
									});*/
									var resultFeature = featureSet.features[0];
									DOT.showImage(resultFeature.attributes.Name);
									var resultLocPt = resultFeature.geometry.centroid;
									var screenPt = DOT.map.toScreen(resultLocPt);
									DOT.map.popup.close();
									DOT.map.popup.title = "Project ID: " + resultFeature.attributes.ID;
									var formatString = "<span style='display:none;' id='prjKeySelected'>" + resultFeature.attributes.Name + "</span><b>Project Key: </b>" + resultFeature.attributes.ProjectKey + "<br><b>Project Title: </b>" + resultFeature.attributes.ProjectTitle;
									if (resultFeature.attributes.FederalProject != "Null" && resultFeature.attributes.FederalProject) formatString += "<br><b>Federal Project #: </b>" + resultFeature.attributes.FederalProject;
									if (resultFeature.attributes.StateProject != "Null" && resultFeature.attributes.StateProject) formatString += "<br><b>State Project #: </b>" + resultFeature.attributes.StateProject;
									if (resultFeature.attributes.County != "Null" && resultFeature.attributes.County) formatString += "<br><b>County: </b>" + resultFeature.attributes.County;
									if (resultFeature.attributes.SignSystem != "Null" && resultFeature.attributes.SignSystem) formatString += "<br><b>Sign System: </b>" + resultFeature.attributes.SignSystem;
									if (resultFeature.attributes.FiscalYear != "Null" && resultFeature.attributes.FiscalYear) formatString += "<br><b>Fiscal Year: </b>" + resultFeature.attributes.FiscalYear;
									if (resultFeature.attributes.RouteNumber != "Null" && resultFeature.attributes.RouteNumber) formatString += "<br><b>Route #: </b>" + resultFeature.attributes.RouteNumber;
									if (resultFeature.attributes.BeginMile != "Null" && resultFeature.attributes.BeginMile) formatString += "<br><b>Begin Mile: </b>" + resultFeature.attributes.BeginMile;
									if (resultFeature.attributes.BridgeNumbers != "Null" && resultFeature.attributes.BridgeNumbers) formatString += "<br><b>Bridge Numbers: </b>" + resultFeature.attributes.BridgeNumbers;
									var reportUrl = "https://mapwv.gov/dotplans/ProjectDetails.php?scanID=" + resultFeature.attributes.ID;
									formatString += "<br><a style='cursor:pointer;' target='_blank' href='" + reportUrl + "'>Click Here</a> for More Information";
									//formatString += '<br><a style="cursor:pointer;" onclick="DOT.showImage(\'' + resultFeature.attributes.Name + '\')">Click Here</a> to Show Plan Image';
									DOT.map.popup.content = formatString;
									DOT.map.popup.open({
										location: resultLocPt,
									});

									$(".titleButton.prev").addClass("hidden");
									$(".titleButton.next").addClass("hidden");
									$("#linkType_plan").prop("disabled", false);
									if ($("input[name='linkType']").filter(":checked").val() && $("#btnShareLink").is(":disabled")) $("#btnShareLink").prop("disabled", false);
									$("#sharePlan").css("color", "black");
								}
							});
							/*, function(e){
								console.log(e);
								$("#" + warning11).css("display", "table-row");
								//alert("This plan has no corresponding geometry available.");
							});*/
						});
					}
				}
				$("#planTotalReturns").html("<b>" + resultIDs.length + "</b> plan(s) found. Click on a record to zoom in and view its detailed info.");
				if (resultIDs.length == 1) $("#plan_search_results").find("tbody").children('tr:first').trigger("click");
				else if (resultIDs.length > 1) {
					var shpGeometry = geometryEngine.union(shpGeometries);
					DOT.map.extent = shpGeometry.extent;
				}
			}
			$("#plan_search_results").append("</tbody");
		}

		this.buildBasemap = function() {
			var basemaps = [];
			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"
			});*/
			basemaps.push(Basemap.fromId("streets-vector"),Basemap.fromId("osm"),DOT.basemapBestLeavesOff,Basemap.fromId("satellite"),Basemap.fromId("hybrid"),Basemap.fromId("terrain"),Basemap.fromId("dark-gray-vector"),Basemap.fromId("gray-vector"));

			// ESRI Street
			/*var basemapLayerEsriStreet = new MapImageLayer({
				url : services_basemap.esri_street
			});
			basemapEsriStreet = new Basemap({
				id : "ESRI_STREET",
				baseLayers : [basemapLayerEsriStreet],
				title : "ESRI Street",
				thumbnailUrl : "images/basemap_icon/esri_streets.jpg"
			});
			basemaps.push(basemapEsriStreet);
			
			// OpenStreetMap
			var basemapOSM = new Basemap({
				id : "OpenStreetMap",
				baseLayers : [new MapImageLayer({
					type : "OpenStreetMap"
				})],
				title : "OpenStreetMap",
				thumbnailUrl : "images/basemap_icon/openstreetmap.png"
			});
			basemaps.push(basemapOSM);
			
			// Bing Road
			var basemapBingRoad = new Basemap({
				id : "BING_ROAD",
				baseLayers : [new MapImageLayer({
					type : "BingMapsRoad"
				})],
				title : "Bing Road",
				"data-content" : "Bing Road basemap service: through ESRI's map service",
				thumbnailUrl : "images/basemap_icon/bing_road.png"
			});
			basemaps.push(basemapBingRoad);
			
			// Bing Hybrid
			basemapBingHybrid = new Basemap({
				id : "BING_HYBRID",
				baseLayers : [new MapImageLayer({
					type : "BingMapsHybrid"
				})],
				title : "Bing Hybrid",
				thumbnailUrl : "images/basemap_icon/bing_hybrid.png"
			});
			basemaps.push(basemapBingHybrid);
			
			// WV Best Leaves Off
			var basemapLayerBestLeavesOff = new MapImageLayer({
				url : services_basemap.gistc_leafoff
			});
			basemapBestLeavesOff = new Basemap({
				id : "IMAGE_BESTLEAVESOFF",
				baseLayers : [basemapLayerBestLeavesOff],
				title : "WV Best Leaves Off",
				thumbnailUrl : "images/basemap_icon/wvgistc_bestleavesoff.png"
			});
			basemaps.push(basemapBestLeavesOff);
			
			// Bing Imagery
			var basemapBingImagery = new Basemap({
				id : "BING_AERIAL",
				baseLayers : [new MapImageLayer({
					type : "BingMapsAerial"
				})],
				title : "Bing Imagery",
				thumbnailUrl : "images/basemap_icon/bing_aerial.png"
			});
			basemaps.push(basemapBingImagery);
			
			// ESRI Imagery
			var basemapLayerEsriImage = new MapImageLayer({
				url : services_basemap.esri_imagery
			});
			basemapEsriImage = new Basemap({
				id : "ESRI_IMAGERY",
				baseLayers : [basemapLayerEsriImage],
				title : "ESRI Imagery",
				thumbnailUrl : "images/basemap_icon/esri_imagery.jpg"
			});
			basemaps.push(basemapEsriImage);
			
			// WV DEP Hillshade
			var basemapLayerDEPHillshade = new MapImageLayer({
				url : services_basemap.wvdep_hill
			});
			basemapDEPHillshade = new Basemap({
				id : "DEP_HILLSHADE",
				baseLayers : [basemapLayerDEPHillshade],
				title : "WV DEP Hillshade*",
				thumbnailUrl : "images/basemap_icon/wvdep_hillshade.png"
			});
			basemaps.push(basemapDEPHillshade);
			
			// WV DEP Topography
			var basemapLayerDEPTopo = new MapImageLayer({
				url : services_basemap.wvdep_topo
			});
			basemapDEPTopo = new Basemap({
				id : "DEP_TOPO",
				baseLayers : [basemapLayerDEPTopo],
				title : "WV DEP Topography*",
				thumbnailUrl : "images/basemap_icon/wvdep_topo.png"
			});
			basemaps.push(basemapDEPTopo);
			
			// ESRI Topography
			var basemapLayerEsriTopo = new MapImageLayer({
				url : services_basemap.esri_topo
			});
			basemapEsriTopo = new Basemap({
				id : "ESRI_TOPO",
				baseLayers : [basemapLayerEsriTopo],
				title : "ESRI Topography",
				thumbnailUrl : "images/basemap_icon/esri_topo.jpg"
			});
			basemaps.push(basemapEsriTopo);

			// USA Topography
			var basemapLayerUSATopo = new MapImageLayer({
			url : services_basemap.esri_usa_topo
			});
			basemapUsaTopo = new Basemap({
				id : "USA_TOPO",
				baseLayers : [basemapLayerUSATopo],
				title : "USA Topography",
				thumbnailUrl : "images/basemap_icon/usa_topo.jpg"
			});
			basemaps.push(basemapUsaTopo);

			// National Geographiy
			var basemapLayerNationalGeographiy = new MapImageLayer({
				url : services_basemap.esri_NatGeo
			});
			basemapNationalGeographiy = new Basemap({
				id : "NATIONAL_GEOGRAPHY",
				baseLayers : [basemapLayerNationalGeographiy],
				title : "National Geographic",
				thumbnailUrl : "images/basemap_icon/esri_natgeo.jpg"
			});
			basemaps.push(basemapNationalGeographiy);

			// GISTC Basemap
			var basemapLayerGISTCBasemap = new MapImageLayer({
				url : services_basemap.gistc_basemap
			});
			basemapGISTCBasemap = new Basemap({
				id : "GISTC_BASEMAP",
				baseLayers : [basemapLayerGISTCBasemap],
				title : "WV GISTC Basemap",
				thumbnailUrl : "images/basemap_icon/wv_elevation.png"
			});
			basemaps.push(basemapGISTCBasemap);

			// ESRI Dark Gray
			var basemapLayerDarkGray = new MapImageLayer({
				url : services_basemap.esri_dark_gray
			});
			basemapDarkgray = new Basemap({
				id : "esri_darkgray",
				baseLayers : [basemapLayerDarkGray],
				title : "Dark Gray Canvas",
				thumbnailUrl : "images/basemap_icon/esri_darkgrey_canvas.png"
			});
			basemaps.push(basemapDarkgray);

			// ESRI Light Gray
			var basemapLayerLightGray = new MapImageLayer({
			url : services_basemap.esri_light_gray
			});
			basemapLightgray = new Basemap({
				id : "esri_lightgray",
				baseLayers : [basemapLayerLightGray],
				title : "Light Gray Canvas",
				thumbnailUrl : "images/basemap_icon/Light_Gray_Canvas.png"
			});
			basemaps.push(basemapLightgray);*/
			
			return basemaps;
		}

		this.toggle_basemap = function(){
			$("#basemapToggleStreet").on("click", function(){
				DOT.basemapGallery.select("ESRI_STREET");
				$("#basemapToggleStreet").hide();
				$("#basemapToggleImagery").show();
			});
			$("#basemapToggleImagery").on("click", function(){
				DOT.basemapGallery.select("IMAGE_BESTLEAVESOFF");
				$("#basemapToggleImagery").hide();
				$("#basemapToggleStreet").show();
			});
			$("#galleryNode_IMAGE_BESTLEAVESOFF").on("click", function(){
				$("#basemapToggleImagery").hide();
				$("#basemapToggleStreet").show();
			});
			$("#galleryNode_ESRI_STREET").on("click", function(){
				$("#basemapToggleImagery").show();
				$("#basemapToggleStreet").hide();
			});
		}

		this.openFAQ = function(){
			$('a[href="#faq"]').tab('show');
			if (!$("#help").is(":visible")) $("#btnHelp").trigger("click");
			if ($("#hideDetail").is(":visible")) $("#hideDetail").trigger("click");
		}
	}
})