﻿///
/// Code for handling the identification of data at a given point 
///
var mouseCoordinateTracker, countyName, firmPanel, currentClick;
var firmPanelQueryTask = new esri.tasks.QueryTask(queryService + layerFirmPanels);
var countyQueryTask = new esri.tasks.QueryTask(queryService + layerCounty);
var townshipRangeQueryTask = new esri.tasks.QueryTask(queryService + layerPLSS);
var allParcelQueryTask = new esri.tasks.QueryTask(queryService + allParcelsLayer);
var floodZoneQueryTask = new esri.tasks.QueryTask(queryService + proposedFloodLayer);
var zoomToResults = false;
var parcelZoomLevel = 15;

//variables for legacy report page
var County;
var MapStatus;
var reportPoint;
//end variables for legacy report page

var parcelGeom;
// Data store for all firm panels returned by searching
var firmPanelStore = new Ext.data.JsonStore({
  storeId: 'firmPanelStore',
  root: 'features',
  idProperty: 'firmPanel',
  fields: [{ name: 'firmPanel', mapping: 'attributes.FIRM_PAN' },
            { name: 'countyCode', mapping: 'attributes.PCOMM'}]
});


var parcelStore = new Ext.data.JsonStore({
  storeId: 'parcelStore',
  root: 'features',
  idProperty: 'parcelId',
  fields: [{ name: 'geom', mapping: 'geometry' },
  { name: 'parcelId', mapping: 'attributes.PARCEL' },
  { name: 'county', mapping: 'attributes.County' },
  { name: 'Perc1Elev', mapping: 'attributes.TXTBFE' },
  { name: 'Perc10Elev', mapping: 'attributes.TXT10YR' },
  { name: 'Perc50Elev', mapping: 'attributes.TXT2YR'}]
});

var floodZone;
var InSFHA;
var floodway;
var nResults;
var getFloodZoneSuccess = function(results) {
    floodZone = "X";
    InSFHA = "No";
    floodway = "No";
    nResults = results.features.length;
    var flZone = "";

    if (nResults >= 1) {
        floodZone = "";
        for (i = 0; i < nResults; i++) {

            if (results.features[i].attributes.FLD_ZONE != "X") {
                flZone = results.features[i].attributes.FLD_ZONE;
                if (results.features[i].attributes.FLD_ZONE.search("0.2") >= 0) {
                    flZone = "X 0.2 PCT";
                }
                if (flZone === "AE" && results.features[i].attributes.FLOODWAY === "FLOODWAY") {
                    flZone = "AE FW";
                }

                if (floodZone.search(flZone) === -1) {
                    floodZone = floodZone + flZone + ", ";
                }
            }
            if (results.features[i].attributes.SFHA_TF != "F") {
                InSFHA = "Yes";
            }
            if (results.features[i].attributes.FLOODWAY === "FLOODWAY") {
                floodway = "Yes";
            }
        }
        floodZone = floodZone.slice(0, floodZone.lastIndexOf(","))
    }
}

// Gets the flood zone for the current parcel (as specified in the marker)
function getFloodZone(searchPolygon) {
    var query = new esri.tasks.Query();
    query.geometry = searchPolygon;
    query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
    query.outFields = ['FLD_ZONE', 'FLOODWAY', 'SFHA_TF'];
    var returnDef = floodZoneQueryTask.execute(query);
    returnDef.addCallbacks(getFloodZoneSuccess, queryTaskFailed);
}

var STR;
var getSTRSuccess = function(results) {
    if (results.features.length < 1) {
        STR = "Not Available";
    } else {
        STR = "S" + results.features[0].attributes.SEC + " " + "T" + results.features[0].attributes.TWN + " " + "R" + results.features[0].attributes.RNG;        
    }
}

// Gets the TWN RNG SEC
function getSTR(searchPoint){
    var query = new esri.tasks.Query();
    query.geometry = searchPoint;
    query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
    query.outFields = ['TWN', 'RNG', 'SEC'];
    var returnDef = townshipRangeQueryTask.execute(query);
    returnDef.addCallbacks(getSTRSuccess, queryTaskFailed);
}
  
/// Launch legacy report page
function legacyReport(reportPoint) {
  //setup for report
  County = activeCounty.countyName;
  MapStatus = activeCounty.popupMsg;
  //open report
  openReportNew(reportPoint);
}

