/**************************************************
 * Custom map layers:
 * Adapted from Jef Poskanzer's Acme Mapper
 * (http://mapper.acme.com/)
 * Rg - 2007-04 to 2008-04
 * Rg - SA version: cut certain map type, slim down control
 * Rg - 2009-09 - rename this file to "CustomMapTypesAndControl_V2.js"
 * Rg M2.001 - added Canadian Vector maps based on code from le Club de Montagne le Canadien
 * Rg   (http://www.clubmontagnecanadien.qc.ca/sentier/toporama.htm)
 * Rg M2.002 - rearange WMS URL strings for more clarity
 * Rg M2.003 - Modify WMSGetTileUrl() so CanVec can get reaster tiles at low zoom levels 
 * Rg M2.004 - rename map type to "C_xxx_yyy"
 **************************************************/
  var WMSStandardArgs = '?version=1.1.1&request=GetMap&styles=&srs=EPSG:4326&exceptions=INIMAGE&bgcolor=0xCCCCCC&transparent=true';
  var C_NRCAN_RASTER = WMSCreateMap('CanRas', '<a target="copyright" href="http://www.geogratis.gc.ca/geogratis/en/licence.jsp">&copy; Department of Natural Resources Canada</a>', 'NRCan raster maps unavailable',
    10, 15, 256, 'http://wms.cits.rncan.gc.ca/cgi-bin/cubeserv.cgi'+WMSStandardArgs, 'PUB_50K:CARTES_MATRICIELLES/RASTER_MAPS');
  var C_NRCAN_VECTOR = WMSCreateMap('CanVec', '<a target="copyright" href="http://www.geogratis.gc.ca/geogratis/en/licence.jsp">&copy; Department of Natural Resources Canada</a>', 'NRCan vector maps unavailable',
    3, 18, 256, 'http://wms.ess-ws.nrcan.gc.ca/wms/toporama_en'+WMSStandardArgs+'&format=image/gif', 'WMS-Toporama'); 
  var C_USGS_TOPO = WMSCreateMap('Topo', '<a target="copyright" href="http://education.usgs.gov/common/lessons/terraserver.html">&copy; USGS.gov</a>', 'USGS topo maps unavailable',
    10, 17, 256, 'http://terraservice.net/ogcmap6.ashx'+WMSStandardArgs, 'DRG');
  var C_USGS_AERIAL = WMSCreateMap('Aerial','<a target="copyright" href="http://education.usgs.gov/common/lessons/terraserver.html">&copy; USGS.gov</a>','USGS aerial imagery unavailable',
    10, 18, 256, 'http://terraservice.net/ogcmap6.ashx'+WMSStandardArgs, 'DOQ');
  var C_USGS_NRCAN_TOPO = WMSCreateMap('US+CA Topo', '<a target="copyright" href="http://education.usgs.gov/common/lessons/terraserver.html">&copy; USGS.gov</a>', 'USGS topo maps unavailable',
    10, 17, 256, 'http://terraservice.net/ogcmap6.ashx'+WMSStandardArgs, 'DRG');
  var C_BLANK = customCreateMap('Blank','blank map','',
    7, 22, 256, '/images/blank_tile.gif');

function addCustomMapTypes(map) {
  map.addMapType(C_USGS_TOPO);
  map.addMapType(C_USGS_AERIAL);
  map.addMapType(C_NRCAN_RASTER);
  map.addMapType(C_NRCAN_VECTOR);
  map.addMapType(C_USGS_NRCAN_TOPO);
  map.addMapType(C_BLANK);
}

function WMSCreateMap(name,copyright,errorMessage,minResolution,maxResolution,tileSize,baseUrl,layer) {
  var crc = new GCopyrightCollection();
  crc.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, copyright));
  var tileLayer = new GTileLayer(crc,minResolution,maxResolution);
  tileLayer.baseUrl = baseUrl;
  tileLayer.tileSize = tileSize;
  tileLayer.getTileUrl = WMSGetTileUrl;
  tileLayer.layer = layer;
  tileLayer.name = name;
  var tileLayers = [tileLayer];
  if (name=='US+CA Topo') tileLayers.push(C_NRCAN_VECTOR.getTileLayers()[0]);
  return new GMapType(tileLayers,G_SATELLITE_MAP.getProjection(),name,{errorMessage:errorMessage,tileSize:tileSize});
}

function WMSGetTileUrl(tile,zoom) {
  // raster map used for zoom levels < 11 for C_NRCAN_VECTOR 
  //if (this.name=='CanVec' && zoom<11) {var baseUrl = C_NRCAN_RASTER.getTileLayers()[0].baseUrl; var layer = C_NRCAN_RASTER.getTileLayers()[0].layer;} 
  //else {var baseUrl = this.baseUrl; var layer = this.layer;}
  var baseUrl = this.baseUrl; var layer = this.layer;
  var southWestPixel = new GPoint(tile.x*this.tileSize,(tile.y+1)*this.tileSize);
  var northEastPixel = new GPoint((tile.x+1)*this.tileSize,tile.y*this.tileSize);
  var southWestCoords = G_SATELLITE_MAP.getProjection().fromPixelToLatLng(southWestPixel,zoom);
  var northEastCoords = G_SATELLITE_MAP.getProjection().fromPixelToLatLng(northEastPixel,zoom);
  var bbox = southWestCoords.lng()+','+southWestCoords.lat()+','+northEastCoords.lng()+','+northEastCoords.lat();
  return baseUrl+'&layers='+layer+'&bbox='+bbox+'&width='+this.tileSize+'&height='+this.tileSize;
}

