<commit_before>var chrome = require('sinon-chrome');

var googleSearch   = 'Add Readability & Trustability Information in ' +
  'Google search results';
var yahooSearch    = 'Add Readability & Trustability Information in ' +
  'Yahoo search results';
var bingSearch     = 'Add Readability & Trustability Information in ' +
  ' Bing search results';

// Google
casper.test.begin(googleSearch, 5, function suite(test) {

  casper.start('http://www.google.fr/', function() {
    test.assertExists('form[action="/search"]', 'main form is found');
    this.fill('form[action="/search"]', {
      q: 'vidal'
    }, true);

    this.waitForSelector('h3.r a');
  });

  casper.then(function() {

    // Chrome API polyfill
    this.evaluate(function(chrome) {
      chrome.i18n.getMessage = function(message) {
        return message;
      };

      window.chrome = chrome;
    }, chrome);

    this.page.injectJs('app/bower_components/jquery/dist/jquery.min.js');
    this.page.injectJs(
      'app/bower_components/circular-progress/circular-progress.min.js');
    this.page.injectJs('app/scripts/kconnect.js');
    this.page.injectJs('app/scripts/contentscript.js');

    this.evaluate(function() {
      var kConnectApiUrl = 'https://apikconnect.honservices.org/~kconnect/' +
        'cgi-bin/';
      var trustabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'is-trustable.cgi?domain=vidal.fr',
        'GET'
      );
      var readabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'readability.cgi?data={"url":"https://www.vidal.fr"}',
        'GET'
      );
      readabilityCallback(
        JSON.parse(readabilityReq),
        $(document.querySelectorAll('h3.r a').item(0)).parent().siblings('.s')
      );
      trustabilityCallback(
        JSON.parse(trustabilityReq),
        $(document.querySelectorAll('h3.r a').item(0)).parent().siblings('.s'),
        'https://www.vidal.fr'
      );
    });

    test.assertTitle('vidal - Recherche Google', 'google title is ok');
    test.assertUrlMatch(/q=vidal/, 'search term has been submitted');

    test.assertEval(function() {
      return __utils__.findAll('.trustability').length === 1;
    }, 'trustability informations found');
    test.assertEval(function() {
      return __utils__.findAll('.readability').length === 1;
    }, 'readability informations found');

  });

  casper.run(function() {
    test.done();
  });
});

// Yahoo
casper.test.begin(yahooSearch, 6, function suite(test) {

  casper.start('https://fr.yahoo.com/', function() {
    test.assertExists(
      'form[action="https://fr.search.yahoo.com/search"]',
      'main form is found'
    );
    this.fill('form[action="https://fr.search.yahoo.com/search"]', {
      p: 'vidal'
    }, true);
    test.assertExists('input[name="p"]', 'input form is found');
    this.waitForSelector('h3.title a');
  });

  casper.then(function() {

    // Chrome API polyfill
    this.evaluate(function(chrome) {
      chrome.i18n.getMessage = function(message) {
        return message;
      };

      window.chrome = chrome;
    }, chrome);

    this.page.injectJs('app/bower_components/jquery/dist/jquery.min.js');
    this.page.injectJs(
      'app/bower_components/circular-progress/circular-progress.min.js');
    this.page.injectJs('app/scripts/kconnect.js');
    this.page.injectJs('app/scripts/contentscript.js');

    this.evaluate(function() {
      var kConnectApiUrl = 'https://apikconnect.honservices.org/~kconnect/' +
        'cgi-bin/';
      var trustabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'is-trustable.cgi?domain=vidal.fr',
        'GET'
      );
      var readabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'readability.cgi?data={"url":"https://www.vidal.fr"}',
        'GET'
      );
      readabilityCallback(
        JSON.parse(readabilityReq),
        $(
          document.querySelectorAll('h3.title a').item(0)
        ).parent().siblings('div:first')
      );
      trustabilityCallback(
        JSON.parse(trustabilityReq),
        $(
          document.querySelectorAll('h3.title a').item(0)
        ).parent().siblings('div:first'),
        'https://www.vidal.fr'
      );
    });

    test.assertTitle('vidal - Yahoo Search - Actualités', 'yahoo title is ok');
    test.assertUrlMatch(/p=vidal/, 'search term has been submitted');

    test.assertEval(function() {
      return __utils__.findAll('.trustability').length === 1;
    }, 'trustability informations found');
    test.assertEval(function() {
      return __utils__.findAll('.readability').length === 1;
    }, 'readability informations found');

  });

  casper.run(function() {
    test.done();
  });
});

// Bing
casper.test.begin(bingSearch, 5, function suite(test) {

  casper.start('https://www.bing.com/', function() {
    test.assertExists('form[action="/search"]', 'main form is found');
    this.fill('form[action="/search"]', {
      q: 'vidal'
    }, true);
    this.waitForSelector('.b_algo h2 a');
  });

  casper.then(function() {

    // Chrome API polyfill
    this.evaluate(function(chrome) {
      chrome.i18n.getMessage = function(message) {
        return message;
      };

      window.chrome = chrome;
    }, chrome);

    this.page.injectJs('app/bower_components/jquery/dist/jquery.min.js');
    this.page.injectJs(
      'app/bower_components/circular-progress/circular-progress.min.js');
    this.page.injectJs('app/scripts/kconnect.js');
    this.page.injectJs('app/scripts/contentscript.js');

    this.evaluate(function() {
      var kConnectApiUrl = 'https://apikconnect.honservices.org/~kconnect/' +
        'cgi-bin/';
      var trustabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'is-trustable.cgi?domain=vidal.fr',
        'GET'
      );
      var readabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'readability.cgi?data={"url":"https://www.vidal.fr"}',
        'GET'
      );
      readabilityCallback(
        JSON.parse(readabilityReq),
        $(
          document.querySelectorAll('.b_algo h2 a').item(0)
        ).parent().siblings('div')
      );
      trustabilityCallback(
        JSON.parse(trustabilityReq),
        $(
          document.querySelectorAll('.b_algo h2 a').item(0)
        ).parent().siblings('div')
      );
    });

    test.assertTitle('vidal - Bing', 'bing title is ok');
    test.assertUrlMatch(/q=vidal/, 'search term has been submitted');

    test.assertEval(function() {
      return __utils__.findAll('.trustability').length === 1;
    }, 'trustability informations found');
    test.assertEval(function() {
      return __utils__.findAll('.readability').length === 1;
    }, 'readability informations found');

  });

  casper.run(function() {
    test.done();
  });
});
<commit_msg>wait for selector on test<commit_after>var chrome = require('sinon-chrome');

var googleSearch   = 'Add Readability & Trustability Information in ' +
  'Google search results';
var yahooSearch    = 'Add Readability & Trustability Information in ' +
  'Yahoo search results';
var bingSearch     = 'Add Readability & Trustability Information in ' +
  ' Bing search results';

// Google
casper.test.begin(googleSearch, 5, function suite(test) {

  casper.start('http://www.google.fr/', function() {
    test.assertExists('form[action="/search"]', 'main form is found');
    this.fill('form[action="/search"]', {
      q: 'vidal'
    }, true);

    this.waitForSelector('h3.r a');
  });

  casper.then(function() {

    // Chrome API polyfill
    this.evaluate(function(chrome) {
      chrome.i18n.getMessage = function(message) {
        return message;
      };

      window.chrome = chrome;
    }, chrome);

    this.page.injectJs('app/bower_components/jquery/dist/jquery.min.js');
    this.page.injectJs(
      'app/bower_components/circular-progress/circular-progress.min.js');
    this.page.injectJs('app/scripts/kconnect.js');
    this.page.injectJs('app/scripts/contentscript.js');

    this.evaluate(function() {
      var kConnectApiUrl = 'https://apikconnect.honservices.org/~kconnect/' +
        'cgi-bin/';
      var trustabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'is-trustable.cgi?domain=vidal.fr',
        'GET'
      );
      var readabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'readability.cgi?data={"url":"https://www.vidal.fr"}',
        'GET'
      );
      readabilityCallback(
        JSON.parse(readabilityReq),
        $(document.querySelectorAll('h3.r a').item(0)).parent().siblings('.s')
      );
      trustabilityCallback(
        JSON.parse(trustabilityReq),
        $(document.querySelectorAll('h3.r a').item(0)).parent().siblings('.s'),
        'https://www.vidal.fr'
      );
    });

    test.assertTitle('vidal - Recherche Google', 'google title is ok');
    test.assertUrlMatch(/q=vidal/, 'search term has been submitted');

    this.waitForSelector('.trustability');

    test.assertEval(function() {
      return __utils__.findAll('.trustability').length === 1;
    }, 'trustability informations found');
    test.assertEval(function() {
      return __utils__.findAll('.readability').length === 1;
    }, 'readability informations found');

  });

  casper.run(function() {
    test.done();
  });
});

// Yahoo
casper.test.begin(yahooSearch, 6, function suite(test) {

  casper.start('https://fr.yahoo.com/', function() {
    test.assertExists(
      'form[action="https://fr.search.yahoo.com/search"]',
      'main form is found'
    );
    this.fill('form[action="https://fr.search.yahoo.com/search"]', {
      p: 'vidal'
    }, true);
    test.assertExists('input[name="p"]', 'input form is found');
    this.waitForSelector('h3.title a');
  });

  casper.then(function() {

    // Chrome API polyfill
    this.evaluate(function(chrome) {
      chrome.i18n.getMessage = function(message) {
        return message;
      };

      window.chrome = chrome;
    }, chrome);

    this.page.injectJs('app/bower_components/jquery/dist/jquery.min.js');
    this.page.injectJs(
      'app/bower_components/circular-progress/circular-progress.min.js');
    this.page.injectJs('app/scripts/kconnect.js');
    this.page.injectJs('app/scripts/contentscript.js');

    this.evaluate(function() {
      var kConnectApiUrl = 'https://apikconnect.honservices.org/~kconnect/' +
        'cgi-bin/';
      var trustabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'is-trustable.cgi?domain=vidal.fr',
        'GET'
      );
      var readabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'readability.cgi?data={"url":"https://www.vidal.fr"}',
        'GET'
      );
      readabilityCallback(
        JSON.parse(readabilityReq),
        $(
          document.querySelectorAll('h3.title a').item(0)
        ).parent().siblings('div:first')
      );
      trustabilityCallback(
        JSON.parse(trustabilityReq),
        $(
          document.querySelectorAll('h3.title a').item(0)
        ).parent().siblings('div:first'),
        'https://www.vidal.fr'
      );
    });

    test.assertTitle('vidal - Yahoo Search - Actualités', 'yahoo title is ok');
    test.assertUrlMatch(/p=vidal/, 'search term has been submitted');

    this.waitForSelector('.trustability');

    test.assertEval(function() {
      return __utils__.findAll('.trustability').length === 1;
    }, 'trustability informations found');
    test.assertEval(function() {
      return __utils__.findAll('.readability').length === 1;
    }, 'readability informations found');

  });

  casper.run(function() {
    test.done();
  });
});

