// File: Core.js

//Core functions -- Javascript Ninjas only!
//----------------------------------------
dojo.require("esri.map");
dojo.require("esri.tasks.identify");
dojo.require("esri.tasks.query");
dojo.require("esri.tasks.find");

dojo.require("esri.toolbars.draw");
dojo.require("esri.toolbars.navigation");

dojo.require("dojo.parser");

dojo.require("dojo.data.ItemFileReadStore");

dojo.require("dijit.Dialog");
dojo.require("dijit.form.Button");
dojo.require("dijit.form.CheckBox");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dijit.form.ValidationTextBox");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.Toolbar");


var _map, _mapService_Layer, _aeriallayer, _identifyTb, _drawBufferShapeTb, _selectTb;
var _navigateTB, _measureTb, _queryTaskPlatSearch;
var _selectionList = [], _selectionExtent = null, _selectedParcelID = -1;
var _listCacheCaption, _listCacheBody;

//This value is set in index.php.  This allows an argument to be passed between
//code executing on the server and code executing on the client.
//It appears that a comma delimited list of GP's may be passed but I have not
//tested that assumption.
var _urlGPList = "";
//This value is set in index.php.  This allows an argument to be passed between
//code executing on the server and code executing on the client.  This particular
//variable was created to allow the Transfer Index web pages to link to a plat.
//It is possible that we would want to search by palt name but the Transfer
//Index has the platnum to begin with so we will use that for the time being.
var _platnum = "";

var _mapSelectedParcelID  = -1;
//Set in index.php and printpage.php
var _MapLayers = null;
var _mapAerials = null;
var _measureStage = ""; // either "", "STARTED", "DRAWING", "ENDDED"
var _baseURL = "";


//Initial and Setup Functions Start
//-----------------------------

/*------------------------------------------------------------------------+
|  FUNCTION: init                                                         |
|  DESCRIPTION: Function to triggered after the DOM has finished loading  |
|     and widgets declared in markup have been instantiated. Images and   |
|     CSS files may or may not have finished downloading when the         |
|     specified function is called.                                       |
|     (Note that widgets' CSS and HTML code is guaranteed to be           |
|     downloaded before said widgets are instantiated.)                   |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009  Created                                     |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
function init() {
  dojo.parser.parse(dojo.byId("wrapper"));

  esri.config.defaults.io.proxyUrl = "proxy.php";
  esri.config.defaults.io.alwaysUseProxy = true;
  esri.config.defaults.map.zoomDuration = 200; //time in milliseconds; default is 250
  esri.config.defaults.map.zoomRate = 20; //refresh rate of zoom animation; default is 25
  esri.config.defaults.map.panDuration = 200; //time in milliseconds; default panDuration:250
  esri.config.defaults.map.panRate = 20; //refresh rate of zoom animation; default panRate:25

  //Setup the Map Layers - NOTE: We have not setup the actual map yet.
  _mapService_Layer = new esri.layers.ArcGISDynamicMapServiceLayer(MapServiceURL, {useMapImage:false});
  _mapService_Layer.setImageFormat("png24");
  dojo.connect(_mapService_Layer, "onUpdate", hideMapLoading);
  dojo.connect(_mapService_Layer, "onVisibilityChange", hideMapLoading);

  if (_mapService_Layer.loaded) {
    //In my testing I could not get this line of code to execute.
    setupQuery();
  } else {
    dojo.connect(_mapService_Layer, "onLoad", setupQuery);
  }

  //Kill mouse selection on overlay elements:
  disableSelection(dojo.byId('mapscaleinfo'));
  disableSelection(dojo.byId('mapmeasureinfo'));
  disableSelection(dojo.byId('mapbufferinfo'));
  disableSelection(dojo.byId('mapactivelayer'));
  disableSelection(dojo.byId('mapcursorinfo'));
}

/*------------------------------------------------------------------------+
|  FUNCTION: setupQuery                                                   |
|  DESCRIPTION: Event handler for the Map Service Layer Load event.       |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009  Created                                     |
|     scunnin     08-11-2009  Added option to display a plat.             |
|  ARGUMENTS:                                                             |
|     layer - Not sure what this is supposed to be and I not sure we      |
|             really need this since it's never referenced in this        |
|             function.                                                   |
+------------------------------------------------------------------------*/
function setupQuery(layer) {
  if (_urlGPList != '') {
    processQuery("GP IN ('" + _urlGPList.replace(/,/g, '\',\'') + "')",
                 null, null, 0,
                  function(featureSet) {
                    if (featureSet.features.length) {
                      _selectionExtent = getExtents(featureSet);
                      if (_selectionExtent != null) {
                        MapExtentXMin = _selectionExtent.xmin;
                        MapExtentYMin = _selectionExtent.ymin;
                        MapExtentXMax = _selectionExtent.xmax;
                        MapExtentYMax = _selectionExtent.ymax;
                      }
                    }
                    map_setup();
                  }
                );
  } else if (_platnum != ''){
    map_setup();
    executePlatSearch_byPlatnum(_platnum);
  } else {
    map_setup();
  }
}

