var centreLat=37.75128478585922;
var centreLon=-122.20075607299805;
var initialZoomLevel=5;
var n_buttonText="Map"; //Text that shows up on the button for the custom layer (n=normal, s=sat, h=hybrid)
var s_buttonText="Satellite";
var h_buttonText="Hybrid";
var mapBounds=new GLatLngBounds(new GLatLng(32.53422628800007,-124.40968580099991),new GLatLng(41.99853664900007,-117.07953197699993));
var map; //the GMap2 itself
var opacity=0.5;
var choice;  //has the user selected to display Erosion or Flooding layers
var folder=Array();
var zoom = 6;
var zoomInDiv;

//We are contractually obligated NOT to zoom in too far on the flood layers.
//set the max zoom level here in a global variable one time to avoid duplication
var maxZoom = 14;

var geoXml = new Array();
var toggleState = new Array();
toggleState[0]= 1;

var r = Math.floor(Math.random()*11);

geoXml[-1]= new GGeoXml("http://www.pacinst.org/reports/sea_level_rise/kml/coastzn.kmz?rand="+r);
geoXml[0] = new GGeoXml("http://www.pacinst.org/reports/sea_level_rise/kml/hospitals.kmz?rand="+r);
geoXml[1] = new GGeoXml("http://www.pacinst.org/reports/sea_level_rise/kml/schools.kmz?rand="+r);
geoXml[2] = new GGeoXml("http://www.pacinst.org/reports/sea_level_rise/kml/police.kmz?rand="+r);
geoXml[3] = new GGeoXml("http://www.pacinst.org/reports/sea_level_rise/kml/fire.kmz?rand="+r);
geoXml[4] = new GGeoXml("http://www.pacinst.org/reports/sea_level_rise/kml/wwtp.kmz?rand="+r);
geoXml[5] = new GGeoXml("http://www.pacinst.org/reports/sea_level_rise/kml/epa.kmz?rand="+r);


folder[0]="flood-tiles";
folder[1]="erosion-tiles";
folder[2]="frontier-tiles";

function customGetTileURL(a,b) {
  //converts tile x,y into keyhole string
  
  //b = zoom level from 0 to 20
  //a.x = horizontal number of the tile
  //a.y = vertical tile number
  //document.getElementById("x").innerHTML=a.x +", ";
  //document.getElementById("y").innerHTML=a.y;
  
  //if the user has not checked either of the options, display a blank tile only
  if (choice==null) {
    return "erosion-tiles/blank-tile.png"; 
    }
    
  //document.getElementById("zoom").innerHTML=b;
  //handle the case where the user zooms in further than we have rendered tiles
  if (b>maxZoom) { 
    document.getElementById("floodlayers").style.backgroundColor="#dddddd";
    //document.getElementById("x").innerHTML="Zoom out to view";
    return "erosion-tiles/blank-tile.png"; 
    };
    
  document.getElementById("floodlayers").style.backgroundColor="#ffffff"
  var c=Math.pow(2,b);
  var x=360/c*a.x-180;
  var y=180-360/c*a.y;
  var x2=x+360/c;
  var y2=y-360/c;
  var lon=x; //Math.toRadians(x); //would be lon=x+lon0, but lon0=0 degrees
  var lat=(2.0*Math.atan(Math.exp(y/180*Math.PI))-Math.PI/2.0)*180/Math.PI; //in degrees
  var lon2=x2;
  var lat2=(2.0*Math.atan(Math.exp(y2/180*Math.PI))-Math.PI/2.0)*180/Math.PI; //in degrees
  var tileBounds=new GLatLngBounds(new GLatLng(lat2,lon),new GLatLng(lat,lon2));

  if (!tileBounds.intersects(mapBounds)) { return "erosion-tiles/blank-tile.png"; };
    var d=a.x;
    var e=a.y;
    var f="t";
    for(var g=0;g<b;g++){
        c=c/2;
        if(e<c){
            if(d<c){f+="q"}
            else{f+="r";d-=c}
        }
        else{
            if(d<c){f+="t";e-=c}
            else{f+="s";d-=c;e-=c}
        }
    }
    return folder[choice] + "/" + f + ".png"
}

