<commit_before>/**
 * # WaitRoomView widget for nodeGame
 * Copyright(c) 2019 Stefano Balietti
 * MIT Licensed
 *
 * Shows requirements settings
 *
 * www.nodegame.org
 * ---
 */

(function(node) {
  ("use strict");

  node.widgets.register("WaitRoomView", WaitRoomView);

  var JSUS = node.JSUS;

  // ## Meta-data

  WaitRoomView.version = "0.0.1";
  WaitRoomView.description = "Displays a waitroom settings.";

  WaitRoomView.title = "WaitRoom Settings";
  WaitRoomView.className = "waitroomview";

  // ## Dependencies
  WaitRoomView.dependencies = {
    JSUS: {},
    Table: {}
  };

  var originalTable = {};

  function WaitRoomView(options) {
    var that = this;
    this.table = new W.Table({
      className: "table table-striped viewer",
      id: "settingsTable",
      render: {
        pipeline: function(item) {
          //x = 0 y = 0 first row first column
          //x = 0 y = 1 first row second column
          if (originalTable[item.x] === undefined) {
            originalTable[item.x] = {};
          }
          if (item.y % 2 === 0) {
            originalTable[item.x]["content"] = item.content;
            return document.createTextNode(item.content + ": ");
          } else if (item.y % 2 === 1) {
            originalTable[item.x]["value"] = item.content;

            var inp = document.createElement("input");
            inp.placeholder = originalTable[item.x].value;
            inp.disabled = true;
            inp.id = originalTable[item.x].content;
            return inp;
          }
        }
      }
    });
    this.editSaveButton = document.createElement("button");
    this.editSaveButton.className = "btn btn-primary";
    this.editSaveButton.innerHTML = "Edit";

    this.span = document.createElement("span");
    this.span.className = "origContent";
    this.table.setHeader(["Setting", "Value"]);
    // Creates table.table.
    this.table.parse();
  }

  WaitRoomView.prototype.append = function() {
    var that = this;

    this.bodyDiv.appendChild(this.table.table);
    this.span.appendChild(this.editSaveButton);
    this.bodyDiv.appendChild(this.span);
  };

  WaitRoomView.prototype.listeners = function() {
    var that;
    that = this;
    node.on("CHANNEL_SELECTED", function() {
      that.displayData();
    });
  };

  WaitRoomView.prototype.displayData = function() {
    var i, t, s, tmp;
    var that = this;

    // Not ready yet.
    if (!node.game.gamesInfo) return;
    s = node.game.gamesInfo[node.game.channelInUse].waitroom;
    t = this.table;
    t.clear();

    //LEVELS in case later use
    node.game.gamesInfo[node.game.channelInUse].levels;

    //my settings
    var mySettings =
      node.game.gamesInfo[node.game.channelInUse].settings.standard;

    //remove unnecessary settings
    delete mySettings.SESSION_ID;
    delete mySettings.TIMER;
    delete mySettings.treatmentName;
    delete mySettings.name;

    //I dont think deleting them from a copy object affects anything
    delete s.EXECUTION_MODE;
    delete s.CHOSEN_TREATMENT;
    delete s.TEXTS;
    delete s.SOUND;

    var combinedSettings = mergeObjects(s, mySettings);

    console.log("WAITROOM S: " + JSON.stringify(s));
    console.log("MY SETTINGS: " + JSON.stringify(mySettings));
    console.log("COMBINED " + JSON.stringify(combinedSettings));

    this.editSaveButton.onclick = function() {
      var listOfSettings = [
        (repeat = W.gid("REPEAT")),
        (imageDir = W.gid("IMG_DIR")),
        (nOfNeighbors = W.gid("N_OF_NEIGHBORS")),
        (maleNamesPath = W.gid("MALE_NAMES_FILE")),
        (femaleNamesPath = W.gid("FEMALE_NAMES_FILE")),
        (group_size = W.gid("GROUP_SIZE")),
        (playWithBots = W.gid("ALLOW_PLAY_WITH_BOTS"))
      ];

      if (that.editSaveButton.innerHTML == "Edit") {
        that.editSaveButton.innerHTML = "Save";
        for (let x = 0; x < listOfSettings.length; x++) {
          var currentSetting = listOfSettings[x];
          var currentContent = originalTable[x + 1].content;
          var originalValue = originalTable[x + 1].value;

          if (
            currentSetting.value === "" ||
            currentSetting.placeholder == originalValue
          ) {
            //do nothing
          } else {
            currentSetting.placeholder = currentSetting.value;

            //update table structure for prev value
            originalTable[x + 1].value = currentSetting.value;
          }

          currentSetting.disabled = false;
        }
      } else if (that.editSaveButton.innerHTML == "Save") {
        that.editSaveButton.innerHTML = "Edit";

        var changes = {};
        changes["s"] = {};
        changes["mySettings"] = {};
        //disable the field
        for (let x = 0; x < listOfSettings.length; x++) {
          var currentSetting = listOfSettings[x];
          var currentContent = originalTable[x + 1].content;
          var originalValue = originalTable[x + 1].value;
          var currentValue = currentSetting.value;

          //not changed
          if (
            currentSetting.value === "" ||
            currentSetting.value == originalValue
          ) {
          } else {
            //SAVE IN A OBJECT AS STATED

            //waitroom s settings
            if (
              currentContent == "GROUP_SIZE" ||
              currentContent == "ALLOW_PLAY_WITH_BOTS"
            ) {
              changes["s"][currentContent] = currentValue;
            }
            //mySettings
            else {
              changes["mySettings"][currentContent] = currentValue;
            }
            //update original table if any of the inputs is not empty
            originalTable[x + 1].value = currentValue;
          }

          currentSetting.disabled = true;
        }

        //send changes in waitingroom
        if (!isEmptyObject(changes.s)) {
          node.socket.send(
            node.msg.create({
              target: "SERVERCOMMAND",
              text: "UPDATE_SETTINGS",
              data: {
                type: "waitingroom", // or requirements or settings, etc.
                update: changes.s
              }
            })
          );
        }

        //send changes in settings
        if (!isEmptyObject(changes.mySettings)) {
          node.socket.send(
            node.msg.create({
              target: "SERVERCOMMAND",
              text: "UPDATE_SETTINGS",
              data: {
                type: "settings", // or requirements or settings, etc.
                update: changes.mySettings
              }
            })
          );
        }

        //send the new data back to server
      }
    };

    for (let setting in mySettings) {
      if (mySettings.hasOwnProperty(setting)) {
        t.addRow([setting, mySettings[setting]]);
      }
    }

    //standard properties
    for (i in s) {
      if (s.hasOwnProperty(i)) {
        t.addRow([i, s[i]]);
      }
    }

    t.parse();
  };

  //check if object is empty or not (utility function)
  function isEmptyObject(obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) return false;
    }
    return true;
  }

  function mergeObjects(obj1, obj2) {
    var obj3 = {};
    for (var attrname in obj1) {
      obj3[attrname] = obj1[attrname];
    }
    for (var attrname in obj2) {
      obj3[attrname] = obj2[attrname];
    }
    return obj3;
  }
})(node);
<commit_msg>updated monitor with edit options<commit_after>/**
 * # WaitRoomView widget for nodeGame
 * Copyright(c) 2019 Stefano Balietti
 * MIT Licensed
 *
 * Shows requirements settings
 *
 * www.nodegame.org
 * ---
 */