/*------------------------------------------------------------------------+
|  FUNCTION: map_setup                                                    |
|  DESCRIPTION:                                                           |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009   Created                                    |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
function map_setup() {
  //Setup the Map Service
  var customExtent = new esri.geometry.Extent(MapExtentXMin,
                                              MapExtentYMin,
                                              MapExtentXMax,
                                              MapExtentYMax,
                                              new esri.SpatialReference({"wkid": MapWKID}));

  if ((typeof(AerialServiceURL) !== 'undefined') && (dojo.byId("mapinfobar"))) {
    _map = new esri.Map("map", {extent:customExtent});
  } else {
    _map = new esri.Map("map", {extent:customExtent, slider:false, nav:false });
  }

  //Assign map event handlers
  dojo.connect(_map, "onLoad", null, map_onLoad);
  dojo.connect(_map, "onZoomStart", showMapLoading);
  dojo.connect(_map, "onPanStart", showMapLoading);

  //Aerial Layer:
      //Note: We are not using an aerial service 
  if (typeof(AerialServiceURL) !== 'undefined') {

    if (typeof(AerialServiceLevels) !== 'undefined') {
      _aeriallayer = new esri.layers.ArcGISTiledMapServiceLayer(
                                          AerialServiceURL,
                                          {visible: ShowInitialAerials,
                                          displayLevels:AerialServiceLevels});
    } else {
      _aeriallayer = new esri.layers.ArcGISTiledMapServiceLayer(
                                          AerialServiceURL,
                                          {visible: ShowInitialAerials});
    }
    dojo.connect(aeriallayer, "onUpdate", hideMapLoading);

    if (_mapAerials != null) {
      //Set Special visible layers
      if (_mapAerials == "1") {
        _aeriallayer.show();
      } else {
        _aeriallayer.hide();
      }
    }

    _map.addLayer(aeriallayer);
  }

  if (_MapLayers != null) {
    //Set Special visible layers
    _mapService_Layer.setVisibleLayers(_MapLayers.split(','));
  }

  //Add the Auditors Map Layer to the Map
  _map.addLayer(_mapService_Layer);
}

/*------------------------------------------------------------------------+
|  FUNCTION: map_onLoad                                                   |
|  DESCRIPTION:                                                           |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009   Created                                    |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
function map_onLoad() {
  showMapLoading();

  //Set the plat search dates to todays date
  var today = new Date();
  if (dojo.byId("date_PlatFrom")) {
    dojo.byId("date_PlatFrom").value = (today.getMonth() + 1) + "/" +
                                        today.getDate() + "/" +
                                        today.getFullYear();
  }
  if (dojo.byId("date_PlatTo")) {
    dojo.byId("date_PlatTo").value = (today.getMonth() + 1)  + "/" +
                                      today.getDate()+ "/" +
                                      today.getFullYear();
  }

  //after map loads, assign mouse event handlers
  dojo.connect(_map, "onMouseMove", updateInfoBar);
  dojo.connect(_map, "onMouseDrag", updateInfoBar);
  dojo.connect(_map, "onMouseDown",
                function(evt){
                  if (_measureStage == "STARTED") {
                    _measureStage = "DRAWING";
                    dojo.byId("mapmeasureinfo").innerHTML =
                      "Double-Click on the map to end Measuring..";
                  }
                }
              );


  //IDENTIFY TOOLBAR COMMAND
  var identifyParams = new esri.tasks.IdentifyParameters();
  identifyParams.tolerance = 12;
  identifyParams.returnGeometry = true;
  //identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_VISIBLE;
  identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;
  identifyParams.width = 600;
  identifyParams.height = 500;
  var identify = new esri.tasks.IdentifyTask(MapServiceURL);
  dojo.connect(identify, "onComplete", selectResults);
  _identifyTb = new esri.toolbars.Draw(_map);
  dojo.connect(_identifyTb, "onDrawEnd",
                function(geometry) {
                  updateResultsTab("Results", "<img src='" + _baseURL +
                                   "images/loader.gif' alt=\"loader.gif\"/> Identifying Features...");

                  identifyParams.geometry = geometry;
                  identifyParams.mapExtent = _map.extent;
                  identifyParams.layerIds = [dijit.byId("activeLayer").value];
                  identify.execute(identifyParams);
                }
              );


  //BUFFER TOOLBAR COMMAND
    //Setup the buffer Parameters
  var geometryService = new esri.tasks.GeometryService(GeometryServiceURL);
  var bufferParams = new esri.tasks.BufferParameters();
  bufferParams.unit = esri.tasks.BufferParameters.UNIT_FOOT;
  _drawBufferShapeTb = new esri.toolbars.Draw(_map);
  dojo.connect(_drawBufferShapeTb, "onDrawEnd",
                function(geometry) {
                  updateResultsTab("Results", "<img src='" + _baseURL +
                     "images/loader.gif' alt=\"loader.gif\"/> Buffering Features...");

                  var symbol = new esri.symbol.SimpleMarkerSymbol();
                  var graphic = new esri.Graphic(geometry, symbol);

                  bufferParams.features = [graphic];
                  bufferParams.distances = [dojo.byId('bufferDistance').value];
                  geometryService.buffer(bufferParams);
                }
              );
  dojo.connect(geometryService, "onBufferComplete",
                function(graphics) {
                  var symbol = new esri.symbol.SimpleFillSymbol(
                                    "none",
                                    new esri.symbol.SimpleLineSymbol(
                                        "dashdot",
                                        new dojo.Color([255,0,0]), 2),
                                        new dojo.Color([255,255,0,0.25]));
                  var graphic = new esri.Graphic(graphics[0].geometry,symbol);
                  _map.graphics.add(graphic);

                  processQuery("right(left(" + ParcelPolyFieldName + ", 7), 1) <> '6'",
                               esri.tasks.Query.SPATIAL_REL_INTERSECTS,
                               graphics[0].geometry, 0, showResults);
                }
              );

  //SELECT TOOLBAR COMMAND
  var selectParams = new esri.tasks.IdentifyParameters();
  selectParams.tolerance = 2;
  selectParams.returnGeometry = true;
  selectParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_VISIBLE;
  selectParams.width = 600;
  selectParams.height = 500;
  selectParams.layerIds = [getLayerIDFromName(SearchLayerNames[0])];
  var select = new esri.tasks.IdentifyTask(MapServiceURL);
  dojo.connect(select, "onComplete", selectResults);
  _selectTb = new esri.toolbars.Draw(_map);
  dojo.connect(_selectTb, "onDrawEnd", function(geometry) {
    updateResultsTab("Results", "<img src='" + _baseURL +
                     "images/loader.gif' alt=\"loader.gif\"/> Selecting Parcels...");

    selectParams.geometry = geometry;
    selectParams.mapExtent = _map.extent;
    select.execute(selectParams);
  });

  //MEASURE TOOLBAR COMMAND
  _measureTb = new esri.toolbars.Draw(_map);
  dojo.connect(_measureTb, "onDrawEnd", function(geometry) {
    _map.graphics.clear();
    var graphic = _map.graphics.add(new esri.Graphic(geometry, new esri.symbol.SimpleFillSymbol()));

    //Figure out length
    var length = 0.0;
    for (var i = 0; i < (geometry.paths[0].length - 1); i++) {
      var x1 = geometry.paths[0][i][0];
      var y1 = geometry.paths[0][i][1];
      var x2 = geometry.paths[0][i+1][0];
      var y2 = geometry.paths[0][i+1][1];

      var distance = Math.sqrt((x1 -= x2) * x1 + (y1 -= y2) * y1);

      length += distance;
    }

    _measureStage = "ENDDED";
    dojo.byId("mapmeasureinfo").innerHTML = "Length is: " +
                                                length.toFixed(1) + " Feet";
  });

  //NAVIGATION TOOLBAR COMMAND
  _navigateTB = new esri.toolbars.Navigation(_map);
  dojo.connect(_navigateTB, "onExtentHistoryChange", extentHistoryChangeHandler);

  _queryTaskPlatSearch = new esri.tasks.QueryTask(MapServiceURL + "/" +
                                            getLayerIDFromName(SubsLayerName));
  dojo.connect(_queryTaskPlatSearch, "onComplete", identifyPlatResults);
  //8-11-2009 - Added error handler
  dojo.connect(_queryTaskPlatSearch, "onError", error_Handler);


  activatePan();

  setupLayersTab();


  //8-27-2009
  command_Identify_list_build();

  //_map.resize();
  //_map.reposition();

  if (dojo.byId("disclaimer")) {
    dijit.byId('disclaimer').show();
  }

  //I've had problems handling dispaying the map when a parcel is passed
  //with the URL.  It may seem to be a little voodoo but it might be best
  //not to move this section of code to any place else in this function.
  //The actual problem appears to be related to how the event handlers deal
  //with displaying the map, getting the parcel shape of interest and displaying
  //its database information.
  //Catch when arguments are passed with the URL to index.php and printpage.php
  if (_urlGPList != '') {
    //build query filter for PIN
    processQuery("GP IN ('" + _urlGPList.replace(/,/g, '\',\'') + "')",
                 null, null, 0, showResults);
  }

  dojo.byId("siteloading").style.display = 'none';

  if (dojo.byId("wrapper").filters) {
    if (dojo.byId("wrapper").filters.alpha) {
      dojo.byId("wrapper").filters.alpha.opacity = 100;
    }
  } else {
    showControl("wrapper", 1, 1000);
  }

  if (dojo.byId("mapinfobar")) {
    updateInfoBar(null);
    showControl("mapinfobar", 0.7, 500);
    showControl("mapcursorinfo", 1, 500);
    showControl("mapscaleinfo", 1, 500);
  }

}

function error_Handler(myError) {
  var error_contents = myError;
  updateResultsTab("Results", "<img src='" + _baseURL +
                   "images/loader.gif' alt=\"loader.gif\"  alt=\"loader.gif\"/> Error <b>" +
                   myError.details + "</b>...");
  showMapLoading();
}

/*------------------------------------------------------------------------+
|  FUNCTION: setupLayersTab                                               |
|  DESCRIPTION: Populates the DOM layersTab.                              |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     scunnin     08-26-2009  Created                                     |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
function setupLayersTab() {
  var content = "";
  var currentLayerInfo;

  var layer_tab = dijit.byId('layersTab');
  if (layer_tab) {
    for (var k=0; k < _mapService_Layer.layerInfos.length; k++) {
      currentLayerInfo = _mapService_Layer.layerInfos[k];
      if (!isLayerBlacklisted(currentLayerInfo)) {
        //toc_build will handle all of the child nodes so
        //we only need to hand of the root layers
        if (currentLayerInfo.parentLayerId == -1 ) {
          content += toc_build(currentLayerInfo.id);
        }
      }
    }
    content += "<p align=center><i>" +
               "Aerial imagery courtesy of the<br>" +
               "Polk County Assessor</i></p>";
    layer_tab.attr("content", content );

    //Contract all of our toc entries
    for (var j=0; j<_mapService_Layer.layerInfos.length; ++j ) {
      currentLayerInfo = _mapService_Layer.layerInfos[j];
      if (currentLayerInfo.subLayerIds != null) {
        toc_expand_contract(currentLayerInfo.id, "none");
      }
    }

  }
}

/*------------------------------------------------------------------------+
|  FUNCTION: toc_build                                                    |
|  DESCRIPTION: Recursively builds the html for the                       |
|               Table of Contents Layer list.                             |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     scunnin     08-26-2009  Created                                     |
|  ARGUMENTS:                                                             |
|     Array <=  Array of levels to build html for.                        |
+------------------------------------------------------------------------*/
function toc_build (layer_list){
  var layers;
  var html = "";

  if (layer_list.length == undefined) {
    //Coerce single layer string to an array
    layers = new Array();
    layers[0] = layer_list;
  } else {
    layers = layer_list;
  }

  for (var i = 0; i <= layers.length-1; ++i) {
    var layer_info = _map._layers.layer0.layerInfos[layers[i]];
    if (!isLayerBlacklisted(layer_info)) {
      html += "<div id=\"layerdiv" + layer_info.id + "\">";
      html += "<table cellspacing=\"0px\" cellpadding=\"0px\">";

      html += "<tr>";
      var layer_depth = getLayerDepth(layer_info.id);
      //add cell padding
      for (j=1; j <= layer_depth; ++j){
        html += "<td><div style=\"width: 20px; height: 100%;\"></div></td>";
      }
      //plus/minus icon cell
      if (layer_info.subLayerIds != null ) {
        html += "<td>";
        html += "<img id=\"toggle_icon_" + layer_info.id + "\"" +
                   " src=\"images/toc_minus.gif\" alt=\"Toc_Minus.gif\" " +
                   "onmouseup = \"toc_icon_click\(" + layer_info.id + "\)\;\"";
        html += "</td>";
      } else {
        html += "<td><div style=\"width: 20px; height: 100%;\"></div></td>";
      }
      html += "<td>";
      html += "<input id=\"layer" + layer_info.id +
                        "\" dojotype=\"dijit.form.CheckBox\" onclick=\"map_Layers_setVisible\"" +
                        ((layer_info.defaultVisibility)?"checked=\"checked\" value=\"on\"":"") +
                          " type=\"checkbox\" />";
      html += "</td>";
      html += "<td>";
      html += layer_info.name;
      html += "</td>";
      html += "</tr>";
      //create table
      html += "</table></div>";


      //If we have child layers we need to process those
      var child_layers = layer_info.subLayerIds;
      if (child_layers != null) {
        if (child_layers.length > 0) {
          html += toc_build (child_layers);
        }
      }
    }
  }

  return html;
}