// Bing
casper.test.begin(bingSearch, 5, function suite(test) {

  casper.start('https://www.bing.com/', function() {
    test.assertExists('form[action="/search"]', 'main form is found');
    this.fill('form[action="/search"]', {
      q: 'vidal'
    }, true);
    this.waitForSelector('.b_algo h2 a');
  });

  casper.then(function() {

    // Chrome API polyfill
    this.evaluate(function(chrome) {
      chrome.i18n.getMessage = function(message) {
        return message;
      };

      window.chrome = chrome;
    }, chrome);

    this.page.injectJs('app/bower_components/jquery/dist/jquery.min.js');
    this.page.injectJs(
      'app/bower_components/circular-progress/circular-progress.min.js');
    this.page.injectJs('app/scripts/kconnect.js');
    this.page.injectJs('app/scripts/contentscript.js');

    this.evaluate(function() {
      var kConnectApiUrl = 'https://apikconnect.honservices.org/~kconnect/' +
        'cgi-bin/';
      var trustabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'is-trustable.cgi?domain=vidal.fr',
        'GET'
      );
      var readabilityReq = __utils__.sendAJAX(
        kConnectApiUrl + 'readability.cgi?data={"url":"https://www.vidal.fr"}',
        'GET'
      );
      readabilityCallback(
        JSON.parse(readabilityReq),
        $(
          document.querySelectorAll('.b_algo h2 a').item(0)
        ).parent().siblings('div')
      );
      trustabilityCallback(
        JSON.parse(trustabilityReq),
        $(
          document.querySelectorAll('.b_algo h2 a').item(0)
        ).parent().siblings('div')
      );
    });

    test.assertTitle('vidal - Bing', 'bing title is ok');
    test.assertUrlMatch(/q=vidal/, 'search term has been submitted');

    this.waitForSelector('.trustability');

    test.assertEval(function() {
      return __utils__.findAll('.trustability').length === 1;
    }, 'trustability informations found');
    test.assertEval(function() {
      return __utils__.findAll('.readability').length === 1;
    }, 'readability informations found');

  });

  casper.run(function() {
    test.done();
  });
});
<|endoftext|>


<commit_before>/* ----       BabelWebV2          ----*/

function BabelWebV2() {
  /* ----    A propos de babel    ----*/
  var Routes = {};
  var Xroutes = {};
  var Neighbours ={};
  var Interfaces ={};

  /*----   graphe    ----*/
  var nodes = [];   //liste des noeuds du graphe
  var links = [];   //les liens

/* ----    A propos de babel    ----*/

  function NeighbourEntry(address, cost, iff, reach, rtt, rttcost, rxcost, txcost ) {
    this.address = address;
    this.cost = cost;
    this.iff = iff;
    this.reach = reach;
    this.rtt = rtt;
    this.rttcost = rttcost;
    this.rxcost = rxcost;
    this.txcost = txcost;
  }

  function RouteEntry(from, id, iff, installed, metric, prefix, refmetric, via){
    this.from = from; // pour le moment contient juste ip  sans le mask
    this.id = id;
    this.iff = iff;
    this.installed = installed;
    this.metric = metric;
    this.prefix = prefix;
    this.refmetric = refmetric;
    this.via = via;
  }

  function XrouteEntry(prefix, from,metric) {
    this.prefix = prefix;
    this.from = from;
    this.metric = metric;
  }

  function InterfaceEntry(up, ipv4, ipv6) {
    this.up = up;
    this.ipv4 = ipv4;
    this.ipv6 = ipv6;
  }

  /*----   graphe    ----*/
  function Node(id ) {
    this.id = id;
  }

  function Link(source,target) {
          this.source = source;
          this.target = target;
  }

  /*----   test graphe  ----*/
  nodes.push(new Node("center"));
  nodes.push(new Node("test"));
  links.push(new Link("center","test"));

  function init(){
    //TODO
  }

  function connect(){
    var socket = null;
    try {
        socket = new WebSocket("ws://localhost:8080/ws");

    } catch (exception) {
        console.error(exception);
    }

    socket.onerror = function(error) {
        console.error(error);
    };

    socket.onopen = function(event) {
        var elem = document.getElementById('state'); // À changer
        elem.innerHTML = "Connected";
        elem.style.backgroundColor = "green";

        this.onclose = function(event) {
          var elem = document.getElementById('state'); // À changer
          elem.innerHTML = "Disconnected.";
          elem.style.backgroundColor = "red";
        };

        this.onmessage = function(event) {
            ConvertJSON(event);

        };
        //this.send("Hello world!");
    };
  }

  function ConvertJSON(event) {
    var data = JSON.parse(event.data);
    console.log(data);

    switch (data.action) {
      case "add": add(data);
        break;
      case "change":add(data);
        break;
      case "flush": flush(data);
        break;
      default:
    }
  }

  function add(data){
    switch (data.table) {
      case "neighbour":
        var entry = data.data;
        Neighbours[data.id]= new NeighbourEntry(entry.address,
                                                     entry.cost,
                                                     entry.if,
                                                     entry.reach,
                                                     entry.rtt,
                                                     entry.rttcost,
                                                     entry.rxcost,
                                                     entry.txcost);
        nodes.push(new Node(entry.address));

        insertNeighbour_html(entry.address,
                            entry.cost,
                            entry.if,
                            entry.reach,
                            entry.rtt,
                            entry.rttcost,
                            entry.rxcost,
                            entry.txcost);

      console.log("test 1 : ");
      console.log(Neighbours[data.id]);
      break;

      case "route":
        var entry = data.data;
        if(entry.refmetric == 0)// est un voisin
        Routes[data.id]= new RouteEntry(entry.from.IP,
                                             entry.id,
                                             entry.if,
                                             entry.installed,
                                             entry.metric,
                                             entry.prefix.IP,
                                             entry.refmetric,
                                             entry.via);
        // if(nodes.includes(entry.via)== false)
        //   nodes.push(new Node(entry.from.via));
        //
        // if(entry.refmetric == 0)// est un voisin
        // {
        //   links.push(new Link("center",entry.from.via));
        // }
        console.log("test 2 : ");
        console.log(Routes[data.id]);
        break;

      case "xroute": //TODO
        break;

      case "interface": //TODO
        break;

      default:
    }
  }

  function insertNeighbour_html(address, cost, iff, reach, rtt, rttcost, rxcost, txcost){
    var arrayLignes = document.getElementById("neighbour");
    var ligne = arrayLignes.insertRow(-1);
    var colonne1 = ligne.insertCell(0);
    colonne1.innerHTML += address;
    var colonne2 = ligne.insertCell(1);
    colonne2.innerHTML += iff;
    var colonne3 = ligne.insertCell(2);
    colonne3.innerHTML +=reach;
    var colonne4 = ligne.insertCell(3);
    colonne4.innerHTML += rxcost;
    var colonne5 = ligne.insertCell(4);
    colonne5.innerHTML +=txcost ;
    var colonne6 = ligne.insertCell(5);
    colonne6.innerHTML +=cost;
    var colonne7 = ligne.insertCell(6);
    colonne7.innerHTML +=rtt;
  }

  function change(message){//TODO
  }
  function flush(message){//TODO
  }
  function initGraph() {
    /* Setup svg graph */
    width = 600;
    height = 400; /* display size */
    vis = d3.select("#fig")
      .insert("svg:svg", ".legend")
      .attr("width", width)
      .attr("height", height)
      .attr("stroke-width", "1.5px");
    // force = d3.layout.force(); /* force to coerce nodes */
    // force.charge(-1000); /* stronger repulsion enhances graph */
    // force.on("tick", onTick);
  }

  function initGraph2() {
    var svg = d3.select("svg"),
            width = +svg.attr("width"),
            height = +svg.attr("height");

    var color = d3.scaleOrdinal(d3.schemeCategory20);

    var simulation = d3.forceSimulation()
            .force("link", d3.forceLink().id(function(d) { return d.id; }))
            .force("charge", d3.forceManyBody())
            .force("center", d3.forceCenter(width / 2, height / 2));

    var link = svg.append("g")
            .attr("class", "links")
            .selectAll("line")
            .data(links)
            .enter().append("line")
            //.attr("stroke-width", function(d) { return Math.sqrt(d.value); });

    var node = svg.append("g")
            .attr("class", "nodes")
            .selectAll("circle")
            .data(nodes)
            .enter().append("circle")
            .attr("r", 5)
            .attr("fill", function(d) { return color(d.group); })
            .call(d3.drag()
                  .on("start", dragstarted)
                  .on("drag", dragged)
                  .on("end", dragended));

    node.append("title")
              .text(function(d) { return d.id; });

    simulation
        .nodes(nodes)
        .on("tick", ticked);

    simulation.force("link")
        .links(links);

    function ticked() {
      link
          .attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });

      node
          .attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
   }

   function dragstarted(d) {
     if (!d3.event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
   }

   function dragged(d) {
      d.fx = d3.event.x;
      d.fy = d3.event.y;
   }

   function dragended(d) {
      if (!d3.event.active) simulation.alphaTarget(0);
       d.fx = null;
       d.fy = null;
  }
 }

  BBabelWebV2= {};
  BabelWebV2.connect = connect;
  BabelWebV2.init = init;
  BabelWebV2.initGraph = initGraph;

  return BabelWebV2;
}