(function(node) {
  ("use strict");

  node.widgets.register("WaitRoomView", WaitRoomView);

  var JSUS = node.JSUS;

  // ## Meta-data

  WaitRoomView.version = "0.0.1";
  WaitRoomView.description = "Displays a waitroom settings.";

  WaitRoomView.title = "WaitRoom Settings";
  WaitRoomView.className = "waitroomview";

  // ## Dependencies
  WaitRoomView.dependencies = {
    JSUS: {},
    Table: {}
  };

  var originalTable = {};

  function WaitRoomView(options) {
    var that = this;
    this.table = new W.Table({
      className: "table table-striped viewer",
      id: "settingsTable",
      render: {
        pipeline: function(item) {
          //x = 0 y = 0 first row first column
          //x = 0 y = 1 first row second column
          if (originalTable[item.x] === undefined) {
            originalTable[item.x] = {};
          }
          if (item.y % 2 === 0) {
            originalTable[item.x]["content"] = item.content;
            return document.createTextNode(item.content + ": ");
          } else if (item.y % 2 === 1) {
            originalTable[item.x]["value"] = item.content;

            var inp = document.createElement("input");
            inp.placeholder = originalTable[item.x].value;
            inp.disabled = true;
            inp.id = originalTable[item.x].content;
            return inp;
          }
        }
      }
    });
    this.editSaveButton = document.createElement("button");
    this.editSaveButton.className = "btn btn-primary";
    this.editSaveButton.innerHTML = "Edit";

    this.span = document.createElement("span");
    this.span.className = "origContent";
    this.table.setHeader(["Setting", "Value"]);
    // Creates table.table.
    this.table.parse();
  }

  WaitRoomView.prototype.append = function() {
    var that = this;

    this.bodyDiv.appendChild(this.table.table);
    this.span.appendChild(this.editSaveButton);
    this.bodyDiv.appendChild(this.span);
  };

  WaitRoomView.prototype.listeners = function() {
    var that;
    that = this;
    node.on("CHANNEL_SELECTED", function() {
      that.displayData();
    });
  };

  WaitRoomView.prototype.displayData = function() {
    var i, t, s, tmp;
    var that = this;

    // Not ready yet.
    if (!node.game.gamesInfo) return;
    s = node.game.gamesInfo[node.game.channelInUse].waitroom;
    t = this.table;
    t.clear();

    //LEVELS in case later use
    node.game.gamesInfo[node.game.channelInUse].levels;

    //my settings
    var mySettings =
      node.game.gamesInfo[node.game.channelInUse].settings.standard;

    //remove unnecessary settings
    delete mySettings.SESSION_ID;
    delete mySettings.TIMER;
    delete mySettings.treatmentName;
    delete mySettings.name;

    //I dont think deleting them from a copy object affects anything
    delete s.EXECUTION_MODE;
    delete s.CHOSEN_TREATMENT;
    delete s.TEXTS;
    delete s.SOUND;

    var combinedSettings = mergeObjects(s, mySettings);

    console.log("WAITROOM S: " + JSON.stringify(s));
    console.log("MY SETTINGS: " + JSON.stringify(mySettings));
    console.log("COMBINED " + JSON.stringify(combinedSettings));

    this.editSaveButton.onclick = function() {
      var listOfSettings = [
        (repeat = W.gid("REPEAT")),
        (imageDir = W.gid("IMG_DIR")),
        (nOfNeighbors = W.gid("N_OF_NEIGHBORS")),
        (maleNamesPath = W.gid("MALE_NAMES_FILE")),
        (femaleNamesPath = W.gid("FEMALE_NAMES_FILE")),
        (group_size = W.gid("GROUP_SIZE")),
        (playWithBots = W.gid("ALLOW_PLAY_WITH_BOTS"))
      ];

      if (that.editSaveButton.innerHTML == "Edit") {
        that.editSaveButton.innerHTML = "Save";
        for (let x = 0; x < listOfSettings.length; x++) {
          var currentSetting = listOfSettings[x];
          var currentContent = originalTable[x + 1].content;
          var originalValue = originalTable[x + 1].value;

          if (
            currentSetting.value === "" ||
            currentSetting.placeholder == originalValue
          ) {
            //do nothing
          } else {
            currentSetting.placeholder = currentSetting.value;

            //update table structure for prev value
            originalTable[x + 1].value = currentSetting.value;
          }

          currentSetting.disabled = false;
        }
      } else if (that.editSaveButton.innerHTML == "Save") {
        that.editSaveButton.innerHTML = "Edit";

        var changes = {};
        changes["s"] = {};
        changes["mySettings"] = {};
        //disable the field
        for (let x = 0; x < listOfSettings.length; x++) {
          var currentSetting = listOfSettings[x];
          var currentContent = originalTable[x + 1].content;
          var originalValue = originalTable[x + 1].value;
          var currentValue = currentSetting.value;

          //not changed
          if (
            currentSetting.value === "" ||
            currentSetting.value == originalValue
          ) {
          } else {
            //SAVE IN A OBJECT AS STATED

            //waitroom s settings
            if (currentContent == "GROUP_SIZE") {
              changes["s"][currentContent] = parseInt(currentValue);
              changes["s"]["POOL_SIZE"] = parseInt(currentValue);
            } else if (currentContent == "ALLOW_PLAY_WITH_BOTS") {
              changes["s"][currentContent] = currentValue == "true";
            } else if (currentContent == "REPEAT") {
              changes["mySettings"][currentContent] = parseInt(currentValue);
            } else if (currentContent == "IMG_DIR") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "N_OF_NEIGHBORS") {
              changes["mySettings"][currentContent] = parseInt(currentValue);
            } else if (currentContent == "MALE_NAMES_FILE") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "FEMALE_NAMES_FILE") {
              changes["mySettings"][currentContent] = currentValue;
            }
            //mySettings

            //update original table if any of the inputs is not empty
            originalTable[x + 1].value = currentValue;
          }

          currentSetting.disabled = true;
        }

        console.log("CHANGES: " + JSON.stringify(changes));

        //send changes in waitingroom
        if (!isEmptyObject(changes.s)) {
          node.socket.send(
            node.msg.create({
              target: "SERVERCOMMAND",
              text: "UPDATE_SETTINGS",
              data: {
                type: "waitroom", // or requirements or settings, etc.
                update: changes.s
              }
            })
          );
        }

        //send changes in settings
        if (!isEmptyObject(changes.mySettings)) {
          node.socket.send(
            node.msg.create({
              target: "SERVERCOMMAND",
              text: "UPDATE_SETTINGS",
              data: {
                type: "settings", // or requirements or settings, etc.
                update: changes.mySettings
              }
            })
          );
        }

        //send the new data back to server
      }
    };

    for (let setting in mySettings) {
      if (mySettings.hasOwnProperty(setting)) {
        t.addRow([setting, mySettings[setting]]);
      }
    }

    //standard properties
    for (i in s) {
      if (s.hasOwnProperty(i)) {
        t.addRow([i, s[i]]);
      }
    }

    t.parse();
  };

  //check if object is empty or not (utility function)
  function isEmptyObject(obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) return false;
    }
    return true;
  }

  function mergeObjects(obj1, obj2) {
    var obj3 = {};
    for (var attrname in obj1) {
      obj3[attrname] = obj1[attrname];
    }
    for (var attrname in obj2) {
      obj3[attrname] = obj2[attrname];
    }
    return obj3;
  }
})(node);
<|endoftext|>


<commit_before>const queryString = require('query-string');

const SHOW_INFRA_ID = '#infra-show';
var show_infra;

const initialize = function (show_infra_func) {
  show_infra = show_infra_func;
};

var show_infra = function (infra_id, current_tab) {
  show_infra(infra_id, current_tab);
};

const reload_infra_index_page = function () {
  const parsed_query_string = queryString.parse(location.search);
  const project_id_query = parsed_query_string.project_id ? `&project_id=${parsed_query_string.project_id}` : '';
  location.href = `/infrastructures?lang=${parsed_query_string.lang}${project_id_query}`;
};

module.exports = {
  SHOW_INFRA_ID,
  initialize,
  show_infra,
  reload_infra_index_page,
};
<commit_msg>Fix: infrastructures/show_infra.jsをリファクタリング<commit_after>const queryString = require('query-string');

const SHOW_INFRA_ID = '#infra-show';

const initialize = (showInfraFunc) => {
  showInfra = showInfraFunc;
};

let showInfra = (infraId, currentTab) => {
  showInfra(infraId, currentTab);
};

const reloadInfraIndexPage = () => {
  const parsedQueryString = queryString.parse(window.location.search);
  const projectIdQuery = parsedQueryString.project_id ? `&project_id=${parsedQueryString.project_id}` : '';
  window.location.href = `/infrastructures?lang=${parsedQueryString.lang}${projectIdQuery}`;
};

module.exports = {
  SHOW_INFRA_ID,
  initialize,
  show_infra: showInfra,
  reload_infra_index_page: reloadInfraIndexPage,
};
<|endoftext|>


<commit_before>requirejs.config({
    baseUrl: '/js',
    shim: {
        jquery:     { exports: '$' },
        d3:         { exports: 'd3' },
        underscore: { exports: '_' },
        backbone:   {
            exports: 'Backbone',
            deps: [ 'underscore', 'jquery' ]
        },
        'backbone.localstorage': {
            exports: 'Backbone',
            deps: [ 'backbone' ]
        },
        colorbrewer: { exports: 'colorbrewer' },
        "jquery.dataTables": [ 'jquery' ]
    },
})
require(['jquery', 'backbone', 'underscore', 'charts/bar'],
    function ($, Backbone, _, BarChart) {
        var demo = $("<div>").addClass("viewport").attr("id", "bar")
        .attr("data-title", "Emails to kbase-devel today")
        .height(400).width(400);
        $("#container")
            .append($("<div>").addClass("row")
                .append($("<div>").addClass("span4")
                    .append(demo)));
        var vis = new BarChart("#bar", {});
        vis.setData([
            { x: 'Shiran', y: 3 },
            { x: 'Bob',    y: 5 }
        ]);
        vis.display();
        return this;
});<commit_msg>Minor CSS change.<commit_after>requirejs.config({
    baseUrl: '/js',
    shim: {
        jquery:     { exports: '$' },
        d3:         { exports: 'd3' },
        underscore: { exports: '_' },
        backbone:   {
            exports: 'Backbone',
            deps: [ 'underscore', 'jquery' ]
        },
        'backbone.localstorage': {
            exports: 'Backbone',
            deps: [ 'backbone' ]
        },
        colorbrewer: { exports: 'colorbrewer' },
        "jquery.dataTables": [ 'jquery' ]
    },
})
require(['jquery', 'backbone', 'underscore', 'charts/bar'],
    function ($, Backbone, _, BarChart) {
        var demo = $("<div>").addClass("viewport").attr("id", "bar")
        .attr("data-title", "Emails to kbase-devel today")
        .height(400).width(400);
        $("#container")
            .append($("<div>").addClass("row")
                .append($("<div>").addClass("span6 offset4")
                    .append(demo)));
        var vis = new BarChart("#bar", {});
        vis.setData([
            { x: 'Shiran', y: 3 },
            { x: 'Bob',    y: 5 }
        ]);
        vis.display();
        return this;
});<|endoftext|>


<commit_before>// Timeout prompt for MOJ
// Dependencies: moj, jQuery, Handlebars

(function () {

  'use strict';

  moj.Modules.timeoutPrompt = {
    timeoutDuration: 1000 * 60 * 17, // ms * s * m = 17 minutes
    respondDuration: 1000 * 60 * 3,
    timeout: null,
    respond: null,
    template: '#tmpl-timeout',
    exitPath: '/abandon',

    init: function () {
      this.cacheEls();
      if (this.$tmpl.length) {
        this.startTimeout(this.timeoutDuration);
      }
    },

    cacheEls: function() {
      this.$tmpl = $(this.template);
      this.notice = this.getTemplate(this.$tmpl);
    },

    startTimeout: function (ms) {
      var self = this;
      this.timeout = setTimeout($.proxy(self.warning, self, self.respondDuration), ms);
    },

    getTemplate: function($tmpl) {
      var self = this,
          template;

      if ($tmpl.length) {
        template = Handlebars.compile($tmpl.html());

        return template({
          respondTime: self.respondDuration / 60 / 1000
        });
      }
    },

    warning: function (ms) {
      var self = this;

      $(self.notice)
        .insertBefore(self.template)
        .focus()
        .end()
        .find('#extend-timeout')
        .on('click', $.proxy(self.removeWarning, self));

      self.respond = setTimeout($.proxy(self.redirect, self), ms);
    },

    redirect: function () {
      window.location.href = this.exitPath;
    },

    removeWarning: function () {
      $('#timeout-prompt').remove();
      clearTimeout(this.timeout);
      this.refreshSession();
    },

    refreshSession: function () {
      var self = this;
      $.ajax({
        url: $('#logo img').attr('src'),
        cache: false
      }).done(function () {
        self.startTimeout();
        clearTimeout(self.respond);
      });
    }
  };

}());
<commit_msg>Refactor TimeoutPrompt into Class<commit_after>// Timeout prompt for MOJ
// Dependencies: moj, jQuery, Handlebars