/*------------------------------------------------------------------------+
|  FUNCTION: command_Identify_list_build                                  |
|  DESCRIPTION: Builds the list for the Identify command.                 |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     scunnin     08-27-2009  Created                                     |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
function command_Identify_list_build () {
  var layerList = {identifier:"value", items: []};
  var active_layer = dijit.byId('activeLayer');

  for (var k=0; k < _mapService_Layer.layerInfos.length; k++) {
    var currentLayerInfo = _mapService_Layer.layerInfos[k];
    if (!isLayerBlacklisted(currentLayerInfo)) {
      var strDisplayValue = "".pad(getLayerDepth(currentLayerInfo.id)*2, "-", 0) +
                                                                  currentLayerInfo.name;
      if (DefaultActiveLayer == currentLayerInfo.name) {
        DefaultActiveLayer = strDisplayValue;
      }
      //Since the address featuer is a label of the parcel shapes
      //the identify command will return a parcel polygon which will
      //be confusing to the public so we filter it out.
      if (currentLayerInfo.name != "Address") {
        layerList.items.push({name:strDisplayValue, value:currentLayerInfo.id}); 
      }
    }
  }

  if (active_layer) {
    active_layer.store = new dojo.data.ItemFileReadStore({data: layerList});
    active_layer.setDisplayedValue(DefaultActiveLayer);
  }

}

/*------------------------------------------------------------------------+
|  FUNCTION: toc_icon_click                                               |
|  DESCRIPTION: Table of Contents icon cleck event handler.               |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     scunnin     08-25-2009  Created                                     |
|  ARGUMENTS:                                                             |
|   toc_number - MapService layer numbers entries to process.             |
+------------------------------------------------------------------------*/
function toc_icon_click (toc_number) {
  var layer_list = _map._layers.layer0.layerInfos[toc_number].subLayerIds;
  //layer_list.unshift(toc_number);
  var icon = dojo.byId ("toggle_icon_" + toc_number);
  var path = icon.src.split("/");
  var src_name = path[path.length-1];
  if (src_name == "toc_plus.gif") {
    icon.src = "./images/toc_minus.gif";
    toc_expand_contract(layer_list, 'block');
  } else {
    icon.src = "./images/toc_plus.gif";
    toc_expand_contract(layer_list, 'none');
  }
}

/*------------------------------------------------------------------------+
|  FUNCTION: toc_expand_contract                                          |
|  DESCRIPTION: Given a list of layers recursively hides or displays the  |
|   Layers Table of Contents entries.                                     |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     scunnin     08-25-2008  Created                                     |
|  ARGUMENTS:                                                             |
|   layer_list - List of MapService layer numbers to process.             |
|   display_type - none, block or inline                                  |
+------------------------------------------------------------------------*/
function toc_expand_contract(layer_list, display_type) {
  var layers;
  //We need an array to iterate through but if only one
  //layer is passed javascript interprets it as a string
  //so we coerce the string to an array
  if (layer_list.length == undefined) {
    layers = new Array();
    layers[0] = layer_list;
  } else {
    layers = layer_list;
  }

  for (var i = 0; i <= layers.length-1; ++i) {
    var currentLayer = _map._layers.layer0.layerInfos[layers[i]];
    var child_layers = currentLayer.subLayerIds;
    var dom_div = dojo.byId ("layerdiv" + layers[i] );

    //If we are setting the display type to none then we
    //need to hide all of the child layers and reset the root layers icon 
    if (child_layers != null && display_type == "none") {
      if (child_layers.length > 0 ) {
        toc_expand_contract (child_layers, display_type);
      }
    }

    if (dom_div != null){
      //We show\hide everthing except our root nodes
      if (currentLayer.parentLayerId > -1 ) {
        dom_div.style.display = display_type;
      }
      if (child_layers != null ) {
        var icon = dojo.byId ("toggle_icon_" + currentLayer.id);
        if (display_type == "none") {
          icon.src = "./images/toc_plus.gif";
        } else {
          //if there is a hidden child div we use the plus sign otherwise we use a minus
          var child_div = dojo.byId ("layerdiv" + child_layers[0] );
          if (child_div.style.display == "none") {           
            icon.src = "./images/toc_plus.gif"; 
          } else {
            icon.src = "./images/toc_minus.gif"; 
          }
        }
      }
    }
  }
}

function zoomToPolysFromPoints(selectionList) {
  var allpoints = new esri.geometry.Multipoint({"wkid": MapWKID});

  for (var i=0; i < selectionList.length; i++) {
    if (!(selectionList[i].attributes[ParcelPointFieldName] == undefined)) {
      if (selectionList[i].geometry.type == "point") {
        allpoints.addPoint(selectionList[i].geometry);
      }
    }
  }

  if (allpoints.points.length == 0) return;

  processQuery(null, esri.tasks.Query.SPATIAL_REL_INTERSECTS, allpoints, 0, function(featureSet) {
    if (featureSet.features.length) {
      if (featureSet.layerId == getLayerIDFromName(SearchLayerNames[0])) {
        _selectionExtent = getExtents(featureSet);

        addToMapSelection(featureSet);

        //if (selectionExtent != null) {
        //  selectionExtent = selectionExtent.union(getExtents(featureSet));
        //} else {
        //
        //}

        _map.setExtent(_selectionExtent);
      }
    }
  });
}
//-----------------------------
//Initial and Setup Functions End


//Utility Functions Start
//-----------------------------
String.prototype.pad = function(l, s, t){
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
};

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
}

/*------------------------------------------------------------------------+
|                                                                         |
|  FUNCTION: getExtents                                                   |
|                                                                         |
|  DESCRIPTION: Given a featureSet an Extent is created and returned.     |
|                                                                         |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009  Created                                     |
|     scunnin     08-12-2009  Fixed a problem where point geometry was not|
|                             being procesed.                             |
|                                                                         |
|  ARGUMENTS:                                                             |
|      esri.tasks.FeatureSet <=  Feature Set                              |
|       esri.geometry.Extent  => Extent of graphic elements               |
+------------------------------------------------------------------------*/
function getExtents(featureSet) {
  var thisExtent = null;

  if (featureSet.features) {
    for (var i=0; i < featureSet.features.length; i++) {
      //Get the current feature from the featureSet. (Query)
      var graphic = featureSet.features[i];

      if (graphic.geometry.type != "point") {
        var extents = graphic.geometry.getExtent();

        if (thisExtent != null) {
          thisExtent = thisExtent.union(extents);
        } else {
          thisExtent = extents;
        }
        //8-12-2009 - Added else block to process point geometry
      } else {
        var point_extent = new esri.geometry.Extent;
        point_extent.xmax = graphic.geometry.x + 100;
        point_extent.xmin = graphic.geometry.x - 100;
        point_extent.ymax = graphic.geometry.y + 100;
        point_extent.ymin = graphic.geometry.y - 100;
        if (thisExtent != null) {
          thisExtent = thisExtent.union(point_extent);
        } else {
          thisExtent = point_extent;
        }
      }
    }
  } else {
    for (var i=0; i < featureSet.length; i++) {
      //Get the current feature from the featureSet. (Identify)
      var graphic = featureSet[i].feature;

      if (graphic.geometry.type != "point") {
        var extents = graphic.geometry.getExtent();

        if (thisExtent != null) {
          thisExtent = thisExtent.union(extents);
        } else {
          thisExtent = extents;
        }
      } else {
        //8-12-2009 - Added else block to process point geometry
        var point_extent = new esri.geometry.Extent;
        point_extent.xmax = graphic.geometry.x + 100;
        point_extent.xmin = graphic.geometry.x - 100;
        point_extent.ymax = graphic.geometry.y + 100;
        point_extent.ymin = graphic.geometry.y - 100;
        if (thisExtent != null) {
          thisExtent = thisExtent.union(point_extent);
        } else {
          thisExtent = point_extent;
        }
      }
    }
  }

  if (thisExtent == null) {
    return null;
  } else {
    return thisExtent.expand(1.5);
  }
}

function addToMapSelection(featureSet) {
  if (featureSet.features) {
    for (var i=0; i < featureSet.features.length; i++) {
      //Get the current feature from the featureSet. (Query)
      var graphic = featureSet.features[i];

      graphic.setSymbol(getSymbol(graphic, false));
      _map.graphics.add(graphic);

      graphic.layerId = featureSet.layerId;
      graphic.fieldAliases = featureSet.fieldAliases;
      graphic.value = featureSet.features[i].attributes[featureSet.displayFieldName];
      _selectionList[_selectionList.length] = graphic;
    }
  } else {
    for (var i=0; i < featureSet.length; i++) {
      //Get the current feature from the featureSet. (Identify)
      var graphic = featureSet[i].feature;

      graphic.setSymbol(getSymbol(graphic, false));
      _map.graphics.add(graphic);

      graphic.layerId = featureSet[i].layerId;
      graphic.value = featureSet[i].value;
      _selectionList[_selectionList.length] = graphic;
    }
  }
}

