'use strict';
dojo.require("dojo.on");
dojo.require("dojo.dom");
dojo.require("dojo.query");
dojo.require("dojo.promise.all");
dojo.require("dojo._base.array");
dojo.require("dojox.grid.DataGrid");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.registry");
dojo.require("esri.tasks.FindTask");
dojo.require("esri.tasks.FindParameters");
dojo.require("esri.tasks.IdentifyParameters");
dojo.require("esri.tasks.IdentifyTask");
dojo.require("esri.tasks.IdentifyResult");
dojo.require("esri.tasks.QueryTask");
dojo.require("esri.tasks.query");
dojo.require("esri.symbols.SimpleMarkerSymbol");
dojo.require("esri.symbols.SimpleLineSymbol");
dojo.require("esri.symbols.SimpleFillSymbol");
dojo.require("esri.symbols.PictureMarkerSymbol");
dojo.require("esri.Color");
dojo.require("esri.geometry.Circle")
dojo.require("esri.tasks.ProjectParameters");
dojo.require("esri.graphic");
dojo.require("esri.toolbars.draw");

var downloadLinks = [];
var searchresultGNIS = [];
var searchresultDOT = [];
var searchresultsGeometry = [];
var idList1 = [];
var idList2 = [];
var fieldList = ['Site_ID', 'Alt_ID'];
var geomType;

function Search(args) {
    /*jshint validthis: true */
    var options = {
        position: {
            //top: '100px',
            //left: '100px',
            //bottom: '100px',
            //right: '100px'
        },
        center: true,
        id: 0
    };
    $.extend(options, args);
    this.options = options;
};