// /*----   test graphe  ----*/
//  nodes.push(new Node("Myriel",1));
//  nodes.push(new Node("Napoleon",1));
//  nodes.push(new Node("Mlle.Baptistine",1));
//  nodes.push(new Node("Mme.Magloire", 1));
//
//  links.push(new Link("Napoleon","Myriel"));
//  links.push(new Link("Mlle.Baptistine","Myriel"));
//  links.push(new Link("Mme.Magloire","Myriel"));
//  links.push(new Link("Mme.Magloire", "Mlle.Baptistine"));

// var nodes = [
//           {"id": "Myriel", "group": 1},
//           {"id": "Napoleon", "group": 1},
//           // {"id": "Mlle.Baptistine", "group": 1},
//           // {"id": "Mme.Magloire", "group": 1},
//           // {"id": "CountessdeLo", "group": 1},
//           // {"id": "Geborand", "group": 1},
//           // {"id": "Champtercier", "group": 1},
//           // {"id": "Cravatte", "group": 1},
//           // {"id": "Count", "group": 1},
//           // {"id": "OldMan", "group": 1},
//           // {"id": "Labarre", "group": 2},
//           // {"id": "Valjean", "group": 2},
//           // {"id": "Marguerite", "group": 3},
//           // {"id": "Mme.deR", "group": 2},
//           // {"id": "Isabeau", "group": 2},
//           // {"id": "Gervais", "group": 2},
//       ]
//
//       var links = [
//           {"source": "Napoleon", "target": "Myriel", "value": 1},
//         // {"source": "Mlle.Baptistine", "target": "Myriel", "value": 8},
//         // {"source": "Mme.Magloire", "target": "Myriel", "value": 10},
//         // {"source": "Mme.Magloire", "target": "Mlle.Baptistine", "value": 6},
//         // {"source": "CountessdeLo", "target": "Myriel", "value": 1},
//         // {"source": "Geborand", "target": "Myriel", "value": 1},
//         // {"source": "Champtercier", "target": "Myriel", "value": 1},
//         // {"source": "Cravatte", "target": "Myriel", "value": 1},
//         // {"source": "Valjean", "target": "Labarre", "value": 1},
//         // {"source": "Valjean", "target": "Mme.Magloire", "value": 3},
//         // {"source": "Valjean", "target": "Mlle.Baptistine", "value": 3},
//       ]
<commit_msg>Parsing the exchange.<commit_after>/* ----       BabelWebV2          ----*/

function BabelWebV2() {
  /* ----    Data base babel    ----*/
  var Routes = {};
  var Xroutes = {};
  var Neighbours ={};
  var Interfaces ={};

  /*----   Graph    ----*/
  var nodes = [];   //Nodes of the graph
  var links = [];

/* ----    The structure of the data base    ----*/

  function NeighbourEntry(address, cost, iff, reach, rtt, rttcost, rxcost, txcost ) {
    this.address = address;
    this.cost = cost;
    this.iff = iff;
    this.reach = reach;
    this.rtt = rtt;
    this.rttcost = rttcost;
    this.rxcost = rxcost;
    this.txcost = txcost;
  }

  function RouteEntry(from, id, iff, installed, metric, prefix, refmetric, via){
    this.from = from; // pour le moment contient juste ip  sans le mask
    this.id = id;
    this.iff = iff;
    this.installed = installed;
    this.metric = metric;
    this.prefix = prefix;
    this.refmetric = refmetric;
    this.via = via;
  }

  function XrouteEntry(prefix, from,metric) {
    this.prefix = prefix;
    this.from = from;
    this.metric = metric;
  }

  function InterfaceEntry(up, ipv4, ipv6) {
    this.up = up;
    this.ipv4 = ipv4;
    this.ipv6 = ipv6;
  }

  /*----   The structure of the graph    ----*/
  function Node(id ) {
    this.id = id;
  }

  function Link(source,target) {
          this.source = source;
          this.target = target;
  }

  /*----   test graph  ----*/
  nodes.push(new Node("center"));
  nodes.push(new Node("test"));
  links.push(new Link("center","test"));

  function init(){
    //TODO
  }

  function connect(){
    var socket = null;
    try {
        socket = new WebSocket("ws://localhost:8080/ws");

    } catch (exception) {
        console.error(exception);
    }

    socket.onerror = function(error) {
        console.error(error);
    };

    socket.onopen = function(event) {
        d3.selectAll("body").select("#state")
        .text("Connected").style("background-color", "green");

        this.onclose = function(event) {
          d3.selectAll("body").select("#state")
          .text("Disconnected").style("background-color", "red");
        };

        this.onmessage = function(event) {
            ConvertJSON(event);

        };
        //this.send("Hello world!");
    };
  }

  function ConvertJSON(event) {
    var data = JSON.parse(event.data);
    console.log(data);

    switch (data.action) {
      case "add": //add(data);
        break;
      case "change"://add(data);
        break;
      case "flush": //flush(data);
        break;
      default:
    }
  }

  function add(data){
    switch (data.table) {
      case "neighbour":
        var entry = data.data;
        Neighbours[data.id]= new NeighbourEntry(entry.address,
                                                     entry.cost,
                                                     entry.if,
                                                     entry.reach,
                                                     entry.rtt,
                                                     entry.rttcost,
                                                     entry.rxcost,
                                                     entry.txcost);
        nodes.push(new Node(entry.address));

        insertNeighbour_html(entry.address,
                            entry.cost,
                            entry.if,
                            entry.reach,
                            entry.rtt,
                            entry.rttcost,
                            entry.rxcost,
                            entry.txcost);

      //console.log("test 1 : ");
      //console.log(Neighbours[data.id]);
      break;

      case "route":
        var entry = data.data;
        if(entry.refmetric == 0)// est un voisin
        Routes[data.id]= new RouteEntry(entry.from.IP,
                                             entry.id,
                                             entry.if,
                                             entry.installed,
                                             entry.metric,
                                             entry.prefix.IP,
                                             entry.refmetric,
                                             entry.via);
        // if(nodes.includes(entry.via)== false)
        //   nodes.push(new Node(entry.from.via));
        //
        // if(entry.refmetric == 0)// est un voisin
        // {
        //   links.push(new Link("center",entry.from.via));
        // }
      //  console.log("test 2 : ");
        //console.log(Routes[data.id]);
        break;

      case "xroute": //TODO
        break;

      case "interface": //TODO
        break;

      default:
    }
  }

  function insertNeighbour_html(address, cost, iff, reach, rtt, rttcost, rxcost, txcost){
    var arrayLignes = document.getElementById("neighbour");
    var ligne = arrayLignes.insertRow(-1);
    var colonne1 = ligne.insertCell(0);
    colonne1.innerHTML += address;
    var colonne2 = ligne.insertCell(1);
    colonne2.innerHTML += iff;
    var colonne3 = ligne.insertCell(2);
    colonne3.innerHTML +=reach;
    var colonne4 = ligne.insertCell(3);
    colonne4.innerHTML += rxcost;
    var colonne5 = ligne.insertCell(4);
    colonne5.innerHTML +=txcost ;
    var colonne6 = ligne.insertCell(5);
    colonne6.innerHTML +=cost;
    var colonne7 = ligne.insertCell(6);
    colonne7.innerHTML +=rtt;
  }

  function change(message){//TODO
  }
  function flush(message){//TODO
  }
  function initGraph() {
    /* Setup svg graph */
    width = 600;
    height = 400; /* display size */
    vis = d3.select("#fig")
      .insert("svg:svg", ".legend")
      .attr("width", width)
      .attr("height", height)
      .attr("stroke-width", "1.5px");
    // force = d3.layout.force(); /* force to coerce nodes */
    // force.charge(-1000); /* stronger repulsion enhances graph */
    // force.on("tick", onTick);
  }

  function initGraph2() {
    var svg = d3.select("svg"),
            width = +svg.attr("width"),
            height = +svg.attr("height");

    var color = d3.scaleOrdinal(d3.schemeCategory20);

    var simulation = d3.forceSimulation()
            .force("link", d3.forceLink().id(function(d) { return d.id; }))
            .force("charge", d3.forceManyBody())
            .force("center", d3.forceCenter(width / 2, height / 2));

    var link = svg.append("g")
            .attr("class", "links")
            .selectAll("line")
            .data(links)
            .enter().append("line")
            //.attr("stroke-width", function(d) { return Math.sqrt(d.value); });

    var node = svg.append("g")
            .attr("class", "nodes")
            .selectAll("circle")
            .data(nodes)
            .enter().append("circle")
            .attr("r", 5)
            .attr("fill", function(d) { return color(d.group); })
            .call(d3.drag()
                  .on("start", dragstarted)
                  .on("drag", dragged)
                  .on("end", dragended));

    node.append("title")
              .text(function(d) { return d.id; });

    simulation
        .nodes(nodes)
        .on("tick", ticked);

    simulation.force("link")
        .links(links);

    function ticked() {
      link
          .attr("x1", function(d) { return d.source.x; })
          .attr("y1", function(d) { return d.source.y; })
          .attr("x2", function(d) { return d.target.x; })
          .attr("y2", function(d) { return d.target.y; });

      node
          .attr("cx", function(d) { return d.x; })
          .attr("cy", function(d) { return d.y; });
   }

   function dragstarted(d) {
     if (!d3.event.active) simulation.alphaTarget(0.3).restart();
        d.fx = d.x;
        d.fy = d.y;
   }

   function dragged(d) {
      d.fx = d3.event.x;
      d.fy = d3.event.y;
   }

   function dragended(d) {
      if (!d3.event.active) simulation.alphaTarget(0);
       d.fx = null;
       d.fy = null;
  }
 }

  BBabelWebV2= {};
  BabelWebV2.connect = connect;
  BabelWebV2.init = init;
  BabelWebV2.initGraph = initGraph;

  return BabelWebV2;
}

