// Base stolen from http://java.sun.com/developer/technicalArticles/J2EE/AJAX/RealtimeValidation/
var json;
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) {
          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_nodelist=eval('(' + responseText + ')');
  if (json_nodelist.length>0){
    list = 'Wireless Leiden nodes on mouseposition:<br /><b>';
    for (var i=0; i<json_nodelist.length; i++){
      list += json_nodelist[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" onchange=filter_user()></select> User<br />';
  var dataset = '<select id="dataset" style="width:104px" onchange=filter_node()></select> Dataset<br />';
  var node = '<select id="node" style="width:104px" onchange=update_filters(this.id)></select> Node<br />';
  var enc = '<select id="enc" style="width:104px"></select> Encryption<br />';
  var date = '<select id="date" style="width:104px" onchange=filter_date()></select> Date<br />';

  // Write form to document
  document.getElementById('filter_list').innerHTML+=(formstart + date + user + dataset + node + enc + colour + layername + formend);
  
  // Request JSON with filter values
  var url = "/website/foofilter";
  var ajax = new AjaxRequest(url, set_filters); 
  ajax.doGet(); 
}


function set_filters(responseText) {
  json=eval('(' + responseText + ')');
  var user = '<option>Select user</option><option>All</option>';
  var dataset = '<option>Select dataset</option><option>All</option>';
  var date = '<option>Select date</option><option>All</option>';
  var node = '<option>Select node</option><option>All</option>';
  for (var i=0; i<json.length; i++){
    user += '<option>' + json[i].gebruiker + '</option>';
    for (m in json[i].meetrondje){
      dataset += '<option>' + json[i].meetrondje[m].naam + '</option>';
      date += '<option>' + json[i].meetrondje[m].datum + '</option>';
      for (n in json[i].meetrondje[m].nodes){
        node += '<option>' + json[i].meetrondje[m].nodes[n] + '</option>';
      }
    }
  }
  document.getElementById('user').innerHTML=user;
  document.getElementById('dataset').innerHTML=dataset;
  document.getElementById('date').innerHTML=date;
  document.getElementById('node').innerHTML=node;
}


function addFilter(){

  var user = $('#user option:selected').text();
  var dataset = $('#dataset option:selected').text();
  var wlnode = $('#wlnode option:selected').text();
  var enc = $('#enc option:selected').text();
  var date = $('#date option:selected').text();
  var colour = encodeURIComponent(document.getElementById("colour").value);
  var lname = encodeURIComponent(document.getElementById("lname").value);

  if ((user != 'Select user') && (user != 'All')){user='&meetrondje__gebruiker__naam='+user;}
  else{user='';}
  if ((dataset != 'Select dataset') && (dataset != 'All')){dataset='&meetrondje__naam='+dataset;} 
  else{dataset='';}
  if ((wlnode != 'Select node') && (dataset != 'All')){wlnode='&accespoint__ssid='+wlnode;} 
  else{wlnode='';}
  if (enc != ''){enc='&accespoint__encryptie='+enc;} 
  if ((date != 'Select date') && (date != 'All')){date='&meetrondje__datum='+date;} 
  else{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
      ];
      document.getElementById('filter_text').innerHTML+="<br />Added: " + url;
      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);
}