Search.prototype.init = function(basicSearch) {

		$("#frmMainSearch").submit(function(event) {
        	event.preventDefault();
            startSearch();
		});

        $(".searchIcon").click(function(event) {
            event.preventDefault();
            startSearch();
        });
        
        $("#selectListCity").append(cityOptions);
		$("#selectListCnty").append(cntyOptions);
		
        function startSearch(){
            
            if ( $("#filterType").val()=="Address" ){
	            var address = {
					"SingleLine": $("#frmMainSearch input").val()
				};
	            var addressParam = {
					address : address,
					outFields : ["Loc_name"]
				};
	
				wvgistcLocator.map = DOT.map;
				wvgistcLocator.address = address;
				wvgistcLocator.locateAddress();
				
				$("#searchContent").css("display", "block");
				$("#address_result").css("display", "block");
				$("#searchTitle").html("<h4><b>Search by Geographic Name</b></h4>");
				var searchPanelHeight = $("#address_result").height() + $("#searchTitle").height() + 23;
				var searchMapHeight = $(window).height() - searchPanelHeight;
				$("#map").css("height",  searchMapHeight);
				$("#searchContent").css("height", searchPanelHeight);
				$("#searchContent").css("top",  searchMapHeight);
			}
			
			if ( $("#filterType").val()=="Coordinate" ){
				//Coordinate_Search();
			}
			
			if ( $("#filterType").val()=="Name" ){
				//Feature_search();
			}
			
			if ( $("#filterType").val()=="Geometry" ) {
				//Geometry_Search();
			}
			
			if ( $("#filterType").val()=="GNIS Name" ){
				GNIS_search();
			}
		};
		
        $("#btnCoordSearch").click(function() {
			DOT.searchGraphic.clear();
        	var id =  $("input[name=rbgCoordType]:checked").attr('id');
        	
			var arrCoord 	= new Array();
			var pPt;
			
        	if ( id == "radioLatLong_decimal" || id == "radioLatLong_dms") {
        		if ( id == "radioLatLong_decimal" || id == "radioLatLong_dms") { 
					arrCoord[0] = $("#dd_lat").val();
					arrCoord[1] = $("#dd_long").val();
				}
				if ( id == "radioLatLong_dms" ) {
					arrCoord[0] = 		( Number($("#dms_lat_s").val())/60 + Number($("#dms_lat_m").val()) )/60 + Number($("#dms_lat_d").val());
					arrCoord[1] = "-" + ( (Number($("#dms_long_s").val())/60 + Number($("#dms_long_m").val()))/60 + Math.abs(Number($("#dms_long_d").val())));
        		}
        		
        		pPt = new esri.geometry.Point( Number(arrCoord[1]), Number(arrCoord[0]), new esri.SpatialReference({wkid:4326}) );
        	}       	
        	
        	if ( id == "radioUTM" ) {
        		arrCoord[1] = $("#utm17_northing").val();
				arrCoord[0] = $("#utm17_easting").val();
				
				pPt = new esri.geometry.Point( Number(arrCoord[1]), Number(arrCoord[0]), new esri.SpatialReference({wkid:26917}) );
        	}
        	
        	var projParms = new esri.tasks.ProjectParameters();
        	projParms.geometries = [pPt];
        	projParms.outSR = new esri.SpatialReference(102100);
        	
        	//DOT.geometryService.on("project-complete", projectComplete);
        	//DOT.geometryService.project(projParms);
        	
        	DOT.geometryService.project(projParms,function(pt) {
        		var g = new esri.Graphic(pt[0], DOT.markerSymbol);
				DOT.searchGraphic.add(g);
        		DOT.map.centerAndZoom(new esri.geometry.Point(pt[0]),10);
        	}, function(e){
        		alert("error zooming to location");
        	});
        });
		
		/*function Feature_search() {
			DOT.searchGraphic.clear();
			$("#downloads1").css("display", "none");
			if ($("#frmMainSearch input").val() != ""){
				if ($("#checkboxes1 input:checked").filter(':visible').length != 0) {
					if (document.getElementById('asiteBox').checked) {
						addIDList(0, idList1);
						addIDList(7, idList1);
					} else {
						dropIDList(0, idList1);
						dropIDList(7, idList1);
					}
					
					if (document.getElementById('asurveyBox').checked) {
						addIDList(1, idList1);
						addIDList(8, idList1);
						if (fieldList.indexOf("Site_Name") < 0) fieldList.push('Site_Name');
					} else {
						dropIDList(1, idList1);
						dropIDList(8, idList1);
						if (fieldList.indexOf("Site_Name") > -1) fieldList.splice(fieldList.indexOf('Site_Name'), 1);
					}
					
					if (document.getElementById('civilBox').checked) {
						addIDList(5, idList1);
						addIDList(12, idList1);
						if (fieldList.indexOf("Battle") < 0) fieldList.push('Battle');
					} else {
						dropIDList(5, idList1);
						dropIDList(12, idList1);
						if (fieldList.indexOf("Battle") > -1) fieldList.splice(fieldList.indexOf('Battle'), 1);
					}
									
					if (document.getElementById('archBox').checked) {
						addIDList(2, idList1);
						addIDList(9, idList1);
						if (fieldList.indexOf('HistName') < 0) fieldList.push('HistName');
						if (fieldList.indexOf('CommonName') < 0) fieldList.push('CommonName');
					} else {
						dropIDList(2, idList1);
						dropIDList(9, idList1);
						if (fieldList.indexOf('HistName') > -1) fieldList.splice(fieldList.indexOf('HistName'), 1);
						if (fieldList.indexOf('CommonName') > -1) fieldList.splice(fieldList.indexOf('CommonName'), 1);
					}
					
					if (document.getElementById('cemeBox').checked) {
						addIDList(6, idList1);
						addIDList(13, idList1);
						if (fieldList.indexOf('HistName') < 0) fieldList.push('HistName');
						if (fieldList.indexOf('ComName') < 0) fieldList.push('ComName');
					} else {
						dropIDList(6, idList1);
						dropIDList(13, idList1);
						if (fieldList.indexOf('HistName') > -1) fieldList.splice(fieldList.indexOf('HistName'), 1);
						if (fieldList.indexOf('ComName') > -1) fieldList.splice(fieldList.indexOf('ComName'), 1);
					}

					if (document.getElementById('nareBox').checked) {
						addIDList(3, idList1);
						addIDList(10, idList1);
						addIDList(4, idList1);
						addIDList(11, idList1);
						if (fieldList.indexOf("HistName") < 0) fieldList.push('HistName');
						if (fieldList.indexOf('CommonName') < 0) fieldList.push('CommonName');
					} else {
						dropIDList(3, idList1);
						dropIDList(10, idList1);
						dropIDList(4, idList1);
						dropIDList(11, idList1);
						if (fieldList.indexOf("HistName") > -1) fieldList.splice(fieldList.indexOf('HistName'), 1);
						if (fieldList.indexOf('CommonName') > -1) fieldList.splice(fieldList.indexOf('CommonName'), 1);
					}
					for (var i=0; i<idList1.length; i++) {
						if (visible.indexOf(idList1[i]) < 0) idList1.splice(i, 1);
					}
					if (idList1.length > 0) {
						for (var i=0; i<idList1.length; i++) {
							if (visible.indexOf(idList1[i]) < 0) idList1.splice(i, 1);
						}
					}
					if (idList1.length > 0) {
						$('#shpoSearchProgress').css("display","block");
						var findParamsSHPO = new esri.tasks.FindParameters();
						findParamsDOT.returnGeometry = true;
						findParamsDOT.layerIds = idList1;
						findParamsDOT.searchFields = fieldList;
						findParamsDOT.searchText = $("#frmMainSearch input").val();
						
						var findTaskSHPO = new esri.tasks.FindTask(services_application.shpo);
						findTaskDOT.execute(findParamsSHPO, function(results){
							downloadLinks = [];
							$("#shpo_search_results").find("tbody")
													.remove()
													.end();
							var str = "";
							var ptorarea = "";
							str += '<tbody>';
							$("#shpo_search_results").append(str);
							searchresultDOT = results;
							if (results.length > 0) {
								if (results.length == 1000) alert("Due to the system's maximum display capacity, only the first 1000 records are shown in the search results. Please refine your search criteria in order to reduce the number of results.");
								var o = results[0].feature;
								if (o.geometry.type == "point")
									var unionedExtent = new esri.geometry.Extent(o.geometry.x, o.geometry.y, o.geometry.x, o.geometry.y, new esri.SpatialReference(102100));
								if (o.geometry.type == "polygon")
									var unionedExtent = new esri.geometry.Extent(o.geometry.getExtent());
								for (var i=0; i<results.length; i++) {
									o = results[i].feature;
									if (o.geometry.type == "point") {
										var pt = new esri.geometry.Point(o.geometry);
										unionedExtent = unionedExtent.union(new esri.geometry.Extent(o.geometry.x, o.geometry.y, o.geometry.x, o.geometry.y, new esri.SpatialReference(102100)));
										ptorarea = "- Point";
										var pt = new esri.geometry.Point(o.geometry);
										var g = new esri.Graphic(pt, DOT.sms2);
									} else if (o.geometry.type == "polygon") {
										var pt = new esri.geometry.Point(o.geometry.getCentroid());
										unionedExtent = unionedExtent.union(new esri.geometry.Extent(o.geometry.getExtent()));
										ptorarea = "- Area";
										var poly = new esri.geometry.Polygon(o.geometry);
										var g = new esri.Graphic(poly, DOT.sfs2);
									}
									//var g = new esri.Graphic(pt, DOT.markerSymbol);
									DOT.searchGraphic.add(g);
									//if (o.geometry.type == "point")
										//unionedExtent = unionedExtent.union(new esri.geometry.Extent(o.geometry.x, o.geometry.y, o.geometry.x, o.geometry.y, new esri.SpatialReference(102100)));
									//if (o.geometry.type == "polygon")
										//unionedExtent = unionedExtent.union(new esri.geometry.Extent(o.geometry.getExtent()));
									var repoUrl = "";
									var repoLink = "";
									var repoUrls = "";
									if 	(o.attributes.PDF_NAMES && o.attributes.PDF_NAMES != "" && o.attributes.PDF_NAMES != "Null") {
										var nameList = o.attributes.PDF_NAMES.split(",")
										for (var j=0; j<nameList.length; j++) {
											if (results[i].layerName.includes("Architecture Site"))
												repoUrl = "https://services.wvgis.wvu.edu/SHPOdocs/PDFs/Architectural/" + nameList[j];
											if (results[i].layerName.includes ("Archaeology Site"))
												repoUrl = "https://services.wvgis.wvu.edu/SHPOdocs/PDFs/ArchaeologySites/" + nameList[j];
											if (results[i].layerName.includes("Archaeology Survey"))
												repoUrl = "https://services.wvgis.wvu.edu/SHPOdocs/PDFs/ArchaeologySurveys/" + nameList[j];
											if (results[i].layerName.includes("National Register"))
												repoUrl = "https://services.wvgis.wvu.edu/SHPOdocs/PDFs/NationalRegister/" + nameList[j];
											if (results[i].layerName.includes("Cemeteries"))
												repoUrl = "https://services.wvgis.wvu.edu/SHPOdocs/PDFs/ArchaeologySites/" + nameList[j];
											repoLink = repoLink + " " + "<a href='" + repoUrl + "' target='_blank'>" + (j+1).toString() + "</a>";
											repoUrls = repoUrls + repoUrl + "; ";
											if (downloadLinks.indexOf(repoUrl)<0) downloadLinks.push(repoUrl);
										}
									} else if (results[i].layerName.includes("Civil War")) {
										repoUrl = "https://wvgis.wvu.edu/resources/dataProductDevelopment/2010_CivilWarGIS_Report.pdf";
										repoLink = "<a href='" + repoUrl + "' target='_blank'>1</a>";
										repoUrls = repoUrl;
									} else if (o.attributes.PDF_NAMES == "" || o.attributes.PDF_NAMES == "Null") {
										repoLink = "N/A";
										repoUrls = "N/A";
									}
									if (results[i].layerName.includes("Architecture Site"))
										str += ('<tr><td>'+ "Architecture Site " + ptorarea + '</td><td><b>Historic Name: </b> ' + o.attributes["Historical Name"] + ';<br><b>Common Name: </b> ' + o.attributes["Common Name"] + ';<br><b>ID:</b> ' + o.attributes["Site ID"] + ';<br><b>Alternate ID:</b> ' + o.attributes["Alternate ID"] + ';<br><b>County:</b> ' + o.attributes["County"] + ';<br><b>Quad:</b> ' + o.attributes["Quad"] + ';<br><b>City:</b> ' + o.attributes["City/Town"] + ';<br><b>Vicinity:</b> ' + o.attributes["Vicinity"] + '</td><td>' + repoLink + '</td><td style="display:none;">' + repoUrls + '</td></tr>');
									if (results[i].layerName.includes("Archaeology Site"))
										str += ('<tr><td>'+ "Archaeology Site " + ptorarea + '</td><td><b>ID:</b> ' + o.attributes["Site ID"] + ';<br><b>County:</b> ' + o.attributes["County"] + ';<br><b>Quad:</b> ' + o.attributes["Quad 1"] + '</td><td>' + repoLink + '</td><td style="display:none;">' + repoUrls + '</td></tr>');
									if (results[i].layerName == "Archaeology Survey - Point")
										str += ('<tr><td>'+ "Archaeology Survey - Point" + '</td><td><b>Project Name: </b> ' + o.attributes["Site Name"] + ';<br><b>ID:</b> ' + o.attributes["Site ID"] + ';<br><b>Alternate ID:</b> ' + o.attributes["Alternate ID"] + ';<br><b>County:</b> ' + o.attributes["County"] + ';<br><b>Quad:</b> ' + o.attributes["Quad"] + '</td><td>' + repoLink + '</td><td style="display:none;">' + repoUrls + '</td></tr>');
									if (results[i].layerName == "Archaeology Survey - Area")
										str += ('<tr><td>'+ "Archaeology Survey - Area" + '</td><td><b>Project Name: </b> ' + o.attributes["Site Name"] + ';<br><b>ID:</b> ' + o.attributes["Site ID"] + ';<br><b>Alternate ID:</b> ' + o.attributes["Alternate ID"] + ';<br><b>County:</b> ' + o.attributes["County"] + ';<br><b>Quad:</b> ' + o.attributes["Quad 1"] + '</td><td>' + repoLink + '</td><td style="display:none;">' + repoUrls + '</td></tr>');
									if (results[i].layerName.includes("National Register"))
										str += ('<tr><td>'+ "National Register " + ptorarea + '</td><td><b>Historic Name: </b> ' + o.attributes["Historical Name"] + ';<br><b>Common Name: </b> ' + o.attributes["Common Name"] + ';<br><b>Reference #:</b> ' + o.attributes["Reference Number"] + ';<br><b>County:</b> ' + o.attributes["County"] + ';<br><b>Quad:</b> ' + o.attributes["Quad"] + ';<br><b>City:</b> ' + o.attributes["City/Town"] + ';<br><b>Vicinity:</b> ' + o.attributes["Vicinity"] + '</td><td>' + repoLink + '</td><td style="display:none;">' + repoUrls + '</td></tr>');
									//if (results[i].layerName.includes("Restricted"))
										//str += ('<tr><td>'+ "Secured National Register " + ptorarea + '</td><td><b>Name: </b> ' + o.attributes.RESNAME + ';<br><b>ID:</b> ' + o.attributes.ID + ';<br><b>County:</b> ' + o.attributes.COUNTY + ';<br><b>Quad:</b> ' + o.attributes.QUAD + ';<br><b>City:</b> ' + o.attributes.CITY + ';<br><b>Address:</b> ' + o.attributes.ADDRESS + '</td><td>' + repoLink + '</td><td style="display:none;">' + repoUrls + '</td></tr>');
									if (results[i].layerName == "Civil War Sites")
										str += ('<tr><td>'+ "Civil War Sites" + '</td><td><b>Battle: </b> ' + o.attributes["Battle"] + ';<br><b>REF #:</b> ' + o.attributes["Reference"] + ';<br><b>Date:</b> ' + o.attributes["Date"] + ';<br><b>County:</b> ' + o.attributes["County"] + ';<br><b>City:</b> ' + o.attributes["City"] + '</td><td>' + repoLink + '</td><td style="display:none;">' + repoUrl + '</td></tr>');
									if (results[i].layerName == "Civil War Battlefields")
										str += ('<tr><td>'+ "Civil War Battlefields" + '</td><td><b>Battle: </b> ' + o.attributes["Battle"] + ';<br><b>Place:</b> ' + o.attributes["Place"] + ';<br><b>County:</b> ' + o.attributes["County"] + '</td><td>' + repoLink + '</td><td style="display:none;">' + repoUrl + '</td></tr>');
									if (results[i].layerName.includes("Cemeteries"))
										str += ('<tr><td>'+ "Cemetery " + ptorarea + '</td><td><b>Historic Name: </b> ' + o.attributes["Historic Name"] + ';<br><b>Common Name: </b> ' + o.attributes["Common Name"] + ';<br><b>ID:</b> ' + o.attributes["Site ID"] + ';<br><b>County:</b> ' + o.attributes["County"] + ';<br><b>Quad:</b> ' + o.attributes["Quad"] + '</td><td>' + repoLink + '</td><td style="display:none;">' + repoUrls + '</td></tr>');
								}
								str += '</tbody>';
								$("#shpo_search_results").append(str);
								DOT.map.setExtent(unionedExtent.expand(1.5));
								$("#downloads1").css("display", "block");
								$(document).on('click', "#shpo_search_results tbody tr", function(event) {
									$("#shpoInfoPanel").css("display","block");
									$("#sideInfo1_img").attr("src", "./images/ui/panel_close_upper.png");
									$("#sideInfo2_img").attr("src", "./images/ui/panel_close_down.png");
									DOT.idGraphic.clear();
									var resultSelected = searchresultDOT[event.currentTarget.rowIndex-1];
									var o222 = resultSelected.feature;
									if (o222.geometry.type == "point") {
										var pt = new esri.geometry.Point(o222.geometry);
									} else if (o222.geometry.type == "polygon") {
										var pt = new esri.geometry.Point(o222.geometry.getCentroid());
										}
									DOT.map.centerAndZoom(pt, 10);
									DOT.onResultsReturn([resultSelected], pt);
									populateSHPOInfo(o222, pt);
									$(document).on('click', '#zoomToFeature', function(event) {
										DOT.zoomToFeature(pt);
									});
								});
							} else {
								$("#shpo_search_results").find("tbody")
														.remove()
														.end();
								str += ('<tr><td>'+ "n/a" + '</td><td>' + "n/a" + '</td><td>' + "n/a" + '</td></tr>');
								str += '</tbody>';
								$("#shpo_search_results").append(str);
							}
							$("#divSHPOCount").html(results.length);
							$('#shpoSearchProgress').css("display","none");
						});
					} else alert("Only layers visible on map AND checked above will be searched. Please turn on and select the layers you want to search.");
				} else alert("At least one checkbox need to be checked");
			} else alert("Valid site ID/name input is required");
		};*/
		
		function GNIS_search() {
			if ($("#frmMainSearch input").val() == "") alert("Valid geographic name input is required");
			else {
				$('#gnisSearchProgress').css("display","block");
				var findParamsGNIS = new esri.tasks.FindParameters();
				findParamsGNIS.returnGeometry = true;
				findParamsGNIS.layerIds = [0];
				findParamsGNIS.searchFields = ['NAME'];
				findParamsGNIS.searchText = $("#frmMainSearch input").val();

				var findTaskGnis = new esri.tasks.FindTask(services_application.gnistask);
				findTaskGnis.execute(findParamsGNIS, function(results){
					DOT.gnisGraphic.clear();
					$("#gnis_search_results").find("tbody")
											.remove()
											.end();
		
					//var sms = new esri.symbol.SimpleMarkerSymbol().setStyle(esri.symbol.SimpleMarkerSymbol.STYLE_SQUARE).setColor(new esri.Color([255,0,0,0.5]));
					
					var str="";
					str += '<tbody>';
					$("#gnis_search_results").append(str);
					searchresultGNIS = results;
					var total = 0;
					if (results.length > 0) {
						if (results.length == 1000) alert("Due to the system's maximum display capacity, only the first 1000 records are shown in the search results. Please refine your search criteria in order to reduce the number of results.");
						var o = results[0].feature;
						var unionedExtent = new esri.geometry.Extent(o.geometry.x, o.geometry.y, o.geometry.x, o.geometry.y, new esri.SpatialReference(102100));
						
						for (var i=0; i<results.length; i++) {
							o = results[i].feature;
							var infoTemp = new esri.InfoTemplate("More information", "<b>Name</b>: ${Name}<br><b>USGS Quad</b>: ${Cell_Name}<br><b>Type</b>: ${Type}<br><b>Map</b>: ${MAP_NAME}<br><b>County</b>: ${COUNTY_NAM}<br><b>Locaton</b>:(${Latitude},${Longitude})<br><b>Elevation</b>: ${ELEV_IN_M}m / ${ELEV_IN_FT}ft");
							var pt = new esri.geometry.Point(o.geometry.x, o.geometry.y, DOT.map.spatialReference);
							var g = new esri.Graphic(pt, DOT.markerSymbol, o.attributes, infoTemp);
							DOT.gnisGraphic.add(g);
							
							unionedExtent = unionedExtent.union(new esri.geometry.Extent(o.geometry.x, o.geometry.y, o.geometry.x, o.geometry.y, new esri.SpatialReference(102100)));
							total += 1;
							str += ('<tr><td>'+o.attributes.Name + '</td><td>' + o.attributes.Cell_Name + '</td><td>' + o.attributes.Type + '</td></tr>');
						}
						str += '</tbody>';
						$("#gnis_search_results").append(str);
						DOT.map.setExtent(unionedExtent.expand(1.5));
			
						$(document).on('click', "#gnis_search_results tbody tr", function(event) {
							var o222 = searchresultGNIS[event.currentTarget.rowIndex-1].feature;

							var txtLblSymbol = new esri.symbol.TextSymbol(o222.attributes.Name);
							var font = new esri.symbol.Font();
							font.setSize("12pt");
							font.setWeight(esri.symbol.Font.WEIGHT_BOLD);
							txtLblSymbol.setFont(font);
							var pt = new esri.geometry.Point(o222.geometry);
							var centerGraphic = new esri.Graphic(pt, txtLblSymbol);
							DOT.gnisGraphic.add(centerGraphic);
							DOT.map.centerAndZoom(pt, 10);
						});
					} else {
						$("#gnis_search_results").find("tbody")
												.remove()
												.end();
						str += ('<tr><td>'+ "n/a" + '</td><td>' + "n/a" + '</td><td>' + "n/a" + '</td></tr>');
						str += '</tbody>';
						$("#gnis_search_results").append(str);
						$("#downloads1").css("display", "none");
					}
					$("#divGNISCount").html(total);	
					$('#gnisSearchProgress').css("display","none");
					
					$("#searchContent").css("display", "block");
					$("#gnis_result").css("display", "block");
					$("#searchTitle").html("<h4><b>Search by Geographic Name</b></h4>");
					var searchPanelHeight = $("#gnis_result").height() + $("#searchTitle").height() + 23;
					var searchMapHeight = $(window).height() - searchPanelHeight;
					$("#map").css("height",  searchMapHeight);
					$("#searchContent").css("height", searchPanelHeight);
					$("#searchContent").css("top",  searchMapHeight);
				});
			}	
		};
		/*
		dojo.query(".selectType").on("click", function (e) {
			
			geomType = e.target.id;
			DOT.geometryGraphic.clear();
			DOT.searchGraphic.clear();
			$("#downloads2").css("display", "none");
			if ($("#checkboxes2 input:checked").filter(':visible').length != 0){
				if (document.getElementById('asiteBox2').checked) {
					addIDList(0, idList2);
					addIDList(7, idList2);
				} else {
					dropIDList(0, idList2);
					dropIDList(7, idList2);
				}
				
				if (document.getElementById('asurveyBox2').checked) {
					addIDList(1, idList2);
					addIDList(8, idList2);
				} else {
					dropIDList(1, idList2);
					dropIDList(8, idList2);
				}
				
				if (document.getElementById('civilBox2').checked) {
					addIDList(5, idList2);
					addIDList(12, idList2);
				} else {
					dropIDList(5, idList2);
					dropIDList(12, idList2);
				}
				
				if (document.getElementById('archBox2').checked){
					addIDList(2, idList2);
					addIDList(9, idList2);
				} else{
					dropIDList(2, idList2);
					dropIDList(9, idList2);
					}
				if (document.getElementById('cemeBox2').checked){
					addIDList(6, idList2);
					addIDList(13, idList2);
				} else{
					dropIDList(6, idList2);
					dropIDList(13, idList2);
					}
				if (document.getElementById('nareBox2').checked){
					addIDList(3, idList2);
					addIDList(10, idList2);
					addIDList(4, idList2);
					addIDList(11, idList2);
				} else{
					dropIDList(3, idList2);
					dropIDList(10, idList2);
					dropIDList(4, idList2);
					dropIDList(11, idList2);
					}
				for (var i=0; i<idList2.length; i++) {
					if (visible.indexOf(idList2[i]) < 0) idList2.splice(i, 1);
				}
				if (idList2.length > 0) {
					for (var i=0; i<idList2.length; i++) {
						if (visible.indexOf(idList2[i]) < 0) idList2.splice(i, 1);
					}
				}
				if (idList2.length > 0) {
					if (tb) tb.activate(geomType);
				} else alert("Only layers visible on map AND types checked above will be searched. Please turn on and select the layers you want to search.");			
			} else alert("At least one checkbox need to be checked");
		});
		
		$('#btnClearGeometry').click(function(){
			DOT.geometryGraphic.clear();
			DOT.searchGraphic.clear();
			tb.deactivate();
		});
		*/
    	$("#mainSelectListCity").change(function() {
			DOT.quickzoomGraphic.clear();
			var t = $("#mainSelectListCity").val();
			if (t && t != "citynull") quickZoom(t, 1, "NAME");
		});

    	$("#mainSelectListCnty").change(function() {
    		DOT.quickzoomGraphic.clear();
			var t = $("#mainSelectListCnty").val();
			if (t && t != "cntynull") quickZoom(t, 3, "NAME");
		});

    	$("#mainSelectListQuad").change(function() {
    		DOT.quickzoomGraphic.clear();
			var t = $("#mainSelectListQuad").val();
			if (t && t != "quadnull") quickZoom(t, 2, "QUAD_NAME");
		});

		$("#address_disclaimer").popover({
			html: true,
    		trigger: 'hover',
    		container: '#searchContent',
    		placement: "right",
    		title: "Address Services",
    		content: ADDRESS_DISCLAIMER		//varible defined in resources.js
    		/*,
    		template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="pop-title"></h3><div class="pop-content"></div></div>'*/
    	});

};


