/**
 * Var 'map' is set global, used in 'heatmap_extensions.js'.
 */
var map;

function init_heatmap(){
  var lat = getURLParameter('lat');
  var lon = getURLParameter('lon');
  var zoom = getURLParameter('zoom');

  if(lat=='null' || lon=='null' || zoom=='null'){
    var lat   = 52.15514;
    var lon   = 4.48959;
    var zoom  = 13;
  }
  var projection_wgs = new OpenLayers.Projection("EPSG:4326"); // WGS 1984

  map = new OpenLayers.Map('heatmap', {
    theme: null,
    controls: [
      new OpenLayers.Control.Navigation(),
      new OpenLayers.Control.Permalink({
        anchor : false,
        createParams: function(center, zoom, layers) {
          center = center || this.map.getCenter();
    
          var params = OpenLayers.Util.getParameters(this.base);
    
          // If there's still no center, map is not initialized yet. 
          // Break out of this function, and simply return the params from the
          // base link.
          if (center) {
    
              //zoom
              params.zoom = zoom || this.map.getZoom();
    
              //lon,lat
              var lat = center.lat;
              var lon = center.lon;
    
              if (this.displayProjection) {
                  var mapPosition = OpenLayers.Projection.transform(
                    { x: lon, y: lat },
                    this.map.getProjectionObject(),
                    this.displayProjection );
                  lon = mapPosition.x;
                  lat = mapPosition.y;
              }
              params.lat = Math.round(lat*100000)/100000;
              params.lon = Math.round(lon*100000)/100000;
    
              //layers        
              layers = layers || this.map.layers;
              params.layers = '';
              for (var i=0, len=layers.length; i<len; i++) {
                  var layer = layers[i];
    
                  if (layer.isBaseLayer) {
                      params.layers += (layer == this.map.baseLayer) ? "B" : "0";
                  } else {
                      params.layers += (layer.getVisibility()) ? "T" : "F";
                  }
              }
              // Update permalink URL to reflect new location and filters
              layerid = 0;
              // First two and last one should be ignored
              for (var i=4, len=layers.length; i < len; i++) {
                var layer = layers[i];
                if ($.isArray(layer.url)) {
                  var url = layer.url[0];
                } else {
                  var url = layer.url;
                }
                var filter = url.split('?')[1];
                layerid += 1;
                params['layername' + layerid] = layer.name;
                params['layercolour' + layerid] = layer.colour;
                params['layerfilter' + layerid] = filter;
              }
              params['layercount']  = layerid;
          }
          return params;
        },
        draw: function() {
          OpenLayers.Control.prototype.draw.apply(this, arguments);

          if (!this.element && !this.anchor) {
            this.element = document.createElement("a");
            this.element.innerHTML = OpenLayers.i18n("Permalink");
            this.element.href="";
            this.div.appendChild(this.element);
          }
          this.map.events.on({
            'moveend': this.updateLink,
            'changelayer': this.updateLink,
            'addlayer': this.updateLink,
            'removelayer': this.updateLink,
            'changebaselayer': this.updateLink,
            scope: this
          });

          // Make it so there is at least a link even though the map may not have
          // moved yet.
          this.updateLink();

          return this.div;
        },
      }),
      new OpenLayers.Control.PanZoomBar(),
      new OpenLayers.Control.ZoomBox(),
      new OpenLayers.Control.OverviewMap({ 
        maximized : false,
        mapOptions: { theme: null }
      }),
      new OpenLayers.Control.MousePosition({ 'displayProjection' : projection_wgs })
      /**
       * Decided to disable these controls.
       * The layerswitcher has been replaced with a custom one. If you want the original back,
       * make sure to disable the custom one to prevent collision.
       */

      //new OpenLayers.Control.PanZoomBav(),
      //new OpenLayers.Control.ScaleLine(),
      //new OpenLayers.Control.LayerSwitcher(),
    ],
    maxExtent: new OpenLayers.Bounds(-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892), 
    numZoomLevels:16, 
    maxResolution:156543.0339, 
    units:'m', 
    projection: "EPSG:900913",
    displayProjection: new OpenLayers.Projection("EPSG:4326")
  });

  map.events.register('click', map, GetMousePos);
  function GetMousePos(pos) {
    var pix = map.getLonLatFromPixel(new OpenLayers.Pixel(pos.xy.x,pos.xy.y));
    var mousepos = OpenLayers.Layer.SphericalMercator.inverseMercator(pix.lon, pix.lat);
    var zoomlevel = map.getZoom();
    getNodeList(zoom, mousepos);
  }

  layerMapnik = new OpenLayers.Layer.OSM.Mapnik("Mapnik");
  map.addLayer(layerMapnik);

  var lonLat = new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
  map.setCenter (lonLat, zoom);


  /**
   * Layers are created and put in switcher
   */
  function add_item(category, layer) {
    map.addLayer(layer);
    var checked = '';
    if (layer.getVisibility()) { checked = "checked='checked'"; };
    $("#" + category).append("<span id=\"" + layer.name + "\">" +
     " <div id='layer_switcher_colour' style='background-color:rgb(" + layer.colour + ")' />" +
     "<input type='checkbox' id='togglelayer' " + checked + " /><font>" + layer.name + " </font><br /></span>"
     );
  }

  var signallayer = new OpenLayers.Layer.OSM.Overlay4("signallayer", {isBaseLayer: false, visibility: false});
  var wlsignalLayer = new OpenLayers.Layer.OSM.Overlay3("Wireless Leiden Coverage", {isBaseLayer: false, visibility: true});
  var nodesLayer = new OpenLayers.Layer.GML.NodesOverlay("Node Locations", {isBaseLayer: false, visibility: false});

  add_item('default', signallayer);
  add_item('default', wlsignalLayer);
  add_item('features', nodesLayer);
}
