/* the initial zoom and center */
var LON = -123.98308181818;
var LAT =   40.511994545455;
var ZOOM = 12;

/* the list of WMS overlays */
var LAYERS = [];
LAYERS['labels']    = { 'url':'/cgi-bin/mapserv?map=/maps/vanduzen/wms.map&', 'layers':'labels', 'opacity':1.0 };
LAYERS['points']    = { 'url':'/cgi-bin/mapserv?map=/maps/vanduzen/wms.map&', 'layers':'points', 'opacity':0.50 };
LAYERS['subbasins'] = { 'url':'/cgi-bin/mapserv?map=/maps/vanduzen/wms.map&', 'layers':'subbasins', 'opacity':0.50 };

/* which point to automatically zoom to and open? default is none. 
   Example: http://server/thismap/?123   would zoom to point with gid=123
 */
var POINT = document.location.search.substring(1);

var map;
var markers = [];
var layerselector;

function startMap() {
    if (GBrowserIsCompatible()) {
        
        layerselector = new LayerSelector(document.getElementById("layers"));
        
        map = new GMap2(document.getElementById("map"),
            {'mapTypes': [G_HYBRID_MAP]});
        
        map.addControl(new GLargeMapControl());
        
        // Markers
        for (i = 0; i < points.length; i++) {
            var item = points[i];
            var marker = new GMarker(new GLatLng(item.lat, item.lon));
            marker.bindInfoWindowHtml(item.html);
            markers.push(marker);
            
            if(POINT == item.id)
            {
                ZOOM = ZOOM + 3;
                LAT = marker.getLatLng().lat();
                LON = marker.getLatLng().lng();
            }
        }
        
        map.setCenter(new GLatLng(LAT, LON), ZOOM);
        
        for (name in LAYERS) {
            // create the layer: a standard GTileLayer, but with the WMS addons to do tile calculation
            var attribs   = LAYERS[name];
            var layer = new GTileLayer(new GCopyrightCollection(), 1, 20);
            layer.getOpacity = function() { return this.opacity; }
            layer.isPng      = function() { return true; }
            layer.getTileUrl = CustomGetTileUrl;
            layer.myFormat   = 'image/png';
            layer.myLayers   = attribs['layers'];
            layer.myBaseURL  = attribs['url'];
            layer.opacity    = attribs['opacity'];
            
            overlay = new GTileLayerOverlay(layer);
            map.addOverlay(overlay);
            
            // add the overlay to the layer-selector so it can be toggled
            layerselector.addLayer(name,overlay,true);
        }
        
        markerset = new GMarkerManager(map, {'borderPadding':216} );
        markerset.addMarkers(markers, 0);
        markerset.refresh();

        layerselector.redraw();
    }
}

function LayerSelector(div) {
   // load the methods
   this.addLayer       = LayerSelector_addLayer;
   this.redraw         = LayerSelector_redraw;
   this.setVisibility  = LayerSelector_setVisibility;

   // initialize variables
   this.div      = div;
   this.layers   = [];
}


LayerSelector_addLayer = function(label,layer,visible) {
   this.layers.push({ 'label':label, 'layer':layer, 'visible':visible });
}



LayerSelector_setVisibility = function(index,status) {
   var target = this.layers[index];
   if (!target) return null;

   if (target.visible) { target.layer.hide(); target.visible=false; }
   else                { target.layer.show(); target.visible=true ; }
}


LayerSelector_redraw = function() {
   var content = '';
   content += '<table>';

   for (index in this.layers) {
      var thislayer   = this.layers[index].layer;
      var thislabel   = this.layers[index].label;
      var checked     = this.layers[index].visible;

      content += '<tr>';
      content += '<td>';
      content += '  <input class="checkbox" type="checkbox" value="'+index+'"';
      content += '         onClick="layerselector.setVisibility('+index+',this.checked);"';
      if (checked) content += 'checked="true" ';
      content += '  />';
      content += '</td>';
      content += '<td>'+ thislabel +'</td>';
      content += '</tr>';
   }

   content += '</table>';
   this.div.innerHTML = content;
}



/*
 * (From this section of code to "END WMS")
 * 
 * Call generic wms service for GoogleMaps v2
 * John Deck, UC Berkeley
 */
 
var MAGIC_NUMBER=6356752.3142;
var WGS84_SEMI_MAJOR_AXIS = 6378137.0;
var WGS84_ECCENTRICITY = 0.0818191913108718138;

var DEG2RAD=0.0174532922519943;
var PI=3.14159267;

//Default image format, used if none is specified
var FORMAT_DEFAULT="image/png";

//Google Maps Zoom level at which we switch from Mercator to Lat/Long.
var MERC_ZOOM_DEFAULT = 15;
function dd2MercMetersLng(p_lng) {
    return WGS84_SEMI_MAJOR_AXIS * (p_lng*DEG2RAD);
}

function dd2MercMetersLat(p_lat) {
    var lat_rad = p_lat * DEG2RAD;
    return WGS84_SEMI_MAJOR_AXIS * Math.log(Math.tan((lat_rad + PI / 2) / 2) * Math.pow( ((1 - WGS84_ECCENTRICITY * Math.sin(lat_rad)) / (1 + WGS84_ECCENTRICITY * Math.sin(lat_rad))), (WGS84_ECCENTRICITY/2)));
}

CustomGetTileUrl=function(a,b,c) {
    if (this.myMercZoomLevel == undefined) {
        this.myMercZoomLevel = MERC_ZOOM_DEFAULT;
    }

    if (this.myFormat == undefined) {
        this.myFormat = FORMAT_DEFAULT;
    }

    if (typeof(window['this.myStyles'])=="undefined") this.myStyles="";
    var lULP = new GPoint(a.x*256,(a.y+1)*256);
    var lLRP = new GPoint((a.x+1)*256,a.y*256);
    var lUL = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lULP,b,c);
    var lLR = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lLRP,b,c);

    // switch between Mercator and DD if merczoomlevel is set
    // NOTE -it is now safe to use Mercator exclusively for all zoom levels (if your WMS supports it)
    // so you can just use the two lines of code below the IF (& delete the ELSE)
    // drg & doq are topozone layers--- they don't work with epsg:54004
    if (this.myLayers!="drg" && this.myLayers!="doq") {
        var lBbox=dd2MercMetersLng(lUL.x)+","+dd2MercMetersLat(lUL.y)+","+dd2MercMetersLng(lLR.x)+","+dd2MercMetersLat(lLR.y);
        //Change for GeoServer - 41001 is mercator and installed by default.
        var lSRS="EPSG:54004";
    } else {
        var lBbox=lUL.x+","+lUL.y+","+lLR.x+","+lLR.y;
        var lSRS="EPSG:4326";
    } 
    var lURL=this.myBaseURL;
    lURL+="&REQUEST=GetMap";
    lURL+="&SERVICE=WMS";
    lURL+="&VERSION=1.1.1";
    lURL+="&LAYERS="+this.myLayers;
    lURL+="&STYLES="+this.myStyles;
    lURL+="&FORMAT="+this.myFormat;
    lURL+="&BGCOLOR=0xFFFFFF";
    lURL+="&TRANSPARENT=TRUE";
    lURL+="&SRS="+lSRS;
    lURL+="&BBOX="+lBbox;
    lURL+="&WIDTH="+256;
    lURL+="&HEIGHT="+256;
    lURL+="&reaspect=false";
    return lURL;
}

function customOpacity() { return this.myOpacity; }

/* END WMS */