function quickZoom(srchTxt, lyrId, fldName) {
	var ft = new esri.tasks.FindTask(services_application.Task_zoom);
	var fp = new esri.tasks.FindParameters();
			
	fp.returnGeometry = true;
	fp.searchFields = [fldName];
	fp.layerIds = [lyrId];
	fp.searchText = srchTxt;
			
	ft.execute(fp, function(e){
		var geo1 = e[0].feature.geometry;
		
		DOT.map.setExtent(geo1.getExtent().expand(2.0));

		var symbol = new esri.symbol.SimpleFillSymbol(
			esri.symbol.SimpleFillSymbol.STYLE_NULL,
      			new esri.symbol.SimpleLineSymbol( esri.symbol.SimpleLineSymbol.STYLE_SOLID, new esri.Color([0,0,0,0.65]), 2),
      			new esri.Color([255,0,0,0.35])
		);

		var txtLblSymbol = new esri.symbol.TextSymbol(srchTxt);
		var font = new esri.symbol.Font();
		font.setSize("16pt");
		font.setWeight(esri.symbol.Font.WEIGHT_BOLD);
		txtLblSymbol.setFont(font);
		
		var pt = new esri.geometry.Point(geo1.getExtent().getCenter());
		var centerGraphic = new esri.Graphic(pt, txtLblSymbol);
		
		
		var g = new esri.Graphic(geo1, symbol);
		DOT.quickzoomGraphic.add(centerGraphic);
		DOT.quickzoomGraphic.add(g);
	});
}
/*				
function addIDList(i, idList) {
	if (visible.indexOf(i)>-1 && idList.indexOf(i)<0)
		idList.push(i);
};

function dropIDList(i, idList) {
	if (visible.indexOf(i)>-1 && idList.indexOf(i)>-1)
		idList.splice(idList.indexOf(i), 1);
}
*/