(function () {

  'use strict';

  window.moj = window.moj || { Modules: {}, Events: $({}) };

  var TimeoutPrompt = function($el, options) {
    this.init($el, options);
    return this;
  };

  TimeoutPrompt.prototype = {

    defaults: {
      timeoutMinutes: 17,
      respondMinutes: 3,
      exitPath: '/abandon'
    },

    timeout: null,
    respond: null,

    init: function ($el, options) {
      this.settings = $.extend({}, this.defaults, options);
      this.settings.timeoutDuration = this.convertToMinutes(this.settings.timeoutMinutes);
      this.settings.respondDuration = this.convertToMinutes(this.settings.respondMinutes);
      this.cacheEls($el);
      this.startTimeout();
    },

    convertToMinutes: function(num) {
      return num * 1000 * 60;
    },

    cacheEls: function($el) {
      this.$el = $el;
      this.notice = this.getTemplate($el);
    },

    startTimeout: function () {
      var self = this;
      this.timeout = setTimeout(
        $.proxy(
          self.warning,
          self,
          self.settings.respondDuration
        ),
        self.settings.timeoutDuration
      );
    },

    getTemplate: function($tmpl) {
      var self = this,
          template;

      if ($tmpl.length) {
        template = Handlebars.compile($tmpl.html());

        return template({
          respondTime: self.settings.respondMinutes
        });
      }
    },

    warning: function (ms) {
      var self = this;

      $(self.notice)
        .insertBefore(self.$el)
        .focus()
        .end()
        .find('#extend-timeout')
        .on('click', $.proxy(self.removeWarning, self));

      self.respond = setTimeout($.proxy(self.redirect, self), ms);
    },

    redirect: function () {
      window.location.href = this.settings.exitPath;
    },

    removeWarning: function () {
      $('#timeout-prompt').remove();
      clearTimeout(this.timeout);
      this.refreshSession();
    },

    refreshSession: function () {
      var self = this;
      $.ajax({
        url: $('#logo img').attr('src'),
        cache: false
      }).done(function () {
        self.startTimeout(self.settings.timeoutDuration);
        clearTimeout(self.respond);
      });
    }
  };

  moj.Modules.TimeoutPrompt = {
    init: function() {
      return $('.TimeoutPrompt').each(function() {
        $(this).data('TimeoutPrompt', new TimeoutPrompt($(this), $(this).data()));
      });
    }
  };

}());
<|endoftext|>


