// JScript File for wmaMATL
// Created by State of Montana Department of Environmental Quality
// December 2008

    var map;
    var lyrFocus;
    var lyrTRS;

    var toggleFocus = 1;
    var toggleTRS = 0;

    var basemaps;
    var search;
    var mapcontrol;
    var scale;
    var myEventListener;
    var overlaycounter = 0;
    var timer;
    var maptype;
    var allowedBounds;    
    var layerItem = "";
    var searchOptions;
    var zoomlevel;
    var divname;
    var divjump;
   
   
   // initialize map on page load
   function initialize()
   {  
   if (GBrowserIsCompatible())
     {  map = new GMap2(document.getElementById("divMapCanvas")); 
        
        // set initial map zoom level and center
        map.setCenter(new GLatLng(48.3, -111.8), 8);
        
        
        
        
        
        // define services for overlays
	  var LyrFocusParams = new esri.arcgis.gmaps.ImageParameters();
        LyrFocusParams.layerIds = [1];
        lyrFocus = new esri.arcgis.gmaps.DynamicMapServiceLayer("http://gisservice.mt.gov/ArcGIS/rest/services/DEQ/MATL_Corridor/MapServer", LyrFocusParams, 0.8);
        
	  var LyrTRSParams = new esri.arcgis.gmaps.ImageParameters();
        LyrTRSParams.layerIds = [5];
        lyrTRS = new esri.arcgis.gmaps.DynamicMapServiceLayer("http://gisservice.mt.gov/ArcGIS/rest/services/DEQ/Reference/MapServer", LyrTRSParams, 0.8);
        
	  basemaps = new GMenuMapTypeControl();              
    
        // add Local Search with options
        search = new google.maps.LocalSearch(
            {resultList : document.getElementById("divResults"), searchFormHint:"Search for Place or Lat, Long", suppressZoomToBounds:true, suppressInitialResultSelection:true});
        
        // add map controls and placement
        mapcontrol = new GLargeMapControl();
        scale = new GScaleControl();      
	    map.enableScrollWheelZoom();        
        map.addControl(mapcontrol);
	    map.addControl(scale, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(260,-37)));        
	    map.addControl(search, new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(-1,-37)));
	    
	    
	    
	    
        // loading functions for initial map load
        loadingStartEvent();
        loadingStart();
        loadingEndEvent();
        OverlayBtnControl13();
                
        // set GMap types
	    
	    map.removeMapType(G_SATELLITE_MAP);
	    map.addMapType(G_PHYSICAL_MAP);
    	G_PHYSICAL_MAP.getName=function(){return"Terrain"};
	    G_HYBRID_MAP.getName=function(){return"Aerials"};
	    G_NORMAL_MAP.getName=function(){return"Road Map"};
	    map.addOverlay(lyrFocus);
	    	    
	    
        // The allowed region which the whole map must be within
        allowedBounds = new GLatLngBounds(new GLatLng(47.4, -112.6), new GLatLng(49.1, -110.9));
        
	    // Add a move listener to restrict the bounds range
        GEvent.addListener(map, "move", function(){CheckMapBounds();});    
        
        // Add a zoom listener to get current zoom level
        GEvent.addListener(map, "zoomend", function(){OverlayBtnControl13();});
        
        // ====== Restricting the range of Zoom Levels =====
        // Get the list of map types      
        maptype = map.getMapTypes();
        ControlZoomExtents();
      
      }
      
        // display a warning if the browser was not compatible
        else {alert("Sorry, this mapping application is not compatible with this browser");}
        
        
     
     }
    
    // Set basemap control for Large Map
    function LargeBaseMap()
    {
        map.addControl(basemaps, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(200,10)));
    }
    
    // Set basemap control for Small Map
    function SmallBaseMap()
    {
        map.addControl(basemaps, new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10)));
    }
     
    // Overwrite the getMinimumResolution() and getMaximumResolution() methods
    function ControlZoomExtents()
    {  
    for (var i=0; i<maptype.length; i++)
        {  
          maptype[i].getMinimumResolution = function()
            {return 8;} // 1:4622324.614000 scale 
          maptype[i].getMaximumResolution = function()
            {return 17;} // 1:9027.977761 scale
        }
    }
  
    
    // If the map position is out of range, move it back
    function CheckMapBounds()
    { 
        // Perform the check and return if OK
        if (allowedBounds.contains(map.getCenter()))
         {return;}
       
        // It`s not OK, so find the nearest allowed point and move there
        var C = map.getCenter();
        var X = C.lng();
        var Y = C.lat();

        var AmaxX = allowedBounds.getNorthEast().lng();
        var AmaxY = allowedBounds.getNorthEast().lat();
        var AminX = allowedBounds.getSouthWest().lng();
        var AminY = allowedBounds.getSouthWest().lat();

        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}
        //alert ("Restricting "+Y+" "+X);
        map.setCenter(new GLatLng(Y,X));
     }
    

     // controls overlay use based on zoom level < 13
     function OverlayBtnControl13()
     {
        zoomlevel = map.getZoom();
        //alert("Zoom Level=" + zoomlevel);
        if (zoomlevel < 13)
         {
            goDim("btnTRS");
            map.removeOverlay(lyrTRS);
            toggleTRS = 0;
         }
        else
         {
           if (toggleTRS==1){
           goActive("btnTRS");
           }else{
           goInactive("btnTRS");
           }
         }   
      }
      
 
     // controls overlay on/off and button style for button click
     function overlayControl(BTN, layer, toggle)
     { if (eval(toggle) == 1)
        { map.removeOverlay(layer);
         goInactive(BTN);
         layerToggle(toggle, 0);
        } else
        { 
         if (toggle == "toggleFocus"){
         loadingStartBtn(1);
         } else {
         loadingStartBtn(2);
         }
         map.addOverlay(layer);
         goActive(BTN);
         layerToggle(toggle, 1);
         overlayPrimaryOn();     
        }
     }     
    
   
    //puts the primary overlay on top of all other overlays
    function overlayPrimaryOn()
    {
     map.removeOverlay(lyrFocus);
     map.addOverlay(lyrFocus);
     toggleFocus = 1;
     goActive("btnFocus");
    }
   
    
    // make divHelp visible
    function HelpOn()
    {
    document.getElementById("divHelpContainer").style.visibility = "visible";
    document.getElementById("divHelpBckgrnd").style.visibility = "visible";
    document.getElementById("divHelpHeader").style.visibility = "visible";
    }
    
    // make divOverlayHelp hidden  divLgndHeader
    function HelpOff()
    {
    document.getElementById("divHelpContainer").style.visibility = "hidden";
    document.getElementById("divHelpBckgrnd").style.visibility = "hidden";
    document.getElementById("divHelpHeader").style.visibility = "hidden";
    }
    
    // make divOverlayHelp hidden  divLgndHeader
    function NoOverlayOff()
    {
    document.getElementById("divNoOverlay").style.visibility = "hidden";
    }
    
    
    // make divLgndContainer visible
    function LegendOn(BTNID)
    {
    document.getElementById("divLgndContainer").style.visibility = "visible";
    document.getElementById("divLgndBkgrnd").style.visibility = "visible";
    document.getElementById("divLgndHeader").style.visibility = "visible";
    DivFromBtn(BTNID);
    }
    
    // jump to related section of legend from overlay btn click
    function DivFromBtn(BTNID)
    {
    divname = BTNID.substring(7);
    divjump = "divLgnd" + divname;
    document.location.href="#" + divjump;   
    }
    
    
    // make divLgndContainer hidden
    function LegendOff()
    {
    document.getElementById("divLgndContainer").style.visibility = "hidden";
    document.getElementById("divLgndBkgrnd").style.visibility = "hidden";
    document.getElementById("divLgndHeader").style.visibility = "hidden";
    }
    
    
    // Button style controls
    function goInactive(BTN)
    {
    document.getElementById(BTN).className= "inactivebutton";
    document.getElementById(BTN).disabled = false;
    document.getElementById(BTN).title="Turn on overlay";
    }

    function goDim(BTN)
    { 
    document.getElementById(BTN).className= "notavailablebutton";
    document.getElementById(BTN).title="Zoom in to access this overlay";
    document.getElementById(BTN).disabled = true;
    }
   
    function goActive(BTN)
    {
    document.getElementById(BTN).className= "activebutton";
    document.getElementById(BTN).disabled = false;
    document.getElementById(BTN).title="Turn off overlay";
    }
    
    function goActiveNoTitle(BTN)
    {
    document.getElementById(BTN).className= "activebutton";
    document.getElementById(BTN).disabled = false;
    }
    
    function goInactiveNoTitle(BTN)
    {
    document.getElementById(BTN).className= "inactivebutton";
    document.getElementById(BTN).disabled = false;
    }
    
   
    
    // starts loading message each time the map is moved or zoom extent changes
    
    function loadingStartEvent()
    {
       GEvent.addListener(map, "moveend", function()
        {
          loadingStart();
        });
    }
  
   
  
    // listens for overlay return from ArcGIS Server to end the loading message
    
    function loadingEndEvent()
    {
      /******************************************************************************/
      // !!!!!!!! ALERT: IMPORTANT NOTE !!!!!!!!
      // This workaround is NOT officially supported and WILL NOT work at version 1.2
      // Remove this workaround once you start using version 1.2
      /******************************************************************************/ 
      // save the original redraw handler
      var _redrawHandler = esri.arcgis.gmaps.DynamicMapServiceLayer.prototype._redrawHandler;
      // create a new method to handle layer redraw
      esri.arcgis.gmaps.DynamicMapServiceLayer.prototype._redrawHandler = function()
       { // setup listener for image load event          
        var listener = GEvent.addDomListener(this._img_loading, "load", function()
         { // include code here to remove your "image loading" message 
          GEvent.removeListener(listener);
          listener = null;
          loadingEnd();
         });
        // call the actual redraw handler
        _redrawHandler.apply(this, arguments);
       }
    }
     
     
     // make NoOverlay div visible or hidden from functions
     function missingOverlays()
     {
     document.getElementById("divNoOverlay").style.visibility = "visible";
     document.getElementById("divLoadingGif").style.visibility = "hidden";
     overlaycounter = 0;
     }
     
     
     // make loadgingGIF DIV visible
     function loadingStart()
     { 
     if (toggleTotal() > 0)
     {
     overlaycounter = toggleTotal();
     document.getElementById("divLoadingGif").style.visibility = "visible";
     //document.getElementById("divNoOverlay").style.visibility = "hidden";
     clearTimeout(timer);
     timer = setTimeout("missingOverlays()", 25000);
     }
     }  
     
     // make loadgingGIF DIV hidden
     function loadingEnd()
     {
     if (overlaycounter == 1)
        {
         document.getElementById("divLoadingGif").style.visibility = "hidden";
         overlaycounter = 0;
         clearTimeout(timer);
        } else {
        overlaycounter = overlaycounter - 1;
        }
     }
     
          
     // count number of active overlays to keep track of continual loading message instead of start/stop 
     function toggleTotal()
     {
      return (toggleFocus
      + toggleTRS);
     }
    
    
     // controls toggle values for each overlay called from overlayControl()
     function layerToggle(toggle, val)
     {
     switch (toggle)
        {
        case 'toggleFocus': toggleFocus = val;break;
        case 'toggleTRS': toggleTRS = val;break;
        }
    }
    
  
    
    // starts loading message when called from overlayControl function
      function loadingStartBtn(val)
      {
        overlaycounter = val;
        document.getElementById("divLoadingGif").style.visibility = "visible";
        document.getElementById("divNoOverlay").style.visibility = "hidden";
        clearTimeout(timer);
        timer = setTimeout("missingOverlays()", 15000); 
      
      }  
    
    
    //resets map to initial extent and clears all overlays except primary overlay
    function resetMap()
    { 
                overlayPrimaryOn();

                map.removeOverlay(lyrTRS);
                goInactive("btnTRS");
                toggleTRS = 0;
                                               
                map.setCenter(new GLatLng(48.3, -111.8), 7);
                
                OverlayBtnControl13();
                              
    }
  

    // Redirect to Large Map
    
    function LargeMap()
    {
    document.location.href="largemap.aspx"
    }
   
    // Redirect to Default Map
    
    function DefaultMap()
    {
    document.location.href="default.aspx"
    }
    
     