function updateInfoBar(evt) {
  if(evt != null && ShowMouseCoords && dojo.byId("mapcursorinfo")) {
    //Get mapPoint from event
    var mp = evt.mapPoint;

    //Update Mouse Cursor Coordinates
    dojo.byId("mapcursorinfo").innerHTML = "Mouse Position: " +
                                              mp.x.toFixed(1) + ", " +
                                              mp.y.toFixed(1);
  }

  //Get Map Extent and Scale
  var me = _map.extent;
  var scale = (me.getWidth() / dojo.byId("map").clientWidth) * 96;

  //Update Map Scale Panel
  dojo.byId("mapscaleinfo").innerHTML = "<img src=\"" + _baseURL +
              "images/north_arrow_scale.png\" alt=\"arrow_scale.png\" />&nbsp;" +
              scale.toFixed(0) + " Feet";
}

function updateResultsTab(caption, content) {
  _listCacheCaption = caption;
  _listCacheBody = content;

  var te = dijit.byId('mainTabContainer');

  if (te) {
    var childrenTabs = te.getChildren();

    for( var t = 0; t < childrenTabs.length; t++) {
      if (childrenTabs[t].id == "resultsTab") {
        childrenTabs[t].controlButton.attr('label',caption);
        childrenTabs[t].attr("content", "<div style=\"padding: 5px;\">" + content + "</div>");
        te.selectChild(childrenTabs[t]);
        return;
      }
    }
  } else {
    dojo.byId("resultsTab").innerHTML = "<div style=\"padding: 5px;\">" + content + "</div>";
  }
}

function glowGeometry(index) {
  if(_map.graphics.graphics == null) return;
  if(_map.graphics.graphics.length == 0) return;

  for (var i=0; i < _map.graphics.graphics.length; i++) {
    var selected = _map.graphics.graphics[i];

    if(i == index) {
      selected.setSymbol(getSymbol(selected, true)); //Highlight this graphic
    } else {
      selected.setSymbol(getSymbol(selected, false)); //UnHighlight this graphic
    }
  }
}

function getLayerIDFromName(name) {
  for (var k=0; k < _mapService_Layer.layerInfos.length; k++) {
    var currentLayerInfo = _mapService_Layer.layerInfos[k];

    if (currentLayerInfo.name == name) {
      return currentLayerInfo.id;
    }
  }

  return -1;
}

function getLayerDepth(layerid) {
  var depth = 0;

  for (var k=0; k < _mapService_Layer.layerInfos.length; k++) {
    var currentLayerInfo = _mapService_Layer.layerInfos[k];

    if (currentLayerInfo.id == layerid) {

      if (currentLayerInfo.parentLayerId > -1) {
        depth++;
        depth += (getLayerDepth(currentLayerInfo.parentLayerId));
      }

    }
  }

  return depth;
}

/*------------------------------------------------------------------------+
|  FUNCTION: map_Layers_setVisible                                        |
|  DESCRIPTION: Sets the visible layers of our map.  If the _MapLayers    |
|   variable is set that list is used otherwise the Map Service layers    |
|   settings are used.                                                    |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009   Created                                    |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
function map_Layers_setVisible() {
  showMapLoading();

  var visibleLayers = [];

  //_MapLayers can be set from the index.php and printpage.php and can be passed
  //as command line arguments to those pages.
  //I know that the printpage.php sets this variable based on the layers settings
  //set in index.pgp when the printpage.php page is called.
  if ( typeof _MapLayers !== 'undefined' ) {
    if (_MapLayers !== null) {
      _mapService_Layer.setVisibleLayers(_MapLayers);
      return;
    }
  }

  //Iterate through the Map Service Layers and if the corresponding
  //check box in the DOMs Layers Tabs is checked we turn that layer on.
  for (var k=0; k < _mapService_Layer.layerInfos.length; k++) {
    var currentLayerInfo = _mapService_Layer.layerInfos[k];
    if (!isLayerBlacklisted(currentLayerInfo)) {
        if (currentLayerInfo.subLayerIds == null) {
          if (map_Layer_getVisible(currentLayerInfo.id)) {
            visibleLayers.push(currentLayerInfo.id);
          }
        }
    }
  }

  _mapService_Layer.setVisibleLayers(visibleLayers);

  if (typeof(AerialServiceURL) !== 'undefined') {
    var currentLayerInfo = aeriallayer.layerInfos[0];

    if (getBoolean(dojo.byId('aerial' + currentLayerInfo.id).checked)) {
      aeriallayer.show();
    } else {
      aeriallayer.hide();
    }
  }
}

/*------------------------------------------------------------------------+
|  FUNCTION: map_Layer_getVisible                                         |
|  DESCRIPTION: Given a Map Service Layer Id we see if its corresponding  |
|   entry in the DOMs Layers Tab is checked or not checked.               |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009  Created                                     |
|  ARGUMENTS:                                                             |
|   esri.layers.LayerInfo.id <=  Layer ID assigned by ArcGIS Server for   |
|                                a layer. The topmost layer is 0, and     |
|                                each layer follows sequentially.         |
|                    Boolean  => True - Layer is checked on.              |
|                                False - Layer is not checked.            |
+------------------------------------------------------------------------*/
function map_Layer_getVisible(layerid) {
  for (var k=0; k < _mapService_Layer.layerInfos.length; k++) {
    var currentLayerInfo = _mapService_Layer.layerInfos[k];

    if (currentLayerInfo.id == layerid) {
      var check_boxState = dojo.byId('layer' + currentLayerInfo.id).checked
      //If their is no parent layer we just look at the specified layer
      if (currentLayerInfo.parentLayerId == -1) {
        if (check_boxState == true) {
          return true;
        } else {
          return false;
        }
      } else {
        //If there is a parent layer both the parent layer and
        //the specified layer must both evaluated.
        var isVisibleParent = map_Layer_getVisible(currentLayerInfo.parentLayerId);
        if (check_boxState == true && isVisibleParent == true ) {
          return true;
        //There are no other combinations that can return true
        } else {
          return false;
        }
      }
    }
  }

  return true;
}


/*------------------------------------------------------------------------+
|  FUNCTION: map_Layers_getVisible                                        |
|  DESCRIPTION: Gets a list of all of the visible layers.                 |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009  Created                                     |
|  ARGUMENTS:                                                             |
|   Array  => List of visible layers.                                     |
+------------------------------------------------------------------------*/
function map_Layers_getVisible() {
  var visibleLayers = [];

  //Iterate through the Map Service Layers and if the corresponding
  //check box in the DOMs Layers Tabs is checked we turn that layer on.
  for (var k=0; k < _mapService_Layer.layerInfos.length; k++) {
    var currentLayerInfo = _mapService_Layer.layerInfos[k];
    if (!isLayerBlacklisted(currentLayerInfo)) {
        if (currentLayerInfo.subLayerIds == null) {
          if (map_Layer_getVisible(currentLayerInfo.id)) {
            visibleLayers.push(currentLayerInfo.id);
          }
        }
    }
  }

  return visibleLayers;
}

function isLayerBlacklisted(layerInfo) {
  if (dojo.indexOf(_LayerBlackList, layerInfo.name) > -1) return true;

  if (layerInfo.parentLayerId > -1) {
    for (var k=0; k < _mapService_Layer.layerInfos.length; k++) {
      var currentLayerInfo = _mapService_Layer.layerInfos[k];

      if (currentLayerInfo.id == layerInfo.parentLayerId) {
        return isLayerBlacklisted(currentLayerInfo);
      }
    }
  }

  return false;
}