<commit_before>define(['app',
        './document-metadata-directive.html.js',
    '/app/js/common.js',]
      , function (app) {

app.directive('documentList', function ($http) {
        return {
            restrict: 'EAC',
            templateUrl: '/app/views/directives/document-list.partial.html',
            replace: true,
            // require : "?ngModel",
            scope: {
                  // placeholder: '@',
                  // ngDisabledFn : '&ngDisabled',
                  // binding    : '=ngModel',
                  // locales    : '=',
                  // required   : "@"
                  documents : '=',
                  filter: '@',
                  advanceFilter: '=',
                  showPagination: '@',
                  currentPage: '=',
                  documentCount: '='
            },
            controller: ['$scope', "underscore", "commonjs",function ($scope, underscore, commonjs){

              $scope.formatDate = function formatDate (date) {
                    return moment(date).format('MMMM Do YYYY');
              };
              //console.log($scope.advanceFilter) ;
              if($scope.advanceFilter && $scope.advanceFilter.$==null)
              {
                $scope.advanceFilter.$ = '';
               // console.log($scope.advanceFilter) ;
              }

              $scope.loaded = false;
              $scope.itemsPerPage = 25;
              $scope.pageCount = 0;
              $scope.currentPage = 0;
              $scope.transformedDocuments = [];
              $scope.descriptionLimit = 50;

                $scope.load = function(item,displayDetails) {

                      //occours when a user actions collapses the detail section.
                      if(!displayDetails)
                          return;

                       item.data = {'schema':item.schema, 'url_ss': item.url_ss, 'data': item};

                        if(item.schema=="FOCALPOINT" || item.schema=="MEETING" || item.schema=="NOTIFICATION"
                           || item.schema=="PRESSRELEASE" || item.schema=="STATEMENT")
                        {
                             commonjs.getReferenceRecordIndex(item.schema,item.id).then(function(data){
                                item.data = data.data;
                              });
                        }
                        else
                        {
                              $http.get("/api/v2013/documents/"+item.identifier_s).then(function (result) {
                                  item.data = result.data;

                                  $http.get("/api/v2013/documents/"+item.identifier_s + "?info").then(function (result) {
                                      item.data.info = result.data;
                                  });

                              });
                          }
                    }

                $scope.filterCategory = function(item) {
                            //console.log($scope.filter);
                            if($scope.filter && ($scope.filter == '*' || item.schema.toUpperCase() == $scope.filter.toUpperCase()))
                                return true;

                            return false;

                  }

                $scope.actionSetPage = function (pageNumber) {
                  //debugger;
                                  $scope.currentPage = Math.min($scope.pageCount-1, Math.max(0, pageNumber));
                              };

                $scope.range = function (start, end) {

                    var ret = [];
                    if (!end) {
                        end = start;
                        start = 0;
                    }

                    var maxCount = 10;
                    var middle = 5;
                    var count = end - start;

                    if (count > maxCount) {
                        if ($scope.currentPage > middle)
                            start = $scope.currentPage - middle;

                        end = Math.min(count, start + maxCount);
                        start = Math.max(0, end - maxCount);
                    }

                    for (var i = start; i < end; i++) {
                        ret.push(i);
                    }
                    return ret;
                };

                $scope.$watch('currentPage', function (newValue, oldValue) {
                     if (newValue != oldValue)
                     {
                       //console.log('current page changed');
                        $scope.currentPage = newValue;
                    }
                });

                $scope.$watch('documents', function (newValue, oldValue) {

                     if (newValue != oldValue)
                     {
                        $scope.pageCount = Math.ceil($scope.documentCount / $scope.itemsPerPage);
                       $scope.transformedDocuments = [];
                       $scope.documents.forEach(function (doc) {
                           $scope.transformedDocuments.push(transformDocument(doc));
                        });

                    }
                });

                function transformDocument (document) {

                  var output = {};
                  var locale = "en";//$scope.$root.locale;

                  var formatDate = function formatDate (date) {
                        return date+'';//moment(date).format('MMMM Do YYYY');
                    };
// console.log(document);
                    output.id          = document.id;
                    output.schema      = document.schema_s.toUpperCase();
                    output.title       = document.title_t;
                    output.description = document.description_t;
                    output.source      = document.government_EN_t;
                    output.url_ss      = document.url_ss;
                    output.identifier_s = document.identifier_s;
                    output.doc = document;
                    output.createdDateOn = document.createdDate_dt;

						  //Jason's code. gets a list of countries to find out if they are ratified or what not. TODO: not do this. countries should exist on a high level scope, so I don't have to ajax it. Or there should be a cache. Also use underscore for algorithms.
						  $http.get('/api/v2013/countries', {cache: true}).then(function(response) {
							  var countries = response.data;
							  for(var i=0; i!=countries.length; ++i)
							  		if(countries[i].name.en == output.source) {
									  var treaties = countries[i].treaties;
									  output.isParty = treaties.XXVII8.party;
									  output.isSignatory = treaties.XXVII8b.signature;
									  output.isRatified = treaties.XXVII8b.instrument == "ratification" || treaties.XXVII8b.instrument == "accession" || treaties.XXVII8b.instrument == "acceptance";
									  // console.log(output);
									}
						  });

                    output.cssRecordClass="referenceRecords";
                     // if(document.orgperson_s) {
                     //  var obj = JSON.parse(document.orgperson_s);
                     // // console.log(obj);
                     //  obj.forEach(function(org){
                     //   // console.log(org.organization.en);
                     //  })

                     // }
                    if(document.schema_s=='focalPoint') {
                        output.description  = document.function_t||'';
                        output.description += (document.function_t && document.department_t) ? ', ' : '';
                        output.description += document.department_t||'';
                        output.description2 = document.organization_t||'';
                    }

                    if(document.schema_s=='decision' && document.body_s=='XXVII8-COP' ) output.source = 'COP TO THE CONVENTION';
                    if(document.schema_s=='decision' && document.body_s=='XXVII8b-MOP') output.source = 'COP-MOP TO THE CARTAGENA PROTOCOL ON BIOSAFETY';
                    if(document.schema_s=='decision') output.title       = 'Decision ' + document.code_s;
                    if(document.schema_s=='decision') output.description = document.title_t;

                    if(document.schema_s=='recommendation' && document.body_s=='XXVII8-SBSTTA') { output.source = 'SBSTTA'; output.sourceTooltip = 'Subsidiary Body on Scientific, Technical and Technological Advice'; }
                    if(document.schema_s=='recommendation' && document.body_s=='XXVII8-WGRI'  ) { output.source = 'WGRI';   output.sourceTooltip = 'Working Group on the Review of Implementation'; }
                    if(document.schema_s=='recommendation' && document.body_s=='XXVII8b-ICCP' ) { output.source = 'ICCP';   output.sourceTooltip = 'Intergovernmental Committee for the Cartagena Protocol on Biosafety'; }
                    if(document.schema_s=='recommendation' && document.body_s=='XXVII8c-ICNP' ) { output.source = 'ICNP';   output.sourceTooltip = 'Intergovernmental Committee for the Nagoya Protocol on ABS'; }
                    if(document.schema_s=='recommendation') output.title       = 'Recommendation ' + document.code_s;
                    if(document.schema_s=='recommendation') output.description = document.title_t;

                    if(document.schema_s=='meetingDocument') output.source      = document.meeting_s;
                    if(document.schema_s=='meetingDocument') output.title       = document.symbol_s;
                    if(document.schema_s=='meetingDocument') output.description = document.title_t;
                    if(document.schema_s=='meetingDocument' && document.group_s=='INF') output.source += ' - INFORMATION';
                    if(document.schema_s=='meetingDocument' && document.group_s=='OFC') output.source += ' - PRE-SESSION';

                    if(document.schema_s=='nationalReport') output.description = document.summary_EN_t;
                    if(document.schema_s=='nationalReport') output.type        = document.reportType_EN_t;

                    if(document.schema_s=='implementationActivity') output.type = document.jurisdiction_EN_t + ' - ' + document.completion_EN_t;

                    if(document.schema_s=='marineEbsa') output.schema = 'ECOLOGICALLY OR BIOLOGICALLY SIGNIFICANT AREA';

                    if(document.schema_s=='event') {
                        output.dates = formatDate(document.startDate_s) + ' to ' + formatDate(document.endDate_s);
                        output.venue = document.eventCity_EN_t + ', ' + document.eventCountry_EN_t;
                    }

                     if(document.jurisdiction_EN_t){
                          output.jusrisdiction = document.jurisdiction_EN_t;
                        }

                    if(document.schema_s=='resource') {
                        output.Year = document.publicationYear_is;
                        output.Types = getString(document.resourceTypes_CEN_ss, locale);
                        output.Regions = getString(document.regions_CEN_ss, locale);
                        output.Languages = getString(document.languages_CEN_ss, locale);
                    }else if(document.schema_s=='authority') {
                        output.responsibleForAll = document.responsibleForAll_b;
                        // output.jusrisdiction = document.jurisdiction_EN_t;
                        output.grType = (document.geneticResourceTypes_ss );
                        output.cssRecordClass="nationalRecords";
                    }
                    else if(document.schema_s=='absCheckpoint') {
                        // output.jusrisdiction = document.jurisdiction_EN_t;
                        output.informAllAuthorities = (document.informAllAuthorities_b);
                        output.cssRecordClass="nationalRecords";
                    }
                    else if(document.schema_s=='absPermit') {

                        if(document.usage_CEN_ss){
                          output.usage = '';
                          document.usage_CEN_ss.forEach(function(usage){
                            output.usage +=  (output.usage.length > 0 ? "," : "") +  JSON.parse(usage).en;
                          });
                        }
                        // console.log(output.usage);
                        output.keywords = getString(document.keywords_CEN_ss, locale);
                        output.cssRecordClass="nationalRecords";
                    }
                    else if(document.schema_s=='absCheckpointCommunique') {
                        output.originCountries = (document.originCountries_CEN_ss);
                        output.cssRecordClass="nationalRecords";
                    }
                    else if(document.schema_s=='measure' || document.schema_s=='focalPoint' || document.schema_s=='database') {
                        output.cssRecordClass="nationalRecords";

                        if(document.type_EN_t){
                          output.type = document.type_EN_t;
                        }

                        if(document.status_EN_t){
                          output.status = document.status_EN_t;
                        }
                    }
                    else if(document.schema_s=='meeting') {
                        output.eventCity=document.eventCity_EN_t;
                        output.eventCountry=document.eventCountry_EN_t;
                    }

                    return output;
                }

                function getString(source, key){
                    var lstring = [];

                    if(source!=undefined)
                    {
                          //console.log(JSON.parse('{"response": {   "success": "The activity has been removed",   "message": "0"  }}' ));

                        //  if(angular.isString(source))
                        //  {
                        //   console.log(source);
                        //    var jst = (JSON.parse(( source )));
                        //   console.log((jst[0]));
                        //     //   jst.forEach(function(record){
                        //     //    console.log(record);
                        //     // });
                        // }
                        //console.log(source);
                        source.forEach(function(record){
                          lstring.push(JSON.parse(record)[key] );
                        });

                        return lstring.toString() ;

                    }
                }

                // $scope.$watch('advanceFilter', function(newvalue,old){
                //   console.log(old);
                //   console.log(newvalue);
                // })

            }]

        };
    });
});
<commit_msg>include approval in ratification criteria<commit_after>define(['app',
        './document-metadata-directive.html.js',
    '/app/js/common.js',]
      , function (app) {

app.directive('documentList', function ($http) {
        return {
            restrict: 'EAC',
            templateUrl: '/app/views/directives/document-list.partial.html',
            replace: true,
            // require : "?ngModel",
            scope: {
                  // placeholder: '@',
                  // ngDisabledFn : '&ngDisabled',
                  // binding    : '=ngModel',
                  // locales    : '=',
                  // required   : "@"
                  documents : '=',
                  filter: '@',
                  advanceFilter: '=',
                  showPagination: '@',
                  currentPage: '=',
                  documentCount: '='
            },
            controller: ['$scope', "underscore", "commonjs",function ($scope, underscore, commonjs){

              $scope.formatDate = function formatDate (date) {
                    return moment(date).format('MMMM Do YYYY');
              };
              //console.log($scope.advanceFilter) ;
              if($scope.advanceFilter && $scope.advanceFilter.$==null)
              {
                $scope.advanceFilter.$ = '';
               // console.log($scope.advanceFilter) ;
              }

              $scope.loaded = false;
              $scope.itemsPerPage = 25;
              $scope.pageCount = 0;
              $scope.currentPage = 0;
              $scope.transformedDocuments = [];
              $scope.descriptionLimit = 50;

                $scope.load = function(item,displayDetails) {

                      //occours when a user actions collapses the detail section.
                      if(!displayDetails)
                          return;

                       item.data = {'schema':item.schema, 'url_ss': item.url_ss, 'data': item};

                        if(item.schema=="FOCALPOINT" || item.schema=="MEETING" || item.schema=="NOTIFICATION"
                           || item.schema=="PRESSRELEASE" || item.schema=="STATEMENT")
                        {
                             commonjs.getReferenceRecordIndex(item.schema,item.id).then(function(data){
                                item.data = data.data;
                              });
                        }
                        else
                        {
                              $http.get("/api/v2013/documents/"+item.identifier_s).then(function (result) {
                                  item.data = result.data;

                                  $http.get("/api/v2013/documents/"+item.identifier_s + "?info").then(function (result) {
                                      item.data.info = result.data;
                                  });

                              });
                          }
                    }

                $scope.filterCategory = function(item) {
                            //console.log($scope.filter);
                            if($scope.filter && ($scope.filter == '*' || item.schema.toUpperCase() == $scope.filter.toUpperCase()))
                                return true;

                            return false;

                  }

                $scope.actionSetPage = function (pageNumber) {
                  //debugger;
                                  $scope.currentPage = Math.min($scope.pageCount-1, Math.max(0, pageNumber));
                              };

                $scope.range = function (start, end) {

                    var ret = [];
                    if (!end) {
                        end = start;
                        start = 0;
                    }

                    var maxCount = 10;
                    var middle = 5;
                    var count = end - start;

                    if (count > maxCount) {
                        if ($scope.currentPage > middle)
                            start = $scope.currentPage - middle;

                        end = Math.min(count, start + maxCount);
                        start = Math.max(0, end - maxCount);
                    }

                    for (var i = start; i < end; i++) {
                        ret.push(i);
                    }
                    return ret;
                };

                $scope.$watch('currentPage', function (newValue, oldValue) {
                     if (newValue != oldValue)
                     {
                       //console.log('current page changed');
                        $scope.currentPage = newValue;
                    }
                });

                $scope.$watch('documents', function (newValue, oldValue) {

                     if (newValue != oldValue)
                     {
                        $scope.pageCount = Math.ceil($scope.documentCount / $scope.itemsPerPage);
                       $scope.transformedDocuments = [];
                       $scope.documents.forEach(function (doc) {
                           $scope.transformedDocuments.push(transformDocument(doc));
                        });

                    }
                });

                function transformDocument (document) {

                  var output = {};
                  var locale = "en";//$scope.$root.locale;

                  var formatDate = function formatDate (date) {
                        return date+'';//moment(date).format('MMMM Do YYYY');
                    };
// console.log(document);
                    output.id          = document.id;
                    output.schema      = document.schema_s.toUpperCase();
                    output.title       = document.title_t;
                    output.description = document.description_t;
                    output.source      = document.government_EN_t;
                    output.url_ss      = document.url_ss;
                    output.identifier_s = document.identifier_s;
                    output.doc = document;
                    output.createdDateOn = document.createdDate_dt;

						  //Jason's code. gets a list of countries to find out if they are ratified or what not. TODO: not do this. countries should exist on a high level scope, so I don't have to ajax it. Or there should be a cache. Also use underscore for algorithms.
						  $http.get('/api/v2013/countries', {cache: true}).then(function(response) {
							  var countries = response.data;
							  for(var i=0; i!=countries.length; ++i)
							  		if(countries[i].name.en == output.source) {
									  var treaties = countries[i].treaties;
									  output.isParty = treaties.XXVII8.party;
									  output.isSignatory = treaties.XXVII8b.signature;
									  output.isRatified = treaties.XXVII8b.instrument == "ratification" || treaties.XXVII8b.instrument == "accession" || treaties.XXVII8b.instrument == "acceptance" ||treaties.XXVII8b.instrument == "approval";
									  // console.log(output);
									}
						  });

                    output.cssRecordClass="referenceRecords";
                     // if(document.orgperson_s) {
                     //  var obj = JSON.parse(document.orgperson_s);
                     // // console.log(obj);
                     //  obj.forEach(function(org){
                     //   // console.log(org.organization.en);
                     //  })

                     // }
                    if(document.schema_s=='focalPoint') {
                        output.description  = document.function_t||'';
                        output.description += (document.function_t && document.department_t) ? ', ' : '';
                        output.description += document.department_t||'';
                        output.description2 = document.organization_t||'';
                    }

                    if(document.schema_s=='decision' && document.body_s=='XXVII8-COP' ) output.source = 'COP TO THE CONVENTION';
                    if(document.schema_s=='decision' && document.body_s=='XXVII8b-MOP') output.source = 'COP-MOP TO THE CARTAGENA PROTOCOL ON BIOSAFETY';
                    if(document.schema_s=='decision') output.title       = 'Decision ' + document.code_s;
                    if(document.schema_s=='decision') output.description = document.title_t;

                    if(document.schema_s=='recommendation' && document.body_s=='XXVII8-SBSTTA') { output.source = 'SBSTTA'; output.sourceTooltip = 'Subsidiary Body on Scientific, Technical and Technological Advice'; }
                    if(document.schema_s=='recommendation' && document.body_s=='XXVII8-WGRI'  ) { output.source = 'WGRI';   output.sourceTooltip = 'Working Group on the Review of Implementation'; }
                    if(document.schema_s=='recommendation' && document.body_s=='XXVII8b-ICCP' ) { output.source = 'ICCP';   output.sourceTooltip = 'Intergovernmental Committee for the Cartagena Protocol on Biosafety'; }
                    if(document.schema_s=='recommendation' && document.body_s=='XXVII8c-ICNP' ) { output.source = 'ICNP';   output.sourceTooltip = 'Intergovernmental Committee for the Nagoya Protocol on ABS'; }
                    if(document.schema_s=='recommendation') output.title       = 'Recommendation ' + document.code_s;
                    if(document.schema_s=='recommendation') output.description = document.title_t;

                    if(document.schema_s=='meetingDocument') output.source      = document.meeting_s;
                    if(document.schema_s=='meetingDocument') output.title       = document.symbol_s;
                    if(document.schema_s=='meetingDocument') output.description = document.title_t;
                    if(document.schema_s=='meetingDocument' && document.group_s=='INF') output.source += ' - INFORMATION';
                    if(document.schema_s=='meetingDocument' && document.group_s=='OFC') output.source += ' - PRE-SESSION';

                    if(document.schema_s=='nationalReport') output.description = document.summary_EN_t;
                    if(document.schema_s=='nationalReport') output.type        = document.reportType_EN_t;

                    if(document.schema_s=='implementationActivity') output.type = document.jurisdiction_EN_t + ' - ' + document.completion_EN_t;

                    if(document.schema_s=='marineEbsa') output.schema = 'ECOLOGICALLY OR BIOLOGICALLY SIGNIFICANT AREA';

                    if(document.schema_s=='event') {
                        output.dates = formatDate(document.startDate_s) + ' to ' + formatDate(document.endDate_s);
                        output.venue = document.eventCity_EN_t + ', ' + document.eventCountry_EN_t;
                    }

                     if(document.jurisdiction_EN_t){
                          output.jusrisdiction = document.jurisdiction_EN_t;
                        }

                    if(document.schema_s=='resource') {
                        output.Year = document.publicationYear_is;
                        output.Types = getString(document.resourceTypes_CEN_ss, locale);
                        output.Regions = getString(document.regions_CEN_ss, locale);
                        output.Languages = getString(document.languages_CEN_ss, locale);
                    }else if(document.schema_s=='authority') {
                        output.responsibleForAll = document.responsibleForAll_b;
                        // output.jusrisdiction = document.jurisdiction_EN_t;
                        output.grType = (document.geneticResourceTypes_ss );
                        output.cssRecordClass="nationalRecords";
                    }
                    else if(document.schema_s=='absCheckpoint') {
                        // output.jusrisdiction = document.jurisdiction_EN_t;
                        output.informAllAuthorities = (document.informAllAuthorities_b);
                        output.cssRecordClass="nationalRecords";
                    }
                    else if(document.schema_s=='absPermit') {

                        if(document.usage_CEN_ss){
                          output.usage = '';
                          document.usage_CEN_ss.forEach(function(usage){
                            output.usage +=  (output.usage.length > 0 ? "," : "") +  JSON.parse(usage).en;
                          });
                        }
                        // console.log(output.usage);
                        output.keywords = getString(document.keywords_CEN_ss, locale);
                        output.cssRecordClass="nationalRecords";
                    }
                    else if(document.schema_s=='absCheckpointCommunique') {
                        output.originCountries = (document.originCountries_CEN_ss);
                        output.cssRecordClass="nationalRecords";
                    }
                    else if(document.schema_s=='measure' || document.schema_s=='focalPoint' || document.schema_s=='database') {
                        output.cssRecordClass="nationalRecords";

                        if(document.type_EN_t){
                          output.type = document.type_EN_t;
                        }

                        if(document.status_EN_t){
                          output.status = document.status_EN_t;
                        }
                    }
                    else if(document.schema_s=='meeting') {
                        output.eventCity=document.eventCity_EN_t;
                        output.eventCountry=document.eventCountry_EN_t;
                    }

                    return output;
                }

                function getString(source, key){
                    var lstring = [];

                    if(source!=undefined)
                    {
                          //console.log(JSON.parse('{"response": {   "success": "The activity has been removed",   "message": "0"  }}' ));

                        //  if(angular.isString(source))
                        //  {
                        //   console.log(source);
                        //    var jst = (JSON.parse(( source )));
                        //   console.log((jst[0]));
                        //     //   jst.forEach(function(record){
                        //     //    console.log(record);
                        //     // });
                        // }
                        //console.log(source);
                        source.forEach(function(record){
                          lstring.push(JSON.parse(record)[key] );
                        });

                        return lstring.toString() ;

                    }
                }

                // $scope.$watch('advanceFilter', function(newvalue,old){
                //   console.log(old);
                //   console.log(newvalue);
                // })

            }]

        };
    });
});
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const vue = require('rollup-plugin-vue');
const buble = require('rollup-plugin-buble');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const CleanCSS = require('clean-css');
const {name, dependencies} = require('../package.json');