function ReCheckRadio(coord_type) {
	if ( coord_type == "dd" ) {
		$("#radioLatLong_decimal").prop("checked", true);
	}
	if ( coord_type == "dms" ) {
		$("#radioLatLong_dms").prop("checked", true);
	}
	if ( coord_type == "utm" ) {
		$("#radioUTM").prop("checked", true);
	}
}

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

function resetSearchInterface(t){
	if (searchType_new != searchType_current) {
		$("#divSelectList").css("display","none");
		$("#divUserInput").css("display","none");
		
		$("#searchContent").css("display", "none");
		$("#feature_result").css("display", "none");
		$("#geometry_result").css("display", "none");
		$("#address_result").css("display", "none");
		$("#coord_result").css("display", "none");
		$("#gnis_result").css("display", "none");
		
		$("#mainSelectListCity option[value='citynull']").prop("selected", true);
		$("#mainSelectListCnty option[value='cntynull']").prop("selected", true);
		$("#mainSelectListQuad option[value='quadnull']").prop("selected", true);
		// Address
		if ( t=="Address" ){
			$("#divUserInput").css("display","block");
			$("#mainSearchText").removeAttr("disabled");
			$("#mainSearchText").attr("placeholder", "Format: 123 Street, City, State, Zip");
			$("#mainSearchText").val("");
			$("#map").css("height",  "100%");
			//$("#searchContent").css("display", "block");
			//$("#address_result").css("display", "block");
			//$("#searchTitle").html("<h4><b>Search by Address</b></h4>");
			//var searchPanelHeight = $("#address_result").height() + $("#searchTitle").height() + 23;
			//var searchMapHeight = $(window).height() - searchPanelHeight;
			//$("#map").css("height",  searchMapHeight);
			//$("#searchContent").css("height", searchPanelHeight);
			//$("#searchContent").css("top",  searchMapHeight);
		}
		
		// ID/Name
		if ( t=="Name" ){
			$("#divUserInput").css("display","block");
			$("#mainSearchText").removeAttr("disabled");
			$("#mainSearchText").attr("placeholder", "Search by Name");
			$("#mainSearchText").val("");
			$("#searchContent").css("display", "block");
			$("#feature_result").css("display", "block");
			$("#searchTitle").html("<h4><b>Search by Name</b></h4>");
			var searchPanelHeight = $("#feature_result").height() + $("#searchTitle").height() + 23;
			var searchMapHeight = $(window).height() - searchPanelHeight;
			$("#map").css("height",  searchMapHeight);
			$("#searchContent").css("height", searchPanelHeight);
			$("#searchContent").css("top",  searchMapHeight);
		}
		
		// Geometry
		if ( t=="Geometry" ){
			$("#divUserInput").css("display","block");
			$("#mainSearchText").attr("disabled", "disabled");
			$("#mainSearchText").attr("placeholder", "Search by Geometry");
			$("#mainSearchText").val("");
			$("#geometry_result").css("display", "block");
			$("#searchContent").css("display", "block");
			$("#searchTitle").html("<h4><b>Search by Geometry</b></h4>");
			var searchPanelHeight = $("#geometry_result").height() + $("#searchTitle").height() + 23;
			var searchMapHeight = $(window).height() - searchPanelHeight;
			console.log(searchPanelHeight, searchMapHeight);
			$("#map").css("height",  searchMapHeight);
			$("#searchContent").css("height", searchPanelHeight);
			$("#searchContent").css("top",  searchMapHeight);
		}
	        		
		// Coordinate
		if ( t=="Coordinate" ){
			$("#divUserInput").css("display","block");
			$("#mainSearchText").attr("disabled", "disabled");
			$("#mainSearchText").attr("placeholder", "Search by Coordinate");
			$("#mainSearchText").val("");
			$("#searchContent").css("display", "block");
			$("#coord_result").css("display", "block");
			$("#searchTitle").html("<h4><b>Search by Coordinate</b></h4>");
			var searchPanelHeight = $("#coord_result").height() + $("#searchTitle").height() + 23;
			var searchMapHeight = $(window).height() - searchPanelHeight;
			$("#map").css("height",  searchMapHeight);
			$("#searchContent").css("height", searchPanelHeight);
			$("#searchContent").css("top",  searchMapHeight);
	    }
	        		
		// GNIS Name
	    if ( t=="GNIS Name" ){
			$("#divUserInput").css("display","block");
			$("#mainSearchText").removeAttr("disabled"); 
			$("#map").css("height",  "100%");
			/*if (gnisname.length == 0 ) {					// if gnisname is not populated, run the function below.
				populate_gnisname();						// defined in util.js and for autocomplete gnisname search
				$("#GNISName").autocomplete({source: gnisname});
				$("#mainSearchText").autocomplete({ disabled: false, source: gnisname });
			}
			else {
				$("#mainSearchText").autocomplete({ disabled: false });
			}*/										
			$("#mainSearchText").attr("placeholder", "Search by Geographic Name");
			$("#mainSearchText").val("");
			//$("#searchContent").css("display", "block");
			//$("#gnis_result").css("display", "block");
			//$("#searchTitle").html("<h4><b>Search by Geographic Name</b></h4>");
			//var searchPanelHeight = $("#gnis_result").height() + $("#searchTitle").height() + 23;
			//var searchMapHeight = $(window).height() - searchPanelHeight;
			//$("#map").css("height",  searchMapHeight);
			//$("#searchContent").css("height", searchPanelHeight);
			//$("#searchContent").css("top",  searchMapHeight);
		}
	        		
		// City, County, UGS_Quad
		if ( t=="City" || t=="County" || t=="USGS Quad"){
			$("#map").css("height", "100%");
			$("#searchContent").css("height", "0%");
			$("#searchContent").css("display", "none");			
			$("#divSelectList").css("display","block");
			$("#mainSelectListCity").css("display", "none");
			$("#mainSelectListCnty").css("display", "none");
			$("#mainSelectListQuad").css("display", "none");
			
			if ( t=="City" ) {
				$("#mainSelectListCity").css("display", "block");
			}
			if ( t=="County" ) {
				$("#mainSelectListCnty").css("display", "block");
			}
			if ( t=="USGS Quad" ) {
				$("#mainSelectListQuad").css("display", "block");
			}
		}
	}
	else {
		if ( searchType_new=="Coordinate" || searchType_new=="GNIS Name" || searchType_new=="Name" || searchType_new=="Geometry") {
			console.log("tbd");
		}
	}
	searchType_current = searchType_new;
}