function getFloodRiskReport() {
    var geographicExtent = esri.geometry.webMercatorToGeographic(map.getLayer('printMarker').graphics[0].geometry);
    var currentLoc = esri.geometry.webMercatorToGeographic(Mapping.Ext.Esri.Marker.getLocation());
    var firmPanels = firmPanelStore.getCount() > 0 ? firmPanelStore.collect('firmPanel') : "N/A";
    var opts = Ext.urlEncode({
        xMin: geographicExtent.xmin,
        yMin: geographicExtent.ymin,
        xMax: geographicExtent.xmax,
        yMax: geographicExtent.ymax,
        locLat: currentLoc.y,
        locLong: currentLoc.x,
        mapWidth: map.width,
        mapHeight: map.height,
        firmPanels: firmPanels,
        floodZone: floodZone,
        sfha: InSFHA,
        floodway: floodway,
        parcel: parcelStore.getAt(0).data.parcelId,
        county: activeCounty.countyName,
        FHAStatus: activeCounty.popupMsg,
        STR: STR,
        perc1Elev: parcelStore.getAt(0).data.Perc1Elev,
        perc10Elev: parcelStore.getAt(0).data.Perc10Elev,
        perc50Elev: parcelStore.getAt(0).data.Perc50Elev,
        address: 'No Address'
    });
    window.open('FloodReport.ashx?' + opts);
}

function setZoomToResults(flag) {
  zoomToResults = flag;
}

//// Catch query task failures and handle
var queryTaskFailed = function(err) {
  unmaskSearchForm();
  console.error(err.toString());
  Mapping.Ext.Esri.ErrorManager.esriError(err);
}

var lookupCountyByDFirmKey = function(dkey) {
  for (i = 0; i < srwmdCounties.length; i++) {
    if (dkey == srwmdCounties[i].dfirmKey)
      return srwmdCounties[i].countyName;
  }

  return dkey;
}

/// Sets the parcel pattern text based on county
function setCountySpecificText() {
  Ext.get('activeCountyText').update('Active County: ' + activeCounty.countyName);
  var pp = Ext.get('ParcelPattern');
  if (pp != null)
    pp.update(activeCounty.parcelPattern);

 countyCombo.setValue(activeCounty.countyName);   
  Ext.getCmp('ParcelCounty').setValue(activeCounty.countyName);    
}

/// Switches active county
/// @param countyConfig new county
/// @param {boolean} show msg when changing county
function switchActiveCounty(countyConfig, manual) {
  activeCounty = countyConfig;
  setCountySpecificText();
  if (manual && (activeCounty != allCountiesConfig))
    Ext.MessageBox.alert("Active County",activeCounty.popupMsg);
}

//Switches active county by name
/// @param countyName new county
function switchActiveCountyByName(countyName, manualSwitch) {
  var uppercaseName = countyName.toUpperCase();
  var i=0;
  var searching = true;
  var activeCountyConfig=null;
  do {
    var compName = srwmdCounties[i].countyName.toUpperCase();
    if (uppercaseName == compName) {
      activeCountyConfig = srwmdCounties[i];
      searching = false;
    }
    i++;
  } while ((searching) && (i < srwmdCounties.length));
  if (activeCountyConfig != null)
    switchActiveCounty(activeCountyConfig, manualSwitch);
  else
    switchActiveCounty(allCountiesConfig, manualSwitch);
}

function zoomToActiveCounty() {
  zoomToCounty(activeCounty.countyName);  
}

/// If county found, center map on county
function showCounty(results) {
  if (results.features.length > 0) {
    var geom = results.features[0].geometry;
    Mapping.Ext.Esri.Marker.reset();
    map.centerAndZoom(geom.getExtent().getCenter(), defaultZoomLevel);
  }
}

///Simple calculation of centroid, just uses the first polygon ring.
function getPolygonCenter(poly) {
  var n = poly.rings[0].length;
  var y = 0, x = 0;
  for(var i = 0; i < n-1; i++) {
     var vert = poly.rings[0][i];
     y += vert[1];
     x += vert[0];
  }
  
  y = y/(n-1);
  x = x/(n-1);
  var centroidPt = new esri.geometry.Point(x, y, poly.spatialReference);
  return centroidPt;
} 

