﻿var counties = new Ext.data.SimpleStore({
  fields: ['id', 'name'],
  data: [['1', 'All SRWMD Counties'],
            ['2', 'Alachua'],
            ['3', 'Bradford'],
            ['4', 'Columbia'],
            ['5', 'Dixie'],
            ['6', 'Gilchrist'],
            ['7', 'Hamilton'],
            ['8', 'Lafayette'],
            ['9', 'Levy'],
            ['10', 'Madison'],
            ['11', 'Suwannee'],
            ['12', 'Taylor'],
            ['13', 'Union']]
});

var countyCombo = new Ext.form.ComboBox({
  allowBlank: false,
  editable: false,
  triggerAction: 'all',
  typeAhead: false,
  store: counties,
  mode: 'local',
  fieldLabel: 'Select County: ',
  name: 'countyselect',
  anchor: '90%',
  displayField: 'name',
  valueField: 'name',
  value: 'All SRWMD Counties',
  listeners: {
    scope: this,
    'select': switchCountySelection
  }
});

function switchCountySelection() {
  switchActiveCountyByName(countyCombo.value, true);
  zoomToActiveCounty();
}
var countySelectForm = new Ext.FormPanel({
  height: 250,
  labelAlign: 'left',
  padding: 3,
    title: 'County Select',
    tabTip: 'Zoom to County'
  });

countySelectForm.add(countyCombo);

var parcelSearchForm = new Ext.FormPanel({
  height: 250,
  labelAlign: 'left',
  defaultType: 'textfield',
  padding: 3,
  body: false,
  bodyborder: false,
  items: [
      {
        xtype: 'fieldset',
        id: 'fieldSetParcelId',
        defaultType: 'textfield',
        items: [{
          fieldLabel: 'Parcel Id',
          width: 146,
          name: 'parcelId'
          }, {                       
            xtype: 'compositefield',
            fieldLabel: 'Parcel ex',
            msgTarget: 'under',
            items: [{ 
              xtype: 'displayfield', 
              id: 'ParcelPattern', 
              value: activeCounty.parcelPattern
            }]
          }, {
            xtype: 'displayfield',
            fieldLabel: 'Current County',
            id: 'ParcelCounty',
            value: activeCounty.countyName
          }
        ],
        buttons: [{
          text: 'Search',
          tooltip: 'Searches based on Parcel Id',
          handler: function() {
            parcelSearchFormHandler();
          }
        }]
        } ],
  title: 'Parcel',
  tabTip: 'Search for parcels'
});

var secTownRangeSearchForm = new Ext.FormPanel({
  height: 250,
  labelAlign: 'left',
  padding: 3,
  items: [
  {
          xtype: 'fieldset',
          //title: 'Section/Township/Range Search',
          id: 'fieldSetSecTwnRangeId',
          defaultType: 'compositefield',
          items: [ {
            xtype: 'radiogroup',
            fieldLabel: 'North Or South Township', 
              items: [{ 
              boxLabel: 'North', 
              inputValue: '+', 
              name: 'northOrSouth'
              }, { 
              boxLabel: 'South',
              name: 'northOrSouth',
              inputValue: '-',
              checked: true 
              }] 
            },                           
            {
              xtype: 'compositefield',
              fieldLabel: 'Township',
              msgTarget: 'under',
              items: [
                    { xtype: 'textfield', name: 'Township', width: 40 },
                    { xtype: 'displayfield', value: 'Ex: 04' }
                  ]
              }, {
              xtype: 'compositefield',
              fieldLabel: 'Range',
              msgTarget: 'under',
              items: [
                        { xtype: 'textfield', name: 'Range', width: 40},
                        { xtype: 'displayfield', value: 'Ex: 08' }
                      ]                 
            }, {
            xtype: 'compositefield',
            fieldLabel: 'Section',
            msgTarget: 'under',
            items: [
                        { xtype: 'textfield', name: 'Section', width: 40 },
                        { xtype: 'displayfield', value: 'Ex: 030' }
                      ]      
            }],
            buttons: [{
            text: 'Search',
              tooltip: 'Searches and places a marker at center of grid',
              handler: function() {
                secTownRangeSearchFormHandler();
              }
            }]
        }],
  title: 'Twn Rng Sec',
  tabTip: 'Search by Township, Section and Range'
});