const base = path.resolve(__dirname, '..');
const dist = path.resolve(base, 'dist');

module.exports = {
    entry: path.resolve(base, 'index.js'),
    external: Object.keys(dependencies),
    moduleName: name,
    plugins: [
        vue({
            cssModules: {
                generateScopedName: '[name]__[local]'
            },
            css(style) {
                fs.writeFileSync(path.resolve(dist, `${name}.css`), new CleanCSS().minify(style).styles);
            }
        }),
        buble(),
        resolve({skip: ['vue']}),
        commonjs()
    ]
};
<commit_msg>fix rollup<commit_after>const fs = require('fs');
const path = require('path');
const vue = require('rollup-plugin-vue');
const buble = require('rollup-plugin-buble');
const resolve = require('rollup-plugin-node-resolve');
const commonjs = require('rollup-plugin-commonjs');
const CleanCSS = require('clean-css');
const {name, dependencies} = require('../package.json');

const base = path.resolve(__dirname, '..');
const lib = path.resolve(base, 'lib');
const dist = path.resolve(base, 'dist');

module.exports = {
    entry: path.resolve(lib, 'index.js'),
    external: Object.keys(dependencies),
    moduleName: name,
    plugins: [
        vue({
            cssModules: {
                generateScopedName: '[name]__[local]'
            },
            css(style) {
                fs.writeFileSync(path.resolve(dist, `${name}.css`), new CleanCSS().minify(style).styles);
            }
        }),
        buble(),
        resolve({skip: ['vue']}),
        commonjs()
    ]
};
<|endoftext|>


<commit_before>/* global self */
(function (global) {
  const toolbox = global.toolbox;

  /**
   * Cache first
   */

  // cloudflare cdn
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'cloudflare-cdn',
    },
    origin: /cdnjs\.cloudflare\.com$/
  });

  // gstatic cdn
  // - firebase scripts
  // - google fonts
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'gstatic-cdn',
    },
    origin: /\.gstatic\.com$/
  });

  // googleapis fonts cdn
  // - google fonts css
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'fonts-googleapis-cdn'
    },
    origin: /fonts\.googleapis\.com/
  });

  // github buttons cdn
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'github-buttons-cdn-600',
      maxAgeSeconds: 600
    },
    origin: /buttons\.github\.io/
  });

  // cloud functions legion assult api
  toolbox.router.get(/\/legionAssultTime/, toolbox.cacheFirst, {
    cache: {
      name: 'cloud-functions-legion-assults-time',
      maxAgeSeconds: 86400
    },
    origin: /us-central1-wow-ap-level\.cloudfunctions\.net/
  });

  /**
   * Fastest
   */

  // worldofwarcraft character render
  toolbox.router.get(/character\/(.*?)\.jpg/, toolbox.fastest, {
    cache: {
      name: 'worldofwarcraft-render',
      maxEntries: 50,
      maxAgeSeconds: 86400
    },
    origin: /render-(?:tw|eu|us|kr)\.worldofwarcraft\.com/
  });

  // firebase storage character index
  toolbox.router.get(/index\.json/, toolbox.fastest, {
    origin: /firebasestorage\.googleapis\.com/
  });
}(self));
<commit_msg>update legion assults service worker cache<commit_after>/* global self */
(function (global) {
  const toolbox = global.toolbox;

  // toolbox.options.debug = true;

  /**
   * Cache first
   */

  // cloudflare cdn
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'cloudflare-cdn',
    },
    origin: /cdnjs\.cloudflare\.com$/
  });

  // gstatic cdn
  // - firebase scripts
  // - google fonts
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'gstatic-cdn',
    },
    origin: /\.gstatic\.com$/
  });

  // googleapis fonts cdn
  // - google fonts css
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'fonts-googleapis-cdn'
    },
    origin: /fonts\.googleapis\.com/
  });

  // github buttons cdn
  toolbox.router.get('/(.*)', toolbox.cacheFirst, {
    cache: {
      name: 'github-buttons-cdn-600',
      maxAgeSeconds: 600
    },
    origin: /buttons\.github\.io/
  });

  // cloud functions legion assult api
  toolbox.router.get(/\/legionAssultTime/, toolbox.cacheFirst, {
    cache: {
      name: 'legion-assults-time-86400',
      maxAgeSeconds: 86400
    },
    origin: /us-central1-wow-ap-level\.cloudfunctions\.net/
  });

  /**
   * Fastest
   */

  // worldofwarcraft character render
  toolbox.router.get(/character\/(.*?)\.jpg/, toolbox.fastest, {
    cache: {
      name: 'worldofwarcraft-render',
      maxEntries: 50,
      maxAgeSeconds: 86400
    },
    origin: /render-(?:tw|eu|us|kr)\.worldofwarcraft\.com/
  });

  // firebase storage character index
  toolbox.router.get(/index\.json/, toolbox.fastest, {
    origin: /firebasestorage\.googleapis\.com/
  });
}(self));
<|endoftext|>


<commit_before>function rcCallWinMgr(rcSdk) {
    var t=this;
    t.rcSdk = rcSdk;
    t.domId = '#rcCallWindow';
    t.domIdStatus = '#rcCallWindowStatus';
    t.subscription = null;
    t.refreshIntervalId = null;
    t.show = function() {
        $(t.domId).show();
    }
    t.hide = function() {
        $(t.domId).hide();
    }
    t.toggle = function() {
        $(t.domId).toggle();
    }
    t.start = function(status) {
        t.show();
        $(t.domIdStatus).html(status);
        t.startCounter();
    }
    t.setStatusConnected = function() {
        $(t.domIdStatus).html('Connected');
    }
    t.setStatusEnded = function() {
        $(t.domIdStatus).html('Ended');
    }
    t.startCounter = function() {
        var minutesLabel = document.getElementById("rcMin");
        var secondsLabel = document.getElementById("rcSec");
        var totalSeconds = 0;
        t.refreshIntervalId = setInterval(setTime, 1000);

        function setTime()
        {
            ++totalSeconds;
            secondsLabel.innerHTML = pad(totalSeconds%60);
            minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
        }

        function pad(val)
        {
            var valString = val + "";
            if(valString.length < 2)
            {
                return "0" + valString;
            }
            else
            {
                return valString;
            }
        }
    }
    t.stopCounter = function() {
        if (t.refreshIntervalId) {
            clearInterval(t.refreshIntervalId);
        }
    }
    t.processCall = function(call) {
        console.log('PROCESSING_CALL');
        var ts = call.telephonyStatus;
        $('#rcCallFrom').html(call.from);
        $('#rcCallTo').html(call.to);
        if (ts == 'Ringing') {
            t.start('Ringing');
        } else if (ts == 'CallConnected') {
            $(t.domIdStatus).html('Connected');
        } else if (ts == 'NoCall') {
            var curStatus = $(t.domIdStatus).html();
            if (curStatus == 'Ringing' || curStatus == 'Connected') {
                $(t.domIdStatus).html('Ended');
            }
            t.stopCounter();
        }
    }
    t.startSubscription = function() {
        if (!t.rcSdk.platform().loggedIn()) {
            console.log("E_IS_NOT_AUTHORIZED__SKIP_SUBSCRIPTION");
            return;
        }
        t.subscription = t.rcSdk.createSubscription();

        t.subscription
            .on(t.subscription.events.notification, function(msg) {
                console.log("SUB_ON");

                var calls = msg.body.activeCalls;
                var call0 = calls[0];

                //console.log(msg.body.activeCalls[0].from); // activeCalls is array
                //console.log(msg.body.activeCalls[0].to);
                console.log(call0.from); // activeCalls is array
                console.log(call0.to);

                //var call0 = msg.body.activeCalls[0];
                var callerId = call0.from;
                var json = JSON.stringify(call0);
                console.log(json);
                rcCallWin.processCall(call0);
            });

        t.subscription
            .addEventFilters([
                '/account/~/extension/~/presence?detailedTelephonyState=true'
            ]).register();

            /*
            .then(function(response) {
                console.log(response.text());
                console.log("subscription subscribed");
            });
*/
            /*.register({
                events: [
                    '/account/~/extension/~/presence?detailedTelephonyState=true'
                ],*/
        console.log('createSubscription');
    }
    t.endSubscription = function() {
        if (t.rcSdk.platform.loggedIn()) {
            if (t.subscription) {
                t.subscription.remove({async: false});
            }
        }
        // Detach event listeners
        if (t.subscription) {
            subscription.destroy();
        }
    }
}
<commit_msg>Fixing platform().loggedIn function<commit_after>function rcCallWinMgr(rcSdk) {
    var t=this;
    t.rcSdk = rcSdk;
    t.domId = '#rcCallWindow';
    t.domIdStatus = '#rcCallWindowStatus';
    t.subscription = null;
    t.refreshIntervalId = null;
    t.show = function() {
        $(t.domId).show();
    }
    t.hide = function() {
        $(t.domId).hide();
    }
    t.toggle = function() {
        $(t.domId).toggle();
    }
    t.start = function(status) {
        t.show();
        $(t.domIdStatus).html(status);
        t.startCounter();
    }
    t.setStatusConnected = function() {
        $(t.domIdStatus).html('Connected');
    }
    t.setStatusEnded = function() {
        $(t.domIdStatus).html('Ended');
    }
    t.startCounter = function() {
        var minutesLabel = document.getElementById("rcMin");
        var secondsLabel = document.getElementById("rcSec");
        var totalSeconds = 0;
        t.refreshIntervalId = setInterval(setTime, 1000);

        function setTime()
        {
            ++totalSeconds;
            secondsLabel.innerHTML = pad(totalSeconds%60);
            minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
        }

        function pad(val)
        {
            var valString = val + "";
            if(valString.length < 2)
            {
                return "0" + valString;
            }
            else
            {
                return valString;
            }
        }
    }
    t.stopCounter = function() {
        if (t.refreshIntervalId) {
            clearInterval(t.refreshIntervalId);
        }
    }
    t.processCall = function(call) {
        console.log('PROCESSING_CALL');
        var ts = call.telephonyStatus;
        $('#rcCallFrom').html(call.from);
        $('#rcCallTo').html(call.to);
        if (ts == 'Ringing') {
            t.start('Ringing');
        } else if (ts == 'CallConnected') {
            $(t.domIdStatus).html('Connected');
        } else if (ts == 'NoCall') {
            var curStatus = $(t.domIdStatus).html();
            if (curStatus == 'Ringing' || curStatus == 'Connected') {
                $(t.domIdStatus).html('Ended');
            }
            t.stopCounter();
        }
    }
    t.startSubscription = function() {
        if (!t.rcSdk.platform().loggedIn()) {
            console.log("E_IS_NOT_AUTHORIZED__SKIP_SUBSCRIPTION");
            return;
        }
        t.subscription = t.rcSdk.createSubscription();

        t.subscription
            .on(t.subscription.events.notification, function(msg) {
                console.log("SUB_ON");

                var calls = msg.body.activeCalls;
                var call0 = calls[0];

                //console.log(msg.body.activeCalls[0].from); // activeCalls is array
                //console.log(msg.body.activeCalls[0].to);
                console.log(call0.from); // activeCalls is array
                console.log(call0.to);

                //var call0 = msg.body.activeCalls[0];
                var callerId = call0.from;
                var json = JSON.stringify(call0);
                console.log(json);
                rcCallWin.processCall(call0);
            });

        t.subscription
            .addEventFilters([
                '/account/~/extension/~/presence?detailedTelephonyState=true'
            ]).register();

            /*
            .then(function(response) {
                console.log(response.text());
                console.log("subscription subscribed");
            });
*/
            /*.register({
                events: [
                    '/account/~/extension/~/presence?detailedTelephonyState=true'
                ],*/
        console.log('createSubscription');
    }
    t.endSubscription = function() {
        if (t.rcSdk.platform().loggedIn()) {
            if (t.subscription) {
                t.subscription.remove({async: false});
            }
        }
        // Detach event listeners
        if (t.subscription) {
            subscription.destroy();
        }
    }
}
<|endoftext|>