/// Searches for county based on name
/// success centers on county
function zoomToCounty(name) {
  var query = new esri.tasks.Query();
  var queryWhere = "NAME" + "='" + name.toUpperCase() + "'";
  query.where = queryWhere;
  query.returnGeometry = true;
  query.outSpatialReference = defaultSpatialReference;
  query.outFields = ['COUNTY'];
  var returnDef = countyQueryTask.execute(query);
  returnDef.addCallbacks(showCounty, queryTaskFailed);  
}

var dfirmQuerySuccess = function(results) {
  if (results.features.length > 0) {
    firmPanelStore.loadData(results);
  } else {
    Ext.MessageBox.alert('Data not found', 'DFIRM not found.');
  }

  if (zoomToResults) {
      map.centerAndZoom(parcelGeom.getExtent().getCenter(), parcelZoomLevel);
    zoomToResults = false;
  }

  if (preserveClickPoint != null)
    showCountyInfoMarker(preserveClickPoint);
  else {
    //check if extent center is in geom, if not then calc cnetroid
    if (parcelGeom.contains(parcelGeom.getExtent().getCenter()))
      showCountyInfoMarker(parcelGeom.getExtent().getCenter());
    else {
      //var centroidPt =  getPolygonCenter(parcelGeom);
      showCountyInfoMarker(getPolygonCenter(parcelGeom));
    }
  }
  return results;
}

var dfirmQueryFailed = function(err) {
  console.error(err);
}

/// Not used right now, using polygon version
function findDFIRMByPoint(ctrPoint) {
  var query = new esri.tasks.Query();
  query.geometry = ctrPoint;
  query.returnGeometry = true;
  query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
  query.outFields = ['FIRM_PAN', 'PCOMM'];

  var returnDef = firmPanelQueryTask.execute(query);
  returnDef.addCallbacks(dfirmQuerySuccess, dfirmQueryFailed);  
}

function findDFIRMByGeom(geom) {
  var query = new esri.tasks.Query();
  query.geometry = geom;
  query.returnGeometry = true;
  query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
  query.outFields = ['FIRM_PAN', 'PCOMM'];

  var returnDef = firmPanelQueryTask.execute(query);
  returnDef.addCallbacks(dfirmQuerySuccess, dfirmQueryFailed);
}

// Symbol colors used when selecting a parcel
var parcelSymbol = new esri.symbol.SimpleFillSymbol(
  esri.symbol.SimpleFillSymbol.STYLE_SOLID, 
  new esri.symbol.SimpleLineSymbol(
    esri.symbol.SimpleLineSymbol.STYLE_SOLID, 
    new dojo.Color([0,0,255]), 
    2), 
  new dojo.Color([0,255,0,0.50])
);

function parcelResultsQuerySuccess(results) {
    var resultsCountyName = null;
    var foundParcel;
  var geom = null;
  if (results.features.length > 0) {
    parcelStore.loadData(results);
    if (parcelStore.getCount() > 0) {
      foundParcel = parcelStore.getAt(0).data.parcelId;
      resultsCountyName = parcelStore.getAt(0).data.county; 
      if (foundParcel.indexOf('NOT AVAILABLE') < 0) {
        markerSearchText = parcelMarkerText + foundParcel;
        //Check if need to switch counties
        if (resultsCountyName.toUpperCase() != activeCounty.countyName.toUpperCase()) {
          switchActiveCountyByName(resultsCountyName.toUpperCase(), false);
          Ext.MessageBox.alert("Parcel Search", "Parcel found in " + activeCounty.countyName +
                                        " county");
        }
        geom = parcelStore.getAt(0).data.geom;
        parcelGeom = geom;

        // Reset the marker
        Mapping.Ext.Esri.Marker.reset();
        // Listen to marker being drawn and then hide it (keeping the popup window)
        Mapping.Ext.Esri.Marker.addListener('displayed', function() {
          this.hideMarker();
        }, Mapping.Ext.Esri.Marker, {single: true});

        // Locate the dfirm(s)
        findDFIRMByGeom(parcelGeom);
        
        // Locate the Flood Zone
        getFloodZone(parcelGeom);

        //Locate the STR       
        if (preserveClickPoint === null) {
            preserveClickPoint = parcelGeom.getExtent().getCenter();
        }
        getSTR(preserveClickPoint);
        
        // Draw the parcel on the map
        map.getLayer('selectedParcelGraphics').clear();
        //map.graphics.clear();
        var graphic = new esri.Graphic(results.features[0].geometry, parcelSymbol);
        map.getLayer('selectedParcelGraphics').add(graphic);
        //Mapping.Ext.Esri.Marker.hideMarker();
        dojo.connect(map.getLayer('selectedParcelGraphics'),'onMouseOver', function(){
          Ext.getCmp('markerTip').show();
        });        
      }
    }
  } else {
    Ext.MessageBox.alert("Parcel Search", msgNoParcelFound);
  }

  unmaskSearchForm();
  return results;
}