/*------------------------------------------------------------------------+
|  FUNCTION: getBoolean                                                   |
|  DESCRIPTION: Evaluates the passed variable and returns a boolean       |
|   variable based on the varaibles data type and value.                  |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009  Created                                     |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
function getBoolean(variable) {
  var toReturn;

  if(variable != null) {
    switch(typeof(variable)) {
      case 'boolean':
        return variable;
        break;
      case 'number':
        if(variable == 0)
          toReturn = false;
        else toReturn = true;
        break;
      case 'string':
        if(variable == "true")
          toReturn = true;
        else if(variable == "false")
          toReturn = false;
        else if(variable.length > 0)
          toReturn = true;
        else if(variable.length == 0)
          toReturn = false;
        break;
    }
  }

  return toReturn;
}

function getSymbol(graphic, hilite) {
  if (hilite) {
    switch (graphic.geometry.type) {
      case "point": return symbolHilitePoint;
      case "polyline": return symbolHilitePolyline;
      case "polygon": return symbolHilitePolygon;
      case "multipoint": return symbolHiliteMultipoint;
    }
  } else {
    switch (graphic.geometry.type) {
      case "point": return symbolNormalPoint;
      case "polyline": return symbolNormalPolyline;
      case "polygon": return symbolNormalPolygon;
      case "multipoint": return symbolNormalMultipoint;
    }
  }

  return symbolHilitePolygon;
}

function disableSelection(element) {
  if(!element) return;

  dojo.connect(element, "onselectstart", function(e) {return false;});
  dojo.connect(element, "ondragstart", function(e) {return false;});
  dojo.connect(element, "onmouseover", function(e) {return false;});

  element.unselectable = "on";
  element.style.MozUserSelect = "none";
  element.style.cursor = "default";
}

function processQuery(strWhere, spatialRelationship, geometry, searchIndex, finishFunction){
  var SearchLayerName = SearchLayerNames[searchIndex];
  var SearchFieldName = SearchFieldNames[searchIndex];
  var SearchFields = SearchFieldsArray[searchIndex];

  var queryParams = new esri.tasks.Query();
  queryParams.returnGeometry = true;
  queryParams.outFields = SearchFields;

  if (strWhere) {
    queryParams.where = strWhere; //Modded
  }
  if (spatialRelationship) {
    queryParams.spatialRelationship = spatialRelationship;
  }
  if (geometry) {
    queryParams.geometry = geometry;
  }

  var initqueryTask = new esri.tasks.QueryTask(MapServiceURL +
                              "/" + getLayerIDFromName(SearchLayerName));
  dojo.connect(initqueryTask, "onComplete", function(featureSet) {
    if ((!featureSet.features.length) && ((SearchLayerNames.length-1) > searchIndex)) {
      //See config.js for SearchLayerNames array - the searchIndex+1 allows is to iterate
      //through a list of possible features looking for an element
      processQuery(strWhere, spatialRelationship, geometry, searchIndex+1, finishFunction);
    } else {
      featureSet.layerId = getLayerIDFromName(SearchLayerName);
      finishFunction(featureSet);
    }
  });
  dojo.connect(initqueryTask, "onError", function(error) {
    finishFunction(new esri.tasks.FeatureSet());
  });

  initqueryTask.execute(queryParams);
}

function showControl(element, opacity, duration) {
  if (!dojo.byId(element)) return;

  dojo.style(element,"display","block");
  dojo.anim(element, {opacity: opacity}, duration);
}

function hideControl(element, duration) {
  if (!dojo.byId(element)) return;

  dojo.style(element,"opacity","0");
  dojo.style(element,"display","none");
}
//-----------------------------
//Utility Functions End

function showMapLoading(){
  showControl("maploading", 1, 200);
}

function hideMapLoading(){
  var MapLayerCount = 0;
  var MapLayerLoaded = 0;

  for(var r = 0; r < _map.layerIds.length; r++) {
    if (_map.getLayer(_map.layerIds[r]).visible) {
      MapLayerCount++;
      if (_map.getLayer(_map.layerIds[r]).loaded) MapLayerLoaded++;
    }
  }

  if (MapLayerLoaded == MapLayerCount) {
    hideControl("maploading", 200);
  }
}

//Toolbar Events Start
//-----------------------------
function activateNone() {
  _measureStage = "";

  if (dojo.byId("zoomin")) dojo.byId("zoomin").style.border = "none";
  if (dojo.byId("zoomout")) dojo.byId("zoomout").style.border = "none";
  if (dojo.byId("pan")) dojo.byId("pan").style.border = "none";

  if (dojo.byId("select")) dojo.byId("select").style.border = "none";
  if (dojo.byId("identify")) dojo.byId("identify").style.border = "none";
  if (dojo.byId("measure")) dojo.byId("measure").style.border = "none";
  if (dojo.byId("buffer")) dojo.byId("buffer").style.border = "none";

  if (dojo.byId("mapmeasureinfo")) dojo.byId("mapmeasureinfo").innerHTML = "";

  hideControl("mapmeasureinfo", 500);
  hideControl("mapbufferinfo", 500);
  hideControl("mapactivelayer", 500);

  _drawBufferShapeTb.deactivate();
  _measureTb.deactivate();
  _identifyTb.deactivate();
  _selectTb.deactivate();
  _navigateTB.deactivate();
}

function activateMeasure() {
  activateNone();
  dojo.byId("measure").style.border = "1px solid red";

  _measureStage = "STARTED";
  dojo.byId("mapmeasureinfo").innerHTML = "Click on the map to begin Measuring...";

  showControl("mapmeasureinfo", 0.85, 500);
  _measureTb.activate(esri.toolbars.Draw.POLYLINE);
}

function activateBuffer() {
  activateNone();
  dojo.byId("buffer").style.border = "1px solid red";

  showControl("mapbufferinfo", 0.85, 500);
  _drawBufferShapeTb.activate(esri.toolbars.Draw.POINT);

  _map.enableMapNavigation();
}

function activateIdentify() {
  activateNone();
  dojo.byId("identify").style.border = "1px solid red";

  if (ShowActiveLayer) {
    showControl("mapactivelayer", 0.85, 500);
  }

  _identifyTb.activate(esri.toolbars.Draw.POINT);

  _map.enableMapNavigation();
}

function activateSelect() {
  activateNone();
  dojo.byId("select").style.border = "1px solid red";

  _selectTb.activate(esri.toolbars.Draw.EXTENT);
}

function activateZoomIn() {
  activateNone();
  dojo.byId("zoomin").style.border = "1px solid red";

  _navigateTB.activate(esri.toolbars.Navigation.ZOOM_IN);
}

function activateZoomOut() {
  activateNone();
  dojo.byId("zoomout").style.border = "1px solid red";

  _navigateTB.activate(esri.toolbars.Navigation.ZOOM_OUT);
}

function activatePan() {
  activateNone();
  if (dojo.byId("pan")) dojo.byId("pan").style.border = "1px solid red";

  _map.enableMapNavigation();
}

function activateClear() {
  clearResults();
  updateResultsTab("Results (0)", "No features selected");
}

function activateZoomNext() {
  _navigateTB.zoomToNextExtent();
  extentHistoryChangeHandler();
}

function activateZoomPrev() {
  _navigateTB.zoomToPrevExtent();
  extentHistoryChangeHandler();
}

function activateDownload() {
  var downloadWin = window.open('#', 'PolkDownload'); //TODO
  downloadWin.focus();
}

function activateHelp() {
  var helpWin = window.open('help/index.htm', 'PolkHelp');
  helpWin.focus();
}

function showPrintDialog() {
  var pinlist = "";
  for (var i=0; i < _selectionList.length; i++) {

    var ParcelFieldName;

    if (_selectionList[i].geometry.type == "point") {
      ParcelFieldName = ParcelPointFieldName;
    } else {
      ParcelFieldName = ParcelPolyFieldName;
    }

    if (!(_selectionList[i].attributes[ParcelFieldName] == undefined)) {
      if (pinlist != "") pinlist += ',';
      pinlist += _selectionList[i].attributes[ParcelFieldName];
    }
  }

  var layers = map_Layers_getVisible().join(',');
  var aerials = 0;

  if (typeof(AerialServiceURL) !== 'undefined') {
    var currentLayerInfo = aeriallayer.layerInfos[0];

    if (getBoolean(dojo.byId('aerial' + currentLayerInfo.id).checked)) {
      aerials = 1;
    }
  }

  window.open(_PrintPage + '?gp=' + pinlist + '&selectedparcelid=' + _selectedParcelID + '&extent=' + _map.extent.xmin + ',' + _map.extent.ymin + ',' + _map.extent.xmax + ',' + _map.extent.ymax + '&layers=' + layers + '&aerials=' + aerials);
}
//-----------------------------
//Toolbar Events End


//Search Frame Events Start
//-----------------------------

function executeGPSearch() {
  if (dojo.byId("txtGP").value != "") {
    //build query filter for GP 
    updateResultsTab("Results", "<img src='" + _baseURL + "images/loader.gif' alt=\"loader.gif\"/> Searching for GP matching <b>" + dojo.byId("txtGP").value + "</b>...");

    processQuery("GP = '" + dojo.byId("txtGP").value + "'", null, null, 0, showResults);
  }
}


function executeDPSearch() {
  if (dojo.byId("txtDP").value != "") {
    //build query filter for DP
    updateResultsTab("Results", "<img src='" + _baseURL + "images/loader.gif' alt=\"loader.gif\"/> Searching for DP matching <b>" + dojo.byId("txtDP").value + "</b>...");

    processQuery("DP = '" + dojo.byId("txtDP").value + "'", null, null, 0, showResults);
  }
}


function executePlatSearch() {

  if ((dojo.byId("txtPlatName").value == "") &&
     (dojo.byId("isSearching_PlatDates").checked == false))  {
    return;
  }
  updateResultsTab("Results", "<img src='" + _baseURL +
                   "images/loader.gif' alt=\"loader.gif\"  alt=\"loader.gif\"/> Searching for Plats matching <b>" +
                   dojo.byId("txtPlatName").value + "</b>...");

  showMapLoading();

  //1) Query the Plat name to get a feature 
  var query = new esri.tasks.Query();
  query.returnGeometry = true;
  query.outFields = ['Sub_Poly.PLAT_NUM','plat_name','rec_bk','rec_pg','rec_date'];
  if (dojo.byId("txtPlatName").value != "") {
    var where_clause = " (plat_name LIKE '%" + dojo.byId("txtPlatName").value + "%') ";
  } else {
    var where_clause = " (plat_name LIKE '%') ";
  }
  //query.where = "plat_name LIKE '%" + dojo.byId("txtPlatName").value + "%'";
  if (dojo.byId("isSearching_PlatDates").checked == true) {
  //if (dojo.byId("isSearching_PlatDates").value != "No") {
    var from_date =  new Date(dojo.byId("date_PlatFrom").value);
    var to_date = new Date (dojo.byId("date_PlatTo").value);

    var from_month = from_date.getMonth() + 1;
    from_month += '';
    if (from_month.length == 1) {
      from_month = "0" + from_month;
    }
    var from_day = from_date.getDate();
    from_day += '';
    if (from_day.length == 1 ) {
      from_day = "0" + from_day;
    }
    var from_year = from_date.getFullYear();
    from_year += '';

    var to_month = to_date.getMonth() + 1;
    to_month += '';
    if (to_month.length == 1) {
      to_month = "0" + to_month;
    }
    var to_day = to_date.getDate();
    to_day += '';
    if (to_day.length == 1 ) {
      to_day = "0" + to_day;
    }
    var to_year = to_date.getFullYear();
    to_year += '';

    var from_value = from_year + from_month + from_day;
    var to_value = to_year + to_month + to_day;

    where_clause += " AND (rec_date >= " +  from_value + "  AND rec_date <= " + to_value + ")";
  }

  query.where = where_clause;

  _queryTaskPlatSearch.execute(query);
}

/*------------------------------------------------------------------------+
|  FUNCTION: executePlatSearch_byPlatnum                                  |
|  DESCRIPTION: Function to triggered after the DOM has finished loading  |
|     and widgets declared in markup have been instantiated. Images and   |
|     CSS files may or may not have finished downloading when the         |
|     specified function is called.                                       |
|     (Note that widgets' CSS and HTML code is guaranteed to be           |
|     downloaded before said widgets are instantiated.)                   |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009  Created                                     |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
function executePlatSearch_byPlatnum(platnum) {

  updateResultsTab("Results", "<img src='" + _baseURL +
                   "images/loader.gif' alt=\"loader.gif\"/> " +
                   "Searching for Plat with platnum=<b>" +
                   platnum + "</b>...");

  showMapLoading();

  //1) Query the platnum to get a feature 
  var query = new esri.tasks.Query();
  query.returnGeometry = true;
  query.outFields = ['Sub_Poly.PLAT_NUM','plat_name','rec_bk','rec_pg','rec_date'];
  var where_clause = " (" + _subPlatnumColumn + " = " + platnum + ") ";
  query.where = where_clause;

  _queryTaskPlatSearch.execute(query);
}


function executeOwnerSearch() {
  if (dojo.byId("txtOwnerName").value != "") {
    updateResultsTab("Results", "<img src='" +
                     _baseURL + "images/loader.gif' " +
                     "alt=\"loader.gif\"/> Searching for Owner Name matching <b>" +
                     dojo.byId("txtOwnerName").value + "</b>...");

    dojo.xhrPost( { // ?
      // The following URL must match that used to test the server.
      url: "parcel_list_json.php",
      handleAs: "json",
      content: { ownername : dojo.byId("txtOwnerName").value,
                 activeonly: (dojo.byId("activeonly").checked?"Y":"N") },

      timeout: 10000, // Time in milliseconds

      // The LOAD function will be called on a successful response.
      load: buildSearchResponse,

      // The ERROR function will be called in an error case.
      error: function(response, ioArgs) {
                console.error("HTTP status code: ", ioArgs.xhr.status);
                //06-11-2009 Added update to Tab to show when error occurs
                updateResultsTab("Error","Search failed due to application problem.")
                return response;
              }
    });
  }
}


function executeAddressSearch() {
  if (dojo.byId("txtAddress").value != "") {

    if (dojo.byId("txtHouseNumLow").value != "" && dojo.byId("txtHouseNumHigh").value != "")
      {
        updateResultsTab("Results", "<img src='" + _baseURL +
                         "images/loader.gif' alt=\"loader.gif\"/> Searching for Address matching <b>" +
                         dojo.byId("txtHouseNumLow").value + "-" +
                         dojo.byId("txtHouseNumHigh").value + " " +
                         dojo.byId("txtAddress").value + ", "
                         + dojo.byId("cboCity").value + "</b>...");
      }
    else if (dojo.byId("txtHouseNumHigh").value != "" || dojo.byId("txtHouseNumLow").value != "")
      {
        if (dojo.byId("txtHouseNumHigh").value != "" &&
            dojo.byId("txtHouseNumLow").value == "")
              dojo.byId("txtHouseNumLow").value = dojo.byId("txtHouseNumHigh").value;
        if (dojo.byId("txtHouseNumHigh").value == "" &&
            dojo.byId("txtHouseNumLow").value != "")
              dojo.byId("txtHouseNumHigh").value = dojo.byId("txtHouseNumLow").value;
        updateResultsTab("Results", "<img src='" + _baseURL +
                         "images/loader.gif' alt=\"loader.gif\"/> Searching for Address matching <b>" +
                         dojo.byId("txtHouseNumLow").value + "-" +
                         dojo.byId("txtHouseNumHigh").value + " " +
                         dojo.byId("txtAddress").value + ", " +
                         dojo.byId("cboCity").value + "</b>...");
      }
    else
      {
        updateResultsTab("Results", "<img src='" + _baseURL +
                         "images/loader.gif' alt=\"loader.gif\"/> Searching for Address matching <b>" +
                         dojo.byId("txtAddress").value + ", " +
                         dojo.byId("cboCity").value + "</b>...");
      }


    dojo.xhrPost( { // ?
      // The following URL must match that used to test the server.
      url: "parcel_list_json.php",
      handleAs: "json",
      content: { address : dojo.byId("txtAddress").value,
                 city : dojo.byId("cboCity").value,
                 zip : dojo.byId("cboZip").value,
                 houselow: dojo.byId("txtHouseNumLow").value,
                 househigh: dojo.byId("txtHouseNumHigh").value,
                 activeonly: (dojo.byId("activeonly").checked?"Y":"N") },

      timeout: 10000, // Time in milliseconds

      // The LOAD function will be called on a successful response.
      load: buildSearchResponse,

      // The ERROR function will be called in an error case.
      error: function(response, ioArgs) {
        console.error("HTTP status code: ", ioArgs.xhr.status);
        updateResultsTab("Results", "Error Searching for Address matching <b>" +
                         dojo.byId("txtAddress").value + ", " +
                         dojo.byId("cboCity").value + "</b>...");
        return response;
      }
    });
  }
}


function executeBookSearch() {
  if ((dojo.byId("txtBook").value != "") && (dojo.byId("txtPage").value != "")) {
    updateResultsTab("Results", "<img src='" + _baseURL +
                     "images/loader.gif' alt=\"loader.gif\"/> Searching for Book <b>" +
                     dojo.byId("txtBook").value + "</b> And Page <b>" +
                     dojo.byId("txtPage").value + "</b>...");

    dojo.xhrPost( { // ?
      // The following URL must match that used to test the server.
      url: "parcel_list_json.php",
      handleAs: "json",
      content: { book : dojo.byId("txtBook").value,
                 page : dojo.byId("txtPage").value,
                 activeonly: (dojo.byId("activeonly").checked?"Y":"N") },

      timeout: 10000, // Time in milliseconds

      // The LOAD function will be called on a successful response.
      load: buildSearchResponse,

      // The ERROR function will be called in an error case.
      error: function(response, ioArgs) {
        console.error("HTTP status code: ", ioArgs.xhr.status);
        return response;
      }
    });
  }
}
//-----------------------------
//Search Frame Events End


function clearResults() {
  if (_map.graphics) _map.graphics.clear();
  _selectionList = [];
  _selectionExtent = null;
  _selectedParcelID = -1;
  _listCacheCaption = "";
  _listCacheBody = "";
}

function clearForm(){
  dojo.byId("txtGP").value = "";
  dojo.byId("txtDP").value = "";
  dojo.byId("txtOwnerName").value = "";
  dojo.byId("txtAddress").value = "";
  dojo.byId("txtPlatName").value = "";
  dojo.byId("txtBook").value = "";
  dojo.byId("txtPage").value = "";

  //7-8-2009 - Missed clearing out some fields
  dojo.byId("txtHouseNumLow").value = "";
  dojo.byId("txtHouseNumHigh").value = "";
  //dojo.byId("cboCity").focus();
  dojo.byId("cboCity").value= "<Any>";
  //dojo.byId("cboCity").attr("value","<Any>");

}

function extentHistoryChangeHandler() {
  if (dijit.byId("zoomprev")) {
    dijit.byId("zoomprev").disabled = _navigateTB.isFirstExtent();
    dijit.byId("zoomnext").disabled = _navigateTB.isLastExtent();
  }
  updateInfoBar(null);
}

function selectResults(results) {
  clearResults();

  if(results.length == 0) {
    updateResultsTab("Results (0)", "No Features Selected");
    return;
  }

  _selectionExtent = getExtents(results);

  addToMapSelection(results);

  if (_listCacheCaption != "") {
    updateResultsTab(_listCacheCaption, _listCacheBody);
    return;
  }

  if(_selectionList.length == 1) {
    getParcelDetails(0);
  } else if(_selectionList.length > 1) {
    getParcelList();
  } else {
    activateClear();
  }
}

function showResults(featureSet) {
  clearResults();

  if (featureSet.features.length == 0) {
    updateResultsTab("Results (0)", "No Results Found");
    return;
  }

  _selectionExtent = getExtents(featureSet);

  addToMapSelection(featureSet);

  if (_mapSelectedParcelID != -1) {
    getParcelDetails(_mapSelectedParcelID);
    _mapSelectedParcelID = -1;
  } else {
    if (_listCacheCaption != "") {
      updateResultsTab(_listCacheCaption, _listCacheBody);
      return;
    }

    if(_selectionList.length == 1) {
      getParcelDetails(0);
    } else if(_selectionList.length > 1) {
      getParcelList();
    } else {
      activateClear();
    }
  }
}

function identifyPlatResults(results) {
  clearResults();

  _selectionExtent = getExtents(results);

  var html_content = "";

  if(results.length == 0) {
    updateResultsTab("Results", "No Features Found");
    return;
  } else {
    html_content += "Found " + results.features.length + " plats.<br /><br />";
  }

  for (var i=0; i < results.features.length; i++) {
    //Get the current feature from the featureSet.
    //Feature is a graphic
    var graphic = results.features[i];
    var symbol = getSymbol(graphic, false);

    graphic.setSymbol(symbol);

    //Add graphic to the _map graphics layer.
    _map.graphics.add(graphic);
    _selectionList[_selectionList.length] = graphic;


    //Other Type
    html_content += "<div class=\"ResultItem\" onmouseover=\"this.className = 'ResultItemHover';glowGeometry(" + i + ");\" onmouseout=\"this.className = 'ResultItem';glowGeometry(-1);\" onclick=\"if (_selectionList[" + i + "].geometry.type != 'point') _map.setExtent(_selectionList[" + i + "].geometry.getExtent().expand(1.5));\">";

    for( var p in graphic.attributes) {
      if (p != "Shape") {
        var value = graphic.attributes[p];
        if (value == "Null") value = "<i>n/a</i>";

        if (results.fieldAliases == undefined) {
          html_content += p + ":&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" + value + "</b><br/>";
        } else {
          html_content += results.fieldAliases[p] + ":&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" + value + "</b><br/>";
        }
      }
    }
    html_content += "</div>";
  }

  html_content += "<center><button dojoType=\"dijit.form.Button\" onclick=\"activateClear\">Clear Results</button></center>";

  if (_selectionExtent != null) {
    _map.setExtent(_selectionExtent);
  }

  updateResultsTab("Results", html_content);
}

function getParcelDetails(id) {
  var selected = _selectionList[id];
  var RealFields, AliasFields, ParcelFieldName;

  if (selected.geometry.type == "point") {
    RealFields = ParcelPointFields;
    AliasFields = ParcelPointAlias;
    ParcelFieldName = ParcelPointFieldName;
  } else {
    RealFields = ParcelPolyFields;
    AliasFields = ParcelPolyAlias;
    ParcelFieldName = ParcelPolyFieldName;
  }

  _selectedParcelID = id;

  //Write out Parcel Detail 
  var isParcelLayerType = false;

  for(var i=0; i < SearchLayerNames.length; i++) {
    if (selected.layerId == getLayerIDFromName(SearchLayerNames[i])) {
      isParcelLayerType = true;
    }
  }

  if (!isParcelLayerType) {

    var html_content = "";

    if (_selectionList.length > 1) {
      html_content += '<p id="backToListButton"><button dojoType="dijit.form.Button" onclick="_selectedParcelID = -1;getParcelList();">Back to List</button></p>';
    }

    //Get the current feature from the featureSet.
    for( var p in selected.attributes) {
      if ((p != "Shape") &&
          (p.toUpperCase() != "OBJECT ID") &&
          (p.toUpperCase() != "OBJECTID") &&
          (p.toUpperCase() != "OID")) {
        var value = selected.attributes[p];
        if (value == "Null") value = "<i>n/a</i>";

        if (selected.fieldAliases == undefined) {
          html_content += p + ":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" +
                                                        value + "</b><br/>";
        } else {
          html_content += selected.fieldAliases[p] +
                            ":<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" +
                                                        value + "</b><br/>";
        }
      }
    }

    updateResultsTab("Selected", html_content);

  } else {

    updateParcelDetailTab(selected.attributes[ParcelFieldName]);

  }

  glowGeometry(id);

  if (selected.geometry.type != 'point') {
    _map.setExtent(selected.geometry.getExtent().expand(1.5));
  } else {
    zoomToPolysFromPoints([selected]);
  }
}


function getParcelList() {
  var pinlist = "";
  for (var i=0; i < _selectionList.length; i++) {
    if (pinlist != "") pinlist += ',';
    pinlist += _selectionList[i].attributes[ParcelPolyFieldName];
  }

  updateResultsTab("Results", "<img src='images/loader.gif'/> Pulling list of matching GPs...");

  dojo.xhrPost( { // ?
    // The following URL must match that used to test the server.
    url: "parcel_list_json.php",
    handleAs: "json",
    content: { pin : pinlist, activeonly: (dojo.byId("activeonly").checked?"Y":"N") },

    timeout: 10000, // Time in milliseconds

    // The LOAD function will be called on a successful response.
    load: buildSearchResponse,

    // The ERROR function will be called in an error case.
    error: function(response, ioArgs) {
      console.error("HTTP status code: ", ioArgs.xhr.status);
      return response;
    }
  });
}


/*------------------------------------------------------------------------+
|  FUNCTION: buildSearchResponse                                          |
|  DESCRIPTION: Called to handle the results returned from                |
|   Parcel_list_json.php.                                                 |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009  Created                                     |
|  ARGUMENTS:                                                             |
|     response <= A 2-element array:                                      |
|                   [0] - number of elements in [1]                       |
|                   [1] - a 5-element array:                              |
|                           [0] - DP                                      |
|                           [1] - GP                                      |
|                           [2] - Owner Name                              |
|                           [3] - Building address                        |
|                           [4] - City, State, Zip                        |
+------------------------------------------------------------------------*/
function buildSearchResponse(response) {
  var ResultsFound = response[0];
  var ResultsReturned = (response.length - 1);
  var ResultsBody = "";

  if (ResultsReturned) {
    var ParcelList = "";
    ResultsBody = "<div class=\"ResultHeader\">Found " + ResultsFound + " Matches";

    if (ResultsFound > ResultsReturned) {
      ResultsBody += " <div class=\"ResultSubHeader\">(Showing only " + ResultsReturned + ")</div>";
    }

    ResultsBody += "</div>";

    for (var i=1; i < (ResultsReturned+1); i++) {

      ParcelList += "'" + response[i][0] + "',";
    }

    processQuery("GP IN (" + ParcelList.substring( 0, ParcelList.length - 1) + ")",
                  null, null, 0,
                  function(featureSet) {
                    if (featureSet.features.length) {
                      clearResults();

                      if (featureSet.features.length > 0) {
                        _selectionExtent = getExtents(featureSet);
                        addToMapSelection(featureSet);
                        _map.setExtent(_selectionExtent);
                        var highlightid = -1;

                        for (var i=1; i < (ResultsReturned+1); i++) {
                          for (var y=0; y < _selectionList.length; y++) {
                            var selected = _selectionList[y];
                            var ParcelFieldName;
                            if (selected.geometry.type == "point") {
                              ParcelFieldName = ParcelPointFieldName;
                            } else {
                              ParcelFieldName = ParcelPolyFieldName;
                            }
                            if(selected.attributes[ParcelFieldName] == response[i][0]) {
                              highlightid = y;
                            }
                          }

                          ResultsBody += "<div class=\"ResultItem\" onmouseover=\"this.className = 'ResultItemHover';\" onmouseout=\"this.className = 'ResultItem';\">";
                          ResultsBody += "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" width=\"100%\" onclick=\"getParcelDetails(" + highlightid + ")\" onmouseover=\"glowGeometry(" + highlightid + ")\" onmouseout=\"glowGeometry(-1)\"><tr valign=\"top\">" +
                            "<td><b>" + response[i][0] + "</b><br/>" + response[i][1] + "</td>" +
                            "<td align=\"right\" nowrap=\"nowrap\">" + response[i][2] + "<br>" + response[i][3] + "<br>" + response[i][4] + "</td></tr></table></a>";
                          ResultsBody += "</div>";
                        }

                        ResultsBody += "<p id=\"clearResultsButton\"><button dojoType=\"dijit.form.Button\" onclick=\"activateClear\">Clear Results</button></p>";
                        updateResultsTab("Results (" + ResultsReturned + ")", ResultsBody);
                      }
                    }
                  }
                );
  } else {
    ResultsBody = "<div class=\"ResultHeader\">No Matches Found</div>";
    updateResultsTab("Results (" + ResultsReturned + ")", ResultsBody);
  }

  return response;
}