function clearMarkerShowSearching() {
  Mapping.Ext.Esri.Marker.reset();
  locationSearchWindow.getEl().mask('Searching...');
}

  function clearParcelSearchForm() {
    Ext.getCmp('fieldSetParcelId').findByType('textfield')[0].setValue(""); //clear parcel field
  }

  function parcelSearchFormHandler() {
    cleanSearches('fieldSetParcelId');
    clearMarkerShowSearching();
    clearSecTownRangeSearchForm();
    var parcelIdField = Ext.getCmp('fieldSetParcelId').findByType('textfield')[0];
    Mapping.Ext.Esri.Bookmarks.setDefaultText(parcelIdField.getValue());
    markerSearchText = parcelMarkerText + parcelIdField.getValue();
    setZoomToResults(true);
    findParcelByParcelId(parcelIdField.getValue());
  }

  function secTownRangeSearchFormHandler() {
    cleanSearches('fieldSetSecTwnRangeId');
    clearMarkerShowSearching();
    clearParcelSearchForm();
    locationSearchWindow.getEl().mask('Searching...');
    var section = null;
    var township = null;
    var rang = null;
    var direction;
    Ext.iterate(secTownRangeSearchForm.form.getValues(), function(key, value) {
      if (key == 'northOrSouth') {
        direction = value;
      } else if (key == 'Section') {
        section = value;
      } else if (key == 'Township') {
        township = value;
      } else if (key == 'Range') {
        rang = value;
      }

    }, this);

    if ((section != null) && (section.length > 0) && (township != null) && 
                      (township.length > 0) && (rang != null) && (rang.length >0)) {
      setZoomToResults(true);
      findParcelBySecTwnRng(direction, section, township, rang);
      Mapping.Ext.Esri.Bookmarks.setDefaultText('Sec/Twn/Rng' 
        + section + ' ' + direction + ' ' + township + ' ' + rang);
    } else {
      Ext.MessageBox.alert('Complete Search Criteria', 'Please complete all fields for this search.');
      unmaskSearchForm(); 
    }
  }

  function clearSecTownRangeSearchForm() {
    var secTownRangeFields = Ext.getCmp('fieldSetSecTwnRangeId').findByType('textfield');
    for (var i = 0; i < secTownRangeFields.length; i++) {
      secTownRangeFields[i].setValue("");
    }
  }

  var addressSearchForm = new Ext.FormPanel({
    height: 250,
    defaultType: 'textfield',
    labelAlign: 'left',
    padding: 3,
    items: [{
      fieldLabel: 'Address',
      name: 'address',
      width: 250,
      enableKeyEvents: true,
      listeners: {
        keypress: {
          fn: function(e, val) {
            if (val.getKey() == 13) {
              addressSearchFormHandler();
            }
          },
          scope: this
        }
      }
    }, {
      xtype: 'label',
      labelalign: 'left',
      hidelabels: false,
      text: 'Ex: 1234 Main Street, Anywhere, FL'
    }, {
      xtype: 'displayfield',
      labelalign: 'left',
      hidelabels: false,
      fieldLabel: 'Disclaimer',
      value: 'Locations are approximate'
  }],
      buttons: [{
      text: 'Search',
        handler: function() {
          addressSearchFormHandler();
        }
}],
        title: 'Address',
        tabTip: 'Search by address'
      });

  function addressSearchFormHandler() {
    cleanSearches(addressSearchForm.id);
    clearMarkerShowSearching();
    markerSearchText = addressSearchForm.findByType('textfield')[0].getValue();
    Mapping.Ext.Esri.Bookmarks.setDefaultText(markerSearchText);
    // Run Bing geocoder, callback to showBingCandidates on success, errorHandler is ErrorManager
    var dojoDeferred = veGeocoder.addressToLocations(markerSearchText);
    dojoDeferred.addCallbacks(geocodeSuccess, geocodeFailure);
  }
  
  // Handle success/failure of address search and update form appropriately
  function geocodeSuccess(geocodeResults) {
    unmaskSearchForm();
    setZoomToResults(true);
    showBingCandidates(geocodeResults);
  }
  function geocodeFailure(err) {
    unmaskSearchForm();
    Mapping.Ext.Esri.Marker.reset();
    Mapping.Ext.Esri.ErrorManager.esriError(err);
  }
  function unmaskSearchForm(){ locationSearchWindow.getEl().unmask(); };
