// Uses zoomlevel and 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){
  $.getJSON("/website/nodelist/" + zoomlevel + "," + mousepos.lat + "," + mousepos.lon, 
    function(json){
      content = 'Wireless Leiden nodes on mouseposition:<br /><b>';
      $.each(json, function(i,json){
        content += json.fields.ssid + '<br />';
      });
      content += '</b>';
      $("#node_list").html(content);
    }
  );
}

// Right way to get url parameters?: http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery/1404100#1404100
function getURLParameter(name) {
  return decodeURI(
    (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
  );
}

$(document).ready(function() {
  var signallayer = '';
  var userlist = new Array();
  var nodelist = new Array();

  // add colour picker
  $("#colour").colorPicker();

  // add date picker for start date
  $("#start_date").datepicker({
    dateFormat: "dd/mm/yy",
    onSelect: function(dateValue, inst){
      $("#end_date").datepicker("option", "minDate", dateValue);
    }
  });

  // add date picker for end date
  $("#end_date").datepicker({
    dateFormat: "dd/mm/yy",
  });

  // add slider for signal strength filter
  $("#slider").slider({
    range: true,
    min: 0,
    max: 100,
    values: [0, 100],
    // while sliding, it changes the text above the slider to show the values realtime
    slide: function(event, sig){
      $("#sig_value").text("Signal strength: " + sig.values[0] + " - " + sig.values[1]);
    },
    // on slider stop, it tries to delete the old layer and creates a new layer with the slider values
    stop: function(event, sig){
      if(signallayer){
        map.removeLayer(signallayer);
      }
      OpenLayers.Layer.OSM.Overlay = OpenLayers.Class(OpenLayers.Layer.OSM, {
        initialize: function(name, options) {
          var url = [
            "/website/tile/${z}/${x},${y}.png?colour=250,250,0&signaal__gte=" + sig.values[0] + "&signaal__lte=" + sig.values[1]
          ];
          options = OpenLayers.Util.extend({ numZoomLevels: 21 }, options);
          var newArguments = [name, url, options];
          OpenLayers.Layer.OSM.prototype.initialize.apply(this, newArguments);
        },
      SWITCHER_CLASS: "signal",
      CLASS_NAME: "OpenLayers.Layer.Overlay"
      });
      lname = "Signal strength: " + sig.values[0] + " - " + sig.values[1];
      signallayer = new OpenLayers.Layer.OSM.Overlay(lname, {isBaseLayer: false, visibility: true});
      map.addLayer(signallayer);
    },
  });

  var testarray = new Array();
  $("#filter_text").append("<a id=remove>Get layers</a><br />");
  $("#remove").click(function(){
    testarray = map.getLayersByClass("OpenLayers.Layer.Overlay");
    $.each(testarray, function(v, value){
      colour = value.SWITCHER_COLOUR;
      $("#filter_text").append("<span id=\"" + value.name + "\"><input type=checkbox id=togglelayer /><font style='color:rgb(" + colour + ")'>" + value.name + " </font><a id=rmvlayer>X</a><br /></span>");
    });
  });

  $("#togglelayer").live("click", function(){
    status = $(this).attr("checked");
    layername = $(this).parents('span').attr('id');
    layer = map.getLayersByName(layername);
    layer[0].setVisibility(status);
  }); 

  $("#rmvlayer").live("click", function(){
    layername = $(this).parents('span').attr('id');
    layer = map.getLayersByName(layername);
    $("#filter_text").append("<br />Removed " + layername);
    map.removeLayer(layer[0]);
    $(this).parents('span').remove();
  });

  // menu toggle
  $("#menu_filter").click(function(){
    $("#filter").slideToggle("fast");
    $("#info").slideUp("fast");
  });
  $("#menu_info").click(function(){
    $("#filter").slideUp("fast");
    $("#info").slideToggle("fast"); 
  });

  // Fastest?: http://stackoverflow.com/questions/170986/what-is-the-best-way-to-add-options-to-a-select-from-an-array-with-jquery
  $.getJSON("/website/filters/",
    function(json) {
      $.each(json, function(i,json){
        $("#select_user").append($("<option/>").attr("value",json.gebruiker).text(json.gebruiker));
        userlist.push(json.gebruiker);
        $.each(json.meetrondje, function(m, meetrondje){
          $("#select_dataset").append($("<option/>").attr({"class":json.gebruiker, "value":meetrondje.naam}).text(meetrondje.naam));
          $.each(meetrondje.nodes, function(n, nodes){
            $("#select_node").append($("<option/>").attr({"class":meetrondje.naam, "value":nodes}).text(nodes));
            if(jQuery.inArray(nodes, nodelist)<0){
              nodelist.push(nodes);
            }
          });
        });
      });
    // Initiate the chain
    $("#select_dataset").chained("#select_user");
    $("#select_node").chained("#select_dataset");
    }
  );

  // add filter per user
  $('#user_filter').click(function(){
    if(this.value=='Add userfilter'){
      $.each(userlist, function(u, user){
        colour = Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256);
        OpenLayers.Layer.OSM.Overlay = OpenLayers.Class(OpenLayers.Layer.OSM, {
          initialize: function(name, options) {
            var url = [
              "/website/tile/${z}/${x},${y}.png?&colour=" + colour + "&meetrondje__gebruiker__naam=" + user
            ];
            options = OpenLayers.Util.extend({ numZoomLevels: 21 }, options);
            var newArguments = [name, url, options];
            OpenLayers.Layer.OSM.prototype.initialize.apply(this, newArguments);
          },
        SWITCHER_COLOUR: colour,
        SWITCHER_CLASS: "user",
        CLASS_NAME: "OpenLayers.Layer.Overlay"
        });
        filterlayer = new OpenLayers.Layer.OSM.Overlay("User: "+ user, {isBaseLayer: false, visibility: true});
        map.addLayer(filterlayer);
      });
      $(this).attr('value', 'Del userfilter');
    }
    else{
      $(this).attr('value', 'Add userfilter');
      $.each(userlist, function(u, user){
        layer = map.getLayersByName('User: ' + user);
        map.removeLayer(layer[0]);
      });
    }
  });

  // add filter per node
  $('#node_filter').click(function(){
    if(this.value=='Add nodefilter'){
      $.each(nodelist, function(n, node){
        colour = Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256);
        OpenLayers.Layer.OSM.Overlay = OpenLayers.Class(OpenLayers.Layer.OSM, {
          initialize: function(name, options) {
            var url = [
              "/website/tile/${z}/${x},${y}.png?&colour=" + colour + "&accespoint__ssid=" + node
            ];
            options = OpenLayers.Util.extend({ numZoomLevels: 21 }, options);
            var newArguments = [name, url, options];
            OpenLayers.Layer.OSM.prototype.initialize.apply(this, newArguments);
          },
        SWITCHER_COLOUR: colour,
        SWITCHER_CLASS: "node",
        CLASS_NAME: "OpenLayers.Layer.Overlay"
        });
        nodefilterlayer = new OpenLayers.Layer.OSM.Overlay("Node: "+ node, {isBaseLayer: false, visibility: true});
        map.addLayer(nodefilterlayer);
        console.log(nodefilterlayer);
      });
      $(this).attr('value', 'Del nodefilter');
    }
    else{
      $(this).attr('value', 'Add nodefilter');
      $.each(nodelist, function(n, node){
        layer = map.getLayersByName('Node: ' + node);
        map.removeLayer(layer[0]);
      });
    }
  });

  // add custom filter
  $('#add_filter').click(function(){
    //get values from elements
    user = $('#select_user option:selected').text();
    dataset = $('#select_dataset option:selected').text();
    wlnode = $('#select_node option:selected').text();
    start_date = $('#start_date').val();
    end_date = $('#end_date').val();
    colour = encodeURIComponent(document.getElementById("colour").value);
    lname = encodeURIComponent(document.getElementById("lname").value);

    // HEX to RGB: http://stackoverflow.com/questions/5798868/need-some-tips-with-how-to-convert-a-hexadecimal-color-value-to-a-rgb-one/5798900#5798900
    // '#' comes out as '%23', so substr() starts at char 3
    colour = parseInt((colour.substr(3, 2)),16) + ',' + parseInt((colour.substr(5, 2)),16) + ',' + parseInt((colour.substr(7, 2)),16);

    // some checks if values are correct, and adding them to parts of the link
    if (user != ''){user='&meetrondje__gebruiker__naam='+user;}
    if (dataset != ''){dataset='&meetrondje__naam='+dataset;} 
    if (wlnode != ''){wlnode='&accespoint__ssid='+wlnode;}
    if (start_date && end_date){
      sd_d=start_date.substr(0,2);
      sd_m=start_date.substr(3,2);
      sd_y=start_date.substr(6,4);

      ed_d=end_date.substr(0,2);
      ed_m=end_date.substr(3,2);
      ed_y=end_date.substr(6,4);

      start_date='&meetrondje__datum__gte=' + sd_y +'-'+ sd_m +'-'+ sd_d;
      end_date='&meetrondje__datum__lte=' + ed_y +'-'+ ed_m +'-'+ ed_d;
    }
    if (start_date && !end_date){
      sd_d=start_date.substr(0,2);
      sd_m=start_date.substr(3,2);
      sd_y=start_date.substr(6,4);
      start_date='&meetrondje__datum__gte=' + sd_y +'-'+ sd_m +'-'+ sd_d;
      end_date='';
    }
    if (!start_date && end_date){
      ed_d=end_date.substr(0,2);
      ed_m=end_date.substr(3,2);
      ed_y=end_date.substr(6,4);
      start_date='';
      end_date='&meetrondje__datum__lte=' + ed_y +'-'+ ed_m +'-'+ ed_d;
    }
    if (colour != 'NaN,NaN,NaN'){colour=colour;} 
    else {colour = Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256)+','+Math.floor(Math.random()*256);}
    if (lname != ''){lname=lname;} 
    else {lname = 'Custom Filter';}

    // setting layer
    OpenLayers.Layer.OSM.Overlay = OpenLayers.Class(OpenLayers.Layer.OSM, {
      initialize: function(name, options) {
        var url = [
          "/website/tile/${z}/${x},${y}.png?&colour=" + colour + user + dataset + wlnode + start_date + end_date 
        ];
        options = OpenLayers.Util.extend({ numZoomLevels: 21 }, options);
        var newArguments = [name, url, options];
        OpenLayers.Layer.OSM.prototype.initialize.apply(this, newArguments);
      },
    SWITCHER_COLOURL: colour,
    SWITCHER_CLASS: "custom",
    CLASS_NAME: "OpenLayers.Layer.Overlay"
    });

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