function updateParcelDetailTab(pin) {
  dojo.xhrGet( { // ?
    // The following URL must match that used to test the server.
    url: "parcel_detail.php?pin=" + pin + "&selectedcount=" + _selectionList.length,
    handleAs: "text",

    timeout: 10000, // Time in milliseconds

    // The LOAD function will be called on a successful response.
    load: function(response, ioArgs) {
      updateResultsTab("Parcel Detail", response);
      //10-22-2009 - This command was triggering a spatial intersection
      //process to retrieve the precinct for the parcel.  We now use a lookup
      //table to retrieve that information.
      //getPrecinctName(pin);
      return response;
    },

    // The ERROR function will be called in an error case.
    error: function(response, ioArgs) {
      console.error("HTTP status code: ", ioArgs.xhr.status);
      return response;
    }
  });
}



function submitReport(args) {
  if (args.source == "single") {
    window.open("parcel_report.php?gp=" + args.gp + "&noroads=" + args.noroads.length);
  }

  if (args.source == "selection") {
    var pinlist = "";
    for (var i=0; i < _selectionList.length; i++) {
      if (pinlist != "") pinlist += ',';
      pinlist += _selectionList[i].attributes[ParcelPolyFieldName];
    }

    window.open("parcel_report.php?gp=" + pinlist + "&noroads=" + args.noroads.length);
  }

  if (args.source == "subdivision") {
    //1) Query the Plat name to get a feature
    var queryTaskPlat = new esri.tasks.QueryTask(MapServiceURL + "/" + getLayerIDFromName(SubsLayerName));
    dojo.connect(queryTaskPlat, "onComplete", function(graphics) {
      //2) Query Parcels that intersect this plat
      var queryTaskIntersects = new esri.tasks.QueryTask(MapServiceURL + "/" + getLayerIDFromName(ParcelLayerName));
      dojo.connect(queryTaskIntersects, "onComplete", function(graphics2) {
        //3) Send parcel list to report page
        var pinlist = "";
        for (var i=0; i < graphics2.features.length; i++) {
          if (pinlist != "") pinlist += ',';
          pinlist += graphics2.features[i].attributes[ParcelPolyFieldName];
        }

        window.open("parcel_report.php?gp=" + pinlist + "&noroads=" + args.noroads.length);
      });

      var query = new esri.tasks.Query();
      query.geometry = graphics.features[0].geometry;
      query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
      queryTaskIntersects.execute(query);
    });

    var query = new esri.tasks.Query();
    query.returnGeometry = true;
    query.where = "plat_num = " + args.sub;
    queryTaskPlat.execute(query);

  }

  if (args.source == "quarter") {
    //TODO read args.quarter

  }

  //alert('mode is: ' + args.source);
  //alert('submitted w/args:\n' + dojo.toJson(args, true))
}