function changeOpacity(op) {
//this works as long as there are at least two map types
    var current=map.getCurrentMapType();
    if (current==map.getMapTypes()[0])
      map.setMapType(map.getMapTypes()[1]);
else
map.setMapType(map.getMapTypes()[0]);
    opacity=op;
    map.setMapType(current); //was map.getMapTypes()[1]
}


function getWindowHeight() {
    if (window.self&&self.innerHeight) {
        return self.innerHeight;
    }
    if (document.documentElement&&document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
    return 0;
}

function resizeMapDiv() {
  //Resize the height of the div containing the map.
  //Do not call any map methods here as the resize is called before the map is created.
  var d=document.getElementById("map");
    var offsetTop=0;
    for (var elem=d; elem!=null; elem=elem.offsetParent) {
        offsetTop+=elem.offsetTop;
    }
    var height=getWindowHeight()-offsetTop-16;
    if (height>=0) {
        d.style.height=height+"px";
    }

}


function toggleLayers(i) {
//first, turn off all the other layers

  for(var j=0; j<=2; j++){ 
    if (j!=i){
      unselect(j);
    }
  }
  
  if (document.getElementById("layer" + i).checked == true){
    choice = i;
    }
  else {
    choice = null;
    }
  if (zoom<3){
    map.zoomIn();
    map.zoomOut();
    }
  else{
    map.zoomOut();
    map.zoomIn();
   }
  
  //alert("layer " + choice + " is active");
}


function unselect(num){
  //make sure the user can only check one of the room costs
  var field;
  field = document.getElementById("layer" + num);
  if (field.checked) {
    field.checked=false;
   }
}


function toggleMyKml(i) {
  toggleState[i] = document.getElementById("kml" + i ).checked;
  if (toggleState[i]) {
    map.addOverlay(geoXml[i]);
  } else {
    map.removeOverlay(geoXml[i]);
  }
  //turn off all of the other layers (only show one at a time)
  var n = 6;
  for(var j=-1; j<n; j++){
    if (j!=i){
      map.removeOverlay(geoXml[j]);
      document.getElementById("kml" + j).checked = false;
    }
  }
}

function load() {
  if (GBrowserIsCompatible()) {
    
    // Create custom zoom buttons
    function TextualZoomControl() {
    }
    
    // To "subclass" the GControl, we set the prototype object to
    // an instance of the GControl object
    TextualZoomControl.prototype = new GControl();
    
    // Creates a one DIV for each of the buttons and places them in a container
    // DIV which is returned as our control element. We add the control to
    // to the map container and return the element for the map class to
    // position properly.
    TextualZoomControl.prototype.initialize = function(map) {
      var container = document.createElement("div");
    
      zoomInDiv = document.createElement("div");
      this.setButtonStyle_(zoomInDiv);
      container.appendChild(zoomInDiv);
      zoomInDiv.appendChild(document.createTextNode("Zoom In"));
      GEvent.addDomListener(zoomInDiv, "click", function() {
        if (zoom < maxZoom){
          map.zoomIn();
        }
        
      });
    
      var zoomOutDiv = document.createElement("div");
      this.setButtonStyle_(zoomOutDiv);
      container.appendChild(zoomOutDiv);
      zoomOutDiv.appendChild(document.createTextNode("Zoom Out"));
      GEvent.addDomListener(zoomOutDiv, "click", function() {
        map.zoomOut();
      });
    
      map.getContainer().appendChild(container);
      return container;
    }
    
    // By default, the control will appear in the top left corner of the
    // map with 7 pixels of padding.
    TextualZoomControl.prototype.getDefaultPosition = function() {
      return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
    }
    
    // Sets the proper CSS for the given button element.
    TextualZoomControl.prototype.setButtonStyle_ = function(button) {
      button.style.textDecoration = "underline";
      button.style.color = "#0000cc";
      button.style.backgroundColor = "white";
      button.style.font = "small Arial";
      button.style.border = "1px solid black";
      button.style.padding = "2px";
      button.style.marginBottom = "3px";
      button.style.textAlign = "center";
      button.style.width = "6em";
      button.style.cursor = "pointer";
    }

    
    resizeMapDiv();
    
    var copyrightCollection = new GCopyrightCollection("");
    copyrightCollection.addCopyright(new GCopyright('Demo',
        new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)),
        0,''));


    //create a custom G_NORMAL_MAP layer
    var n_tileLayers = [ G_NORMAL_MAP.getTileLayers()[0], new GTileLayer(copyrightCollection, 0, maxZoom)];
    n_tileLayers[1].getTileUrl = customGetTileURL;
    n_tileLayers[1].isPng = function() { return false; };
    n_tileLayers[1].getOpacity = function() { return opacity; };
    var n_customMap = new GMapType(n_tileLayers, new GMercatorProjection(maxZoom + 1), n_buttonText,
        {maxResolution: maxZoom, minResolution: 0, errorMessage:"Data not available"});

    //create a custom G_SATELLITE_MAP layer
    var s_tileLayers = [ G_SATELLITE_MAP.getTileLayers()[0], new GTileLayer(copyrightCollection, 0, maxZoom)];
    s_tileLayers[1].getTileUrl = customGetTileURL;
    s_tileLayers[1].isPng = function() { return false; };
    s_tileLayers[1].getOpacity = function() { return opacity; };
    var s_customMap = new GMapType(s_tileLayers, new GMercatorProjection(maxZoom + 1), s_buttonText,
        {maxResolution:maxZoom, minResolution:0, errorMessage:"Data not available"});

    //create a custom G_HYBRID_MAP layer
    var h_tileLayers = [ G_HYBRID_MAP.getTileLayers()[0], new GTileLayer(copyrightCollection, 0, maxZoom),G_HYBRID_MAP.getTileLayers()[1]];
    h_tileLayers[1].getTileUrl = customGetTileURL;
    h_tileLayers[1].isPng = function() { return false; };
    h_tileLayers[1].getOpacity = function() { return opacity; };
    var h_customMap = new GMapType(h_tileLayers, new GMercatorProjection(maxZoom + 1), h_buttonText,
        {maxResolution:maxZoom, minResolution:0, errorMessage:"Data not available"});

    //Now create the custom map. Would normally be G_NORMAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP
    map = new GMap2(document.getElementById("map"),{mapTypes:[n_customMap,h_customMap, s_customMap]});
    map.maxResolution=16;
    //map.addControl(new GSmallMapControl());
    map.addControl(new TextualZoomControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    map.enableContinuousZoom();
    //map.enableScrollWheelZoom();
    map.setCenter(new GLatLng(centreLat, centreLon), initialZoomLevel, n_customMap);
    
    //Add the KML overlay
    //map.addOverlay(geoXml[-1]);
    
    //Add a listener to detect the zoom level.  
    GEvent.addListener(map, "zoomend", function(oldzoom,newzoom) {
      zoom = newzoom;
      //document.getElementById("zoom").innerHTML=zoom;

      if (zoom == maxZoom){
          zoomInDiv.style.backgroundColor="#666666";
        }
        else{
          zoomInDiv.style.backgroundColor="#ffffff";
        }
      
    }); 

  }
  choice = 0;
  document.getElementById("layer0").checked=true;
  document.getElementById("layer1").checked=false;
  document.getElementById("layer2").checked=false;
  
  //Check the first checkbox, and clear the others
  document.getElementById("kml-1").checked=false;
  document.getElementById("kml0").checked=false;
  document.getElementById("kml1").checked=false;
  document.getElementById("kml2").checked=false;
  document.getElementById("kml3").checked=false;
  document.getElementById("kml4").checked=false;
  document.getElementById("kml5").checked=false;
  
}