//// Catch query task failures and handle
var parcelQueryTaskFailed = function(err) {
  unmaskSearchForm();
  console.error(err.toString());
  Mapping.Ext.Esri.ErrorManager.esriError(err);
}

/// Queries map service for Parcel based on parcel Id
/// @param string parcelId
function findParcelByParcelId(parcelId) {
  var parcelInCountyQueryTask = new esri.tasks.QueryTask(queryService + '/' +
                                                         allCountiesConfig.parcelLayerID);
  var query = new esri.tasks.Query();
  var queryWhere = activeParcelField + "='" + parcelId + "'";
  query.where = queryWhere;
  query.returnGeometry = true;
  query.outSpatialReference = defaultSpatialReference;
  query.outFields = ['PARCEL', 'County', 'TXTBFE', 'TXT2YR', 'TXT10YR'];
  var returnDef = parcelInCountyQueryTask.execute(query);
  returnDef.addCallbacks(parcelResultsQuerySuccess, parcelQueryTaskFailed);  
}

/// Spatial search for parcel
/// @param searchPoint - will be inside parcel boundary
function findParcelByPoint(searchPoint) {
  var query = new esri.tasks.Query();
  query.geometry = searchPoint;
  query.returnGeometry = true;
  query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
  query.outFields = ['PARCEL', 'County', 'TXTBFE', 'TXT2YR', 'TXT10YR'];
  var returnDef = allParcelQueryTask.execute(query);
  returnDef.addCallbacks(parcelResultsQuerySuccess, parcelQueryTaskFailed);
}

/// Successfull search for parcels intersecting a polygon
var parcelIntersectQuerySuccess = function(results) {
  unmaskSearchForm();
  if (results.features.length > 0) {
    markerSearchText += "<br>Number of parcels: " + results.features.length;
    queryForCountyByPoint(searchPoint);
  } else {
    Ext.MessageBox.alert("Parcel Search", msgNoParcelFound);
  }
  return results;
}

/// Search for parcels intersecting a polygon
/// @param geom - search polygon, looking for parcels that intersect it.
function queryForParcelsByIntersect(geom) {
  searchPoint = geom.getExtent().getCenter();
  var query = new esri.tasks.Query();
  query.geometry = geom;
  query.returnGeometry = true;
  query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
  query.outFields = ['PARCEL'];
  var returnDef = allParcelQueryTask.execute(query);
  returnDef.addCallbacks(parcelIntersectQuerySuccess, queryTaskFailed);
}

//Shape returned from Query from PLSS layer, but really we want parcels,
//so we take the returned shape and query for intersecting parcels
var townshipQuerySuccess = function(results) {
  unmaskSearchForm();
  if (results.features.length > 0) {
    var geom = results.features[0].geometry;
    var thisPt = geom.getExtent().getCenter();
    //map.centerAndZoom(thisPt, defaultParcelZoomLevel);

    //now perform spatial query for parcels 
    queryForParcelsByIntersect(geom);
  } else {
    Ext.MessageBox.alert("Search", "Township/Range/Section not found");
  }
  
  return results;
}
 
/// Find Section, Township and Range
/// @param {string} section The section to search for
/// @param {string} township The township id to search for
/// @param {string} range The range id to search for
function findParcelBySecTwnRng(direction, section, township, range) {
  // do esri query task & request geometry
  var dirTxt ='';
  if (direction == '+')
    dirTxt = 'North ';
  else if (direction == '-')
    dirTxt = 'South ';
  markerSearchText = "Township: " + dirTxt + ' ' + township;
  markerSearchText += " Range:" + range;
  markerSearchText += " Section:" + section;
  
  var query = new esri.tasks.Query();
  var queryWhere = "TWNC='" + township + "'";
  queryWhere += " AND RNGC='" + range + "'";
  queryWhere += " AND SECC='" + section + "'";
  queryWhere += " AND NSC='" + direction + "'";
  query.where = queryWhere;
  query.returnGeometry = true;
  query.outSpatialReference = defaultSpatialReference;
  query.outFields = ['TWNC'];
  var returnDef = townshipRangeQueryTask.execute(query);
  returnDef.addCallbacks(townshipQuerySuccess, queryTaskFailed);  
}