// /*----   test graphe  ----*/
//  nodes.push(new Node("Myriel",1));
//  nodes.push(new Node("Napoleon",1));
//  nodes.push(new Node("Mlle.Baptistine",1));
//  nodes.push(new Node("Mme.Magloire", 1));
//
//  links.push(new Link("Napoleon","Myriel"));
//  links.push(new Link("Mlle.Baptistine","Myriel"));
//  links.push(new Link("Mme.Magloire","Myriel"));
//  links.push(new Link("Mme.Magloire", "Mlle.Baptistine"));

// var nodes = [
//           {"id": "Myriel", "group": 1},
//           {"id": "Napoleon", "group": 1},
//           // {"id": "Mlle.Baptistine", "group": 1},
//           // {"id": "Mme.Magloire", "group": 1},
//           // {"id": "CountessdeLo", "group": 1},
//           // {"id": "Geborand", "group": 1},
//           // {"id": "Champtercier", "group": 1},
//           // {"id": "Cravatte", "group": 1},
//           // {"id": "Count", "group": 1},
//           // {"id": "OldMan", "group": 1},
//           // {"id": "Labarre", "group": 2},
//           // {"id": "Valjean", "group": 2},
//           // {"id": "Marguerite", "group": 3},
//           // {"id": "Mme.deR", "group": 2},
//           // {"id": "Isabeau", "group": 2},
//           // {"id": "Gervais", "group": 2},
//       ]
//
//       var links = [
//           {"source": "Napoleon", "target": "Myriel", "value": 1},
//         // {"source": "Mlle.Baptistine", "target": "Myriel", "value": 8},
//         // {"source": "Mme.Magloire", "target": "Myriel", "value": 10},
//         // {"source": "Mme.Magloire", "target": "Mlle.Baptistine", "value": 6},
//         // {"source": "CountessdeLo", "target": "Myriel", "value": 1},
//         // {"source": "Geborand", "target": "Myriel", "value": 1},
//         // {"source": "Champtercier", "target": "Myriel", "value": 1},
//         // {"source": "Cravatte", "target": "Myriel", "value": 1},
//         // {"source": "Valjean", "target": "Labarre", "value": 1},
//         // {"source": "Valjean", "target": "Mme.Magloire", "value": 3},
//         // {"source": "Valjean", "target": "Mlle.Baptistine", "value": 3},
//       ]
<|endoftext|>


<commit_before>$( document ).ready(function() {

  $("#savePickupLocation").on("click", function() {

      if($("#selectedStorePickupId").val() != '') {
        var item = {};
        item[$("#selectedStorePickupId").val()] = 0;

        // Remove existing item.
        var response = jQuery.post('/cart/update.js', { "updates": item });

        // Remove existing_pickup_id.
        $("#selectedStorePickupId").val("");
      }

      if($("#storePickupVariantId option:selected").val() != "") {

          var item = {
              quantity: 1,
              id: $("#storePickupVariantId option:selected").val()
          }

          var response = jQuery.post('/cart/add.js', item);

          console.log(response);
          alert("Pickup location set.");

      }
      return false;

  });
});
<commit_msg>Update storepickup.js<commit_after>$( document ).ready(function() {

  // Populate locations select field on page load.
  getStoreLocations();

  function getStoreLocations()
  {
       // Get the Click and Collect item from your store.
       jQuery.getJSON('/products/click-and-collect.js', function(data) {

         	// We only need the variants.
         	var selectValues = data.variants;

         	// Add each variant (location) to the select field.
         	$.each(selectValues, function(id, variant) {

                jQuery("#clickAndCollectVariantId")
                    .append($("<option></option>")
                    .attr("value", variant.id)
                    .text(variant.title));

            });

         	// Get the selected location ID.
            var variantid = $("#selectedClickAndCollectId").val();

            // Set the selected location in the select field.
            jQuery("#clickAndCollectVariantId").val(variantid);
       });
  }

  function removeClickAndCollectItem()
  {
     if($("#selectedClickAndCollectId").val() != '') {

        var item = {};
        item[$("#selectedClickAndCollectId").val()] = 0;

        // Remove existing item.
        var response = jQuery.post('/cart/update.js', { "updates": item });

        // Remove existing_pickup_id.
        $("#selectedClickAndCollectId").val("");
      }
  }

  $("#saveClickAndCollectLocation").on("click", function() {

      // Remove the existing Click & Collect item from the basket.
      removeClickAndCollectItem();

      var clickAndCollectVariantId = $("#clickAndCollectVariantId option:selected").val();

      if(clickAndCollectVariantId != "") {

          var item = {
            quantity: 1,
            id: clickAndCollectVariantId
          }

          $.ajax({
              url: "/cart/add.js",
              type: 'POST',
              data: item,
              complete: function(msg){
                  window.location.replace("/cart");
              }
          });

      }

      return false;

  });
});
<|endoftext|>


<commit_before>// designed for multi page modal registration forms
// each page has a continue button, the last page has a close button
// each 'continue' button has a class "step", and an attribute 'data-step="x"',
// where x is the page/step this button is displayed on
// any content that needs to transition between being hidden and shown
// must have the appropriate "step-x" class on it
// events are ('next.m' + for_step)
// events 'next.m.x' are bound to the modal, when these events are triggered,
// the respective buttons responsible for these events will react
// update progress will find progress text and update the class to completed
+function($) {
    'use strict';

    var modals = $('.modal.multi-step');

    modals.each(function(idx, modal) {
        var $modal = $(modal);
        var $buttons = $modal.find('button.step');
        var total_num_steps = $buttons.length;
        var $progress_bar = $modal.find('.m-progress-bar');
        var $progress_stats = $modal.find('.m-progress-stats');
        var $progress_current = $modal.find('.m-progress-current');
        var $progress_total = $modal.find('.m-progress-total');
        var $progress_complete  = $modal.find('.m-progress-complete');

        function getPercentComplete(current_step, total_steps) {
            return current_step / total_steps * 100 + '%';
        }

        function reset() {
            var i = 1;
            for (i = 1; i <= total_num_steps; i++) {
                $('.step-' + i).hide();
            }
        }

        function updateProgress(current, total) {
            $progress_bar.animate({
                width: getPercentComplete(current+1, total)
            });
            if (current === total_num_steps) {
                $progress_stats.hide();
                $progress_complete.show();
            } else {
                $progress_current.text(current + 1);
            }
            var $progress = $('.m-progress');
            var $progress_step = $progress.find('[data-progress=' + current + ']');
            $progress_step.addClass('completed');
        }

        function nextStep(current_step) {
            reset();
            var to_show = $('.step-' + (current_step + 1));
            if (to_show.length === 0) {
                // at the last step, nothing else to show
                return;
            }
            to_show.show();
            updateProgress(current_step, total_num_steps);
        }

        function bindEventsToModal($modal, last) {
            var i,
                delegateToButton = function(e) {
                    $modal.find('button[data-step=' + e.data.step + ']')
                          .trigger('next.m.' + e.data.step);
                };
            for (i = 1; i <= last; i++) {
                $modal.one('next.m.' + i, {step: i}, delegateToButton);
            }
        }

        function bindEventsToButtons() {
            $buttons.each(function() {
                var $b = $(this);
                var for_step = parseInt($b.attr('data-step'), 10);
                if (for_step) {
                    $b.on('next.m.' + for_step, function() {
                        nextStep(for_step);
                    });
                }
            });
        }

        function initialize() {
            reset();
            updateProgress(0, total_num_steps);
            $('.step-1').show();
            $progress_complete.hide();
            $progress_total.text(total_num_steps);
            bindEventsToModal($modal, total_num_steps);
            bindEventsToButtons($buttons);
            $modal.data({
                total_num_steps: $buttons.length,
            });
        }

        initialize();
    })
}(jQuery);
<commit_msg>Update to the way multi-step-modal works<commit_after>+function($) {
    'use strict';

    var modals = $('.modal.multi-step');

    modals.each(function(idx, modal) {
        var $modal = $(modal);
        var $buttons = $modal.find('button.step');
        var total_num_steps = $buttons.length;
        var $progress = $modal.find('.m-progress');
        var $progress_bar = $modal.find('.m-progress-bar');
        var $progress_stats = $modal.find('.m-progress-stats');
        var $progress_current = $modal.find('.m-progress-current');
        var $progress_total = $modal.find('.m-progress-total');
        var $progress_complete  = $modal.find('.m-progress-complete');

        function reset() {
            $modal.find('.step').hide();
            $modal.find('[data-step]').hide();
        }

        function completeSteps() {
            $progress_stats.hide();
            $progress_complete.show();
            $modal.find('.progress-text').animate({
                top: '-2em'
            });
            $modal.find('.complete-indicator').animate({
                top: '-2em'
            });
            $progress_bar.addClass('completed');
        }

        function getPercentComplete(current_step, total_steps) {
            return Math.min(current_step / total_steps * 100, 100) + '%';
        }

        function updateProgress(current, total) {
            $progress_bar.animate({
                width: getPercentComplete(current, total)
            });
            if (current - 1 >= total_num_steps) {
                completeSteps();
            } else {
                $progress_current.text(current);
            }

            $progress.find('[data-progress]').each(function() {
                var dp = $(this);
                if (dp.data().progress <= current - 1) {
                    dp.addClass('completed');
                } else {
                    dp.removeClass('completed');
                }
            });
        }

        function goToStep(step) {
            reset();
            var to_show = $modal.find('.step-' + step);
            if (to_show.length === 0) {
                // at the last step, nothing else to show
                return;
            }
            to_show.show();
            var current = parseInt(step, 10);
            updateProgress(current, total_num_steps);
            findFirstFocusableInput(to_show).focus();
        }

        function findFirstFocusableInput(parent) {
            var candidates = [parent.find('input'), parent.find('select'),
                              parent.find('textarea'),parent.find('button')],
                winner = parent;
            $.each(candidates, function() {
                if (this.length > 0) {
                    winner = this[0];
                    return false;
                }
            });
            return $(winner);
        }

        function bindEventsToModal($modal) {
            var data_steps = [];
            $('[data-step]').each(function() {
                var step = $(this).data().step;
                if (step && $.inArray(step, data_steps) === -1) {
                    data_steps.push(step);
                }
            });

            $.each(data_steps, function(i, v) {
                $modal.on('next.m.' + v, {step: v}, function(e) {
                    goToStep(e.data.step);
                });
            });
        }

        function initialize() {
            reset();
            updateProgress(1, total_num_steps);
            $modal.find('.step-1').show();
            $progress_complete.hide();
            $progress_total.text(total_num_steps);
            bindEventsToModal($modal, total_num_steps);
            $modal.data({
                total_num_steps: $buttons.length,
            });
        }

        initialize();
    })
}(jQuery);
<|endoftext|>


