﻿var map, navToolbar, overviewMapDijit, statusBar, locator, baseLayer, satelliteLayer, streetLayer, veGeocoder;
var srwmdAerialLayer;
var currentMapScale;
var geometryServer;
//var hoverActive = false;
      
function CreateMap(){
  
  // Setup the map default zoom/pan animaton
  esri.config.defaults.map.zoomDuration = 1000;
  esri.config.defaults.map.zoomRate = 50;
  esri.config.defaults.map.panDuration = 750;
  esri.config.defaults.map.panRate = 50;
  esriConfig.defaults.io.proxyUrl = "./proxy.ashx";
  esriConfig.defaults.io.alwaysUseProxy = false;  

  // Create the map
  map = new esri.Map("map", {
    nav: false, 
    slider: false,
    extent: new esri.geometry.Extent(initialExtent)
  });

  dojo.subscribe('esri.Error', function(err){ 
      console.debug('esriError'); 
      console.debug('Code: ' + err.code);
      console.debug('Message: ' + err.code);
      console.debug('details: ' + err.details == null ? err.details.join("\n") : "No details");
      Mapping.Ext.Esri.ErrorManager.esriError(err);
    }
  );

  // Add listener to map whenever mouse moves, update coordinates
  dojo.connect(map, "onLoad", function() {

    GetCurrentScale();
    //after map loads, connect to listen to mouse move & drag events
    //dojo.connect(map, "onMouseMove", ShowCoordinates);
    map.disableKeyboardNavigation();

    // listen for changing zoom level
    dojo.connect(map, "onExtentChange", MapExtentChanged);
    dojo.connect(map, "onZoomEnd", function(){
      // If we are displaying any aerial layer, check zoom level and switch if needed
      if(satelliteLayer.visible || srwmdAerialLayer.visible) {
        if(map.getLevel() > srwmdAerialsLevel && satelliteLayer.visible){
          srwmdAerialLayer.show();
          satelliteLayer.hide();
        } else if (map.getLevel() <= srwmdAerialsLevel && srwmdAerialLayer.visible) {
          srwmdAerialLayer.hide();
          satelliteLayer.show();
        }
      }
      if (map.getLevel() <= srwmdAerialsLevel) {
        hoverOff();
        if (Ext.get('selectedToolText').dom.innerHTML == 'Hover over parcel for ID') {
          Ext.get('selectedToolText').update('Pan tool active');
          Mapping.Ext.Esri.CursorManager.setCursor('mousePan');
          navToolbar.deactivate();
        }  
      }
    });

    // setup map slider and assign current zoom level
    Mapping.Ext.Esri.ZoomSlider.init(map);
    Mapping.Ext.Esri.ZoomSlider.updateLevel(map.getLevel());

    // setup cursor manager and set default cursor to pan
    var tmp = Mapping.Ext.Esri.CursorManager.init(map, 'mousePan');
    Mapping.Ext.Esri.CursorManager.appendCursor('mouseProgress');
    Mapping.Ext.Esri.Marker.init(map);

    // layer for drawing all the parcels on in the parcel hover tool
    var parcelGraphicsLayer = new esri.layers.GraphicsLayer({
      displayOnPan:false, 
      id: 'parcelGraphics', 
      visible: true
    });
    var selectedParcelGraphicsLayer = new esri.layers.GraphicsLayer({
      displayOnPan:false, 
      id: 'selectedParcelGraphics', 
      visible: true
    });    
    map.addLayer(parcelGraphicsLayer);
    map.addLayer(selectedParcelGraphicsLayer);
  });
  
  veGeocoder = new esri.virtualearth.VEGeocoder({
    bingMapsKey: bingKey
  });
  
  streetLayer = new esri.virtualearth.VETiledLayer({
        bingMapsKey: bingKey,
        mapStyle: esri.virtualearth.VETiledLayer.MAP_STYLE_ROAD
    });
  satelliteLayer = new esri.virtualearth.VETiledLayer({
        bingMapsKey: bingKey,
        mapStyle: esri.virtualearth.VETiledLayer.MAP_STYLE_AERIAL_WITH_LABELS
    });
	
  srwmdAerialLayer = new esri.layers.ArcGISDynamicMapServiceLayer(srwmdAerials, {id: 'srwmdAerials',visible:false});
  baseLayer = new esri.layers.ArcGISDynamicMapServiceLayer(baseDataLayer, {id: 'baseLayer'});
  satelliteLayer.hide();  
  srwmdAerialLayer.hide();
  map.addLayer(satelliteLayer);
  map.addLayer(srwmdAerialLayer); 
  map.addLayer(streetLayer); 
  map.addLayer(baseLayer);
  baseLayer.setOpacity(0.60);
  dojo.connect(baseLayer, 'onUpdate', function(){
    Mapping.Ext.Esri.CursorManager.removeCursor('mouseProgress');
  });
  
  // Setup ESRI Navigation Toolbar
  navToolbar = new esri.toolbars.Navigation(map);
  dojo.connect(navToolbar, "onExtentHistoryChange", ExtentHistoryChangeHandler);
  
  // Geolocator from ESRI
  //locator = new esri.tasks.Locator(locatorService);
    
  // Setup listener to fix map when window is resized
  Ext.EventManager.onWindowResize(function(){
    map.resize();
    map.reposition();
  });
  map.resize();
  map.reposition();
  
  // Setup default windows
  navigation();
  overview();
  showLayersWindow();
  locationSearchWindow.show();
  Mapping.Ext.Esri.Bookmarks.init();
  
  Ext.getCmp('disclaimerWindow').show().setActive(true);
  spot.show('disclaimerWindow');  
  
  // Setup geometry server
  //geometryServer = new esri.tasks.GeometryService(geometryService);

  //reference print service make sure it is awake before user gets to report page
  //uncomment if service not ready when user goes to report page.
  //var dynamicMapServiceLayer = new esri.layers.ArcGISDynamicMapServiceLayer(reportPrintMapLayer);
}