/*
  var coordinateSearchForm = new Ext.FormPanel({
    height: 286,
    defaultType: 'textfield',
    items: [{
        fieldLabel: 'Latitude (Y)', 
        name: 'lat'
      },{
        fieldLabel: 'Longitude (X)', 
        name: 'long',
        enableKeyEvents: true,
        listeners: {
          keypress: {
            fn: function(e, val){
              if( val.getKey() == 13){
                coordinateSearchFormHandler();
              }
            },
            scope: this
          }
        }
      }      
    ],
    padding: 3,
    buttons: [{
      text: 'Search',
      handler: function(){
        coordinateSearchFormHandler();
      }
    }],
    title: 'Coordinate',
    tabTip: 'Search by Lat/Long coordinate'
  });
*/
  function coordinateSearchFormHandler() {
    clearMarkerShowSearching();
    findByCoordinates(
      // Lat/Long
      coordinateSearchForm.findByType('textfield')[1].getValue(),
      coordinateSearchForm.findByType('textfield')[0].getValue()
    );  
  }

  function getXValue(v, record){
    return record.locationArray[0].x;
  }
  function getYValue(v, record){
    return record.locationArray[0].y;
  }

  var addressSearchResultsStore = new Ext.data.JsonStore({
    fields: [
      {name: 'address', mapping: 'displayName'},
      {name: 'x', convert: getXValue},
      {name: 'y', convert: getYValue},
      {name: 'score', mapping: 'confidence'}
    ]
  });

  var addressSearchResultsGrid = new Ext.grid.GridPanel({
    autoExpandColumn: 'address', columns: [
      { id: 'address', header: 'Address', sortable: true, dataIndex: 'address' }
    //,{header: 'Rank', sortable: true, dataIndex: 'score', width: 20 }
    ],
    listeners: {
      rowclick: {
        fn: function(grid, rowIndex, e) {
          var selectedCandidate = addressSearchResultsStore.getAt(rowIndex).data;
          markerSearchText = selectedCandidate.address;
          showAddressLocation(selectedCandidate);
          //map.setExtent(esriExtent);          
        }
      }
    },
    store: addressSearchResultsStore,
    stripRows: true,
    title: 'Results',
    tabTip: 'Address Search Results'
  });

  var locationSearchTabs = new Ext.TabPanel({
    activeTab: 0,
    width: 400,
    plain:true,  
    height: 252,
    plain: false,
    padding: 3,
    items: [parcelSearchForm, secTownRangeSearchForm, countySelectForm, addressSearchForm, 
              addressSearchResultsGrid]
  });
  //removed coordinateSearchForm,
  
  var locationSearchWindow = new Ext.Window({
  title: 'Search',
    items: [locationSearchTabs],
    initHidden: true,
    closable: true,
    closeAction: 'hide',
    collapsible: true,
    width: 411,
    height: 276,
    resizable: true,
    x: 100,
    y: 125
  });



  var searches = ['fieldSetParcelId', 'fieldSetSecTwnRangeId', addressSearchForm.id];

  /// Clear all other searches when supplied search is completed
  /// @param {string} Id of the containing form/fieldset of the completed search
  function cleanSearches(currentSearch) {
    // Loop through array of search form/fieldsets 
    // If currentSearch is not the form, clear all fields in the form
    Ext.each(searches, function(form, formIndex, forms) {
      if (currentSearch != form) {
        Ext.each(Ext.getCmp(form).findByType('field'), function(field, fieldIndex, fields) {
          field.reset();
        });
      }
    });
  }