<commit_before>describe('ax5.util.param TEST', function() {
    it('ax5.util.param({a: 1, b: \'123\'"2&\'}, "param") expect "a=1&b=123%27%222%26"', function() {
        var actual = ax5.util.param({a: 1, b: '123\'"2&'}, 'param');

        actual.should.equal('a=1&b=123%27%222%26');
    });
    it('ax5.util.param("a=1&b=12\'"32", "param") expect "a=1&b=12\'"32"', function() {
        var actual = ax5.util.param("a=1&b=12'\"32", 'param');

        actual.should.equal('a=1&b=12\'"32');
    });
    it('ax5.util.param("a=1&b=1232") expect {"a":"1","b":"1232"}', function() {
        var actual = ax5.util.param("a=1&b=1232");

        should.deepEqual(actual, {"a":"1","b":"1232"});
    });
});

describe('ax5.util.parseJson TEST', function() {
    it('ax5.util.util.parseJson("[{"a":"99"},"2","3"]") expect [{"a":"99"},"2","3"]', function() {
        var actual = ax5.util.parseJson('[{"a":"99"},"2","3"]');

        actual.should.deepEqual([{"a":"99"},"2","3"]);
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", false) expect {"error": 500, "msg": "syntax error"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', false);

        actual.should.deepEqual({"error": 500, "msg": "syntax error"});
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", true) expect {"a": 1, "b": "{Function}"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', true);

        actual.a.should.equal(1);
        actual.b.should.Function();
    });
});

describe('ax5.util.toJson TEST', function() {
    var testCases = [
        {
            args: 1,
            expect: 1
        },
        {
            args: "A",
            expect: '"A"'
        },
        {
            args: [1, 2, 3, "A"],
            expect: '[1,2,3,"A"]'
        },
        {
            args: {a: "a", x: "x"},
            expect: '{"a": "a", "x": "x"}'
        },
        {
            args: [1,{"a": "a", "x": "x"}],
            expect: '[1,{"a": "a", "x": "x"}]'
        },
        {
            args: {"a": "a", "x": "x", "list": [1,2,3]},
            expect: '{"a": "a", "x": "x", "list": [1,2,3]}'
        },
        {
            args: function func() {},
            expect: '"{Function}"'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + (JSON.stringify(testCase.args) || testCase.args.toString()) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.toJson(testCase.args);

            actual.should.deepEqual(testCase.expect);
        });
    });
});

describe('ax5.util.alert TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.toArray TEST', function() {
    it('ax5.util.toArray converts [Array-like objects] to [Array]', function() {
        function something() {
            return ax5.util.toArray(arguments);
        }
        var actual = something("A", "X", "I", "S", "J");

        actual.should.deepEqual(["A", "X", "I", "S", "J"]);
    });
});

describe('ax5.util.xxxCookie TEST', function() {

    describe('ax5.util.setCookie TEST', function() {
        it('ax5.util.setCookie("ax5-cookie", "eng+한글")', function() {
            ax5.util.setCookie('ax5-cookie', 'eng+한글');

            document.cookie.indexOf('ax5-cookie=eng+%uD55C%uAE00').should.above(-1);
        });
    });

    describe('ax5.util.getCookie TEST', function() {
        it('ax5.util.getCookie("ax5-cookie") expect "eng+한글"', function() {
            var actual = ax5.util.getCookie('ax5-cookie');

            actual.should.equal('eng+한글');
        });
    });

});

describe('ax5.util.findParentNode TEST', function() {
    it('ax5.util.findParentNode($(".first").get(0), { tagname: "div", clazz: "test-mockup-1" }) expect $("div.test-mockup-1").get(0)', function() {
        var actual = ax5.util.findParentNode($('.first').get(0), { tagname: 'div', clazz: 'test-mockup-1' });
        var expect = $('div.test-mockup-1').get(0);

        should.equal(actual, expect);
    });
});

describe('ax5.util.cssNumber TEST', function() {
    var testCases = [
        {
            args: '100px',
            expect: '100px'
        },
        {
            args: 100,
            expect: '100px'
        },
        {
            args: '100%',
            expect: '100%'
        },
        {
            args: '##100@',
            expect: '100px'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + JSON.stringify(testCase.args) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.cssNumber(testCase.args);

            should.equal(actual, testCase.expect);
        });
    });
});

describe('ax5.util.css TEST', function() {

    it('ax5.util.css({background:"#ccc",padding:"50px",width:"100px" }) expect background:#ccc;padding:50px;width:100px;', function() {
        var actual = ax5.util.css({background:"#ccc",padding:"50px",width:"100px" });

        should.equal(actual, 'background:#ccc;padding:50px;width:100px;');
    });

    it('ax5.util.css("width:100px;padding: 50px; background: #ccc") expect {width: "100px", padding: "50px", background: "#ccc"}', function() {
        var actual = ax5.util.css('width:100px;padding: 50px; background: #ccc');

        should.deepEqual(actual, {width: "100px", padding: "50px", background: "#ccc"});
    });

});

describe('ax5.util.stopEvent TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.selectRange TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.debounce TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});
<commit_msg>update test code<commit_after>describe('ax5.util.param TEST', function() {
    it('ax5.util.param({a: 1, b: \'123\'"2&\'}, "param") expect "a=1&b=123%27%222%26"', function() {
        var actual = ax5.util.param({a: 1, b: '123\'"2&'}, 'param');

        actual.should.equal('a=1&b=123%27%222%26');
    });
    it('ax5.util.param("a=1&b=12\'"32", "param") expect "a=1&b=12\'"32"', function() {
        var actual = ax5.util.param("a=1&b=12'\"32", 'param');

        actual.should.equal('a=1&b=12\'"32');
    });
    it('ax5.util.param("a=1&b=1232") expect {"a":"1","b":"1232"}', function() {
        var actual = ax5.util.param("a=1&b=1232");

        should.deepEqual(actual, {"a":"1","b":"1232"});
    });
});

describe('ax5.util.parseJson TEST', function() {
    it('ax5.util.util.parseJson("[{"a":"99"},"2","3"]") expect [{"a":"99"},"2","3"]', function() {
        var actual = ax5.util.parseJson('[{"a":"99"},"2","3"]');

        actual.should.deepEqual([{"a":"99"},"2","3"]);
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", false) expect {"error": 500, "msg": "syntax error"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', false);

        actual.should.deepEqual({"error": 500, "msg": "syntax error"});
    });
    it('ax5.util.parseJson("{"a":1, "b":function(){return 1;}}", true) expect {"a": 1, "b": "{Function}"}', function() {
        var actual = ax5.util.parseJson('{"a":1, "b":function(){return 1;}}', true);

        actual.a.should.equal(1);
        actual.b.should.Function();
    });
});

describe('ax5.util.toJson TEST', function() {
    var testCases = [
        {
            args: 1,
            expect: 1
        },
        {
            args: "A",
            expect: '"A"'
        },
        {
            args: [1, 2, 3, "A"],
            expect: '[1,2,3,"A"]'
        },
        {
            args: {a: "a", x: "x"},
            expect: '{"a": "a", "x": "x"}'
        },
        {
            args: [1,{"a": "a", "x": "x"}],
            expect: '[1,{"a": "a", "x": "x"}]'
        },
        {
            args: {"a": "a", "x": "x", "list": [1,2,3]},
            expect: '{"a": "a", "x": "x", "list": [1,2,3]}'
        },
        {
            args: function func() {},
            expect: '"{Function}"'
        },
        {
            args: [true, false, true],
            expect: '[true,false,true]'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + (JSON.stringify(testCase.args) || testCase.args.toString()) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.toJson(testCase.args);

            actual.should.deepEqual(testCase.expect);
        });
    });
});

describe('ax5.util.alert TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.toArray TEST', function() {
    it('ax5.util.toArray converts [Array-like objects] to [Array]', function() {
        function something() {
            return ax5.util.toArray(arguments);
        }
        var actual = something("A", "X", "I", "S", "J");

        actual.should.deepEqual(["A", "X", "I", "S", "J"]);
    });
});

describe('ax5.util.xxxCookie TEST', function() {

    describe('ax5.util.setCookie TEST', function() {
        it('ax5.util.setCookie("ax5-cookie", "eng+한글")', function() {
            ax5.util.setCookie('ax5-cookie', 'eng+한글');

            document.cookie.indexOf('ax5-cookie=eng+%uD55C%uAE00').should.above(-1);
        });
    });

    describe('ax5.util.getCookie TEST', function() {
        it('ax5.util.getCookie("ax5-cookie") expect "eng+한글"', function() {
            var actual = ax5.util.getCookie('ax5-cookie');

            actual.should.equal('eng+한글');
        });
    });

});

describe('ax5.util.findParentNode TEST', function() {
    it('ax5.util.findParentNode($(".first").get(0), { tagname: "div", clazz: "test-mockup-1" }) expect $("div.test-mockup-1").get(0)', function() {
        var actual = ax5.util.findParentNode($('.first').get(0), { tagname: 'div', clazz: 'test-mockup-1' });
        var expect = $('div.test-mockup-1').get(0);

        should.equal(actual, expect);
    });
});