///
/// Displays mouse coordinates
/// @param {Object} evt The event causing the method to fire
/// 
function ShowCoordinates(evt) {
  //get mapPoint from event and convert from WebMercator
  var mp = esri.geometry.webMercatorToGeographic(evt.mapPoint);
  
  //display mouse coordinates
  statusBar === Ext.getCmp('coordinates-statusbar');
  if(statusBar != null){
    statusBar.setStatus({
      text: 'Coordinates: Lat:' + mp.y.toFixed(4) + ', Long:' + mp.x.toFixed(4),
      iconCls: 'x-status-custom'
    });
  }
  if(Ext.get('mouseCoordinateDiv') != null){
    Ext.get('mouseCoordinateDiv').update('Lat: ' + mp.y.toFixed(4) + '<br/>Long: ' + mp.x.toFixed(4));
  }
}

// Displays current lat/long next to mouse
function toggleMouseCoordinates(){
  if(mouseCoordinateTracker == null){
    mouseCoordinateTracker = new Ext.ToolTip({
      target: 'map',
      title: 'Lat/Long',
      width: 90,
      dismissDelay: 0,
      html: '<div id="mouseCoordinateDiv"> </div>',
      trackMouse:true
    });
  } else {
    mouseCoordinateTracker.destroy();
    mouseCoordinateTracker = null;
  }
}

///
/// Handles display of Previous/Next extent buttons based on current navigation
/// 
function ExtentHistoryChangeHandler() {
  if (navToolbar.isFirstExtent()) {
    Ext.getCmp('previousExtentButton').disable();
  } else {
    Ext.getCmp('previousExtentButton').enable();
  }

  if (navToolbar.isLastExtent()) {
    Ext.getCmp('nextExtentButton').disable();
  } else {
    Ext.getCmp('nextExtentButton').enable();
  }
}

function MapExtentChanged(){
  GetCurrentScale();
  // Update layers list based on current zoom level
  if (layersGenerated) {
    updateTableOfContents(map.getLevel());
  }
  Mapping.Ext.Esri.CursorManager.appendCursor('mouseProgress')
}

///
/// Gets and sets the current scale
/// Updates the scale bar and the ToC
///
function GetCurrentScale(){

  // Get scale in Feet (convert from inches)
  currentMapScale = esri.geometry.getScale(map.extent, map.width, 102100);
  var scaleText = currentMapScale / 12;
  
  // Show scale in miles if >= 1 mile or in ft if less than 1 mile
  if(scaleText < 5280){
    dojo.byId("scaleInfo").innerHTML = scaleText.toFixed(0) + " ft";
  } else {
    scaleText = scaleText / 5280;
    dojo.byId("scaleInfo").innerHTML = scaleText.toFixed(2) + " mi";
  }
}

// Change to street map
function displayStreetLayer(){
  satelliteLayer.hide();
  streetLayer.show();
  srwmdAerialLayer.hide();
}

// Change to satellite map
function displaySatelliteLayer(){
  streetLayer.hide();
  if(map.getLevel() > srwmdAerialsLevel) {
    srwmdAerialLayer.show();
  } else {
    satelliteLayer.show();  
  }
}