/// Centers map at location
/// @param {esri.geometry} geometry Geometry in WebMercator
function showLocation(cp) {
  map.centerAt(cp); 
}

var countyQuerySuccess = function(results) {
  if (results.features.length > 0) {
    var attributes = results.features[0].attributes;
    switchActiveCountyByName(attributes["NAME"], false);
    showCountyInfoMarker(searchPoint);
    map.centerAt(searchPoint);
  } else {
    Ext.MessageBox.alert('Data not found','Address falls outside SRWMD Counties');
  }
  return results;
}

function queryForCountyByPoint(flPoint) {
  searchPoint = flPoint; //store point for later use
  var query = new esri.tasks.Query();
  query.geometry = flPoint;
  query.returnGeometry = true;
  query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_WITHIN;
  query.outFields = ['NAME'];

  var returnDef = countyQueryTask.execute(query);
  returnDef.addCallbacks(countyQuerySuccess, queryTaskFailed);
}

function showLocationExtent(zoomToExtent) {
  map.setExtent(zoomToExtent);
  showCountyInfoMarker(zoomToExtent.getCenter());
}

function showCountyInfoMarker(mapPoint) {
  reportPoint = mapPoint;
  Mapping.Ext.Esri.Marker.setTitle('Flood Insurance Study');
  var markerTipContent = markerSearchText;
  markerTipContent += '<br>' + activeCounty.popupMsg + '<br><br>';
  if (markerTipContent.indexOf(parcelMarkerText) > -1) {
      markerTipContent += '<a href="javascript:(showPrintWindow());" title="Flood Risk Report">Flood Risk Report</a><br/>';
    for (var i = 0; i < firmPanelStore.getCount(); i++) {
      var firmPanelName = firmPanelStore.getAt(i).data.firmPanel;
      var panelCounty = firmPanelStore.getAt(i).data.countyCode;
      panelCounty = lookupCountyByDFirmKey(panelCounty);
      var link = baseDFIRMURL + panelCounty + "/" + firmPanelName + DFIRMFileExt;
      markerTipContent += '<a href="' + link + '" target="new">View DFIRM: ' + firmPanelName + '</a><br/>';
    }
  }

  markerTipContent += '<a href="' + baseCountyFISURL + activeCounty.countyName + '.pdf" target="new">View Flood Insurance Study for ' + activeCounty.countyName + ' county</a><br/>';
  markerTipContent += '<br><br><a href="javascript:(map.centerAndZoom(Mapping.Ext.Esri.Marker.getLocation(),' + (sliderText.length - 1) + '));">Zoom to point</a>';

  Mapping.Ext.Esri.Marker.setContent(markerTipContent);
  Mapping.Ext.Esri.Marker.setLocation(mapPoint);

  preserveClickPoint = null; //reset
}


//Parcel hover methods
//JTODO merge with existing code base
var extent;
var symbol, infoTemplate;
var Handle1, Handle2, Handle3;
var mapTipPoint;
var currentParcel;
var InsideInfoGeometry = false;
var ExitParcel = true;
var handles;
var preserveClickPoint = null;

// get point where user clicked during parcel hover tool
function findParcelByClickHover(evt) {
  preserveClickPoint = evt.mapPoint;
  findParcelByPoint(preserveClickPoint);
}


var hoverOn = function() {
    //if at/below proper scale go ahead and query for parcels
    if (map.getLevel() >= srwmdAerialsLevel) {   
      
      symbol = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_NULL, new dojo.Color([255, 0, 0]), 2), new dojo.Color([255, 255, 0, 0]));
      symbol2 = new esri.symbol.SimpleFillSymbol(esri.symbol.SimpleFillSymbol.STYLE_SOLID, new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0, 0, 255]), 2), new dojo.Color([0, 255, 0, 0.5]));
      executeQueryTask();
      return true;
    } else {
      Ext.Msg.alert('Zoom closer', 'You must zoom closer to use this feature'); 
      return false;
    }
}