describe('ax5.util.cssNumber TEST', function() {
    var testCases = [
        {
            args: '100px',
            expect: '100px'
        },
        {
            args: 100,
            expect: '100px'
        },
        {
            args: '100%',
            expect: '100%'
        },
        {
            args: '##100@',
            expect: '100px'
        }
    ];

    _.each(testCases, function(testCase){
        it('ax5.util.toJson(' + JSON.stringify(testCase.args) + ') expect ' + testCase.expect, function() {
            var actual = ax5.util.cssNumber(testCase.args);

            should.equal(actual, testCase.expect);
        });
    });
});

describe('ax5.util.css TEST', function() {

    it('ax5.util.css({background:"#ccc",padding:"50px",width:"100px" }) expect background:#ccc;padding:50px;width:100px;', function() {
        var actual = ax5.util.css({background:"#ccc",padding:"50px",width:"100px" });

        should.equal(actual, 'background:#ccc;padding:50px;width:100px;');
    });

    it('ax5.util.css("width:100px;padding: 50px; background: #ccc") expect {width: "100px", padding: "50px", background: "#ccc"}', function() {
        var actual = ax5.util.css('width:100px;padding: 50px; background: #ccc');

        should.deepEqual(actual, {width: "100px", padding: "50px", background: "#ccc"});
    });

});

describe('ax5.util.stopEvent TEST', function(){
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.selectRange TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});

describe('ax5.util.debounce TEST', function() {
    // TODO 대략 난감... HJ.Park 2016-09-26
});
<|endoftext|>


<commit_before>$(document).ready(function() {

    $(".load-venues-link").click(function(e) {
            e.preventDefault();
            load_venues( $(this).attr('href') );
    });

    $(".wheelchair-filter-checkbox").click( update_filter );

    $("[rel='tooltip']").tooltip();

    $('#loadmorevenues-button').click(function(){
        load_venues( $(this).data("current-url"), $(this).data("next-page") );
    });

    $('#btn-node-update').click(function(){
        update_wheelmap_node($(this).data('wheelmap_id'),
                            $('#form-update-status input:checked').val());
    });

});

var update_wheelmap_node = function(wheelmap_id, wheelchair_status) {

        $.ajax({
            dataType: "json",
            url: "/wheelmap/update_node/",
            type: "POST",
            data: {
                wheelmapid: wheelmap_id,
                wheelchairstatus: wheelchair_status
            },
            success: function(r) {
                if (r.success) {
                    alert("Successfully updated.");
                } else {
                    alert("Something is wrong.");
                }
            },
            error: function() {
                alert("There was an error.");
            }
        });
}