function generateDemographicReport(){
  var reportContent = "";


  //TODO: Check for at least a selected parcel

  updateResultsTab("Results", "<img src='images/loader.gif'/> Generating Census report...");


  //1) Query Blocks that intersect this parcel
  var queryTaskBlock = new esri.tasks.QueryTask(MapServiceURL + "/" + getLayerIDFromName(BlockLayer));
  dojo.connect(queryTaskBlock, "onComplete", function(graphics) {
    for( var p in graphics.features[0].attributes) {
      if (p != "Shape") {
        var value = graphics.features[0].attributes[p];
        if (value == "Null") value = "<i>n/a</i>";

        reportContent += p + ":&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>" + value + "</b><br/>";
      }
    }

    //Finished
    updateResultsTab("Results", reportContent);
    return;
  });

  var query = new esri.tasks.Query();
  query.geometry = getSelectedParcel().geometry;
  query.outFields = ["POPULATION", "WHITE", "BLACK", "AM_INDIAN", "ASIAN", "HAWAIIAN", "LATINO"];
  query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
  queryTaskBlock.execute(query);
}

function getSelectedParcel(){
  for (var i=0; i < _selectionList.length; i++) {
    var selected = _selectionList[_selectedParcelID];
    if(selected) {
      return selected;
    }
  }
}