<commit_before>
let spawn = require('../../util/spawn')
let glob = require('../../promised/glob')
let fs = require('../../promised/fs')

let errors = require('../errors')

let ibrew = require('../../util/ibrew')
let log = require('../../util/log')('installers/air')

let path = require('path')

// Adobe Air docs: http://help.adobe.com/en_US/air/redist/WS485a42d56cd19641-70d979a8124ef20a34b-8000.html

let MANIFEST_GLOB = '**/META-INF/AIR/application.xml'
let ID_RE = /<id>(.*)<\/id>/

let self = {
  install: async function (opts) {
    if (!opts.has_user_blessing) {
      throw new errors.Transition({
        to: 'ask-before-install',
        reason: `going to pop up an UAC dialog, need user's permission first`
      })
    }

    let archive_path = opts.archive_path
    let dest_path = opts.dest_path

    let spawn_opts = {
      command: 'elevate.exe',
      args: [
        archive_path, // the installer
        '-silent', // run the installer silently
        '-eulaAccepted', // let AIR install if it so wishes
        '-location', dest_path // install where we want to
      ],
      ontoken: (token) => log(opts, token)
    }
    let code = await spawn(spawn_opts)
    log(opts, `inno installer exited with code ${code}`)
  },

  uninstall: async function (opts) {
    log(opts, `Grabbing adobe's Air Runtime Helper if needed...`)

    let dest_path = opts.dest_path
    let logger = opts.logger

    let ibrew_opts = {
      logger,
      onstatus: (msg) => log(opts, `ibrew status: ${msg}`)
    }
    await ibrew.fetch(ibrew_opts, 'arh')

    log(opts, `Locating app manifest`)

    let candidates = await glob(MANIFEST_GLOB, {cwd: dest_path})
    if (candidates.length === 0) {
      throw new Error(`Adobe AIR app manifest not found, cannot uninstall`)
    }

    log(opts, `Found app manifest at ${candidates[0]}`)

    let manifest_path = path.join(dest_path, candidates[0])
    let manifest_contents = await fs.readFileAsync(manifest_path, {encoding: 'utf8'})
    let matches = ID_RE.execute(manifest_contents)
    if (!matches) {
      throw new Error(`Could not extract app id from manifest at ${manifest_path}`)
    }

    let appid = matches[1]
    log(opts, `Found appid ${appid}, uninstalling...`)

    let spawn_opts = {
      command: 'arh',
      args: [
        '-uninstallAppSilent',
        appid
      ],
      ontoken: (tok) => log(opts, `arh: ${tok}`)
    }
    let code = await spawn(spawn_opts)
    if (code !== 0) {
      throw new Error(`arh uninstall failed with code ${code}`)
    }
  }
}

module.exports = self
<commit_msg>Handle AIR errors more gracefully<commit_after>
let spawn = require('../../util/spawn')
let glob = require('../../promised/glob')
let fs = require('../../promised/fs')

let errors = require('../errors')

let ibrew = require('../../util/ibrew')
let log = require('../../util/log')('installers/air')

let path = require('path')

// Adobe Air docs: http://help.adobe.com/en_US/air/redist/WS485a42d56cd19641-70d979a8124ef20a34b-8000.html

let MANIFEST_GLOB = '**/META-INF/AIR/application.xml'
let ID_RE = /<id>(.*)<\/id>/
let CODE_MESSAGES = {
  1: 'Successful, but restart required for completion',
  2: 'Usage error (incorrect arguments)',
  3: 'Runtime not found',
  4: 'Loading runtime failed',
  5: 'Unknown error',
  6: 'Installation canceled',
  7: 'Installation failed',
  8: 'Installation failed; update already in progress',
  9: 'Installation failed; application already installed'
}

let self = {
  install: async function (opts) {
    if (!opts.has_user_blessing) {
      throw new errors.Transition({
        to: 'ask-before-install',
        reason: `going to pop up an UAC dialog, need user's permission first`
      })
    }

    let archive_path = opts.archive_path
    let dest_path = opts.dest_path

    let spawn_opts = {
      command: 'elevate.exe',
      args: [
        archive_path, // the installer
        '-silent', // run the installer silently
        '-eulaAccepted', // let AIR install if it so wishes
        '-location', dest_path // install where we want to
      ],
      ontoken: (token) => log(opts, token)
    }
    let code = await spawn(spawn_opts)
    log(opts, `air installer exited with code ${code}`)

    if (code !== 0) {
      let message = CODE_MESSAGES[code]
      throw new Error(`AIR installer error: ${message}`)
    }
  },

  uninstall: async function (opts) {
    log(opts, `Grabbing adobe's Air Runtime Helper if needed...`)

    let dest_path = opts.dest_path
    let logger = opts.logger

    let ibrew_opts = {
      logger,
      onstatus: (msg) => log(opts, `ibrew status: ${msg}`)
    }
    await ibrew.fetch(ibrew_opts, 'arh')

    log(opts, `Locating app manifest`)

    let candidates = await glob(MANIFEST_GLOB, {cwd: dest_path})
    if (candidates.length === 0) {
      throw new Error(`Adobe AIR app manifest not found, cannot uninstall`)
    }

    log(opts, `Found app manifest at ${candidates[0]}`)

    let manifest_path = path.join(dest_path, candidates[0])
    let manifest_contents = await fs.readFileAsync(manifest_path, {encoding: 'utf8'})
    let matches = ID_RE.execute(manifest_contents)
    if (!matches) {
      throw new Error(`Could not extract app id from manifest at ${manifest_path}`)
    }

    let appid = matches[1]
    log(opts, `Found appid ${appid}, uninstalling...`)

    let spawn_opts = {
      command: 'arh',
      args: [
        '-uninstallAppSilent',
        appid
      ],
      ontoken: (tok) => log(opts, `arh: ${tok}`)
    }
    let code = await spawn(spawn_opts)
    if (code !== 0) {
      throw new Error(`arh uninstall failed with code ${code}`)
    }
  }
}

module.exports = self
<|endoftext|>


<commit_before>var orderedByStatus = true;
var sortByStat;
var sortByParty;
var redraw;
var grouped = null;
var mod2Scope, highlight;