function customCreateMap(name,copyright,errorMessage,minResolution,maxResolution,tileSize,baseUrl) {
  var tileLayer = new GTileLayer(new GCopyrightCollection(copyright),minResolution,maxResolution);
  tileLayer.baseUrl = baseUrl;
  tileLayer.tileSize = tileSize;
  tileLayer.getTileUrl = function(tile,zoom) {return this.baseUrl;};
  tileLayer.getCopyright = function() { return { prefix:'',copyrightTexts:[copyright]}; };
  var tileLayers = [tileLayer];
  return new GMapType(tileLayers,G_SATELLITE_MAP.getProjection(),name,{errorMessage:errorMessage,tileSize:tileSize});
}

	



/**************************************************
 * End Custom map layers
 **************************************************/

/**************************************************
 * Custom map-type control:
 **************************************************
 *  These scripts were adapted from code in
 *  myGME - GSAK Google Maps Export
 *  by Mark Pelletier 
 *  posted on the GSAK discussion forum
 **************************************************
 * Various tweaks 
 * Rg - 2007-04 to 2008-04
 *   Rg 1.001 - set separate map type (NORMAL) for overview map
 *   Rg 1.002 - put in logic to detect map type changes 
 *     from outside and reset the selector.
 *   Rg 1.003 - remove call to Add_Custom_Layers()
 *     so it must go in the user's main line.
 *   Rg 1.004,5 - add Terrain map type (G_PHYSICAL_MAP).
 * Rg - 2009-09 - rename this file to "CustomMapTypesAndControl_V2.js"
 *   Rg C2.001 - add NRCan vector maps
 *   Rg C2.002 - put fix in for scale control problem when the map type changes
 *   Rg C2.003 - move above code to main line map program
 *   Rg C2.004 - clean out old unused logic for <div> type control, change name to selectorMapTypeControl
 *   Rg C2.005 - rename map types 
 **************************************************/

filter_map_types = (self.filter_map_types!=null) ? filter_map_types : true;

function selectorMapTypeControl() {}

  selectorMapTypeControl.prototype = new GControl();
  selectorMapTypeControl.prototype.initialize = function(map) {

  var map_types = [
    { label:'Map',    type:'G_NORMAL_MAP',      title:'Google street map',bounds:[-180,-90,180,90],excluded:[] }
   ,{ label:'Sat',    type:'G_SATELLITE_MAP',   title:'Google satellite map',bounds:[-180,-90,180,90],excluded:[] }
   ,{ label:'Hybrid', type:'G_HYBRID_MAP',      title:'Google "hybrid" map',bounds:[-180,-90,180,90],excluded:[] }
   ,{ label:'Terrain',type:'G_PHYSICAL_MAP',    title:'Google "terrain" map',bounds:[-180,-90,180,90],excluded:[] }
   ,{ label:'Earth',  type:'G_SATELLITE_3D_MAP',title:'Google "Earth" map',bounds:[-180,-90,180,90],excluded:[] }
   ,{ label:'Topo',   type:'C_USGS_TOPO',       title:'USGS topographic map',bounds:[-169,18,-66,72],excluded:[] }
   ,{ label:'Aerial', type:'C_USGS_AERIAL',     title:'USGS aerial photos (black/white)',bounds:[-152,17,-65,65],excluded:[] }
   ,{ label:'CanRas', type:'C_NRCAN_RASTER',    title:'NRCan/Toporama raster map',bounds:[-141,41.7,-52,85],excluded:[-141,41.7,-86,48] }
   ,{ label:'CanVec', type:'C_NRCAN_VECTOR',    title:'NRCan/Toporama vector map',bounds:[-141,41.7,-52,85],excluded:[-141,41.7,-86,48] }
   ,{ label:'Blank',  type:'C_BLANK',           title:'Blank map',bounds:[-180,-90,180,90],excluded:[] }
  ];

  this.map_types = map_types;

  var center_lat = map.getCenter().lat();
  var center_lng = map.getCenter().lng();

  var map_selector = document.createElement("select");
  map_selector.id = "map_selector";
  map_selector.style.fontFamily = "Verdana";
  map_selector.style.fontSize = "12px";
  map_selector.style.fontWeight = "bold";
  for (j=0; j<map_types.length; j++) {
    if (!filter_map_types || filter_map_types < 0 || ( (center_lng >= map_types[j]['bounds'][0] && center_lat >= map_types[j]['bounds'][1] && center_lng <= map_types[j]['bounds'][2] && center_lat <= map_types[j]['bounds'][3]) && !(center_lng >= map_types[j]['excluded'][0] && center_lat >= map_types[j]['excluded'][1] && center_lng <= map_types[j]['excluded'][2] && center_lat <= map_types[j]['excluded'][3]) ) ) {
      var opt = document.createElement("option");
      opt.value = map_types[j]['type'];
      opt.appendChild(document.createTextNode(map_types[j]['label']));
      map_selector.appendChild(opt);
      if (map.getCurrentMapType() == eval(opt.value)) { map_selector.selectedIndex = map_selector.length - 1; }
    }
  }

  GEvent.addDomListener(map_selector, "change", function(){
    map.setMapType(eval(this.value));
  });

  //Rg - add listener to set the selector to the correct map type if it changes from outside this code
  GEvent.addListener(map,"maptypechanged",function(){
    for (j=0; j<map_types.length; j++) {
      if (map.getCurrentMapType() == eval(map_types[j]['type'])) { map_selector.selectedIndex = j; }
    } 
  });
  
  map.getContainer().appendChild(map_selector);
    return map_selector;
}

selectorMapTypeControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(15,7));
}

/**************************************************
 * End Custom map-type control:
 **************************************************/