// Base stolen from http://java.sun.com/developer/technicalArticles/J2EE/AJAX/RealtimeValidation/
function AjaxRequest(url, callback, filter, field) {

  var req = init();
  req.onreadystatechange = processRequest;
        
  function init() {
    if (window.XMLHttpRequest) {
      return new XMLHttpRequest();
    } else if (window.ActiveXObject) {
      return new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
    
  function processRequest () {
    if (req.readyState == 4) {
      if (req.status == 200) {
        if (callback) {
          if (filter) callback(filter, field, req.responseText);
          else callback(req.responseText);
        }
      }
    }
  }

  this.doGet = function() {
    req.open("GET", url, true);
    req.send(null);
  }
}


// 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 url = "/website/nodelist/" + zoomlevel + "," + mousepos.lat + "," + mousepos.lon;
  var ajax = new AjaxRequest(url, setNodeList); 
  ajax.doGet(); 
}


function setNodeList(responseText) {
  json=eval('(' + responseText + ')');
  if (json.length>0){
    list = 'Wireless Leiden nodes on mouseposition:<br /><b>';
    for (var i=0; i<json.length; i++){
      list += json[i].fields.ssid + '<br />';
    }
    list += '</b>';
  }
  else{
    list = 'No nodes to display.';
  }
  document.getElementById('node_list').innerHTML=list;
}


function get_filters() {

  // Create form
  var formstart = '<form method="get" action="">';
  var formend = '<input type="button" value="Add filter" onClick="addFilter()"/></form>';
  var layername = '<input type="text" id="lname" name="lname" size="10"/> Layername<br />';
  var colour = '<input type="text" id="colour" name="colour" size="10"/> Colour<br />';
  var user = '<select id="user" style="width:104px"><option></option></select> User<br />';
  var dataset = '<select id="dataset" style="width:104px"><option></option></select> Dataset<br />';
  var node = '<select id="node" style="width:104px"><option></option></select> Node<br />';
  var enc = '<select id="enc" style="width:104px"><option></option></select> Encryption<br />';
  var date = '<select id="date" style="width:104px"><option></option></select> Date<br />';

  // Write form to document
  document.getElementById('filter_list').innerHTML+=(formstart + user + dataset + node + enc + date + colour + layername + formend);
  
  // Get values for select boxes
  // filters[] first value is what to get, second value is which field values will be shown in select box
  var filters = [['user','naam'],['dataset','naam'],['node','ssid']]
  for (var i=0; i<filters.length; i++) {
    get_json(filters[i][0], filters[i][1]);
  }
}


function get_json(filter, field) {
  var url = "/website/filter/filter_" + filter;
  var ajax = new AjaxRequest(url, set_filter, filter, field); 
  ajax.doGet(); 
}


function set_filter(filter, field, responseText) {
  json=eval('(' + responseText + ')');
  var options = '';
  for (var i=0; i<json.length; i++){
    options += '<option>' + json[i].fields[field] + '</option>';
  }
  document.getElementById(filter).innerHTML+=options;
}


function addFilter(){

  var user = encodeURIComponent(document.getElementById("user").value);
  var dataset = encodeURIComponent(document.getElementById("dataset").value);
  var wlnode = encodeURIComponent(document.getElementById("node").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);

  if (user != ''){user='&gebruiker__naam='+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);
}