(function () {

    var thelawfactory = window.thelawfactory || (window.thelawfactory = {});

    var setMod2Size = thelawfactory.utils.setModSize("#viz", 1),
        clean_amd_subject = function (s) {
        return s.replace(/ART[\.\s]+/i, "Article ")
            .replace(/A(vant|près) A/i, "A$1 l'A");
        },
        slugArticle = function (a) {
            return "art_" + a.toLowerCase()
                    .replace("è", "e")
                    .replace(/article/, '')
                    .replace(/[i1]er?/, '1')
                    .trim()
                    .replace(/\W/g, '-')
        };

    thelawfactory.mod2 = function () {

        function get_status_img(e) {
            if (e.sort === "adopté") return "img/ok.png";
            if (e.sort === "rejeté") return "img/ko.png";
            if (e.sort === "non-voté") return "img/nd.png";
            return "";
        }

        function vis(data, vizTitle, helpText) {

            var drawing = false,
                articles = data.sujets,
                groups = data.groupes,
                api_root = data.api_root_url,
                resetHighlight;

            mod2Scope = $('.mod2').scope();

            highlight = function(group) {
                thelawfactory.utils.highlightGroup(vizTitle, helpText, groups, group);
            };

            resetHighlight = function() {
                thelawfactory.utils.resetHighlight(vizTitle, helpText);
            };

            if (Object.keys(articles).length < 2)
                $('#display_menu').parent().hide();

            selectRow = function (art, pos) {
                if (d3.event) d3.event.stopPropagation();
                var sel = d3.select("." + slugArticle(art));
                if (!sel.empty()) {
                    resetHighlight();
                    d3.selectAll("g").style("opacity", 0.2);
                    sel.style("opacity", 1);
                    if (pos) $("#viz").animate({scrollTop: sel.attr("data-offset")})
                }
            };

            deselectRow = function () {
                if (d3.event) d3.event.stopPropagation();
                resetHighlight();
                $("#readMode").hide();
                d3.selectAll("g").style("opacity", 1);
            };

            var artArray = d3.values(articles).sort(function (a, b) {
                return a.order - b.order
            });

            var w, rw, minheight, nsq, z,
                lineh = 30,
                x = 0, y, h,
                jumpLines = 0,
                offset = 0;
            var readSizes = function () {
                rw = $("#viz").width();
                w = rw - 30;
                minheight = $("#viz").height() - 5;
                z = 20;
                nsq = Math.round((w - 40) / z);
                h = lineh * artArray.length + 40;
                y = h / z;
            };
            readSizes();
            var svg = d3.select("#viz").append("svg")
                .attr("width", rw)
                .attr("height", Math.max(minheight, h))
                .on("click", deselectRow);

            var compare_partys = function (a, b) {
                    if (groups[a].order < groups[b].order) return -1;
                    if (groups[a].order > groups[b].order) return 1;
                },
                statsorder = {"adopté": 0, "rejeté": 1, "non-voté": 2, "en attente": 3},
                compare_stats = function (a, b) {
                    if (statsorder[a] < statsorder[b]) return -1;
                    if (statsorder[a] > statsorder[b]) return 1;
                },
                compare_by_party = function (a, b) {
                    if (a.groupe != b.groupe) return compare_partys(a.groupe, b.groupe);
                    if (a.sort != b.sort) return compare_stats(a.sort, b.sort);
                    return a.numero.replace(/^\D+/, '') - b.numero.replace(/^\D+/, '');
                },
                compare_by_stat = function (a, b) {
                    if (a.sort != b.sort) return compare_stats(a.sort, b.sort);
                    if (a.groupe != b.groupe) return compare_partys(a.groupe, b.groupe);
                    return a.numero.replace(/^\D+/, '') - b.numero.replace(/^\D+/, '');
                },
                check_half = function (g) {
                    var half_col = false;
                    var maxlen;
                    if (!g) maxlen = d3.max(artArray, function (d) {
                        return d.amendements.length
                    });
                    else maxlen = grouped.amendements.length;

                    if (maxlen < nsq / 2) {
                        x = nsq / 2 - 1;
                        half_col = true;
                    }
                    else x = nsq;
                    return half_col;
                };

            sortByStat = function () {
                $("#display_order .chosen").removeClass('chosen');
                $("#display_order #do-stat").addClass('chosen');
                $("#menu-order .selectedchoice").text('sort final');
                orderedByStatus = true;
                redraw();
            };

            sortByParty = function () {
                $("#display_order .chosen").removeClass('chosen');
                $("#display_order #do-party").addClass('chosen');
                $("#menu-order .selectedchoice").text('groupe politique');
                orderedByStatus = false;
                redraw();
            };
            redraw = function (merged) {
                var selected_amd = d3.selectAll(".actv-amd");
                if (selected_amd[0].length) selected_amd = selected_amd[0][0].id;
                else selected_amd = "";
                setMod2Size();
                thelawfactory.utils.setTextContainerHeight();
                readSizes();
                if (merged == undefined) merged = grouped;
                $('#menu-display .selectedchoice').text(merged ? 'groupée' : 'par articles');
                $("svg").empty();
                thelawfactory.utils.spinner.start();
                $("svg").animate({opacity: 0}, 50, function () {
                    jumpLines = 0;
                    (merged ? drawMerged() : draw());
                    var a = d3.select("svg").select("g:last-child").attr("data-offset"),
                        ah = d3.select("svg").select("g:last-child").node().getBBox().height;
                    svg.attr("height", Math.max(minheight, z + parseInt(a) + ah));
                    if (mod2Scope.article != null)
                        selectRow(mod2Scope.article, true);
                    thelawfactory.utils.spinner.stop(function () {
                        svg.attr("width", $("#viz").width());
                        $("svg").animate({opacity: 1}, 50);
                        drawing = true;
                        setTimeout(thelawfactory.utils.setTextContainerHeight, 250);
                        if (selected_amd) $("#" + selected_amd).d3Click();
                        drawing = false;
                    });
                });
            };

            function draw() {
                $("#display_menu .chosen").removeClass('chosen');
                $("#display_menu #dm-draw").addClass('chosen');
                grouped = null;
                artArray.forEach(function (d) {
                    d['amendements'].sort((orderedByStatus ? compare_by_stat : compare_by_party));
                });

                var half_col = check_half();
                artArray.forEach(function (d, i) {
                    drawLines(d, i, half_col)
                });
            }

            function drawMerged() {
                $("#display_menu .chosen").removeClass('chosen');
                $("#display_menu #dm-merged").addClass('chosen');
                if (!grouped) {
                    grouped = {titre: 'Tous les amendements', key: 'all articles', amendements: []};
                    artArray.forEach(function (d) {
                        grouped.amendements = grouped.amendements.concat(d.amendements)
                    });
                }

                var half_col = check_half(grouped);
                grouped['amendements'].sort((orderedByStatus ? compare_by_stat : compare_by_party));
                drawLines(grouped, 0, half_col);
            }

            function drawLines(d, i, half) {

                var multi = false;
                len = d.amendements.length;
                lines = Math.ceil(len / x);
                if (lines > 1) {
                    multi = true;
                    lines += 1;
                }
                var k = Math.floor(i / 2);
                d.offset = offset;
                var curRow = svg.append("g")
                    .classed(slugArticle(d.titre), true)
                    .classed("first-art-s", i == 0)
                    .attr("transform", function () {
                        if (!half) return "translate(" + 10 + "," + (i * 20 + i * lineh + 10 + jumpLines * (lineh - 10)) + ")";
                        else {
                            return "translate(" + (10 + (i % 2) * w / 2) + "," + (k * 20 + k * lineh + 10 + jumpLines * (lineh - 10)) + ")";
                        }
                    })
                    .attr("data-offset", function () {
                        if (!half) return i * 20 + i * lineh + 10 + jumpLines * (lineh - 10);
                        else return k * 20 + k * lineh + 10 + jumpLines * (lineh - 10);
                    })
                    .call(function () {
                        if (!multi) {
                            n = d.amendements.length;
                            offset = Math.floor(n / x);
                            jumpLines = jumpLines + offset;
                        }
                        else jumpLines += lines - 1;
                    });

                var bg = curRow
                    .selectAll(".bg")
                    .data(d3.range(x * lines))
                    .enter();

                bg.append("rect")
                    .attr("x", function (f) {
                        return (f % x) * z + 21
                    })
                    .attr("y", function (f) {
                        return Math.floor(f / x) * z + 21
                    })
                    .attr("width", z - 2)
                    .attr("height", z - 2)
                    .classed("bg", true)
                    .style("fill", "#F0F0F0");

                curRow.append("text")
                    .attr("x", 20)
                    .classed("row-txt", true)
                    .attr("y", 15)
                    .style("fill", "#716259")
                    .attr("font-size", "0.85em")
                    .text(d.titre)
                    .on("click", function () {
                        selectRow(d.titre, false);
                    });

                var popover = function (e) {
                    var date = e.date.split('-'),
                        div = d3.select(document.createElement("div")).style("width", "100%");
                    div.append("p").html("" + groups[e.groupe].nom + "");
                    div.append("p").html("Sort : " + e.sort + "");
                    div.append("p").html("" + [date[2], date[1], date[0]].join("/") + "");
                    return {
                        title: "Amendement " + e.numero,
                        content: div,
                        placement: "mouse",
                        gravity: "right",
                        displacement: [10, -80],
                        mousemove: true
                    };
                };

                var amds = curRow
                    .selectAll(".amd")
                    .data(d.amendements)
                    .enter();
                amds.append("rect")
                    .attr("x", function (f, j) {
                        if (multi)  return Math.floor(j / lines) * z + 21;
                        else return (j % x) * z + 21
                    })
                    .attr("y", function (f, j) {
                        if (multi)  return Math.floor(Math.floor(j / lines) % 2 == 0 ? j % lines : lines - (j % lines) - 1) * z + 21;
                        return Math.floor(j / x) * z + 21
                    })
                    .attr("width", z - 2)
                    .attr("height", z - 2)
                    .attr("id", function (e) {
                        return "a_" + e.numero.replace(/[^a-z\d]/ig, '')
                    })
                    .attr("class", function (e) {
                        return "amd " + thelawfactory.utils.slugGroup(e.groupe) + " " + thelawfactory.utils.slugGroup(e.sort);
                    })
                    .classed("first-art", function (f, j) {
                        return i == 0 && j == 0;
                    })
                    .style("fill", color_amd)
                    .style("opacity", 0.9)
                    .popover(popover)
                    .on("click", select);

                var imgs = curRow
                    .selectAll("image")
                    .data(d.amendements)
                    .enter();
                imgs.append("svg:image")
                    .attr("x", function (f, j) {
                        if (multi)  return Math.floor(j / lines) * z + 25;
                        else return (j % x) * z + 25
                    })
                    .attr("y", function (f, j) {
                        if (multi)  return Math.floor(Math.floor(j / lines) % 2 == 0 ? j % lines : lines - (j % lines) - 1) * z + 25;
                        return Math.floor(j / x) * z + 25
                    })
                    .attr("width", z - 10)
                    .attr("height", z - 10)
                    .attr("xlink:href", get_status_img)
                    .popover(popover)
                    .on("click", select);
            }

            function select(d) {
                d3.event.stopPropagation();
                if (!drawing) resetHighlight();
                d3.selectAll("#a_" + d.numero.replace(/[^a-z\d]/ig, ''))
                    .classed("actv-amd", true)
                    .style("opacity", 1)
                    .style("stroke", "#333344")
                    .style("stroke-width", 2);
                if (drawing) return;
                $("#readMode").show();
                $("#text-title").text("Amendement " + d.numero);
                $(".text-container").empty();
                thelawfactory.utils.setTextContainerHeight();
                thelawfactory.utils.spinner.start('load_amd');
                setTimeout(function () {
                    d3.json(api_root + d.id_api + '/json?'+new Date(), function (error, json) {
                        var currAmd = json.amendement,
                            source_am = '.fr     ',
                            statico = get_status_img(d),
                            col = color_amd(d);
                        if (currAmd.url_nosdeputes) source_am = currAmd.url_nosdeputes + '"> NosDéputés' + source_am + 'Assemblée nationale';
                        else if (currAmd.url_nossenateurs) source_am = currAmd.url_nossenateurs + '"> NosSénateurs' + source_am + 'Sénat';
                        $(".text-container").html(
                            '' + d3.time.format("%d/%m/%Y")(d3.time.format("%Y-%m-%d").parse(d.date)) + "" +
                            '' + currAmd.sort + "  " +
                            '
Sujet : ' + clean_amd_subject(currAmd.sujet) + "
" +
                            '
Signataires : ' + currAmd.signataires + "
" +
                            '
Exposé des motifs : ' + currAmd.expose + "
" +
                            '
Texte : ' + currAmd.texte + '
' +
                            '
<a target="_blank" href="' + source_am + '
'
                        );
                        thelawfactory.utils.spinner.stop(function () {
                            $(".text-container").animate({opacity: 1}, 350);
                            $('.text-container').scrollTop(0);
                        }, 'load_amd');
                    });
                }, 50);
            }

            function color_amd(d) {
                if (groups[d.groupe]) {
                    return thelawfactory.utils.adjustColor(groups[d.groupe].color).toString();
                } else return "#E6E6E6";
            }

            $(document).ready(function () {
                $(".text-container").empty().html(helpText);
                thelawfactory.utils.drawGroupsLegend(groups);
                $('.readMode').tooltip({animated: 'fade', placement: 'bottom'});
                if ($(".others div").length) $(".others").append('

');
                [
                    {nom: 'Adopté', id: 'adopt', img: 'ok'},
                    {nom: 'Rejeté', id: 'rejet', img: 'ko'},
                    {nom: 'Non voté', id: 'nonvot', img: 'nd'}
                ].forEach(function (d) {
                        var oncl = 'onclick="highlight(\'' + d.id + '\')" title="Amendements ' + d.nom.toLowerCase() + 's" data-toggle="tooltip" data-placement="left">';
                        $(".others").append('
<div class="leg-value" style="background-color: rgb(180,180,180); background-image: url(img/' + d.img + '.png); background-repeat:no-repeat; background-position:50% 50%;"' + oncl + '
<div class="leg-key"' + oncl + d.nom + '

');
                    });
                $(".leg-value").tooltip();
                $(".leg-key").tooltip();
                redraw(false);
                $(window).resize(function () {
                    if (drawing || $(".view").scope().mod != "mod2") return;
                    drawing = true;
                    setTimeout(function () {
                        redraw();
                        drawing = false;
                    }, 150);
                });
            });

        } //end function vis

        return vis;
    };

})();
<commit_msg>Remove unused mod2.js<commit_after><|endoftext|>


<commit_before>function insertAvaForm() {
    $('.avaform-wrapper').append('
 Request a Free AvaTax Account <form id="trial-form">
 First Name / Given Name <input type="text" class="form-control" id="firstName" name="firstName" placeholder="" >

 Last Name / Family Name <input type="text" class="form-control" id="lastName" name="lastName" placeholder="">

 Email Address <input type="email" class="form-control" id="email" name="email" placeholder="">

 Company <input type="text" class="form-control" id="company" name="company" placeholder="">

 Website <input type="text" class="form-control" id="website" name="website" placeholder="">

 Phone <input type="tel" class="form-control" id="phone" name="phone" placeholder="">

 Street Address <input type="text" class="form-control" id="street-address" name="street-address" placeholder="">

 City <input type="text" class="form-control" id="city" name="city" placeholder="">

 Region / State / Province <input type="text" class="form-control" id="region" name="region" placeholder="">

 Country <input type="text" class="form-control" id="country" name="country" placeholder="">

 Postal Code <input type="text" class="form-control" id="postal-code" name="postal-code" placeholder="">

<input type="checkbox" id="terms-and-conditions"> Click here to indicate that you have read and agree to the terms in the Avalara Terms and Conditions</input>
 <button type="button" id="submit" class="btn btn-primary" onclick="return submitShort();" style="clear:both;">Submit</button> </form>

');
}

function submitShort() {
    const inputArr = $('#trial-form')[0];
    let failCount = 0;

    for (let i = 0; i < (inputArr.length - 1); i++) {
        const input = inputArr[i];

        if (input.value !== '') {
            input.className = inputArr[i].classList[0];
        }

        if (input.value === '') {
            input.placeholder = 'Required';
            input.className += ' required';
            failCount++;
        }
    }

    if (failCount > 0) {
        $('#ava-form-info').html('You are missing ' + failCount + ' required field(s).');
        $('#ava-form-alert').attr('class', 'alert alert-warning fade in');
        $('#ava-form-alert').show();
        return;
    }

    if($('#terms-and-conditions').is(':checked')) {
    } else {
        $('#ava-form-info').html('Please accept our terms and conditions.');
        $('#ava-form-alert').attr('class', 'alert alert-warning fade in');
        $('#ava-form-alert').show();
        return;
    }

    var c_id = null;

    // AvaTag is a marketing feature that gathers informaton and persists it across site visits
    if (AvaTag.getCombinedData()['CampaignID']) {
        c_id = AvaTag.getCombinedData()['CampaignID'];
    }
    // console.log("c_id = " + c_id);
    $('#ava-form-alert').hide();
    var payload = {
        firstName: $('#firstName').val(),
        lastName: $('#lastName').val(),
        email: $('#email').val(),
        company: $('#company').val(),
        website: $('#website').val(),
        phone: $('#phone').val(),
        campaign: c_id,
        companyAddress: {
            line: $('#street-address').val(),
            city: $('#city').val(),
            region: $('#region').val(),
            country: $('#country').val(),
            postalCode: $('#postal-code').val()
        }
    };

    // console.log("payload: ", JSON.stringify(payload));
    $.ajax({
        url: 'https://rest.avatax.com/api/v2/accounts/freetrials/request',
        data: JSON.stringify(payload),
        contentType: 'application/json',
        beforeSend: function() {
            $('#submit').prop('disabled', true); // disable button
        },
        error: function(err) {
            var avataxerror = $.parseJSON(err.responseText);
            $('#ava-form-info').html(avataxerror.error.message);
            $('#ava-form-alert').attr('class', 'alert alert-warning fade in');
            $('#submit').prop('disabled', false);
            $('#ava-form-alert').show();
            // console.log('response: ', err);
        },
        dataType: 'json',
        success: function(data) {
            $('#ava-form-info').html('Success!  Your account credentials have been sent to ' + data.accountDetailsEmailedTo + '.');
            $('#ava-form-alert').attr('class', 'alert alert-success fade in');
            $('#submit').prop('disabled', false);
            $('#ava-form-alert').show();
            // console.log('response: ', data);
        },
        type: 'POST'
    });
    return false;
}

// Populate forms on ready
$(
    function() {
        insertAvaForm();
    }
);
<commit_msg>added the link to the terms and conditions<commit_after>function insertAvaForm() {
    $('.avaform-wrapper').append('
 Request a Free AvaTax Account <form id="trial-form">
 First Name / Given Name <input type="text" class="form-control" id="firstName" name="firstName" placeholder="" >

 Last Name / Family Name <input type="text" class="form-control" id="lastName" name="lastName" placeholder="">

 Email Address <input type="email" class="form-control" id="email" name="email" placeholder="">

 Company <input type="text" class="form-control" id="company" name="company" placeholder="">

 Website <input type="text" class="form-control" id="website" name="website" placeholder="">

 Phone <input type="tel" class="form-control" id="phone" name="phone" placeholder="">

 Street Address <input type="text" class="form-control" id="street-address" name="street-address" placeholder="">

 City <input type="text" class="form-control" id="city" name="city" placeholder="">

 Region / State / Province <input type="text" class="form-control" id="region" name="region" placeholder="">

 Country <input type="text" class="form-control" id="country" name="country" placeholder="">

 Postal Code <input type="text" class="form-control" id="postal-code" name="postal-code" placeholder="">

<input type="checkbox" id="terms-and-conditions"> Click here to indicate that you have read and agree to the terms in Avalara\'s Terms and Conditions</input>
 <button type="button" id="submit" class="btn btn-primary" onclick="return submitShort();" style="clear:both;">Submit</button> </form>

');
}

function submitShort() {
    const inputArr = $('#trial-form')[0];
    let failCount = 0;

    for (let i = 0; i < (inputArr.length - 1); i++) {
        const input = inputArr[i];

        if (input.value !== '') {
            input.className = inputArr[i].classList[0];
        }

        if (input.value === '') {
            input.placeholder = 'Required';
            input.className += ' required';
            failCount++;
        }
    }

    if (failCount > 0) {
        $('#ava-form-info').html('You are missing ' + failCount + ' required field(s).');
        $('#ava-form-alert').attr('class', 'alert alert-warning fade in');
        $('#ava-form-alert').show();
        return;
    }

    if($('#terms-and-conditions').is(':checked')) {
    } else {
        $('#ava-form-info').html('Please accept our terms and conditions.');
        $('#ava-form-alert').attr('class', 'alert alert-warning fade in');
        $('#ava-form-alert').show();
        return;
    }

    var c_id = null;

    // AvaTag is a marketing feature that gathers informaton and persists it across site visits
    if (AvaTag.getCombinedData()['CampaignID']) {
        c_id = AvaTag.getCombinedData()['CampaignID'];
    }
    // console.log("c_id = " + c_id);
    $('#ava-form-alert').hide();
    var payload = {
        firstName: $('#firstName').val(),
        lastName: $('#lastName').val(),
        email: $('#email').val(),
        company: $('#company').val(),
        website: $('#website').val(),
        phone: $('#phone').val(),
        campaign: c_id,
        companyAddress: {
            line: $('#street-address').val(),
            city: $('#city').val(),
            region: $('#region').val(),
            country: $('#country').val(),
            postalCode: $('#postal-code').val()
        }
    };

    // console.log("payload: ", JSON.stringify(payload));
    $.ajax({
        url: 'https://rest.avatax.com/api/v2/accounts/freetrials/request',
        data: JSON.stringify(payload),
        contentType: 'application/json',
        beforeSend: function() {
            $('#submit').prop('disabled', true); // disable button
        },
        error: function(err) {
            var avataxerror = $.parseJSON(err.responseText);
            $('#ava-form-info').html(avataxerror.error.message);
            $('#ava-form-alert').attr('class', 'alert alert-warning fade in');
            $('#submit').prop('disabled', false);
            $('#ava-form-alert').show();
            // console.log('response: ', err);
        },
        dataType: 'json',
        success: function(data) {
            $('#ava-form-info').html('Success!  Your account credentials have been sent to ' + data.accountDetailsEmailedTo + '.');
            $('#ava-form-alert').attr('class', 'alert alert-success fade in');
            $('#submit').prop('disabled', false);
            $('#ava-form-alert').show();
            // console.log('response: ', data);
        },
        type: 'POST'
    });
    return false;
}

// Populate forms on ready
$(
    function() {
        insertAvaForm();
    }
);
<|endoftext|>