// Uses zoomlevel en mouseposition to call the nodelist.py view. View returns nodes in json format which is read and printed in document element.
function getNodeList(zoomlevel, mousepos){
  var nodelist;

  if (window.XMLHttpRequest){
    nodelist=new XMLHttpRequest();
  }
  else{
    nodelist=new ActiveXObject("Microsoft.XMLHTTP");
  }

  nodelist.onreadystatechange=function(){
    if (nodelist.readyState==4 && nodelist.status==200){
      json=eval('(' + nodelist.responseText + ')');
      var list = '<br>';
      for (var i=0; i<json.length; i++){
        list += json[i].fields.ssid + '<br>';
      }
      document.getElementById('nodelist').innerHTML=list;
    }
  }
  nodelist.open("GET","/website/nodelist/" + zoomlevel + "," + mousepos.lat + "," + mousepos.lon,true);
  nodelist.send();
}


// Retrieve form values for filter and pass them on to addFilter()
function filters(){
  var user = encodeURIComponent(document.getElementById("user").value);
  var dataset = encodeURIComponent(document.getElementById("dataset").value);
  var wlnode = encodeURIComponent(document.getElementById("wlnode").value);
  var enc = encodeURIComponent(document.getElementById("enc").value);
  var date = encodeURIComponent(document.getElementById("date").value);
  var colour = encodeURIComponent(document.getElementById("colour").value);
  var lname = encodeURIComponent(document.getElementById("lname").value);

  addFilter(user, dataset, wlnode, enc, date, colour, lname);
}


// Some value checks, create an overlay using these values and place it on the map.
function addFilter(user, dataset, wlnode, enc, date, colour, lname){

  if (user != ''){user='&accespoint__id='+user;} 
  if (dataset != ''){dataset='&meetrondje__naam='+dataset;} 
  if (wlnode != ''){wlnode='&accespoint__ssid='+wlnode;} 
  if (enc != ''){enc='&accespoint__encryptie='+enc;} 
  if (date != ''){date='&meetrondje__datum='+date;} 
  if (colour != ''){colour='colour='+colour;} 
  else {colour = '&colour='+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256);}
  if (lname != ''){lname=lname;} 
  else {lname = 'Custom Filter';}

  var baseurl = "/website/tile/${z}/${x},${y}.png?";

  OpenLayers.Layer.OSM.Overlay = OpenLayers.Class(OpenLayers.Layer.OSM, {
    initialize: function(name, options) {
      var url = [
        baseurl + colour + user + dataset + wlnode + enc + date
      ];
      options = OpenLayers.Util.extend({ numZoomLevels: 21 }, options);
      var newArguments = [name, url, options];
      OpenLayers.Layer.OSM.prototype.initialize.apply(this, newArguments);
    },
  CLASS_NAME: "OpenLayers.Layer.Overlay"
  });

  filterlayer = new OpenLayers.Layer.OSM.Overlay(lname, {isBaseLayer: false, visibility: true});
  map.addLayer(filterlayer);
}