var load_venues = function(url, page) {
    if ( typeof page == "undefined" )
        page = 0

    // For the first page, clear the screen
    if ( page == 0 )
        $('#venues').html("")

    $load_div = $("
Loading venues from foursquare...

");

    $('#venues').append($load_div);

    $.ajax({
        url: "/foursquare/venues/" + url + "/" + page,
        success: function( html ) {
            $('#venues').append(html);
            $('#loadmorevenues').show();
            $('#loadmorevenues-button').data("next-page", ++page);
            $('#loadmorevenues-button').data("current-url", url);
            load_wheelmap_info();
        },
        error: function() {
            $('#venues').append("
There was a problem. We couldn't reach foursquare, sorry!
");
        },
        complete: function() {
            $load_div.remove();
        }
    });
}

var load_wheelmap_info = function() {
    $.each( $('div#venues>div.venue'), function(index, div) {

        // Load Wheelmap Node
        $.ajax({
        dataType: "json",
        url: "/wheelmap/nodes",
        data: {
            lat: $(div).data('lat'),
            lng: $(div).data('lng'),
            name: $(div).data('name')
        },
        success: function( r ) {
            if ( r.wheelmap ) {
                // Add class for the status for filtering of visible infos
                $(div).addClass("wheelchair-" + r.wheelchair);
                // Change the headline to the name of the venue.
                $(div).find('.nodeheadline').html(r.name);
                // Add the response data to the box
                $nodeinfo = $(div).find('.nodeinfo');
                $nodeinfo.find('.wheelmap-link')[0].pathname += r.wheelmap_id;
                $nodeinfo.find('.wheelmap-status').text(r.wheelchair);
                $nodeinfo.find('.wheelmap-description').text(r.wheelchair_description);
                $nodeinfo.show();

                $nodeinfo.find('.edit-wheelchair-status').click(function(){
                        $('#myModalLabel').text(r.name);
                        $('#editwheelmap input[value="' + r.wheelchair + '"]').prop('checked', true);
                        $('#btn-node-update').data('wheelmap_id', r.wheelmap_id);
                        $('#editwheelmap').modal('show');
                });

                $(div).find('.map img.mapmarker').attr("src", "/static/img/" + r.wheelchair + ".png");
            } else {
                // Add class for the status for filtering of visible infos
                $(div).addClass("wheelchair-notfound");
                // Change headline to not found
                $(div).find('.nodeheadline').html("Not found on wheelmap");
                $nodenotfound = $(div).find(".nodenotfound");
                $search_link = $nodenotfound.find(".wheelmap-search-link")[0];
                $search_link.href = $search_link.href.replace("0lat0", $(div).data('lat'));
                $search_link.href = $search_link.href.replace("0lon0", $(div).data('lng'));
                $nodenotfound.show();

                $(div).find('.map img.mapmarker').attr("src", "/static/img/notfound.png");
            }
            // Hide the ones, that are not wanted
            update_filter();
        },
        error: function() {
            $(div).find('.nodeheadline').html("Error: There was a problem contacting wheelmap.");
        }
        });
    });
};

var update_filter = function () {
    // Function for filtering the results by wheelchair status

    $(".wheelchair-filter-checkbox").each(function() {
        wheelchair_status = $(this).data("wheelchair");
        if ( $(this).is(":checked") ) {
            $(".wheelchair-" + wheelchair_status).each(function(){
                if( !$(this).hasClass('in') ) {
                    $(this).collapse('show');
                }
            });
        } else {
            $(".wheelchair-" + wheelchair_status).each(function(){
                if( $(this).hasClass('in') ) {
                    $(this).collapse('hide');
                }
            });
        }
    });
}
<commit_msg>Load startpage with ajax and abort other requests in that case<commit_after>$(document).ready(function() {

    $(".load-venues-link").click(function(e) {
            e.preventDefault();
            load_venues( $(this).attr('href') );
    });

    $(".wheelchair-filter-checkbox").click( update_filter );

    $("[rel='tooltip']").tooltip();

    $('#loadmorevenues-button').click(function(){
        load_venues( $(this).data("current-url"), $(this).data("next-page") );
    });

    $('.brand').click(function(e){
        e.preventDefault();
        $('#venues').html("Loading..");
        $.ajaxQ.abortAll();
        $.get("/", function(r){
            $('#venues').html(r);
        });
    });

    $('#btn-node-update').click(function(){
        update_wheelmap_node($(this).data('wheelmap_id'),
                            $('#form-update-status input:checked').val());
    });

    // Keeping track of the ajax calls to abort them
    // From: http://stackoverflow.com/a/11612641/1462065
    $.ajaxQ = (function(){
      var id = 0, Q = {};

      $(document).ajaxSend(function(e, jqx){
        jqx._id = ++id;
        Q[jqx._id] = jqx;
      });
      $(document).ajaxComplete(function(e, jqx){
        delete Q[jqx._id];
      });

      return {
        abortAll: function(){
          var r = [];
          $.each(Q, function(i, jqx){
            r.push(jqx._id);
            jqx.abort();
          });
          return r;
        }
      };

    })();

});

var update_wheelmap_node = function(wheelmap_id, wheelchair_status) {

        $.ajax({
            dataType: "json",
            url: "/wheelmap/update_node/",
            type: "POST",
            data: {
                wheelmapid: wheelmap_id,
                wheelchairstatus: wheelchair_status
            },
            success: function(r) {
                if (r.success) {
                    alert("Successfully updated.");
                } else {
                    alert("Something is wrong.");
                }
            },
            error: function() {
                alert("There was an error.");
            }
        });
}

var load_venues = function(url, page) {
    if ( typeof page == "undefined" )
        page = 0

    // For the first page, clear the screen
    if ( page == 0 )
        $('#venues').html("")

    $load_div = $("
Loading venues from foursquare...

");

    $('#venues').append($load_div);

    $.ajax({
        url: "/foursquare/venues/" + url + "/" + page,
        success: function( html ) {
            $('#venues').append(html);
            $('#loadmorevenues').show();
            $('#loadmorevenues-button').data("next-page", ++page);
            $('#loadmorevenues-button').data("current-url", url);
            load_wheelmap_info();
        },
        error: function() {
            $('#venues').append("
There was a problem. We couldn't reach foursquare, sorry!
");
        },
        complete: function() {
            $load_div.remove();
        }
    });
}

var load_wheelmap_info = function() {
    $.each( $('div#venues>div.venue'), function(index, div) {

        // Load Wheelmap Node
        $.ajax({
        dataType: "json",
        url: "/wheelmap/nodes",
        data: {
            lat: $(div).data('lat'),
            lng: $(div).data('lng'),
            name: $(div).data('name')
        },
        success: function( r ) {
            if ( r.wheelmap ) {
                // Add class for the status for filtering of visible infos
                $(div).addClass("wheelchair-" + r.wheelchair);
                // Change the headline to the name of the venue.
                $(div).find('.nodeheadline').html(r.name);
                // Add the response data to the box
                $nodeinfo = $(div).find('.nodeinfo');
                $nodeinfo.find('.wheelmap-link')[0].pathname += r.wheelmap_id;
                $nodeinfo.find('.wheelmap-status').text(r.wheelchair);
                $nodeinfo.find('.wheelmap-description').text(r.wheelchair_description);
                $nodeinfo.show();

                $nodeinfo.find('.edit-wheelchair-status').click(function(){
                        $('#myModalLabel').text(r.name);
                        $('#editwheelmap input[value="' + r.wheelchair + '"]').prop('checked', true);
                        $('#btn-node-update').data('wheelmap_id', r.wheelmap_id);
                        $('#editwheelmap').modal('show');
                });

                $(div).find('.map img.mapmarker').attr("src", "/static/img/" + r.wheelchair + ".png");
            } else {
                // Add class for the status for filtering of visible infos
                $(div).addClass("wheelchair-notfound");
                // Change headline to not found
                $(div).find('.nodeheadline').html("Not found on wheelmap");
                $nodenotfound = $(div).find(".nodenotfound");
                $search_link = $nodenotfound.find(".wheelmap-search-link")[0];
                $search_link.href = $search_link.href.replace("0lat0", $(div).data('lat'));
                $search_link.href = $search_link.href.replace("0lon0", $(div).data('lng'));
                $nodenotfound.show();

                $(div).find('.map img.mapmarker').attr("src", "/static/img/notfound.png");
            }
            // Hide the ones, that are not wanted
            update_filter();
        },
        error: function() {
            $(div).find('.nodeheadline').html("Error: There was a problem contacting wheelmap.");
        }
        });
    });
};

var update_filter = function () {
    // Function for filtering the results by wheelchair status

    $(".wheelchair-filter-checkbox").each(function() {
        wheelchair_status = $(this).data("wheelchair");
        if ( $(this).is(":checked") ) {
            $(".wheelchair-" + wheelchair_status).each(function(){
                if( !$(this).hasClass('in') ) {
                    $(this).collapse('show');
                }
            });
        } else {
            $(".wheelchair-" + wheelchair_status).each(function(){
                if( $(this).hasClass('in') ) {
                    $(this).collapse('hide');
                }
            });
        }
    });
}
<|endoftext|>


<commit_before>/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var EXPORTED_SYMBOLS = ["PdfJs"];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cm = Components.manager;
const Cu = Components.utils;

const PREF_PREFIX = 'pdfjs';
const PREF_DISABLED = PREF_PREFIX + '.disabled';
const PREF_MIGRATION_VERSION = PREF_PREFIX + '.migrationVersion';
const PREF_PREVIOUS_ACTION = PREF_PREFIX + '.previousHandler.preferredAction';
const PREF_PREVIOUS_ASK = PREF_PREFIX + '.previousHandler.alwaysAskBeforeHandling';
const PREF_DISABLED_PLUGIN_TYPES = 'plugin.disable_full_page_plugin_for_types';
const TOPIC_PDFJS_HANDLER_CHANGED = 'pdfjs:handlerChanged';
const PDF_CONTENT_TYPE = 'application/pdf';

Cu.import('resource://gre/modules/XPCOMUtils.jsm');
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://pdf.js.components/PdfStreamConverter.js');

let Svc = {};
XPCOMUtils.defineLazyServiceGetter(Svc, 'mime',
                                   '@mozilla.org/mime;1',
                                   'nsIMIMEService');

function getBoolPref(aPref, aDefaultValue) {
  try {
    return Services.prefs.getBoolPref(aPref);
  } catch (ex) {
    return aDefaultValue;
  }
}

function getIntPref(aPref, aDefaultValue) {
  try {
    return Services.prefs.getIntPref(aPref);
  } catch (ex) {
    return aDefaultValue;
  }
}

// Register/unregister a constructor as a component.
let Factory = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory]),
  _targetConstructor: null,

  register: function register(targetConstructor) {
    this._targetConstructor = targetConstructor;
    var proto = targetConstructor.prototype;
    var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
    registrar.registerFactory(proto.classID, proto.classDescription,
                              proto.contractID, this);
  },

  unregister: function unregister() {
    var proto = this._targetConstructor.prototype;
    var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
    registrar.unregisterFactory(proto.classID, this);
    this._targetConstructor = null;
  },

  // nsIFactory
  createInstance: function createInstance(aOuter, iid) {
    if (aOuter !== null)
      throw Cr.NS_ERROR_NO_AGGREGATION;
    return (new (this._targetConstructor)).QueryInterface(iid);
  },

  // nsIFactory
  lockFactory: function lockFactory(lock) {
    // No longer used as of gecko 1.7.
    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  }
};

let PdfJs = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]),
  _registered: false,

  init: function init() {
    if (!getBoolPref(PREF_DISABLED, true)) {
      this._migrate();
    }

    if (this.enabled)
      this._ensureRegistered();
    else
      this._ensureUnregistered();

    // Listen for when pdf.js is completely disabled or a different pdf handler
    // is chosen.
    Services.prefs.addObserver(PREF_DISABLED, this, false);
    Services.obs.addObserver(this, TOPIC_PDFJS_HANDLER_CHANGED, false);
  },

  _migrate: function migrate() {
    const VERSION = 1;
    var currentVersion = getIntPref(PREF_MIGRATION_VERSION, 0);
    if (currentVersion >= VERSION) {
      return;
    }
    if (currentVersion < 2) {
      this._becomeHandler();
    }
    Services.prefs.setIntPref(PREF_MIGRATION_VERSION, VERSION);
  },

  _becomeHandler: function _becomeHandler() {
    let handlerInfo = Svc.mime.getFromTypeAndExtension(PDF_CONTENT_TYPE, 'pdf');
    let prefs = Services.prefs;
    if (handlerInfo.preferredAction !== Ci.nsIHandlerInfo.handleInternally &&
        handlerInfo.preferredAction !== false) {
      // Store the previous settings of preferredAction and
      // alwaysAskBeforeHandling in case we need to revert them in a hotfix that
      // would turn pdf.js off.
      prefs.setIntPref(PREF_PREVIOUS_ACTION, handlerInfo.preferredAction);
      prefs.setBoolPref(PREF_PREVIOUS_ASK, handlerInfo.alwaysAskBeforeHandling);
    }

    let handlerService = Cc['@mozilla.org/uriloader/handler-service;1'].
                         getService(Ci.nsIHandlerService);

    // Change and save mime handler settings.
    handlerInfo.alwaysAskBeforeHandling = false;
    handlerInfo.preferredAction = Ci.nsIHandlerInfo.handleInternally;
    handlerService.store(handlerInfo);

    // Also disable any plugins for pdfs.
    var stringTypes = '';
    var types = [];
    if (prefs.prefHasUserValue(PREF_DISABLED_PLUGIN_TYPES)) {
      stringTypes = prefs.getCharPref(PREF_DISABLED_PLUGIN_TYPES);
    }
    if (stringTypes !== '') {
      types = stringTypes.split(',');
    }

    if (types.indexOf(PDF_CONTENT_TYPE) === -1) {
      types.push(PDF_CONTENT_TYPE);
    }
    prefs.setCharPref(PREF_DISABLED_PLUGIN_TYPES, types.join(','));
  },

  // nsIObserver
  observe: function observe(aSubject, aTopic, aData) {
    if (this.enabled)
      this._ensureRegistered();
    else
      this._ensureUnregistered();
  },

  /**
   * pdf.js is only enabled if it is both selected as the pdf viewer and if the
   * global switch enabling it is true.
   * @return {boolean} Wether or not it's enabled.
   */
  get enabled() {
    var disabled = getBoolPref(PREF_DISABLED, true);
    if (disabled)
      return false;

    var handlerInfo = Svc.mime.
                        getFromTypeAndExtension('application/pdf', 'pdf');
    return handlerInfo.alwaysAskBeforeHandling == false &&
           handlerInfo.preferredAction == Ci.nsIHandlerInfo.handleInternally;
  },

  _ensureRegistered: function _ensureRegistered() {
    if (this._registered)
      return;

    Factory.register(PdfStreamConverter);
    this._registered = true;
  },

  _ensureUnregistered: function _ensureUnregistered() {
    if (!this._registered)
      return;

    Factory.unregister();
    this._registered = false;
  }
};
<commit_msg>Add comment for migration.<commit_after>/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var EXPORTED_SYMBOLS = ["PdfJs"];

const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cm = Components.manager;
const Cu = Components.utils;

const PREF_PREFIX = 'pdfjs';
const PREF_DISABLED = PREF_PREFIX + '.disabled';
const PREF_MIGRATION_VERSION = PREF_PREFIX + '.migrationVersion';
const PREF_PREVIOUS_ACTION = PREF_PREFIX + '.previousHandler.preferredAction';
const PREF_PREVIOUS_ASK = PREF_PREFIX + '.previousHandler.alwaysAskBeforeHandling';
const PREF_DISABLED_PLUGIN_TYPES = 'plugin.disable_full_page_plugin_for_types';
const TOPIC_PDFJS_HANDLER_CHANGED = 'pdfjs:handlerChanged';
const PDF_CONTENT_TYPE = 'application/pdf';

Cu.import('resource://gre/modules/XPCOMUtils.jsm');
Cu.import('resource://gre/modules/Services.jsm');
Cu.import('resource://pdf.js.components/PdfStreamConverter.js');

let Svc = {};
XPCOMUtils.defineLazyServiceGetter(Svc, 'mime',
                                   '@mozilla.org/mime;1',
                                   'nsIMIMEService');

function getBoolPref(aPref, aDefaultValue) {
  try {
    return Services.prefs.getBoolPref(aPref);
  } catch (ex) {
    return aDefaultValue;
  }
}

function getIntPref(aPref, aDefaultValue) {
  try {
    return Services.prefs.getIntPref(aPref);
  } catch (ex) {
    return aDefaultValue;
  }
}

// Register/unregister a constructor as a component.
let Factory = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIFactory]),
  _targetConstructor: null,

  register: function register(targetConstructor) {
    this._targetConstructor = targetConstructor;
    var proto = targetConstructor.prototype;
    var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
    registrar.registerFactory(proto.classID, proto.classDescription,
                              proto.contractID, this);
  },

  unregister: function unregister() {
    var proto = this._targetConstructor.prototype;
    var registrar = Cm.QueryInterface(Ci.nsIComponentRegistrar);
    registrar.unregisterFactory(proto.classID, this);
    this._targetConstructor = null;
  },

  // nsIFactory
  createInstance: function createInstance(aOuter, iid) {
    if (aOuter !== null)
      throw Cr.NS_ERROR_NO_AGGREGATION;
    return (new (this._targetConstructor)).QueryInterface(iid);
  },

  // nsIFactory
  lockFactory: function lockFactory(lock) {
    // No longer used as of gecko 1.7.
    throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  }
};

