//(function () {

angular.module('MobileWebLogistics')
	.service('parcelSearch', function () {
		var self = this;
		this.switchSearchMode = function ($scope, $event) {
			var searchButtons = $(".searchButton button");
			var searchContainers = $(".searchContainer");
			$("#mapContainer").removeClass("oneQueryTop");
			$("#listCont").removeClass("oneQueryTop");
			$("#detailPanels").removeClass("oneQueryTop");
			if ($event.target.innerHTML == "Default") {
				$(searchButtons[1]).removeClass("active");
				//$("#search1").addClass("hidebtn").removeClass("showbtn");
				//$("#search2").removeClass("hidebtn").addClass("showbtn");
				$("#ndefaultSearch").css("display", "block");
				$("#nadvancedSearch").css("display", "none");
				$(searchContainers[1]).removeClass("active");
				$(searchButtons[0]).addClass("active");
				$(searchButtons[1]).removeClass("active");
				$(searchContainers[0]).addClass("active");
				if ($scope.numOfDefQueryVar == '1') {
					//mapContainer, listCont, .detailPanels
					$("#mapContainer").addClass("oneQueryTop");
					$("#listCont").addClass("oneQueryTop");
					$("#detailPanels").addClass("oneQueryTop");
				}
			} else {
				$(searchButtons[0]).removeClass("active");
				//$("#search2").addClass("hidebtn").removeClass("showbtn");
				//$("#search1").removeClass("hidebtn").addClass("showbtn");
				$("#ndefaultSearch").css("display", "none");
				$("#nadvancedSearch").css("display", "block");
				$(searchContainers[0]).removeClass("active");
				$(searchButtons[2]).removeClass("active");
				$(searchButtons[3]).addClass("active");
				$(searchContainers[1]).addClass("active");
				if ($scope.numOfAdvQueryVar == '1') {
					//mapContainer, listCont, .detailPanels
					$("#mapContainer").addClass("oneQueryTop");
					$("#listCont").addClass("oneQueryTop");
					$("#detailPanels").addClass("oneQueryTop");
				}
			}
		}

		this.search = function ($scope, fromTypeahead) {
			$scope.clearParcelSearch();
			if ($("#selectByGraphicTool").hasClass("active")) {
				$("#selectByGraphicTool").removeClass("active");
				$("#openSelectByGraphic").removeClass("active");
				$scope.toolbar.deactivate();
			}
			if ($scope.customDefSearchBar == 'true' || $scope.customAdvSearchBar == 'true') {
				$scope.localCustom.search($scope, fromTypeahead);
			} else {
				//searchFrame
				$scope.advSearch1 = false;
				$scope.advSearch2 = false;
				$scope.advSearch3 = false;
				$scope.advSearch4 = false;


				$("#searchFrame").collapse('hide');
				$scope.closeDialog();
				if ($scope.searchBtn == "submitSearchMap") {
					$scope.showMap();
					$("#identifyPreloaderContainer").addClass("active");
				} else {
					$scope.showList();
				}

				var drawButtons = $("#drawTools > div");
				for (var i = 0; i < drawButtons.length; i++) {
					if ($(drawButtons[i]).hasClass("selected")) {
						$("#openDrawTools").removeClass("active");
						$("#drawTools").removeClass("active");
						$("#drawTools .selected").removeClass("selected");
						$("#drawTools .unselected").removeClass("unselected");
						$scope.toolbar.deactivate();
					}
				}

				$("#searchPreloaderContainer").addClass("active");
				$("#listResults").addClass("inactive");

				setTimeout(function () {
					$scope.thisSearchMode = $("#search1").hasClass("active");
					$scope.queryTask = new $scope.QueryTask($scope.queryTaskUrl);
					$scope.query2.outFields = $scope.initParcelFields;
					$scope.query2.returnGeometry = true;
					$scope.query2.outSpatialReference = {
						wkid: 102100
					};
					var numQueryField = 1;
					$scope.thisTxtboxSearch = "";
					$scope.queryStringDate = "";
					$scope.queryStringPrice = "";
					$scope.searchQueryString = "";
					if ($("#search1").hasClass("active")) {
						if (fromTypeahead.length > 0) {
							//==========this is for the calls from the county's assessment system
							if (fromTypeahead.indexOf("address=") > -1) {
								var qinput = fromTypeahead.replace("address=", "");
								$scope.searchQueryString = "" + $scope.urlParameterSearchAddress + " = '" + qinput + "'";
							} else if (fromTypeahead.indexOf("ownername=") > -1) {
								var qinput = fromTypeahead.replace("ownername=", "");
								$scope.searchQueryString = "" + $scope.urlParameterSearchOwnerName + " = '" + qinput + "'";
							} else if (fromTypeahead.indexOf("parcelID=") > -1) {
								var qinput = fromTypeahead.replace("parcelID=", "");
								$scope.searchQueryString = "" + $scope.urlParameterSearchParcelID + " = '" + qinput + "'";
							} else { //==========end of codes for the calls from the county's assessment system
								$scope.thisTxtboxSearch = $("#defSearch" + fromTypeahead.toString()).val().trim().replace(/'/g, "''");
								//$scope.query2.where = ""+$scope.addToSearchAheadOutFields[fromTypeahead-1]+" LIKE '%" + $scope.thisTxtboxSearch + "%'";
								$scope.searchQueryString = "" + $scope.addToSearchAheadOutFields[fromTypeahead - 1] + " = '" + $scope.thisTxtboxSearch + "'";
							}
						} else {
							//=====================

							while (numQueryField < $scope.numDqueryField + 1) { //create query string for textboxes
								//alert(numQueryField.toString());
								$scope.thisTxtboxSearch = $("#defSearch" + numQueryField.toString()).val().trim().replace(/'/g, "''");
								if (numQueryField > 1) {
									$scope.searchQueryString += " AND ";
								}
								if ($scope.thisTxtboxSearch.length > 0) {
									$scope.searchQueryString += "(" + $scope.addToSearchAheadOutFields[numQueryField - 1] + " LIKE '%" + $scope.thisTxtboxSearch + "%')";
								} else {
									$scope.searchQueryString += "(" + $scope.addToSearchAheadOutFields[numQueryField - 1] + " LIKE '%" + $scope.thisTxtboxSearch + "%' OR " + $scope.addToSearchAheadOutFields[numQueryField - 1] + " IS NULL)";
								}
								numQueryField++;
							}
							if ($("#ndefaultSearch #startDate").length) {
								$scope.thisSearchStartDate = $("#ndefaultSearch #startDate").val().trim().replace(/'/g, "''");
								$scope.thisSearchEndDate = $("#ndefaultSearch #endDate").val().trim().replace(/'/g, "''");

								$scope.queryStringStartDate = "";
								$scope.queryStringEndDate = "";

								if ($scope.thisSearchStartDate.length > 0) { //create query string for sale date
									$scope.queryStringStartDate = " (" + $scope.saleDateFld + " >= '" + $scope.thisSearchStartDate + "')";
								}
								if ($scope.thisSearchEndDate.length > 0) {
									$scope.queryStringEndDate = " (" + $scope.saleDateFld + " <= '" + $scope.thisSearchEndDate + "')";
								}

								if (($scope.thisSearchStartDate.length > 0) && ($scope.thisSearchEndDate.length > 0)) {
									$scope.queryStringDate = $scope.queryStringStartDate + " AND" + $scope.queryStringEndDate;
								} else {
									$scope.queryStringDate = $scope.queryStringStartDate + $scope.queryStringEndDate;
								}

							}
							if ($("#ndefaultSearch #priceSlider-value-min").length) { //create query string for sale price
								$scope.priceMin = $("#ndefaultSearch #priceSlider-value-min").html().replace('$', '').replace(/,/g, '');
								$scope.priceMax = $("#ndefaultSearch #priceSlider-value-max").html().replace('$', '').replace(/,/g, '');

								if ($scope.priceMax == $scope.searchPriceMax) {
									$scope.priceMax = 99999999999;
								}
								$scope.queryStringPriceMin = "";
								$scope.queryStringPriceMax = "";

								if ($scope.priceMin > $scope.searchPriceMin) {
									$scope.queryStringPriceMin = " (" + $scope.salePriceFld + " >= '" + $scope.priceMin + "')";
								}
								if ($scope.priceMax < 99999999999) {
									$scope.queryStringPriceMax = " (" + $scope.salePriceFld + " <= '" + $scope.priceMax + "')";
								}

								if (($scope.priceMin > $scope.searchPriceMin) && ($scope.priceMax < 99999999999)) {
									$scope.queryStringPrice = $scope.queryStringPriceMin + " AND" + $scope.queryStringPriceMax;
								} else {
									$scope.queryStringPrice = $scope.queryStringPriceMin + $scope.queryStringPriceMax;
								}
							}
							//querystring+=dateQuerystring
							if ($scope.queryStringDate.length > 0) {
								$scope.searchQueryString += " AND " + $scope.queryStringDate;
							}
							//querystring+=priceQuerystring
							if ($scope.queryStringPrice.length > 0) {
								$scope.searchQueryString += " AND " + $scope.queryStringPrice;
							}
							// console.log($scope.searchQueryString);		            

						}
						$scope.query2.where = $scope.searchQueryString;
						$scope.queryTask.execute($scope.query2, $scope.showResults);
						//console.log($scope.searchQueryString);

					} else { //advanced search *separate from default search in case of customization
						$scope.advSearch1Query = "";
						$scope.advSearch2Query = "";
						$scope.advSearch3Query = "";
						$scope.advSearch4Query = "";
						$scope.advSearch5Query = "";
						$scope.advSearch6Query = "";

						var datePriceFldCt = 0;
						if ($("#ndefaultSearch").find("#dateFromOpt").length != 0) {
							datePriceFldCt = 1
						}
						if ($("#ndefaultSearch").find("#priceBar").length != 0) {
							datePriceFldCt += 1
						}
						//=====================addToSearchAheadOutFields-numOfAdvQueryVar
						if ($scope.directAdvSearch == 'true') {
							while (numQueryField < $scope.numAqueryField + 1) {
								$scope.thisTxtboxSearch = $("#advSearch" + numQueryField.toString()).val().trim().replace(/'/g, "''");

								if ($scope.thisTxtboxSearch.length > 0) {
									if ($scope.searchQueryString.length > 1) {
										$scope.searchQueryString += " AND ";
									}
									$scope.searchQueryString += "(" + $scope.addToSearchAheadOutFields[numQueryField + $scope.numDqueryField + datePriceFldCt - 1] + " = '" + $scope.thisTxtboxSearch + "')";
								}
								numQueryField++;
							}
						} else {
							while (numQueryField < $scope.numAqueryField + 1) {
								$scope.thisTxtboxSearch = $("#advSearch" + numQueryField.toString()).val().trim().replace(/'/g, "''");
								if (numQueryField > 1) {
									$scope.searchQueryString += " AND ";
								}
								if ($scope.thisTxtboxSearch.length > 0) {
									$scope.searchQueryString += "(" + $scope.addToSearchAheadOutFields[numQueryField + $scope.numDqueryField + datePriceFldCt - 1] + " LIKE '%" + $scope.thisTxtboxSearch + "%')";
								} else {
									$scope.searchQueryString += "(" + $scope.addToSearchAheadOutFields[numQueryField + $scope.numDqueryField + datePriceFldCt - 1] + " LIKE '%" + $scope.thisTxtboxSearch + "%' OR " + $scope.addToSearchAheadOutFields[numQueryField + $scope.numDqueryField + datePriceFldCt - 1] + " IS NULL)";
								}
								numQueryField++;
							}
						}


						if ($("#nadvancedSearch #startDate").length) {
							$scope.thisSearchStartDate = $("#nadvancedSearch #startDate").val().trim().replace(/'/g, "''");
							$scope.thisSearchEndDate = $("#nadvancedSearch #endDate").val().trim().replace(/'/g, "''");

							$scope.queryStringStartDate = "";
							$scope.queryStringEndDate = "";

							if ($scope.thisSearchStartDate.length > 0) {
								$scope.queryStringStartDate = " (" + $scope.saleDateFld + " >= '" + $scope.thisSearchStartDate + "')";
							}
							if ($scope.thisSearchEndDate.length > 0) {
								$scope.queryStringEndDate = " (" + $scope.saleDateFld + " <= '" + $scope.thisSearchEndDate + "')";
							}

							if (($scope.thisSearchStartDate.length > 0) && ($scope.thisSearchEndDate.length > 0)) {
								$scope.queryStringDate = $scope.queryStringStartDate + " AND" + $scope.queryStringEndDate;
							} else {
								$scope.queryStringDate = $scope.queryStringStartDate + $scope.queryStringEndDate;
							}

						}
						if ($("#nadvancedSearch #priceSlider-value-min").length) {
							$scope.priceMin = $("#nadvancedSearch #priceSlider-value-min").html().replace('$', '').replace(/,/g, '');
							$scope.priceMax = $("#nadvancedSearch #priceSlider-value-max").html().replace('$', '').replace(/,/g, '');
							if ($scope.priceMax == $scope.searchPriceMax) {
								$scope.priceMax = 99999999999;
							}
							$scope.queryStringPriceMin = "";
							$scope.queryStringPriceMax = "";

							if ($scope.priceMin > $scope.searchPriceMin) {
								$scope.queryStringPriceMin = " (" + $scope.salePriceFld + " >= '" + $scope.priceMin + "')";
							}
							if ($scope.priceMax < 99999999999) {
								$scope.queryStringPriceMax = " (" + $scope.salePriceFld + " <= '" + $scope.priceMax + "')";
							}

							if (($scope.priceMin > $scope.searchPriceMin) && ($scope.priceMax < 99999999999)) {
								$scope.queryStringPrice = $scope.queryStringPriceMin + " AND" + $scope.queryStringPriceMax;
							} else {
								$scope.queryStringPrice = $scope.queryStringPriceMin + $scope.queryStringPriceMax;
							}
						}
						//querystring+=dateQuerystring
						if ($scope.queryStringDate.length > 0) {
							if ($scope.searchQueryString.length > 0) {
								$scope.searchQueryString += " AND " + $scope.queryStringDate;
							} else {
								$scope.searchQueryString = $scope.queryStringDate;
							}
						}
						//querystring+=priceQuerystring
						if ($scope.queryStringPrice.length > 0) {
							if ($scope.searchQueryString.length > 0) {
								$scope.searchQueryString += " AND " + $scope.queryStringPrice;
							} else {
								$scope.searchQueryString = $scope.queryStringPrice;
							}
						}
						//console.log($scope.searchQueryString);
						if ($scope.searchQueryString.length < 1) {
							$scope.searchQueryString = '1=1';
						}
						$scope.query2.where = $scope.searchQueryString;

						$scope.queryTask.execute($scope.query2, $scope.showResults2);
					}
				}, 300);
			}
		}

		this.getAdjoiners = function ($scope) {

			$scope.bufferLayer.clear(); //alert("adjoiner");
			$scope.forceImmediateAdjoiners = false;


			$("#adjoinerList").css("z-index", 0);
			$("#parcelPreloaderContainer").addClass("active");
			$scope.adjoinerList = [];
			$scope.lastBufferDistance = $scope.adjoinerBufferDistance;

			$scope.lastBufferUnit = $scope.SelectedUnit;
			if ($scope.lastBufferDistance == 0) {
				$("#refreshSearch").addClass("fadeOut");
			}
			// issue with hosted feature services and fetching immediate adjoiners
			// need to add a minimal search distance to find immediate adjoiners on corner lots
			// set the distance to 1 foot if immediate adjoiners is checked and it's a feature service
			// this should find the immediate adjoiner(s) and not introduce any error
			if ($scope.immediateAdjoiners && !$scope.isFeatureService) {
				$("#customBuffer").addClass("fadeOut");
				var query = new $scope.Query();
				query.geometry = $scope.selectedParcel['geometry'];
				query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
				query.returnGeometry = true;
				query.outFields = $scope.initParcelFields;
				$scope.queryTaskTouches.execute(query);
			} else {
				var params = new $scope.BufferParameters();
				var distances = new Array();
				params.distances = distances;
				//params.outSpatialReference = map.spatialReference;
				params.outSpatialReference = new $scope.SpatialReference({
					wkid: 102100
				})
				if ($scope.SelectedUnit == "Feet") {
					params.unit = esri.tasks.GeometryService.UNIT_FOOT;
					distances[0] = $scope.adjoinerBufferDistance;
					if (distances[0] == 0) {
						distances[0] = 1;
						$scope.forceImmediateAdjoiners = true;
					}
				} else if ($scope.SelectedUnit == "Meters") {
					params.unit = esri.tasks.GeometryService.UNIT_METER;
					distances[0] = $scope.adjoinerBufferDistance;
					if (distances[0] == 0) {
						distances[0] = 1;
						params.unit = esri.tasks.GeometryService.UNIT_FOOT;
						$scope.forceImmediateAdjoiners = true;
					}
				} else if ($scope.SelectedUnit == "Miles") {
					params.unit = esri.tasks.GeometryService.UNIT_FOOT;
					//distances[0] = ($scope.adjoinerBufferDistance * 5280) / 100;
					distances[0] = ($scope.adjoinerBufferDistance * 5280);
					if (distances[0] == 0) {
						distances[0] = 1;
						$scope.forceImmediateAdjoiners = true;
					}
				}
				params.distances = distances;
				params.geodesic = true; //for 10.1 and above

				//esriConfig.defaults.geometryService = new GeometryService(geometryServiceUrl ); //for dev6.timmons.com
				//esriConfig.defaults.geometryService = new GeometryService(esriGeometryServiceUrl ); //for localhost              
				$scope.selectedParcel['geometry'].spatialReference.wkid = $scope.dataWkid;
				//alert("b:"+$scope.selectedParcel['geometry'].spatialReference.wkid);	//102113

				$scope.normalizeUtils.normalizeCentralMeridian([$scope.selectedParcel['geometry']], $scope.esriConfig.defaults.geometryService).then(function (normalizedGeometries) {
					var geometries = new Array();
					//alert(normalizedGeometries[0].spatialReference.wkid);	//102113
					geometries.push(normalizedGeometries[0]);
					params.geometries = geometries;
					//alert(params.geometries.spatialReference);
					$scope.esriConfig.defaults.geometryService.buffer(params, function (bufferedGeometry) {
						$scope.bufferLayer.clear();
						if (!$scope.forceImmediateAdjoiners) {
							var bufferGraphic = new $scope.Graphic(bufferedGeometry[0], $scope.bufferSymbol);
							$scope.bufferLayer.add(bufferGraphic);
						}
						var distanceQuery = new $scope.Query();
						distanceQuery.geometry = bufferedGeometry[0];
						distanceQuery.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
						distanceQuery.returnGeometry = true;
						distanceQuery.outFields = ["*"];
						//console.log(bufferedGeometry[0]);
						$scope.queryTaskTouches.execute(distanceQuery);
					});
				});
			}
		}

		this.searchByGraphics = function ($scope) {
			//alert("searchByGraphics");
			var geometries = new Array();
			var polygon = new $scope.Polygon;
			var polyline = new $scope.Polyline;
			var lastGraphicIndex = $scope.drawLayerForSelect.graphics.length - 1;
			if (lastGraphicIndex == 0) {
				$scope.queryResults = [];
				$scope.multiSelectedLayer.clear();
			}

			geometries.push($scope.drawLayerForSelect.graphics[lastGraphicIndex].geometry);
			/*if ($scope.drawLayer.graphics[0].geometry.type == "polygon"){
				polygon = $scope.drawLayer.graphics[0].geometry;
				if($scope.drawLayer.graphics.length > 1){
					for (var j = 1; j < $scope.drawLayer.graphics.length; j++) {
						polygon.addRing($scope.drawLayer.graphics[j].geometry.rings[0]);
					}	
				}			
				geometries.push(polygon);
			}
			else if ($scope.drawLayer.graphics[0].geometry.type == "polyline"){
				polyline = $scope.drawLayer.graphics[0].geometry;
				if($scope.drawLayer.graphics.length > 1){
					for (var j = 1; j < $scope.drawLayer.graphics.length; j++) {
						polyline.addPath($scope.drawLayer.graphics[j].geometry.paths[0]);
					}	
				}			
				geometries.push(polyline);
			}*/

			var distanceQuery = new $scope.Query();
			distanceQuery.geometry = geometries[0];
			//console.log(geometries);
			distanceQuery.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
			distanceQuery.returnGeometry = true;
			distanceQuery.outFields = ["*"];
			$scope.queryTaskTouchesByGraphics.execute(distanceQuery);
		}

		this.getNearby = function ($scope) { //$scope.NearbyParams
			$scope.fromNearby = true;
			var params = $scope.NearbyParams;

			//params.outSpatialReference = map.spatialReference;
			params.outSpatialReference = new $scope.SpatialReference({
				wkid: 102100
			})
			params.geodesic = true; //for 10.1 and above

			//esriConfig.defaults.geometryService = new GeometryService(geometryServiceUrl ); //for dev6.timmons.com
			//esriConfig.defaults.geometryService = new GeometryService(esriGeometryServiceUrl ); //for localhost              
			//$scope.selectedParcel['geometry'].spatialReference.wkid = '102100';
			//alert("b:"+$scope.selectedParcel['geometry'].spatialReference.wkid);	//102113


			$scope.esriConfig.defaults.geometryService.buffer(params, function (bufferedGeometry) {
				$scope.bufferLayer.clear();
				var bufferGraphic = new $scope.Graphic(bufferedGeometry[0], $scope.bufferSymbol);
				$scope.bufferLayer.add(bufferGraphic);
				var distanceQuery = new $scope.Query();
				distanceQuery.geometry = bufferedGeometry[0];
				distanceQuery.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
				distanceQuery.returnGeometry = true;
				distanceQuery.outFields = ["*"];

				$scope.queryTaskTouchesNearby.execute(distanceQuery);
			});


		}
		this.newParcel = function ($scope, result, panel, layer) {
			$scope.selectedParcel = result;
			if (panel == 'p1') {
				$scope.showPanel2 = false;
				$scope.stackedFeatureStatus = false;
			} else if (panel == 'p2') {
				$scope.showPanel2 = true
			} else if (panel == 'p1-1') {
				$scope.showPanel2 = false;
				$scope.stackedFeature = false;
			} else if (panel == 'm') {
				$scope.map.infoWindow.hide();
				$scope.map.graphics.clear();
			}
			if (panel != 'm' && $scope.noReport == 'true') {
				panel = 'adjoiner';
			}
			if ($scope.queryLyr == 'pt') {
				$scope.queryObjectId($scope.selectedParcel[$scope.addrPtUid], '', panel, 'pt');
			} else {
				$scope.queryObjectId($scope.selectedParcel[$scope.parcelUid], $scope.selectedParcel[$scope.parcelOID], panel);
			}
			$scope.adjoinerList = [];
			for (var key in $scope.selectedParcel) {
				thisKey = $scope.selectedParcel[key.toString()];
				$scope.selectedParcel[key.toString()] = $scope.formatParcelData(key, thisKey, $scope.selectedParcel[key.toString()]);
			}
			$scope.immediateAdjoiners = true;
			//$scope.getAdjoiners();
			if (panel != 'm') {
				//setTimeout(function(){$scope.showDetail();}, 200);
				$scope.showDetail();
			} else {
				$scope.hideDetail();
			}
		}

		this.UpdateUnit = function ($scope) {
			if ($("#adjoinerDistance").val().length < 1) {
				$("#refreshSearch").addClass("fadeOut");
			} else {
				$("#refreshSearch").removeClass("fadeOut");
			}
			if ($scope.SelectedUnit == "Feet") {
				$("#adjoinerDistance").attr("min", 1);
				$("#adjoinerDistance").attr("max", 1300);
				$("#adjoinerDistance").attr("step", 1);
			} else if ($scope.SelectedUnit == "Meters") {
				$("#adjoinerDistance").attr("min", 1);
				$("#adjoinerDistance").attr("max", 400);
				$("#adjoinerDistance").attr("step", 1);
			} else if ($scope.SelectedUnit == "Miles") {
				$("#adjoinerDistance").attr("min", 0.01);
				$("#adjoinerDistance").attr("max", 0.25);
				$("#adjoinerDistance").attr("step", 0.01);
			}

			if ($("#adjoinerDistance").val() * 1 > $("#adjoinerDistance").attr("max") * 1) {
				$("#adjoinerDistance").val($("#adjoinerDistance").attr("max"));
			}
		}

		this.submitBuffer = function ($scope) {
			if ($scope.submitBufferDelay == 0) {
				$scope.submitBufferDelay = 1;
				if (parseFloat($("#bufferForm > input").val()) > 0) {
					var buffDist = parseFloat($("#bufferForm > input").val());
					var selBuffUnit = $("#bufferForm > select").val(); //0: feet, 1:meter, 2:mile
					var selBuffUnit = selBuffUnit.replace("string:", "");

					if (selBuffUnit.toString() == "Feet") {
						if (buffDist > 1300) {
							alert("Max buffer distance is 1300 ft")
						} else {
							$("#adjoinerDistance").blur();
							$("#bufferForm > input").submit();
						}
					} else if (selBuffUnit.toString() == "Meters") {
						if (buffDist > 400) {
							alert("Max buffer distance is 400 meters")
						} else {
							$("#adjoinerDistance").blur();
							$("#bufferForm > input").submit();
						}
					} else if (selBuffUnit.toString() == "Miles") {
						if (buffDist > 0.25) {
							alert("Max buffer distance is 0.25 miles")
						} else {
							$("#adjoinerDistance").blur();
							$("#bufferForm > input").submit();
						}
					}
					//else{$("#adjoinerDistance").blur(); $("#bufferForm > input").submit();alert("s2");}     
				} else {
					alert("Please enter an valid buffer distance");
				}
			}
			setTimeout(function () {
				$scope.submitBufferDelay = 0;
			}, 1000);
		}
		//========bufferUI=========//    	
		this.bufferFormSubmit = function ($scope, getAdjoiners) {
			$scope.adjoinerBufferDistance = $("#adjoinerDistance").val();
			$scope.SelectedUnit = $("#bufferForm option:selected").text();
			$scope.getAdjoiners();
		}

		this.adjoinerDistanceInput = function ($scope, lastBufferDistance, SelectedUnit, lastBufferUnit, event) {
			if (event.target.value.length < 1) {
				$("#refreshSearch").addClass("fadeOut");
			} else {
				$("#refreshSearch").removeClass("fadeOut");
			}
			var thisMax = parseFloat($("#adjoinerDistance").attr("max"));
			if (parseFloat(event.target.value) > thisMax) {
				$("#adjoinerDistance").val(thisMax);
			}
		}

		this.numberInput = function (inputId) {
			var selInputBox = $("#" + inputId);
			var thisMax = parseFloat(selInputBox.attr("max"));
			var thisMin = parseFloat(selInputBox.attr("min")); //alert(parseFloat($("#"+inputId).val()));

			if (parseFloat(selInputBox.val()) > thisMax) {
				selInputBox.val(thisMax); //alert("aaa");
				//workaround for no focus change once selInputBox.val(thisMax); happens 
				var el = document.getElementById(inputId);
				ev = document.createEvent('Event');
				ev.initEvent('change', true, false);
				el.dispatchEvent(ev);
			} else if (parseFloat(selInputBox.val()) < thisMin) { //alert(parseFloat(selInputBox.val()));
				selInputBox.val(thisMin);
				//workaround for no focus change once selInputBox.val(thisMin); happens
				var el = document.getElementById(inputId);
				ev = document.createEvent('Event');
				ev.initEvent('change', true, false);
				el.dispatchEvent(ev);
			} else if (isNaN(parseFloat(selInputBox.val()))) {
				selInputBox.val('');
				var el = document.getElementById(inputId);
				ev = document.createEvent('Event');
				ev.initEvent('change', true, false);
				el.dispatchEvent(ev);
			}

		}

		this.nearbyInput = function (event) {
			var thisMax = parseFloat($("#nearbyBufferDist").attr("max"));
			var thisMin = parseFloat($("#nearbyBufferDist").attr("min"));
			if (parseFloat(event.target.value) > thisMax) {
				$("#nearbyBufferDist").val(thisMax);
			} else if (parseFloat(event.target.value) < thisMin) {
				$("#nearbyBufferDist").val(thisMin);
			}
		}
		this.getLocation = function ($scope, location) {

			$scope.pt = new esri.geometry.Point({
				latitude: location.coords.latitude,
				longitude: location.coords.longitude
				//latitude: 37.296004,
				//longitude: -78.401300
			});
			$scope.NearbyParams = new $scope.BufferParameters();
			$scope.NearbyParams.geometries = [$scope.pt];
			$scope.NearbyParams.distances = [$('#nearbyBufferDist').val()];

			$scope.NearbyParams.unit = $scope.GeometryService.UNIT_FOOT;
			self.getNearby($scope);

			var highlightGraphic = new $scope.Graphic($scope.pt, $scope.mlsd);
			$scope.bmLayer.clear();
			$scope.bmLayer.add(highlightGraphic);
			$scope.map.centerAndZoom($scope.pt, 17);
		}
		this.locationError = function (navigator, error) {
			$('#floatingBarsH').remove();
			if (navigator.geolocation) {
				navigator.geolocation.clearWatch(watchId);
			}
			switch (error.code) {
				case error.PERMISSION_DENIED:
					alert("Location not provided");
					break;

				case error.POSITION_UNAVAILABLE:
					alert("Current location not available");
					break;

				case error.TIMEOUT:
					alert("Timeout");
					break;

				default:
					alert("unknown error");
					break;
			}
		}
	});

//})();