/**
 * Esri mapping scripts
 */
      function loadEsriMap(esriApiKey,geocodingServiceUrl) {
        //Esri require
        require([
          "esri/config",
          "esri/Map",
          "esri/views/MapView",
          "esri/rest/locator",
          "esri/widgets/Locate",
          "esri/Graphic",
          "esri/layers/FeatureLayer",
        "esri/widgets/BasemapToggle"
          ], function (esriConfig, Map, MapView, locator, Locate, Graphic, FeatureLayer,BasemapToggle) {
          esriConfig.apiKey = esriApiKey;
          const defaultLatitude = 44.2919108;
    	  const defaultLongitude = -101.4834125;
          esriMap = new Map({
            basemap: "hybrid"
          });
          const view = new MapView({
            container: "esriMap",
            map: esriMap,
            center: [defaultLongitude,defaultLatitude],//44.2919108084727,-101.4834125
            zoom: 3
          });
          esriMapView = view;
         const toggle = new BasemapToggle({
               view: view, 
               nextBasemap: "arcgis-navigation"
         });
         view.ui.add(toggle, "bottom-right");
          // Create a symbol for drawing the point
          const markerSymbol = {
            type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
            color: [230, 76, 0],//Flame Red [230, 76, 0]
            size: "18px",  // pixels
            outline: {
              // autocasts as new SimpleLineSymbol()
              color: [255, 255, 255],
              width: "2px"
            }
          };

          const labelClass = {
            // autocasts as new LabelClass()
            symbol: {
              type: "text",  // autocasts as new TextSymbol()
              color: "white",
              //xoffset:"1px",
              font: {  // autocast as new Font()
                //family: "Playfair Display",
                size: "14px",
                weight: "bold"
              }
            },
            labelPlacement: "center-center",
            labelExpressionInfo: {
              expression: "$feature.counter"
            }
          };
        const locate = new Locate({
            view: view,
            useHeadingEnabled: false,
            goToOverride: function(view, options) {
              options.target.scale = 1500;
              return view.goTo(options.target);
            }
        });
          //Location Point Graphic
          function createGraphic(result) {
            // First create a point geometry
            const point = {
              type: "point", // autocasts as new Point()
              longitude: result.location.longitude,
              latitude: result.location.latitude,
            };
            const data = {
              counter: result.counter,
              latitude: result.location.latitude,
              longitude: result.location.longitude,
              address: result.address
            };
            const popupTemplate = {
              title: "{title}",
              content: result.address + "<br><br>" + parseFloat(result.location.longitude).toFixed(6) + "," + parseFloat(result.location.latitude).toFixed(6) + ""
            };
            // Create a graphic and add the geometry and symbol to it
            const pointGraphic = new Graphic({
              geometry: point,
              //symbol: markerSymbol,
              attributes: data,
              popupTemplate: popupTemplate
            });
            return pointGraphic;
          }

          //To execute a default search
          view.when(() => {
            //loadDefaultMap();
          });

          function search() {
            $("#drc-locator span.drc-results-count").html("&mdash; " + "Loading...");
            var address = $('#search-drc').val();
            geocode(address, geocodeCallback);
          }
        function searchByState(address) {
            $("#drc-locator span.drc-results-count").html("&mdash; " + "Loading...");
            geocode(address, geocodeCallbackState);
        }
          function geocode(query, callback) {
            view.graphics.removeAll();
            var address = query;
            const params = {
              address: {
                "address": address
              },
              countryCode: "USA",
              outFields: "*"
            };
            locator.addressToLocations(geocodingServiceUrl, params).then((results) => {
                callback(results, addLocations);
           
            });
          }

          function addLocations(requestedLocation, locations) {
            //clear any existing features
            var layer = esriMap.findLayerById("DRCLocatorFL");
            if ( typeof layer !== "undefined" ) {
              view.popup.close();
              layer.clear();
              //layer.definitionExpression ="";
                esriMap.remove(layer);
            }
            if ( locations.length > 0 ){
            var graphics = [];
            locations.forEach(location => graphics.push(createGraphic(location)));
            var layer = createLayer(graphics);
            layer.id = "DRCLocatorFL";
            layer.definitionExpression ="";
            layer
              .when(() => {
                return layer.queryExtent();
              })
              .then((response) => {
                view.goTo(response.extent);
              });
            addToView(layer);
            } else {
                //goto requested location
                view.goTo({
                      center: [requestedLocation.longitude, requestedLocation.latitude],
                      zoom: 3
                });
            }
          }
          // Adds a given layer to the map in the view
          function addToView(layer) {
            view.map.add(layer);
          }


          //  Creates a client-side FeatureLayer from an array of graphics
          function createLayer(graphics) {
            return new FeatureLayer({
              source: graphics,
              labelingInfo: [labelClass],
              objectIdField: "OBJECTID",
              fields: [{
                name: "OBJECTID",
                type: "oid"
              },
              {
                name: "counter",
                alias: "Counter",
                type: "string"
              },
              {
                name: "type",
                alias: "Type",
                type: "string"
              },
              {
                name: "latitude",
                alias: "Latitude",
                type: "double"
              },
              {
                name: "longitude",
                alias: "Longitude",
                type: "double"
              },
              {
                name: "distance",
                alias: "Distance",
                type: "string"
              },
              {
                name: "county",
                alias: "County",
                type: "string"
              },
              {
                name: "name",
                alias: "Name",
                type: "string"
              },
              {
                name: "address",
                alias: "Address",
                type: "string"
              },
              {
                name: "url",
                alias: "url",
                type: "string"
              }

              ],
              popupTemplate: {
                title: (event) => {
                  return "Address";
                }
                , content: "{address}"
              },
              renderer: {
                type: "simple",
                symbol: markerSymbol
              }
            });
          }

          view.on("click", (event) => {
            const opts = {
              //include: featureLayer
            }
            view.hitTest(event, opts).then((response) => {
              // check if a feature is returned from the featureLayer
              if ((response.results.length) && (response.results[0].layer.type == 'feature')) {
                showDrcInfo(response.results[0].graphic.attributes.counter);
              }
            });
          });

          $("#searchByLocation").closest('label').on('click', function (e) {
            if ($("div.locationField").length === 0) {
              $("div.stateField").remove();
              $("div#search-criteria-above").append("<div class='form-group locationField'><label for='search-drc' class='col-sm-2'>Search Address</label><div class='input-group col-sm-6'><input type='text' id='search-drc' class='form-control input-sm' title='Enter an address to start your search.' placeholder='Enter an address to start your search.' /><span class='input-group-btn'><a href='#' class='btn btn-primary btn-sm' role='button' id='btnSearch' title='Search Address'><i class='fa fa-search'><span class='sr-only'>Search</span></i></a><a href='#' class='btn btn-default btn-sm' role='button' id='btnGeo' title='Search using Current Location'><i class='fa fa-location-arrow'><span class='sr-only'>Current Location</span></i></a></span></div></div>");
              $("div#search-criteria-above").append("<div class='locationField'><fieldset class='form-group'><legend class='top col-sm-2'>Search Radius</legend><div class='btn-group btn-group-sm col-sm-10 search-radius' data-toggle='buttons'><label class='btn btn-default' for='drcRadius-005'><input name='drcRadius' id='drcRadius-005' value='5' type='radio'>5 mi</label><label class='btn btn-default' for='drcRadius-010'><input name='drcRadius' id='drcRadius-010' value='10' type='radio'>10 mi</label><label class='btn btn-default active' for='drcRadius-025'><input name='drcRadius' id='drcRadius-025' value='25' type='radio' checked>25 mi</label> <label class='btn btn-default' for='drcRadius-050'><input name='drcRadius' id='drcRadius-050' value='50' type='radio'>50 mi</label><label class='btn btn-default' for='drcRadius-100'><input name='drcRadius' id='drcRadius-100' value='100' type='radio'>100 mi</label><label class='btn btn-default' for='drcRadius-any'><input name='drcRadius' id='drcRadius-any' value='' type='radio'>Any Distance</label></div></fieldset></div>");
              $('#btnSearch').on('click', function () {
                search();
              });
              $('#btnGeo').on('click', function () {
                      //throws GeolocationPositionError if location services is not enabled: 
                       locate.locate();
              });
            }
          });
          
        $("#searchByState").closest('label').on('click', function(e){
            if($("div.stateField").length === 0) {
                $("div.locationField").remove();
                $("div#search-criteria-above").append("<div class='stateField form-group'><label for='selState' class='col-sm-2'>State</label><div class='input-group col-sm-6'><select name='selState' id='selState' class='form-control input-sm' ><option></option></select></div></div>");
                var $states;
                var address = "";
                if(isCssDisabled() === true) {
                    $states = $('#selState');
                } else {
                    $states = $('#selState').select2({
                        allowClear: true,
                        placeholder: "State",
                        escapeMarkup: function(markup) {return markup;}
                    });
                }

                $stateRequest.then(function(data) {
                    for(var i=0;i<data.length; i++) {
                        var item = data[i];
                        var option = new Option(item.stName, item.stCd, false, false);
                        $states.append(option);
                    }
                   });
                if(isCssDisabled() === true) {
                    $('#selState').on('change', function(e) {
                        //address = 
                        //searchByState(address);
                    });
                } else {
                    $('#selState').on('select2:select', function(e) {
                        address = $('#selState').select2('data')[0].text;
                        searchByState(address);
                    });
                }
            }
        });


        $("#searchByLocation").closest('label').click();

        $('div.drc-result').addClass('hidden');
        $('span.drc-results-count').addClass('hidden');
          
        //Populate states
        var $stateRequest = $.ajax({
            url: context + "/getStates",
            dataType: 'json',
            cache: true
        });

        $("#search-form").submit(function(e){
            e.preventDefault();
            search();
        });

        });
        //end of Esri require
      } //end of esri mapping scripts
		
	  $(document).ready(function() {
          let checkDiv = setInterval(function() {
              if ($('canvas').length && $('.esri-view-surface').length) {

                  $('.esri-view-surface').attr('aria-label', 'Esri Map Container');
                  $('canvas').attr('aria-label', 'Esri Map Container');

                  const canvas = document.getElementById("myCanvas");
                  const pElement = document.createElement("p");
                  pElement.textContent = "The map content is not keyboard accessible.";
                  canvas.parentNode.insertBefore(pElement, canvas);


                  let mapContainer = $('canvas');
                  // Using Esri-view-surface as the fallback content for canvas
                  let fallbackDiv = $('.esri-view-surface');

                  // When the map container receives focus, set focus to the fallback div
                  mapContainer.on("focusin", function() {
                      fallbackDiv.focus();
                  });

                  // When the fallback div is activated (Enter or Space), set focus back to the map container
                  fallbackDiv.on("keydown", function(event) {
                      if (event.keyCode === 13 || event.keyCode === 32) { // Enter or Space
                          mapContainer.focus();
                      }
                  });

                  clearInterval(checkDiv);
              }
          }, 100);

          loadEsriMap(yekIpaIrse,geocodingServiceUrl);
	  });
      