// 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=update_filters(this.id)><option></option></select> User<br />';
  var dataset = '<select id="dataset" style="width:104px" onchange=update_filters(this.id)><option></option></select> Dataset<br />';
  var node = '<select id="node" style="width:104px" onchange=update_filters(this.id)><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" onchange=update_filters(this.id)><option></option></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 value="empty"></option>';
  var dataset = '<option value="empty"></option>';
  var date = '<option value="empty"></option>';
  for (var i=0; i<json.length; i++){
    user += '<option value="user">' + json[i].gebruiker + '</option>';
    for (m in json[i].meetrondje){
      dataset += '<option value="dataset">' + json[i].meetrondje[m].naam + '</option>';
      date += '<option value="date">' + json[i].meetrondje[m].datum + '</option>';
    }
  }
  document.getElementById('user').innerHTML=user;
  document.getElementById('dataset').innerHTML=dataset;
  document.getElementById('date').innerHTML=date;
}




function update_filters(filter_id){
  var user_text = $('#user option:selected').text();
  var user_val = $('#user option:selected').val();
  var dataset_text = $('#dataset option:selected').text();
  var user = '<option value="empty"></option>';
  var dataset = '<option value="empty"></option>';

  if (filter_id=='user'){
    if (!user_text){
      for (var i=0; i<json.length; i++){
        for (m in json[i].meetrondje){
          dataset += '<option value="dataset">' + json[i].meetrondje[m].naam + '</option>';
        }
      }
    }
    else{
      for (var i=0; i<json.length; i++){
        for (m in json[i].meetrondje){
          if (json[i].gebruiker == user_text){
            dataset += '<option value="dataset">' + json[i].meetrondje[m].naam + '</option>';
          }
        }
      }
    }
  document.getElementById('dataset').innerHTML=dataset;
  }
}





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 != ''){user='&meetrondje__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);
}