// disconnect all hover handlers
function ClearHoverHandles() {
  if (Handle1 != null) {
    dojo.disconnect(Handle1);
    Handle1 = null;
  }
  if (Handle2 != null) {
    dojo.disconnect(Handle2);
    Handle2 = null;
  }
  if (Handle3 != null) {
    dojo.disconnect(Handle3);
    Handle3 = null;
  }
}
// turn off the hover tool
function hoverOff() {
  //Disconect any event handlers
  ClearHoverHandles();
  // hide parcel hover popup
  toggleMouseParcels(false);
  if (currentParcel != null) {
    currentParcel.setSymbol(symbol);
  }
  map.getLayer('parcelGraphics').clear();
}
// show the parcels on the map
function showHoverResults(featureSet) {
  Ext.MessageBox.hide();
  //Disconect any event handlers
  ClearHoverHandles();
  
  // Turn off the parcel hover window and clean up
  toggleMouseParcels(true);  
  map.getLayer('parcelGraphics').clear();
  var features = featureSet.features;
    
  //QueryTask returns a featureSet.  Loop through features in the featureSet and add them to the map.
  for (var i = 0, il = features.length; i < il; i++) {
    //Get the current feature from the featureSet.
    //Feature is a graphic
    var graphic = features[i];
    graphic.setSymbol(symbol);
     
    //Add graphic to the map graphics layer.
    map.getLayer('parcelGraphics').add(graphic);
  }

  // Turn on the parcel hover window and set cursor
  toggleMouseParcels(true);
  Mapping.Ext.Esri.CursorManager.removeCursor('mouseProgress');
  
  Handle1 = dojo.connect(map.getLayer('parcelGraphics'), "onMouseMove", updateMapToolTip);
  Handle2 = dojo.connect(map.getLayer('parcelGraphics'), "onMouseOut", clearMapToolTip);
  Handle3 = dojo.connect(map.getLayer('parcelGraphics'), "onClick", findParcelByClickHover);
}

function executeQueryTask() {
  Ext.MessageBox.wait('loading parcels...');
  //build query filter
  var query = new esri.tasks.Query();
  query.returnGeometry = true;
  query.outFields = ["PARCEL"];
  query.geometry = map.extent;

  //Execute task and call showResults on completion
  allParcelQueryTask.execute(query, showHoverResults);
  dojo.connect(allParcelQueryTask, function(err) {
    alert(err.message);
    Ext.MessageBox.hide();
  });
}

function updateMapToolTip(evt) {

  var eventGraphic = evt.graphic;
  var SameParcel = false;

  if (!InSameParcel(evt.graphic, evt.mapPoint)) {
    if (currentParcel != null) {
      currentParcel.setSymbol(symbol);
    }
    
    currentParcel = eventGraphic;
    currentParcel.setSymbol(symbol2);
    
    if(mouseCoordinateTracker != null){
     //mouseCoordinateTracker.show();
     if (Ext.get('mouseParcelDiv') != null) {
      Ext.get('mouseParcelDiv').update(eventGraphic.attributes.PARCEL);
     }
    } 
  }
}

function clearMapToolTip(evt) {
  if (!InSameParcel(evt.graphic, evt.mapPoint)) {
    //map.infoWindow.hide();
    currentParcel.setSymbol(symbol);
    if(mouseCoordinateTracker != null){
      if (Ext.get('mouseParcelDiv') != null) {
        Ext.get('mouseParcelDiv').update('N/A');
      }
    }    
  }
}

function InSameParcel(g, p) {
  var sp = false;
  
  if (currentParcel != null) {
    sp = currentParcel.geometry.contains(p);
  }
    
  return sp;
}

// Displays current lat/long next to mouse
function toggleMouseParcels(state) {
  if(state && mouseCoordinateTracker == null) {
    mouseCoordinateTracker = new Ext.ToolTip({
      target: 'map',
      title: 'Parcel Number',
      width: 150,
      dismissDelay: 0,
      html: '<div id="mouseParcelDiv"> </div>',
      trackMouse:true
    });
  } else if (!state && mouseCoordinateTracker != null) {
    mouseCoordinateTracker.destroy();
    mouseCoordinateTracker = null;
  }
}