function generateElectedOfficialsReport(){
  dijit.byId('electedofficials').attr('content', '<img src="images/loader.gif">&nbsp;<b>Generating Report...</b>');
  dijit.byId('electedofficials').show();

  //Query precinct_poly
  //7-7-2009 - Renamed Precinct Poly to Precincts 
  //var query3 = new esri.tasks.QueryTask(MapServiceURL + "/" + getLayerIDFromName("Precinct_Poly"));
  var query3 = new esri.tasks.QueryTask(MapServiceURL + "/" + getLayerIDFromName("Precincts"));
  dojo.connect(query3, "onComplete", function(graphics) {
    if (graphics.features.length > 0) {

      var precinct = graphics.features[0].attributes['PRECINCT'].trim()

      //Populate the Elected Officials Report
      dijit.byId('electedofficials').setHref("report_elected_officials.php?dp=" + getSelectedParcel().attributes['DP'] + "&precinct=" + precinct);
    }
  });

  var query = new esri.tasks.Query();
  query.geometry = getSelectedParcel().geometry;
  query.outFields = ["PRECINCT"];
  query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
  query3.execute(query);

}

//10-22-2009 - This function was running a spatial intersection
//process to retrieve the precinct for the parcel.  We now use a lookup
//table to retrieve that information.
/*function getPrecinctName(pin){
  var geometry;

  for (var i=0; i < _selectionList.length; i++) {
    if (_selectionList[i].attributes[ParcelPolyFieldName] == pin) {
      geometry = _selectionList[i].geometry;
    }
  }

  //1) Query Precincts that intersect this parcel
  var queryTaskPrecinct = new esri.tasks.QueryTask(MapServiceURL + "/" + getLayerIDFromName(PrecinctPolyLayer));
  dojo.connect(queryTaskPrecinct, "onComplete", function(graphics) {
    var value = graphics.features[0].attributes["PRECINCT"];
    if (value == "Null") value = "<i>n/a</i>";

    document.getElementById('precinctname').innerHTML = "<b>" + value + "</b>";
  });

  var query = new esri.tasks.Query();
  query.geometry = geometry;
  query.outFields = ["PRECINCT"];
  query.spatialRelationship = esri.tasks.Query.SPATIAL_REL_INTERSECTS;
  queryTaskPrecinct.execute(query);
}*/

/*------------------------------------------------------------------------+
|  FUNCTION: Plat_Date_CheckBox_MouseUp.                                  |
|  DESCRIPTION: Enables or diables the plat date range controls when      |
|    the CheckBox is toggled.                                             |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     scunnin     07-27-2009   Created                                    |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
function plat_Date_CheckBox_MouseUp(){
    /*dojo.byId(String id)
    This function is a synonym for document.all.id in IE or document.getElementById(id)
    in standard DOM. So you can say:

      dojo.byId("breadbox").style.fontSize = "72pt";

    dijit.byId(String id)

      Because of the almost-identical spelling, this method is commonly mixed up
      with dojo.byId(String id). Here's the difference: dijit.byId() returns a
      Dijit widget instance - technically, an instance of dijit._Widget or one of
      its subclasses like dijit.Toolbar or dijit.TreeNode.
      If document.getElementById() works in all modern browsers, why use this?
      Sadly, bugs persist in Internet Explorer which make getElementById()
      unstable in some common scenarios. Also, dojo.byId() is easier to type.
      So here's the way to remember it:

        * If you need a DOM Node, use dojo.byId.
            You need a DOM node anytime you call a standard browser function,
            change a standard property, etc.
        * If you need a widget, use dijit.byId.
            From it you can access all of the attributes, methods and
            extension points listed in Part 2.*/
  dijit.byId('date_PlatFrom').attr('disabled', !dijit.byId('date_PlatFrom').attr('disabled'));
  dijit.byId('date_PlatTo').attr('disabled', !dijit.byId('date_PlatTo').attr('disabled'));

}


/*------------------------------------------------------------------------+
|  FUNCTION: Main entry point.                                            |
|  DESCRIPTION: Module start up code.                                     |
|  HISTORY:                                                               |
|     User        Date        Description                                 |
|     ---------   ---------   -----------------------------------------   |
|     sidwell     01-01-2009   Created                                    |
|  ARGUMENTS:                                                             |
+------------------------------------------------------------------------*/
/* dojo.addOnLoad() -  Registers a function to be triggered after the DOM has
                       finished loading and widgets declared in markup have been
                       instantiated. Images and CSS files may or may not have
                       finished downloading when the specified function is called.
                       (Note that widgets' CSS and HTML code is guaranteed to be
                       downloaded before said widgets are instantiated.) */
dojo.addOnLoad(init);

window.onresize = function(){
  if(_map == null) return;
  if(!_map.loaded) return;

  _map.reposition();
}