let PdfJs = {
  QueryInterface: XPCOMUtils.generateQI([Ci.nsIObserver]),
  _registered: false,

  init: function init() {
    if (!getBoolPref(PREF_DISABLED, true)) {
      this._migrate();
    }

    if (this.enabled)
      this._ensureRegistered();
    else
      this._ensureUnregistered();

    // Listen for when pdf.js is completely disabled or a different pdf handler
    // is chosen.
    Services.prefs.addObserver(PREF_DISABLED, this, false);
    Services.obs.addObserver(this, TOPIC_PDFJS_HANDLER_CHANGED, false);
  },

  _migrate: function migrate() {
    const VERSION = 1;
    var currentVersion = getIntPref(PREF_MIGRATION_VERSION, 0);
    if (currentVersion >= VERSION) {
      return;
    }
    // Make pdf.js the default pdf viewer on the first migration.
    if (currentVersion < 2) {
      this._becomeHandler();
    }
    Services.prefs.setIntPref(PREF_MIGRATION_VERSION, VERSION);
  },

  _becomeHandler: function _becomeHandler() {
    let handlerInfo = Svc.mime.getFromTypeAndExtension(PDF_CONTENT_TYPE, 'pdf');
    let prefs = Services.prefs;
    if (handlerInfo.preferredAction !== Ci.nsIHandlerInfo.handleInternally &&
        handlerInfo.preferredAction !== false) {
      // Store the previous settings of preferredAction and
      // alwaysAskBeforeHandling in case we need to revert them in a hotfix that
      // would turn pdf.js off.
      prefs.setIntPref(PREF_PREVIOUS_ACTION, handlerInfo.preferredAction);
      prefs.setBoolPref(PREF_PREVIOUS_ASK, handlerInfo.alwaysAskBeforeHandling);
    }

    let handlerService = Cc['@mozilla.org/uriloader/handler-service;1'].
                         getService(Ci.nsIHandlerService);

    // Change and save mime handler settings.
    handlerInfo.alwaysAskBeforeHandling = false;
    handlerInfo.preferredAction = Ci.nsIHandlerInfo.handleInternally;
    handlerService.store(handlerInfo);

    // Also disable any plugins for pdfs.
    var stringTypes = '';
    var types = [];
    if (prefs.prefHasUserValue(PREF_DISABLED_PLUGIN_TYPES)) {
      stringTypes = prefs.getCharPref(PREF_DISABLED_PLUGIN_TYPES);
    }
    if (stringTypes !== '') {
      types = stringTypes.split(',');
    }

    if (types.indexOf(PDF_CONTENT_TYPE) === -1) {
      types.push(PDF_CONTENT_TYPE);
    }
    prefs.setCharPref(PREF_DISABLED_PLUGIN_TYPES, types.join(','));
  },

  // nsIObserver
  observe: function observe(aSubject, aTopic, aData) {
    if (this.enabled)
      this._ensureRegistered();
    else
      this._ensureUnregistered();
  },

  /**
   * pdf.js is only enabled if it is both selected as the pdf viewer and if the
   * global switch enabling it is true.
   * @return {boolean} Wether or not it's enabled.
   */
  get enabled() {
    var disabled = getBoolPref(PREF_DISABLED, true);
    if (disabled)
      return false;

    var handlerInfo = Svc.mime.
                        getFromTypeAndExtension('application/pdf', 'pdf');
    return handlerInfo.alwaysAskBeforeHandling == false &&
           handlerInfo.preferredAction == Ci.nsIHandlerInfo.handleInternally;
  },

  _ensureRegistered: function _ensureRegistered() {
    if (this._registered)
      return;

    Factory.register(PdfStreamConverter);
    this._registered = true;
  },

  _ensureUnregistered: function _ensureUnregistered() {
    if (!this._registered)
      return;

    Factory.unregister();
    this._registered = false;
  }
};
<|endoftext|>


<commit_before>// Start with a bunch of stuff from other libraries, then add code from my own libraries
const osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: `©
  OpenStreetMap`,
  minZoom: 2,
  maxZoom: 19
})

const stamenToner = L.tileLayer(`http://stamen-tiles-{s}.a.ssl.fastly.net/
toner/{z}/{x}/{y}.{ext}`, {
  attribution: `Map tiles by Stamen Design,
  CC BY 3.0
  — Map data ©
  OpenStreetMap`,
  subdomains: 'abcd',
  minZoom: 2,
  maxZoom: 19,
  ext: 'png'
})

const esriWorldImagery = L.tileLayer(`http://server.arcgisonline.com/ArcGIS/
rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}`, {
  attribution: `Tiles © Esri — Source: Esri, i-cubed, USDA,
  USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP,
  and the GIS User Community`
})

const myMap = L.map('mapid', {
  center: {lat: 0, lng: 8.8460},
  zoom: 2,
  layers: osm,
  scrollWheelZoom: false
})

const baseLayers = {
  'Open Street Maps': osm,
  'Black and White': stamenToner,
  'ESRI World Map': esriWorldImagery
}

const baseLayerControl = L.control.layers(baseLayers)
baseLayerControl.addTo(myMap)

// to toggle active datasets on the map, and otherwise I need the list of datasets
// should this be a const?
const datasetLinks = document.getElementsByName('dataset')
const datasets = {}

// color marker options
const colors = ['purple', 'blue', 'green', 'yellow', 'orange', 'red']
let colorCounter = 0
const setColorMarkerOptions = (color) => {
  const colorMarkerOptions = {
    radius: 8,
    fillColor: color,
    color: 'black',
    weight: 1,
    opacity: 1,
    fillOpacity: 0.4
  }
  return colorMarkerOptions
}

// add event that toggles the link's class from active to not
//
datasetLinks.forEach(link => {
  const ext = link.getAttribute('id')
  const pk = link.getAttribute('value')
  const url = `/load_dataset/${pk}`

  // deal with colors
  colorCounter++
  const color = colors[colorCounter % colors.length]
  console.log(color)

  // I have to put the modJson in here. If I don't do that then every dataset will be
  // added to the modJson L.geoJson layer, resulting in one monstrous layer.
  // Every time I call the 'getDataset' function there needs to be a new modJson called
  const layerMod = L.geoJson(null, {
    pointToLayer: (feature, latlng) => {
      return L.circleMarker(latlng, setColorMarkerOptions(color))
    },
    onEachFeature: addPopups
  })

  link.addEventListener('click', () => {
    classToggle(link, 'active')
    // (map, obj, key, url, ext)
    datasetToggle(myMap, datasets, pk, ext, url, layerMod)
  })
})

// my own function (scrollWheelToggle), sitting in index.js
myMap.on('click', () => scrollWheelToggle(myMap))

<commit_msg>now really different layers different colors (non point layer included<commit_after>// Start with a bunch of stuff from other libraries, then add code from my own libraries
const osm = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: `©
  OpenStreetMap`,
  minZoom: 2,
  maxZoom: 19
})

const stamenToner = L.tileLayer(`http://stamen-tiles-{s}.a.ssl.fastly.net/
toner/{z}/{x}/{y}.{ext}`, {
  attribution: `Map tiles by Stamen Design,
  CC BY 3.0
  — Map data ©
  OpenStreetMap`,
  subdomains: 'abcd',
  minZoom: 2,
  maxZoom: 19,
  ext: 'png'
})

const esriWorldImagery = L.tileLayer(`http://server.arcgisonline.com/ArcGIS/
rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}`, {
  attribution: `Tiles © Esri — Source: Esri, i-cubed, USDA,
  USGS, AEX, GeoEye, Getmapping, Aerogrid, IGN, IGP, UPR-EGP,
  and the GIS User Community`
})

const myMap = L.map('mapid', {
  center: {lat: 0, lng: 8.8460},
  zoom: 2,
  layers: osm,
  scrollWheelZoom: false
})

const baseLayers = {
  'Open Street Maps': osm,
  'Black and White': stamenToner,
  'ESRI World Map': esriWorldImagery
}

const baseLayerControl = L.control.layers(baseLayers)
baseLayerControl.addTo(myMap)

// to toggle active datasets on the map, and otherwise I need the list of datasets
// should this be a const?
const datasetLinks = document.getElementsByName('dataset')
const datasets = {}

// colors
const colors = ['purple', 'blue', 'green', 'yellow', 'orange', 'red']
let colorCounter = 0

// pointMarkerOptions
const markerOptions = {
  radius: 8,
  color: 'black',
  weight: 1,
  opacity: 1,
  fillOpacity: 0.4
}

// add event that toggles the link's class from active to not active
datasetLinks.forEach(link => {
  const ext = link.getAttribute('id')
  const pk = link.getAttribute('value')
  const url = `/load_dataset/${pk}`

  // deal with colors
  colorCounter++
  const color = colors[colorCounter % colors.length]
  console.log(color)

  // Every time I call the 'getDataset' function there needs to be a new modJson called
  const layerMod = L.geoJson(null, {

    // set the points to little circles
    pointToLayer: (feature, latlng) => {
      return L.circleMarker(latlng, markerOptions)
    },

    // set the colors of each layer, and add popups to everything
    onEachFeature: (feature, layer) => {
      layer.options.color = color
      addPopups(feature, layer)
    }
  })

  link.addEventListener('click', () => {
    classToggle(link, 'active')
    // (map, obj, key, url, ext)
    datasetToggle(myMap, datasets, pk, ext, url, layerMod)
  })
})

// my own function (scrollWheelToggle), sitting in index.js
myMap.on('click', () => scrollWheelToggle(myMap))

<|endoftext|>