extends layout

block content
  //-
  mixin spi(name, field, expr, c)
    dt.context-menu-one #{name}
      input(id="SPIck-#{field}", type="checkbox", class="#{c}-group")
    dd(id="SPIda-#{field}", molochexpr=expr)

  mixin spion(name, field, expr, c)
    dt.context-menu-one #{name}
      input.spion(id="SPIck-#{field}", type="checkbox", class="#{c}-group")
    dd(id="SPIda-#{field}", molochexpr=expr)

  mixin title(name, c)
    h1 #{name}
      input(id="SPItck-#{c}-group", type="checkbox")

  script(src='jquery-jvectormap-1.2.2.min.js')
  script(src='jquery-jvectormap-world-en.js')
  script(src='jquery.autocomplete.js')
  script(src='jQuery-contextMenu/src/jquery.ui.position.js')
  script(src='jQuery-contextMenu/src/jquery.contextMenu.js')
  link(rel='stylesheet', type='text/css', href='jQuery-contextMenu/src/jquery.contextMenu.css')

  div(style="margin-bottom: 12px")
  div#bsqErr
  div#sessionsInfo.sessionsInfo
    div#world-map-wrapper.world-map-wrapper
      div#world-map.world-map
    div#sessionGraph.sessionGraph
    select#sessionGraphSelect
      option(value="lpHisto") sessions
      option(value="paHisto") packets
      option(value="dbHisto") databytes
  div#spiViewInfo
    span#recordsText
  div#spiview
    -var cats = Object.keys(categories).sort();
    -cats.splice(cats.indexOf("general"), 1);
    -cats.unshift("general");
    each ckey in cats
      -var cvalue = categories[ckey]
      +title(ckey, ckey)
      dl
        each fvalue,fkey in cvalue
          - if (fvalue.noFacet || fvalue.regex)
            - continue
          - else if (fvalue.dbField.match(/^(a1|a2|prot-term)/))
              +spion(fvalue.friendlyName, fvalue.dbField, fvalue.exp, ckey)
          - else if (fvalue.dbField.match(/\.snow$/))
            +spi(fvalue.friendlyName, fvalue.dbField.replace(".snow", ".raw"), fvalue.exp, ckey)
            +spi(fvalue.friendlyName + " Tokens", fvalue.dbField, fvalue.exp, ckey)
          - else if (fvalue.rawField)
              +spi(fvalue.friendlyName, fvalue.rawField, fvalue.exp, ckey)
              +spi(fvalue.friendlyName + " Tokens", fvalue.dbField, fvalue.exp, ckey)
          - else
              +spi(fvalue.friendlyName, fvalue.dbField, fvalue.exp, ckey)

  script(type='text/javascript').
    var initialDisplayLength = 100;
    var doPushState = 1;
    var fetchSize = {};
    var spiTerms = {};

    $(".spion").prop("checked", "checked");

    $(window).bind('popstate', function(e) {
      if (window.history.ready) {
        doPushState = 0;
        handleUrlParams();
        loadData();
      }
    });

    function fetchData(theQueue, state) {
      var params = buildParams();
      state += "&" + $.param(params);
      var url = "spiview.json?" + state;
      if (doPushState && state !== window.location.search.substring(1) && 'pushState' in history) {
        var fullstate = "";
        $("[id^=SPIck]").each(function(index, item) {
          var field = item.id.substring(6);
          if (fetchSize[field]) {
            fullstate += "," + field + ":" + fetchSize[field];
          } else if ($(item).prop("checked")) {
            fullstate += "," + field + ":100";
          }
        });
        fullstate += "&" + $.param(params);
        history.pushState({}, this.title || '', "spiview?spi=" + fullstate.substring(1));
      } else {
        doPushState = 1;
      }

      $.ajaxQueue(theQueue, {
         "dataType": 'json',
          "type": "GET",
          "url": url,
          "success": function (json) {
            updateHealth(json.health);

            if (json.lpHisto && json.lpHisto[0]) {
              if ($("#startDate").val() === "") {
                $("#startDate").val(dateString(json.lpHisto[0][0]/1000, ' '));
              }
              if ($("#stopDate").val() === "") {
                $("#stopDate").val(dateString(json.lpHisto[json.lpHisto.length-1][0]/1000) + 59, ' ');
              }
            }

            updateGraph(json.graph);
            updateMap(json.map);
            updateString("#bsqErr", json.bsqErr);

            $("#actionsForm").data("moloch-visible", -1)
                             .data("moloch-all", json.iTotalDisplayRecords);
            $("#recordsText").text("Showing " + numberWithCommas(json.iTotalDisplayRecords) + " entries filtered from " + numberWithCommas(json.iTotalRecords) + " total entries");

            $.each(json.spi, function(spii, spi) {
              var spida = $("[id='SPIda-" + spii + "']");
              if (spi.terms.length !== 0) {
                spida.text("");
              } else {
                spida.html("&nbsp;");
              }

              var spiterm = "";
              var finfo = db2Field(spii);
              if (spii.match(/^(a1|a2|xff|dnsip|eip|socksip)$/) !== null ||
                  (finfo && finfo.type === "ip")) {
                $.each(spi.terms, function(i, term) {
                  if (i !== 0) {
                    spida.append(", ");
                    spiterm += ",";
                  }
                  spiterm += ipString(term.term);
                  spida.append($('<a></a>').attr("href","#")
                                           .text(ipString(term.term))
                                           .click(function() {
                                             addExpression(spida.attr("molochexpr") + "==" + ipString(term.term));
                                             return false;
                                           }));
                  spida.append("<span class=\"spicount\">(" + term.count + ")</span>");
                });
              } else if (finfo && finfo.type === "seconds") {
                $.each(spi.terms, function(i, term) {
                  if (i !== 0) {
                    spida.append(", ");
                    spiterm += ",";
                  }
                  spiterm += dateString(term.term, " ");
                  spida.append($('<a></a>').attr("href","#")
                                           .text(dateString(term.term, " "))
                                           .click(function() {
                                             addExpression(spida.attr("molochexpr") + "==" + dateString(term.term, " "));
                                             return false;
                                           }));
                  spida.append("<span class=\"spicount\">(" + term.count + ")</span>");
                });
              } else {
                $.each(spi.terms, function(i, term) {
                  if (i !== 0) {
                    spida.append(", ");
                    spiterm += ",";
                  }
                  var quoted = term.term;
                  if (typeof term.term == "string" && term.term.match(/[^\w]/)) {
                    quoted = '"' + quoted + '"';
                  }
                  spiterm += quoted;
                  spida.append($('<a></a>').attr("href","#")
                                           .text(""+term.term)
                                           .click(function() {
                                             addExpression(spida.attr("molochexpr") + "==" + quoted);
                                             return false;
                                           }));
                  spida.append("<span class=\"spicount\">(" + term.count + ")</span>");
                });
              }
              spiTerms[spii] = spiterm;

              if (spi.other > 0) {
                  spida.append(", <a href=\"#\" onclick='return moreSPI(\"" +
                               spii +
                               "\");'</a> &hellip;</a>");
                  spida.append("<span class=\"spicount\">(" + spi.other + ")</span>");
              }
            });
          }
      });
    }

    function fetchState(item, append) {
      var field = item.attr('id').substring(6);
      var state = "";

      var spida = $("[id='SPIda-" + field + "']");
      if (item.prop("checked")) {
        if (!fetchSize[field]) {
          fetchSize[field] = 100;
        }
        state = field + ":" + fetchSize[field];
        if (append) {
          spida.append(" <img src=\"spinning.gif\">");
        } else {
          spida.html("<img src=\"spinning.gif\">");
        }
      } else {
        delete fetchSize[field];
        spida.html("&nbsp;");
      }
      return state;
    }
    var loadQueue = $({});
    var clickQueue = $({});

    function loadData() {
      loadQueue.clearQueue();
      clickQueue.clearQueue();

      var state = "facets=1&spi=";
      var num = 0;
      $("[id^=SPIck]").each(function(index, item) {
        var istate = fetchState($(item), false);

        if (istate !== "") {
          if (num > 0) {
            state += ",";
          }
          num++;
          state += istate;
          if (num === 3) {
            fetchData(loadQueue, state);
            num = 0;
            state = "spi=";
          }
        }
      });

      if (num > 0) {
        fetchData(loadQueue, state);
      }
    }

    function moreSPI(spii) {
      var spick = $("[id='SPIck-" + spii + "']");
      if (fetchSize[spii]) {
        fetchSize[spii] += 100;
      }
      var state = fetchState(spick, true);
      fetchData(clickQueue, "spi=" + state);
      return false;
    }

    $('#searchForm').submit(function() {
      loadData();
      return false;
    });

    $(window).resize(function(e) {
      expressionResize();
    });

    $(":checkbox").on('change', function(e) {
      if (e.target.id.match(/SPItck/)) {
        var item = $(e.target);
        if (item.prop("checked")) {
          $("." + e.target.id.substring(7)).each(function() {
            $(this).prop("checked", "checked").triggerHandler('change');
          });
        } else {
          $("." + e.target.id.substring(7)).each(function() {
            $(this).prop("checked", false).triggerHandler('change');
          });
        }
        return true;
      }
      var state = fetchState($(e.target), true);
      if (state !== "") {
        fetchData(clickQueue, "spi=" + state);
      }
      return false;
    });

    $(document).ready(function() {
      var initialParams = handleUrlParams();
      if (initialParams.spi) {
        initialParams.spi.split(",").forEach(function (item) {
          var parts = item.split(":");
          var spick = $("[id='SPIck-" + parts[0] + "']");
          fetchSize[parts[0]] = +parts[1];
          spick.prop("checked", "checked");
        });
      }

      loadData();

      setupGraph();
      expressionResize();
      setupMap();

      $.contextMenu({
          selector: '.context-menu-one',
          build: function($trigger, e) {
            var checkbox = $(e.target).find("input");
            items = {
              spigraph: {name: "Open SPI Graph " + $(e.target).text(), mtype:0, field: checkbox.attr("id").substring(6)},
              items: {name: "Export Unique " + $(e.target).text(), mtype:1, counts:0, field: checkbox.attr("id").substring(6)},
              itemcounts: {name: "Export Unique " + $(e.target).text() + " with Counts", mtype:1, counts:1, field: checkbox.attr("id").substring(6)},
              pivot: {name: "Pivot on " + $(e.target).text(), mtype:2, counts:0, field: checkbox.attr("id").substring(6)}
            };
            return {
              callback: function(key, options) {
                var params = buildParams();
                var url;

                if (items[key].mtype === 2) {
                  var spida = $("[id='SPIda-" + items[key].field + "']");
                  var str = spida.attr("molochexpr") + " == [" + spiTerms[items[key].field] + "]";

                  $("#expression").val(str);
                  return true;
                } else if (items[key].mtype === 0) {
                  params.push({name:'field', value:items[key].field});
                  url = "spigraph?" + $.param(params);
                } else {
                  params.push({name:'field', value:items[key].field});
                  params.push({name:'counts', value:items[key].counts});
                  url = "unique.txt?" + $.param(params);
                }

                window.open(url);
              },
              items: items
            };
          }
      });

      var searchStuffOffset = $('#searchStuff').offset().top;
      $(window).scroll(function () {
        var scrollTop = $(window).scrollTop(); // check the visible top of the browser

        if (searchStuffOffset < scrollTop) {
          $('#searchStuff').addClass('fixedsearch');
          $('#logo').hide();
        } else {
          $('#searchStuff').removeClass('fixedsearch');
          $('#logo').show();
        }
      });
    });

