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

  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, 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() {
  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 />';

  document.getElementById('filter_list').innerHTML+=formstart;
  document.getElementById('filter_list').innerHTML+=user;

  var filters = new Array('user');
  for (var i=0; i<filters.length; i++) {
    get_json(filters[i]);
  }

  // todo: Fix formend, it is called before the 'for' filter is completed, making the form look silly.
  document.getElementById('filter_list').innerHTML+=formend;
}


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


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


function addFilter(){

  var user = encodeURIComponent(document.getElementById("user").value);
  var dataset = '';
  var wlnode = '';
  var enc ='';
  var date = '';
  var colour = '';
  var lname = '';

  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);
}


/*

The following code is old, broken and for reference purposes. Will be removed when new code is done.
The above (new) code was used instead to make everything more easy when adding new pieces.

// Get filter values from django view and serve as option list
function getFilters(){
  var filterlist;
  var nodelist;
  var userlist;
  var datasetlist;

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

  var list = '<form method="get" action="">';


  // todo: Get new options if one option is selected; every user has different datasets, make sure when user 'John' is selected, you can only choose datasets who are his.

  userlist.onreadystatechange=function(){
    if (userlist.readyState==4 && userlist.status==200){
      userlist=eval('(' + userlist.responseText + ')');
      
      list += '<select id="user" style="width:104px"><option></option>';
      for (var i=0; i<userlist.length; i++){
        list += '<option>' + userlist[i].fields.naam + '</option>';
      }
      list += '</select> User<br />';

      document.getElementById('filter_list').innerHTML=list;
    }
  }




  nodelist.onreadystatechange=function(){
    if (nodelist.readyState==4 && nodelist.status==200){
      nodelist=eval('(' + nodelist.responseText + ')');

      list += '<select id="wlnode" style="width:104px"><option></option>';
      for (var i=0; i<nodelist.length; i++){
        list += '<option>' + nodelist[i].fields.ssid + '</option>';
      }
      list += '</select> WLnode<br />';

      document.getElementById('filter_list').innerHTML=list;
    }
  }


  datasetlist.onreadystatechange=function(){
    if (datasetlist.readyState==4 && datasetlist.status==200){
      datasetlist=eval('(' + datasetlist.responseText + ')');

      list += '<select id="dataset" style="width:104px"><option></option>';
      for (var i=0; i<datasetlist.length; i++){
        list += '<option>' + datasetlist[i].fields.naam + '</option>';
      }
      list += '</select> Dataset<br />';

      document.getElementById('filter_list').innerHTML=list;
    }
  }


  list += '<input type="text" id="enc" name="enc" size="10"/> Encrypted<br />';
  list += '<input type="text" id="colour" name="colour" size="10"/> Colour<br />';
  list += '<input type="text" id="lname" name="lname" size="10"/> Layername<br />';
  list += '<input type="button" value="Add filter" onClick="addFilter()"/>';
  list += '</form>';





  nodelist.open("GET","/website/filters/1",true);
  nodelist.send();
  userlist.open("GET","/website/filters/2",true);
  userlist.send();
  datasetlist.open("GET","/website/filters/3",true);
  datasetlist.send();
}
*/
