<commit_before>// IFG-Anfragen Vis
// (c) 2013 Stefan Wehrmeyer

(function($){

  var isTouch = ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;

  var margin = {top: 20, right: 20, bottom: 20, left: 20};
  var innerX = {top: 0, right: 50, bottom: 30, left: 80};
  var innerY = {top: 30, right: 80, bottom: 80, left: 30};

  d3.selection.prototype.moveToFront = function() {
    return this.each(function() {
      this.parentNode.appendChild(this);
    });
  };

  var containerWidth = document.getElementById('vis').offsetWidth;

  var width = Math.max(containerWidth, 768) - margin.left - margin.right,
      height = 468 - margin.top - margin.bottom;

  var parseYear = d3.time.format("%Y").parse;

  var innerXWidth = width - innerX.right - innerX.left;
  var x = d3.time.scale()
      .range([0, innerXWidth]);

  var innerYHeight = height - innerY.top - innerY.bottom;
  var y = d3.scale.linear()
      .domain([0, 100])
      .range([innerYHeight, 0]);

  var yAxis = d3.svg.axis()
      .scale(y)
      .tickSize(-width, 0, 0)
      .ticks(5)
      .tickFormat(function(d){ return d + '%'; })
      .orient("left");

  var xAxis = d3.svg.axis()
      .scale(x)
      .tickSize(-height + innerY.bottom, 0, 0)
      .tickPadding(6)
      .orient("top");

  var circleRadius = d3.scale.sqrt()
      .rangeRound([1, IFGVis.maxDotSize]);

  var connectionLine = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("basis")
    .defined(function(d){
      return d.defined;
    });

  var svg = d3.select("#vis").append("svg:svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);

  svg = svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
    .attr("class", "y axis")
    .attr('transform', 'translate(' + innerY.left + ',' + innerY.top + ')')
    .call(yAxis);

  svg.select('.y.axis .major line').classed('bottomline', true);

  var activeGroups = 0;

  var activateGroup = function(key, hover) {
    return function(){
      var obj = groups[key];
      obj.group.moveToFront();
      svg.selectAll("." + key).style("fill", IFGVis.colors[key]).classed('active', true);
      obj.group.select('.line').style('display', 'block');
      if (stack[stack.length - 1] === key) {
        svg.select('#label')
          .attr('transform', 'translate(' + (innerXWidth + innerX.left + 40) + ',' + (obj.labelpos + 12) + ')')
          .style('display', 'block');
        svg.select('#label-triangle')
          .attr('transform', 'translate(' + (innerXWidth + innerX.left) + ',' + (obj.labelpos + 22) + ')');
        svg.select('#label-text')
          .text(IFGVis.labels[key])
          .style('fill', IFGVis.colors[key]);
        var bbox = svg.select('#label-text').node().getBBox();
        svg.select('#label-rect')
          .attr('transform', 'translate(' + (-bbox.width - 5) + ',' + (-20) + ')')
          .attr('width', bbox.width + 10)
          .attr('height', bbox.height + 5);
        svg.selectAll('.label').style('display', 'block');
        obj.group.selectAll('.circle-number').style('display', 'block');
      } else {
        obj.group.selectAll('.circle-number').style('display', 'none');
      }
      activeInForeground();
    };
  };

  var permanentlyActivateGroup = function(key){
    return function(){
      var obj = groups[key];
      obj.isActive = !obj.isActive;
      if (obj.isActive) {
        activateGroup(key)();
      } else {
        deactivateGroup(key)();
      }
    };
  };

  var deactivateGroup = function(key) {
    return function() {
      var obj = groups[key];
      if (obj.isActive) { return; }
      obj.group.select('.line').style('display', 'none');
      svg.selectAll("." + key).style("fill", "").classed('active', false);
      obj.group.selectAll('.circle-number').style('display', 'none');
      refreshAllActiveGroups();
    };
  };

  var activeInForeground = function(){
    for (var key in groups){
      if (groups[key].isActive){
        groups[key].group.moveToFront();
      }
    }
    if (stack.length > 0) {
      groups[stack[stack.length - 1]].group.moveToFront();
    }
    svg.selectAll('.label').moveToFront();
  };

  var refreshAllActiveGroups = function(){
    for (var key in groups){
      if (groups[key].isActive){
        activateGroup(key)();
      }
    }
    activeInForeground();
  };

  var groups = {};

  var getLineData = function(groupData){
    var newData = [], d, rad, dist;
    for (var i = 0; i < groupData.length; i += 1){
      if (i < groupData.length - 1) {
        dist = x(groupData[1].year) - x(groupData[0].year);
        dist = Math.round((dist - 50) / 2);
      }
      rad = dist;
      if (i > 0){
        d = $.extend({}, groupData[i]);
        d.rad = rad;
        d.x = x(d.year) - rad;
        d.y = y(d.transparency);
        d.defined = true;
        newData.push(d);
      }
      d = $.extend({}, groupData[i]);
      d.x = x(d.year);
      d.y = y(d.transparency);
      d.defined = true;
      newData.push(d);
      if (i < groupData.length - 1) {
        d = $.extend({}, groupData[i]);
        d.x = x(d.year) + rad;
        d.y = y(d.transparency);
        d.defined = true;
        newData.push(d);
      }
    }

    return newData;
  };

  var makeTriangle = (function() {
    var t = d3.svg.symbol();
    t.size(100);
    return t;
  }());

  var makeGroup = function(key, groupData){
    var group = svg.append('g')
      .attr('transform', 'translate(' + innerX.left + ',' + innerY.top + ')')
      .attr('class', 'group ' + key);

    var connectionData = getLineData(groupData);

    group.append("svg:path")
        .attr('class', 'line')
        .style('stroke', IFGVis.colors[key])
        .style('display', 'none')
        .attr("d", connectionLine(connectionData));

    var groupSelect = group
      .selectAll("." + key)
      .data(groupData);

    var circleGroup = groupSelect
      .enter().append("g");

    circleGroup.append('path')
      .attr('d', makeTriangle.type('triangle-up')())
      .attr('class', 'triangle circle-number label-background')
      .attr('transform', function(d){
        return 'translate(' + (x(d.year)) + ',' + (y(d.transparency) + 8) + ')';
      })
      .style('display', 'none');

    var circleGroupText = circleGroup.append('g')
      .attr('class', 'circle-number');

    circleGroupText.append('rect')
        .attr('width', '70')
        .attr('class', 'label-background')
        .attr('height', '70')
        .attr('transform', function(d){
          return 'translate(' + (x(d.year) - 35) + ',' + (y(d.transparency) + 12) + ')';
        });

    var t = circleGroupText.append('text')
      .attr('class', 'circle-number highlight')
      .style('fill', IFGVis.colors[key])
      .attr('transform', function(d){
        return 'translate(' + (x(d.year)) + ',' + (y(d.transparency) + 31) + ')';
      })
      .style('display', 'none')
      .attr('text-anchor', 'middle');

    t.append('tspan')
      .attr('x', 0)
      .text(function(d){
          return d.transparency + '%';
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text(function(d){
          return 'von ' + d.count;
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text(function(d){
        return d.count === 1 ? 'Antrag' : 'Anträgen';
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text('bewilligt');

    if (isTouch){
      group.data(groupData)
        .on("touchstart", navigateToKey(key));
    } else {
      group.data(groupData)
        .on("mouseover", activateGroup(key, true))
        .on("mouseout", deactivateGroup(key))
        .on("click", navigateToKey(key));
    }

    var lastBubble = groupData[groupData.length - 1];
    var labelpos = y(lastBubble.transparency);

    return {
      labelpos: labelpos,
      group: group,
      isActive: false
    };
  };

  var dataLoaded = function(error, data) {
    data.forEach(function(d) {
      d.year = parseYear(d.year);
      d.count = parseInt(d.count, 10);
      d.transparency = parseInt(d.transparency, 10);
    });
    data = data.filter(function(d){
      return d.count > 0;
    })
    .sort(function(a, b){
      return a.year - b.year;
    });

    x.domain(d3.extent(data, function(d) { return d.year; }));

    svg.append("g")
      .attr("class", "x axis")
      .attr('transform', 'translate(' + innerX.left + ',' + innerX.top + ')')
      .call(xAxis);

    var label = svg.append('g')
      .attr('id', 'label')
      .attr('class', 'label')
      .style('display', 'none');

    label.append('rect')
      .attr('id', 'label-rect')
      .attr('class', 'label-background')
      .attr('x', 0)
      .attr('y', 0)
      .attr('width', 1)
      .attr('height', 1);
    svg.append('path')
      .attr('id', 'label-triangle')
      .attr('d', makeTriangle.type('triangle-down')())
      .attr('class', 'triangle label label-background');
    label.append('text')
      .attr('id', 'label-text')
      .attr('text-anchor', 'end');

    circleRadius.domain(d3.extent(data, function(d) { return d.count; }));

    var filterFunc = function(key){
      return function(d){ return d.name === key; };
    };

    // Add Circles independent from group
    var circleData = data.slice();
    circleData.sort(function(a, b){
      return b.count - a.count;
    });
    svg.selectAll('.dot')
      .data(circleData)
      .enter()
      .append('circle')
      .attr("class", function(d){
        return "dot circle " + d.name;
      })
      .attr("r", function(d) {
        return circleRadius(d.count);
      });

    var helpCircleData = circleData.slice().filter(function(d, i){
      return circleRadius(d.count) <= IFGVis.dotSizeNeedsHelp;
    });
    svg.selectAll('.helpdot')
      .data(helpCircleData)
      .enter()
      .append('circle')
      .attr("r", IFGVis.helpDotSize)
      .attr("class", "helpdot circle");

    svg.selectAll('.circle')
      .attr('transform', 'translate(' + innerX.left + ',' + innerY.top + ')')
      .attr("cx", function(d) { return x(d.year); })
      .attr("cy", function(d) { return y(d.transparency); });

    if (isTouch){
      svg.selectAll('.circle')
        .on("touchstart", function(d){
          navigateToKey(d.name)();
        });
    } else {
      svg.selectAll('.circle')
        .on("mouseover", function(d){
          activateGroup(d.name, true)();
        })
        .on("mouseout", function(d){
          deactivateGroup(d.name)();
        })
        .on("click", function(d){
          navigateToKey(d.name)();
        });
    }

    for (var key in IFGVis.colors) {
      groups[key] = makeGroup(key, data.filter(filterFunc(key)));
    }

    init();
  };

  var initial = true, stack = [];

  var WorkspaceRouter = Backbone.Router.extend({
    routes: {
      "*args": "show"
    },

    show: function(args) {
      if (initial && args === "") {
        router.navigate(IFGVis.defaultInstitution, {trigger: true});
        initial = false;
        return;
      }
      initial = false;
      args = args.split('&');
      $('.label').hide();
      $('input').prop('checked', false);
      for (var key in groups){
        groups[key].isActive = false;
        deactivateGroup(key)();
      }
      activeGroups = 0;
      stack = [];
      for (var i = 0; i < args.length; i += 1) {
        if (groups[args[i]] !== undefined) {
          stack.push(args[i]);
          $('input[value="' + args[i] + '"]').prop('checked', true);
          activeGroups += 1;
          permanentlyActivateGroup(args[i])();
        }
      }
      refreshAllActiveGroups();
    }

  });

  var init = function(){
    Backbone.history.start();
  };

  var router = new WorkspaceRouter();

  var navigateToKey = function(key){
    return function(){
      var checked = $('input[value="' + key + '"]').prop('checked');
      $('input[value="' + key + '"]').prop('checked', !checked);
      toggleOnStack(key, !checked);
      updateNav();
    };
  };

  var toggleOnStack = function(key, add){
    if (add) {
      stack.push(key);
    } else {
      stack = stack.filter(function(el){
        return el !== key;
      });
    }
  };

  var updateNav = function(){
    var url;
    if (stack.length > 0) {
      url = stack.join('&');
    } else {
      url = '!';
    }
    router.navigate(url, {trigger: true});
  };

  $(function(){
    $('#auswahl-button').on('click touchstart', function(e){
      e.preventDefault();
      $('#auswahl').slideToggle();
    });
    $('#choose-all').on('click touchstart', function(e){
      e.preventDefault();
      $('.auswahl-liste input').prop('checked', true);
      stack = [];
      $('.auswahl-liste input').each(function(i, el){
        stack.push($(el).val());
      });
      updateNav();
    });
    $('#choose-none').on('click touchstart', function(e){
      e.preventDefault();
      $('.auswahl-liste input').prop('checked', false);
      stack = [];
      updateNav();
    });
    $('.auswahl-liste input').change(function(e){
      toggleOnStack($(this).val(), $(this).prop('checked'));
      updateNav();
    });
    $('.close').on('click touchstart', function(e){
      e.preventDefault();
      $('#auswahl').slideUp();
    });
  });

  dataLoaded(null, IFGVis.data);
  // d3.csv("data.csv", dataLoaded);

}(jQuery));
<commit_msg>Load CSV instead of JS data<commit_after>// IFG-Anfragen Vis
// (c) 2013 Stefan Wehrmeyer

(function($){

  var isTouch = ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch;

  var margin = {top: 20, right: 20, bottom: 20, left: 20};
  var innerX = {top: 0, right: 50, bottom: 30, left: 80};
  var innerY = {top: 30, right: 80, bottom: 80, left: 30};

  d3.selection.prototype.moveToFront = function() {
    return this.each(function() {
      this.parentNode.appendChild(this);
    });
  };

  var containerWidth = document.getElementById('vis').offsetWidth;

  var width = Math.max(containerWidth, 768) - margin.left - margin.right,
      height = 468 - margin.top - margin.bottom;

  var parseYear = d3.time.format("%Y").parse;

  var innerXWidth = width - innerX.right - innerX.left;
  var x = d3.time.scale()
      .range([0, innerXWidth]);

  var innerYHeight = height - innerY.top - innerY.bottom;
  var y = d3.scale.linear()
      .domain([0, 100])
      .range([innerYHeight, 0]);

  var yAxis = d3.svg.axis()
      .scale(y)
      .tickSize(-width, 0, 0)
      .ticks(5)
      .tickFormat(function(d){ return d + '%'; })
      .orient("left");

  var xAxis = d3.svg.axis()
      .scale(x)
      .tickSize(-height + innerY.bottom, 0, 0)
      .tickPadding(6)
      .orient("top");

  var circleRadius = d3.scale.sqrt()
      .rangeRound([1, IFGVis.maxDotSize]);

  var connectionLine = d3.svg.line()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .interpolate("basis")
    .defined(function(d){
      return d.defined;
    });

  var svg = d3.select("#vis").append("svg:svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom);

  svg = svg.append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
    .attr("class", "y axis")
    .attr('transform', 'translate(' + innerY.left + ',' + innerY.top + ')')
    .call(yAxis);

  svg.select('.y.axis .major line').classed('bottomline', true);

  var activeGroups = 0;

  var activateGroup = function(key, hover) {
    return function(){
      var obj = groups[key];
      obj.group.moveToFront();
      svg.selectAll("." + key).style("fill", IFGVis.colors[key]).classed('active', true);
      obj.group.select('.line').style('display', 'block');
      if (stack[stack.length - 1] === key) {
        svg.select('#label')
          .attr('transform', 'translate(' + (innerXWidth + innerX.left + 40) + ',' + (obj.labelpos + 12) + ')')
          .style('display', 'block');
        svg.select('#label-triangle')
          .attr('transform', 'translate(' + (innerXWidth + innerX.left) + ',' + (obj.labelpos + 22) + ')');
        svg.select('#label-text')
          .text(IFGVis.labels[key])
          .style('fill', IFGVis.colors[key]);
        var bbox = svg.select('#label-text').node().getBBox();
        svg.select('#label-rect')
          .attr('transform', 'translate(' + (-bbox.width - 5) + ',' + (-20) + ')')
          .attr('width', bbox.width + 10)
          .attr('height', bbox.height + 5);
        svg.selectAll('.label').style('display', 'block');
        obj.group.selectAll('.circle-number').style('display', 'block');
      } else {
        obj.group.selectAll('.circle-number').style('display', 'none');
      }
      activeInForeground();
    };
  };

  var permanentlyActivateGroup = function(key){
    return function(){
      var obj = groups[key];
      obj.isActive = !obj.isActive;
      if (obj.isActive) {
        activateGroup(key)();
      } else {
        deactivateGroup(key)();
      }
    };
  };

  var deactivateGroup = function(key) {
    return function() {
      var obj = groups[key];
      if (obj.isActive) { return; }
      obj.group.select('.line').style('display', 'none');
      svg.selectAll("." + key).style("fill", "").classed('active', false);
      obj.group.selectAll('.circle-number').style('display', 'none');
      refreshAllActiveGroups();
    };
  };

  var activeInForeground = function(){
    for (var key in groups){
      if (groups[key].isActive){
        groups[key].group.moveToFront();
      }
    }
    if (stack.length > 0) {
      groups[stack[stack.length - 1]].group.moveToFront();
    }
    svg.selectAll('.label').moveToFront();
  };

  var refreshAllActiveGroups = function(){
    for (var key in groups){
      if (groups[key].isActive){
        activateGroup(key)();
      }
    }
    activeInForeground();
  };

  var groups = {};

  var getLineData = function(groupData){
    var newData = [], d, rad, dist;
    for (var i = 0; i < groupData.length; i += 1){
      if (i < groupData.length - 1) {
        dist = x(groupData[1].year) - x(groupData[0].year);
        dist = Math.round((dist - 50) / 2);
      }
      rad = dist;
      if (i > 0){
        d = $.extend({}, groupData[i]);
        d.rad = rad;
        d.x = x(d.year) - rad;
        d.y = y(d.transparency);
        d.defined = true;
        newData.push(d);
      }
      d = $.extend({}, groupData[i]);
      d.x = x(d.year);
      d.y = y(d.transparency);
      d.defined = true;
      newData.push(d);
      if (i < groupData.length - 1) {
        d = $.extend({}, groupData[i]);
        d.x = x(d.year) + rad;
        d.y = y(d.transparency);
        d.defined = true;
        newData.push(d);
      }
    }

    return newData;
  };

  var makeTriangle = (function() {
    var t = d3.svg.symbol();
    t.size(100);
    return t;
  }());

  var makeGroup = function(key, groupData){
    var group = svg.append('g')
      .attr('transform', 'translate(' + innerX.left + ',' + innerY.top + ')')
      .attr('class', 'group ' + key);

    var connectionData = getLineData(groupData);

    group.append("svg:path")
        .attr('class', 'line')
        .style('stroke', IFGVis.colors[key])
        .style('display', 'none')
        .attr("d", connectionLine(connectionData));

    var groupSelect = group
      .selectAll("." + key)
      .data(groupData);

    var circleGroup = groupSelect
      .enter().append("g");

    circleGroup.append('path')
      .attr('d', makeTriangle.type('triangle-up')())
      .attr('class', 'triangle circle-number label-background')
      .attr('transform', function(d){
        return 'translate(' + (x(d.year)) + ',' + (y(d.transparency) + 8) + ')';
      })
      .style('display', 'none');

    var circleGroupText = circleGroup.append('g')
      .attr('class', 'circle-number');

    circleGroupText.append('rect')
        .attr('width', '70')
        .attr('class', 'label-background')
        .attr('height', '70')
        .attr('transform', function(d){
          return 'translate(' + (x(d.year) - 35) + ',' + (y(d.transparency) + 12) + ')';
        });

    var t = circleGroupText.append('text')
      .attr('class', 'circle-number highlight')
      .style('fill', IFGVis.colors[key])
      .attr('transform', function(d){
        return 'translate(' + (x(d.year)) + ',' + (y(d.transparency) + 31) + ')';
      })
      .style('display', 'none')
      .attr('text-anchor', 'middle');

    t.append('tspan')
      .attr('x', 0)
      .text(function(d){
          return d.transparency + '%';
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text(function(d){
          return 'von ' + d.count;
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text(function(d){
        return d.count === 1 ? 'Antrag' : 'Anträgen';
      });
    t.append('tspan')
      .attr('x', 0)
      .attr('dy', 15)
      .text('bewilligt');

    if (isTouch){
      group.data(groupData)
        .on("touchstart", navigateToKey(key));
    } else {
      group.data(groupData)
        .on("mouseover", activateGroup(key, true))
        .on("mouseout", deactivateGroup(key))
        .on("click", navigateToKey(key));
    }

    var lastBubble = groupData[groupData.length - 1];
    var labelpos = y(lastBubble.transparency);

    return {
      labelpos: labelpos,
      group: group,
      isActive: false
    };
  };

  var dataLoaded = function(error, data) {
    data.forEach(function(d) {
      d.year = parseYear(d.year);
      d.count = parseInt(d.count, 10);
      d.transparency = parseInt(d.transparency, 10);
    });
    data = data.filter(function(d){
      return d.count > 0;
    })
    .sort(function(a, b){
      return a.year - b.year;
    });

    x.domain(d3.extent(data, function(d) { return d.year; }));

    svg.append("g")
      .attr("class", "x axis")
      .attr('transform', 'translate(' + innerX.left + ',' + innerX.top + ')')
      .call(xAxis);

    var label = svg.append('g')
      .attr('id', 'label')
      .attr('class', 'label')
      .style('display', 'none');

    label.append('rect')
      .attr('id', 'label-rect')
      .attr('class', 'label-background')
      .attr('x', 0)
      .attr('y', 0)
      .attr('width', 1)
      .attr('height', 1);
    svg.append('path')
      .attr('id', 'label-triangle')
      .attr('d', makeTriangle.type('triangle-down')())
      .attr('class', 'triangle label label-background');
    label.append('text')
      .attr('id', 'label-text')
      .attr('text-anchor', 'end');

    circleRadius.domain(d3.extent(data, function(d) { return d.count; }));

    var filterFunc = function(key){
      return function(d){ return d.name === key; };
    };

    // Add Circles independent from group
    var circleData = data.slice();
    circleData.sort(function(a, b){
      return b.count - a.count;
    });
    svg.selectAll('.dot')
      .data(circleData)
      .enter()
      .append('circle')
      .attr("class", function(d){
        return "dot circle " + d.name;
      })
      .attr("r", function(d) {
        return circleRadius(d.count);
      });

    var helpCircleData = circleData.slice().filter(function(d, i){
      return circleRadius(d.count) <= IFGVis.dotSizeNeedsHelp;
    });
    svg.selectAll('.helpdot')
      .data(helpCircleData)
      .enter()
      .append('circle')
      .attr("r", IFGVis.helpDotSize)
      .attr("class", "helpdot circle");

    svg.selectAll('.circle')
      .attr('transform', 'translate(' + innerX.left + ',' + innerY.top + ')')
      .attr("cx", function(d) { return x(d.year); })
      .attr("cy", function(d) { return y(d.transparency); });

    if (isTouch){
      svg.selectAll('.circle')
        .on("touchstart", function(d){
          navigateToKey(d.name)();
        });
    } else {
      svg.selectAll('.circle')
        .on("mouseover", function(d){
          activateGroup(d.name, true)();
        })
        .on("mouseout", function(d){
          deactivateGroup(d.name)();
        })
        .on("click", function(d){
          navigateToKey(d.name)();
        });
    }

    for (var key in IFGVis.colors) {
      groups[key] = makeGroup(key, data.filter(filterFunc(key)));
    }

    init();
  };

  var initial = true, stack = [];

  var WorkspaceRouter = Backbone.Router.extend({
    routes: {
      "*args": "show"
    },

    show: function(args) {
      if (initial && args === "") {
        router.navigate(IFGVis.defaultInstitution, {trigger: true});
        initial = false;
        return;
      }
      initial = false;
      args = args.split('&');
      $('.label').hide();
      $('input').prop('checked', false);
      for (var key in groups){
        groups[key].isActive = false;
        deactivateGroup(key)();
      }
      activeGroups = 0;
      stack = [];
      for (var i = 0; i < args.length; i += 1) {
        if (groups[args[i]] !== undefined) {
          stack.push(args[i]);
          $('input[value="' + args[i] + '"]').prop('checked', true);
          activeGroups += 1;
          permanentlyActivateGroup(args[i])();
        }
      }
      refreshAllActiveGroups();
    }

  });

  var init = function(){
    Backbone.history.start();
  };

  var router = new WorkspaceRouter();

  var navigateToKey = function(key){
    return function(){
      var checked = $('input[value="' + key + '"]').prop('checked');
      $('input[value="' + key + '"]').prop('checked', !checked);
      toggleOnStack(key, !checked);
      updateNav();
    };
  };

  var toggleOnStack = function(key, add){
    if (add) {
      stack.push(key);
    } else {
      stack = stack.filter(function(el){
        return el !== key;
      });
    }
  };

  var updateNav = function(){
    var url;
    if (stack.length > 0) {
      url = stack.join('&');
    } else {
      url = '!';
    }
    router.navigate(url, {trigger: true});
  };

  $(function(){
    $('#auswahl-button').on('click touchstart', function(e){
      e.preventDefault();
      $('#auswahl').slideToggle();
    });
    $('#choose-all').on('click touchstart', function(e){
      e.preventDefault();
      $('.auswahl-liste input').prop('checked', true);
      stack = [];
      $('.auswahl-liste input').each(function(i, el){
        stack.push($(el).val());
      });
      updateNav();
    });
    $('#choose-none').on('click touchstart', function(e){
      e.preventDefault();
      $('.auswahl-liste input').prop('checked', false);
      stack = [];
      updateNav();
    });
    $('.auswahl-liste input').change(function(e){
      toggleOnStack($(this).val(), $(this).prop('checked'));
      updateNav();
    });
    $('.close').on('click touchstart', function(e){
      e.preventDefault();
      $('#auswahl').slideUp();
    });
  });

  // dataLoaded(null, IFGVis.data);
  d3.csv('data.csv', dataLoaded);

}(jQuery));
<|endoftext|>


<commit_before>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2018  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.10.0');
		this.setClientTag('node:18-12-07');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<commit_msg>New clientlib ver<commit_after>// ===================================================================================================
//                           _  __     _ _
//                          | |/ /__ _| | |_ _  _ _ _ __ _
//                          | ' </ _` | |  _| || | '_/ _` |
//                          |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2018  Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
/**
 * The Kaltura Client - this is the facade through which all service actions should be called.
 * @param config the Kaltura configuration object holding partner credentials (type: KalturaConfiguration).
 */
var util = require('util');
var kaltura = require('./KalturaClientBase');
kaltura.services = require('./KalturaServices');
kaltura.objects = require('./KalturaModel');
kaltura.enums = require('./KalturaTypes');

class Client extends kaltura.ClientBase {

	/**
	 * @param Configuration config
	 */
	constructor(config) {
		super(config);
		this.setApiVersion('14.10.0');
		this.setClientTag('node:18-12-08');
	}
}

module.exports = kaltura;
module.exports.Client = Client;

<|endoftext|>


<commit_before><commit_msg>fix(site): consider homebrew sources as standard<commit_after><|endoftext|>


<commit_before>"use strict";

/* global suite, test, setup */

var tld = require('../index.js');
var expect = require('expect.js');
var checkPublicSuffix;

suite('http://publicsuffix.org/list/test.txt', function(){
  setup(function(){
    //ease testing by simply copy/pasting tests from Mozilla Central
    //@see http://mxr.mozilla.org/mozilla-central/source/netwerk/test/unit/data/test_psl.txt?raw=1
    checkPublicSuffix = function(testDomain, expectedResult){
      expect(tld.getDomain(testDomain)).to.be(expectedResult);
    };
  });

  test('NULL input', function(){
    checkPublicSuffix(null, null);
  });

  test('Mixed case', function(){
    checkPublicSuffix('COM', null);
    checkPublicSuffix('example.COM', 'example.com');
    checkPublicSuffix('WwW.example.COM', 'example.com');
  });

  test('Leading dot', function(){
    checkPublicSuffix('.com', null);
    checkPublicSuffix('.example', null);
    checkPublicSuffix('.example.com', null);
    checkPublicSuffix('.example.example', null);
  });

  test('Unlisted TLD', function(){
    checkPublicSuffix('example', null);
    checkPublicSuffix('example.example', 'example.example');
    checkPublicSuffix('b.example.example', 'example.example');
    checkPublicSuffix('a.b.example.example', 'example.example');
  });

  test.skip('Listed, but non-Internet, TLD', function(){
   checkPublicSuffix('local', null);
   checkPublicSuffix('example.local', null);
   checkPublicSuffix('b.example.local', null);
   checkPublicSuffix('a.b.example.local', null);
  });

  test('TLD with only 1 rule', function(){
    checkPublicSuffix('biz', null);
    checkPublicSuffix('domain.biz', 'domain.biz');
    checkPublicSuffix('b.domain.biz', 'domain.biz');
    checkPublicSuffix('a.b.domain.biz', 'domain.biz');
  });

  test('TLD with some 2-level rules', function(){
    checkPublicSuffix('com', null);
    checkPublicSuffix('example.com', 'example.com');
    checkPublicSuffix('b.example.com', 'example.com');
    checkPublicSuffix('a.b.example.com', 'example.com');
    checkPublicSuffix('uk.com', null);
    checkPublicSuffix('example.uk.com', 'example.uk.com');
    checkPublicSuffix('b.example.uk.com', 'example.uk.com');
    checkPublicSuffix('a.b.example.uk.com', 'example.uk.com');
    checkPublicSuffix('test.ac', 'test.ac');
  });

  test('TLD with only 1 (wildcard) rule', function(){
    checkPublicSuffix('cy', null);
    checkPublicSuffix('c.cy', null);
    checkPublicSuffix('b.c.cy', 'b.c.cy');
    checkPublicSuffix('a.b.c.cy', 'b.c.cy');
  });

  test('More complex TLD', function(){
    checkPublicSuffix('jp', null);
    checkPublicSuffix('test.jp', 'test.jp');
    checkPublicSuffix('www.test.jp', 'test.jp');
    checkPublicSuffix('ac.jp', null);
    checkPublicSuffix('test.ac.jp', 'test.ac.jp');
    checkPublicSuffix('www.test.ac.jp', 'test.ac.jp');
    checkPublicSuffix('kyoto.jp', null);
    checkPublicSuffix('test.kyoto.jp', 'test.kyoto.jp');
    checkPublicSuffix('ide.kyoto.jp', null);
    checkPublicSuffix('b.ide.kyoto.jp', 'b.ide.kyoto.jp');
    checkPublicSuffix('a.b.ide.kyoto.jp', 'b.ide.kyoto.jp');
    checkPublicSuffix('c.kobe.jp', null);
    checkPublicSuffix('b.c.kobe.jp', 'b.c.kobe.jp');
    checkPublicSuffix('a.b.c.kobe.jp', 'b.c.kobe.jp');
    checkPublicSuffix('city.kobe.jp', 'city.kobe.jp');
    checkPublicSuffix('www.city.kobe.jp', 'city.kobe.jp');
  });

  test('TLD with a wildcard rule and exceptions', function(){
    checkPublicSuffix('om', null);
    checkPublicSuffix('test.om', null);
    checkPublicSuffix('b.test.om', 'b.test.om');
    checkPublicSuffix('a.b.test.om', 'b.test.om');
    checkPublicSuffix('songfest.om', 'songfest.om');
    checkPublicSuffix('www.songfest.om', 'songfest.om');
  });

  test('US K12', function(){
    checkPublicSuffix('us', null);
    checkPublicSuffix('test.us', 'test.us');
    checkPublicSuffix('www.test.us', 'test.us');
    checkPublicSuffix('ak.us', null);
    checkPublicSuffix('test.ak.us', 'test.ak.us');
    checkPublicSuffix('www.test.ak.us', 'test.ak.us');
    checkPublicSuffix('k12.ak.us', null);
    checkPublicSuffix('test.k12.ak.us', 'test.k12.ak.us');
    checkPublicSuffix('www.test.k12.ak.us', 'test.k12.ak.us');
  });
});<commit_msg>Updating tests<commit_after>"use strict";

/* global suite, test, setup */

var tld = require('../index.js');
var expect = require('expect.js');
var checkPublicSuffix;

suite('http://publicsuffix.org/list/test.txt', function(){
  setup(function(){
    //ease testing by simply copy/pasting tests from Mozilla Central
    //@see http://mxr.mozilla.org/mozilla-central/source/netwerk/test/unit/data/test_psl.txt?raw=1
    checkPublicSuffix = function(testDomain, expectedResult){
      expect(tld.getDomain(testDomain)).to.be(expectedResult);
    };
  });

  test('NULL input', function(){
    checkPublicSuffix(null, null);
  });

  test('Mixed case', function(){
    checkPublicSuffix('COM', null);
    checkPublicSuffix('example.COM', 'example.com');
    checkPublicSuffix('WwW.example.COM', 'example.com');
  });

  test('Leading dot', function(){
    checkPublicSuffix('.com', null);
    checkPublicSuffix('.example', null);
    checkPublicSuffix('.example.com', null);
    checkPublicSuffix('.example.example', null);
  });

  test('Unlisted TLD', function(){
    checkPublicSuffix('example', null);
    checkPublicSuffix('example.example', 'example.example');
    checkPublicSuffix('b.example.example', 'example.example');
    checkPublicSuffix('a.b.example.example', 'example.example');
  });

  test.skip('Listed, but non-Internet, TLD', function(){
   checkPublicSuffix('local', null);
   checkPublicSuffix('example.local', null);
   checkPublicSuffix('b.example.local', null);
   checkPublicSuffix('a.b.example.local', null);
  });

  test('TLD with only 1 rule', function(){
    checkPublicSuffix('biz', null);
    checkPublicSuffix('domain.biz', 'domain.biz');
    checkPublicSuffix('b.domain.biz', 'domain.biz');
    checkPublicSuffix('a.b.domain.biz', 'domain.biz');
  });

  test('TLD with some 2-level rules', function(){
    checkPublicSuffix('com', null);
    checkPublicSuffix('example.com', 'example.com');
    checkPublicSuffix('b.example.com', 'example.com');
    checkPublicSuffix('a.b.example.com', 'example.com');
    checkPublicSuffix('uk.com', null);
    checkPublicSuffix('example.uk.com', 'example.uk.com');
    checkPublicSuffix('b.example.uk.com', 'example.uk.com');
    checkPublicSuffix('a.b.example.uk.com', 'example.uk.com');
    checkPublicSuffix('test.ac', 'test.ac');
  });

  test('TLD with only 1 (wildcard) rule', function(){
    checkPublicSuffix('cy', null);
    checkPublicSuffix('c.cy', null);
    checkPublicSuffix('b.c.cy', 'b.c.cy');
    checkPublicSuffix('a.b.c.cy', 'b.c.cy');
  });

  test('More complex TLD', function(){
    checkPublicSuffix('jp', null);
    checkPublicSuffix('test.jp', 'test.jp');
    checkPublicSuffix('www.test.jp', 'test.jp');
    checkPublicSuffix('ac.jp', null);
    checkPublicSuffix('test.ac.jp', 'test.ac.jp');
    checkPublicSuffix('www.test.ac.jp', 'test.ac.jp');
    checkPublicSuffix('kyoto.jp', null);
    checkPublicSuffix('test.kyoto.jp', 'test.kyoto.jp');
    checkPublicSuffix('ide.kyoto.jp', null);
    checkPublicSuffix('b.ide.kyoto.jp', 'b.ide.kyoto.jp');
    checkPublicSuffix('a.b.ide.kyoto.jp', 'b.ide.kyoto.jp');
    checkPublicSuffix('c.kobe.jp', null);
    checkPublicSuffix('b.c.kobe.jp', 'b.c.kobe.jp');
    checkPublicSuffix('a.b.c.kobe.jp', 'b.c.kobe.jp');
    checkPublicSuffix('city.kobe.jp', 'city.kobe.jp');
    checkPublicSuffix('www.city.kobe.jp', 'city.kobe.jp');
  });

  test('TLD with a wildcard rule and exceptions', function(){
    checkPublicSuffix('ck', null);
    checkPublicSuffix('test.ck', null);
    checkPublicSuffix('b.test.ck', 'b.test.ck');
    checkPublicSuffix('a.b.test.ck', 'b.test.ck');
    checkPublicSuffix('www.ck', 'www.ck');
    checkPublicSuffix('www.www.ck', 'www.ck');
  });

  test('US K12', function(){
    checkPublicSuffix('us', null);
    checkPublicSuffix('test.us', 'test.us');
    checkPublicSuffix('www.test.us', 'test.us');
    checkPublicSuffix('ak.us', null);
    checkPublicSuffix('test.ak.us', 'test.ak.us');
    checkPublicSuffix('www.test.ak.us', 'test.ak.us');
    checkPublicSuffix('k12.ak.us', null);
    checkPublicSuffix('test.k12.ak.us', 'test.k12.ak.us');
    checkPublicSuffix('www.test.k12.ak.us', 'test.k12.ak.us');
  });
});<|endoftext|>


<commit_before>
/*
 * www-authenticate
 * https://github.com/randymized/www-authenticate
 *
 * Copyright (c) 2013 Randy McLaughlin
 * Licensed under the MIT license.
 */

'use strict';

var crypto= require('crypto')
  , md5sum = crypto.createHash('md5')
  , ParseAuth= /(\w+)\s+(.*)/  // -> scheme, params
  , Separators= /([",=])/
  ;

function md5(s) {
  return crypto.createHash('md5').update(s).digest('hex');
}

function hex8(num)
{
  return ("00000000" + num.toString(16)).slice(-8);
}

function Parse_WWW_Authenticate(to_parse)
{
  var m= to_parse.match(ParseAuth);
  this.scheme= m[1];
  this.parms= {};
  var err= this.parse_params(m[2].split(Separators));
  if (err) {
    this.scheme= '';
    this.parms= {};
    this.err= err;
  }
}

Parse_WWW_Authenticate.prototype.parse_params= function (m) {
  // This parser will definitely fail if there is more than one challenge
  var tok, last_tok, _i, _len, key, value;
  var state= 0;   //0: token,
  for (_i = 0, _len = m.length; _i < _len; _i++) {
    last_tok= tok;
    tok = m[_i];
    if (!tok.length) continue;
    switch (state) {
      case 0: // token
        key= tok.trim();
        state= 1; // expect equals
        continue;
      case 1: // expect equals
        if ('=' != tok) return 'Equal sign was expected after '+key;
        state= 2;
        continue;
      case 2: // expect value
        if ('"' == tok) {
          value= '';
          state= 3; // expect quoted
          continue;
        }
        else {
          auth_parms[key]= value= tok.trim();
          state= 9; // expect comma or end
          continue;
        }
      case 3: // handling quoted string
        if ('"' == tok) {
          state= 8; // end quoted
          continue;
        }
        else {
          value+= tok;
          state= 3; // continue accumulating quoted string
          continue;
        }
      case 8: // end quote encountered
        if ('"' == tok) {
          // double quoted
          value+= '"';
          state= 3; // back to quoted string
          continue;
        }
        if (',' == tok) {
          this.parms[key]= value;
          state= 0;
          continue;
        }
        else {
          return 'Unexpected token ('+tok+') after '+value+'"';
        }
        continue;
      case 9: // expect commma
        if (',' != tok) return 'Comma expected after '+value;
        state= 0;
        continue;
    }
  }
  switch (state) {  // terminal state
    case 0:   // Empty or ignoring terminal comma
    case 9:   // Expecting comma or end of header
      return;
    case 8:   // Last token was end quote
      this.parms[key]= value;
      return;
    default:
      return 'Unexpected end of www-authenticate value.';
  }
}

module.exports = function(username,password,options)
{
  var cnonce;
  if (options) {
    if (options.cnonce)
      cnonce= options.cnonce;
  }
  if (!cnonce) cnonce= crypto.pseudoRandomBytes(8);
  return function parse_header(www_authenticate,receiver)
  {
    var authorize, nc= 0;

    var parsed= new Parse_WWW_Authenticate(www_authenticate);
    if (parsed.err) return parsed.err;
    var auth_parms= parsed.parms;

    function respond_with(authorize_fn)
    {
      receiver(null, {authorize:authorize_fn, auth_parms:auth_parms,cnonce:cnonce});
    }

    switch(parsed.scheme) {
    case 'Basic':
      var auth_string= 'Basic '+new Buffer(username+':'+password, 'base64').toString('ascii');
      return respond_with(function() {
        return auth_string;
      });
      break;
    case 'Digest':
      var realm= auth_parms.realm;
      if (!realm) {
        return receiver("Realm not found in www-authenticate header.");
      }

      var ha1= md5(username+':'+realm+':'+password);
      var nonce= auth_parms.nonce;
      if (!nonce) {
        return receiver("Nonce not found in www-authenticate header.");
      }

      var fixed= 'Digest username="'+username+'",'+
          ' realm="'+realm+'",'+
          ' nonce="'+nonce+'",';
      var qop= auth_parms.qop;
      if (!qop) {
          return respond_with(function(method,digestURI) {
            var ha2= md5(method+':'+digestURI);
            return fixed+
              ' uri="'+digestURI+'",'+
              ' response="'+md5(ha1+':'+nonce+':'+ha2)+'",';
          });
      }
      else {
        var qopa= qop.split(',');
        var q, x, _i, _len;
        for (_i = 0, _len = qopa.length; _i < _len; _i++) {
          if ('auth' === qopa[_i]) {
            var opaque= auth_parms.opaque;
            var algorithm= auth_parms.algorithm;
            if (algorithm) {
              fixed+= ', algorithm="'+algorithm+'"';
            }
            else {
              algorithm= 'MD5';
            }
            var a1= 'MD5-sess' == algorithm ?
              md5(ha1+':'+nonce+':'+cnonce)
              :
              ha1;
            return respond_with(function(method,digestURI) {
              var ha2= md5(method+':'+digestURI);
              nc= nc+1;
              var hexed_nc= hex8(nc);
              var s= fixed+
                ' uri="'+digestURI+'",'+
                ' qop=auth,'+
                ' nc='+hexed_nc+','+
                ' cnonce="'+cnonce+'",'+
                ' response="'+md5(a1+':'+nonce+':'+hexed_nc+':'+cnonce+':auth:'+ha2)+'"';
              if (opaque) {
                s+= ', opaque="'+opaque+'"';
              }
              return s;
            });
          }
          return receiver('Server does not accept any supported quality of protection techniques.');
        }
      }
      break;
    default:
      return receiver("Unknown scheme");
    }
  };
};
<commit_msg>Reindent the scheme cases.<commit_after>
/*
 * www-authenticate
 * https://github.com/randymized/www-authenticate
 *
 * Copyright (c) 2013 Randy McLaughlin
 * Licensed under the MIT license.
 */

'use strict';

var crypto= require('crypto')
  , md5sum = crypto.createHash('md5')
  , ParseAuth= /(\w+)\s+(.*)/  // -> scheme, params
  , Separators= /([",=])/
  ;

function md5(s) {
  return crypto.createHash('md5').update(s).digest('hex');
}

function hex8(num)
{
  return ("00000000" + num.toString(16)).slice(-8);
}

function Parse_WWW_Authenticate(to_parse)
{
  var m= to_parse.match(ParseAuth);
  this.scheme= m[1];
  this.parms= {};
  var err= this.parse_params(m[2].split(Separators));
  if (err) {
    this.scheme= '';
    this.parms= {};
    this.err= err;
  }
}

Parse_WWW_Authenticate.prototype.parse_params= function (m) {
  // This parser will definitely fail if there is more than one challenge
  var tok, last_tok, _i, _len, key, value;
  var state= 0;   //0: token,
  for (_i = 0, _len = m.length; _i < _len; _i++) {
    last_tok= tok;
    tok = m[_i];
    if (!tok.length) continue;
    switch (state) {
      case 0: // token
        key= tok.trim();
        state= 1; // expect equals
        continue;
      case 1: // expect equals
        if ('=' != tok) return 'Equal sign was expected after '+key;
        state= 2;
        continue;
      case 2: // expect value
        if ('"' == tok) {
          value= '';
          state= 3; // expect quoted
          continue;
        }
        else {
          auth_parms[key]= value= tok.trim();
          state= 9; // expect comma or end
          continue;
        }
      case 3: // handling quoted string
        if ('"' == tok) {
          state= 8; // end quoted
          continue;
        }
        else {
          value+= tok;
          state= 3; // continue accumulating quoted string
          continue;
        }
      case 8: // end quote encountered
        if ('"' == tok) {
          // double quoted
          value+= '"';
          state= 3; // back to quoted string
          continue;
        }
        if (',' == tok) {
          this.parms[key]= value;
          state= 0;
          continue;
        }
        else {
          return 'Unexpected token ('+tok+') after '+value+'"';
        }
        continue;
      case 9: // expect commma
        if (',' != tok) return 'Comma expected after '+value;
        state= 0;
        continue;
    }
  }
  switch (state) {  // terminal state
    case 0:   // Empty or ignoring terminal comma
    case 9:   // Expecting comma or end of header
      return;
    case 8:   // Last token was end quote
      this.parms[key]= value;
      return;
    default:
      return 'Unexpected end of www-authenticate value.';
  }
}

module.exports = function(username,password,options)
{
  var cnonce;
  if (options) {
    if (options.cnonce)
      cnonce= options.cnonce;
  }
  if (!cnonce) cnonce= crypto.pseudoRandomBytes(8);
  return function parse_header(www_authenticate,receiver)
  {
    var authorize, nc= 0;

    var parsed= new Parse_WWW_Authenticate(www_authenticate);
    if (parsed.err) return parsed.err;
    var auth_parms= parsed.parms;

    function respond_with(authorize_fn)
    {
      receiver(null, {authorize:authorize_fn, auth_parms:auth_parms,cnonce:cnonce});
    }

    switch(parsed.scheme) {
      case 'Basic':
        var auth_string= 'Basic '+new Buffer(username+':'+password, 'base64').toString('ascii');
        return respond_with(function() {
          return auth_string;
        });
        break;
      case 'Digest':
        var realm= auth_parms.realm;
        if (!realm) {
          return receiver("Realm not found in www-authenticate header.");
        }

        var ha1= md5(username+':'+realm+':'+password);
        var nonce= auth_parms.nonce;
        if (!nonce) {
          return receiver("Nonce not found in www-authenticate header.");
        }

        var fixed= 'Digest username="'+username+'",'+
            ' realm="'+realm+'",'+
            ' nonce="'+nonce+'",';
        var qop= auth_parms.qop;
        if (!qop) {
            return respond_with(function(method,digestURI) {
              var ha2= md5(method+':'+digestURI);
              return fixed+
                ' uri="'+digestURI+'",'+
                ' response="'+md5(ha1+':'+nonce+':'+ha2)+'",';
            });
        }
        else {
          var qopa= qop.split(',');
          var q, x, _i, _len;
          for (_i = 0, _len = qopa.length; _i < _len; _i++) {
            if ('auth' === qopa[_i]) {
              var opaque= auth_parms.opaque;
              var algorithm= auth_parms.algorithm;
              if (algorithm) {
                fixed+= ', algorithm="'+algorithm+'"';
              }
              else {
                algorithm= 'MD5';
              }
              var a1= 'MD5-sess' == algorithm ?
                md5(ha1+':'+nonce+':'+cnonce)
                :
                ha1;
              return respond_with(function(method,digestURI) {
                var ha2= md5(method+':'+digestURI);
                nc= nc+1;
                var hexed_nc= hex8(nc);
                var s= fixed+
                  ' uri="'+digestURI+'",'+
                  ' qop=auth,'+
                  ' nc='+hexed_nc+','+
                  ' cnonce="'+cnonce+'",'+
                  ' response="'+md5(a1+':'+nonce+':'+hexed_nc+':'+cnonce+':auth:'+ha2)+'"';
                if (opaque) {
                  s+= ', opaque="'+opaque+'"';
                }
                return s;
              });
            }
            return receiver('Server does not accept any supported quality of protection techniques.');
          }
        }
        break;
      default:
        return receiver("Unknown scheme");
    }
  };
};
<|endoftext|>


<commit_before>(function() {
  "use strict";
  var states = {
    MAIN: 0,
    VIEW: 1
  };

  var sequenceTypes = {
    ALPHABETICAL: 0,
    NUMERIC: 1
  };

  var casings = {
    LOWERCASE: 0,
    UPPERCASE: 1,
    MIXED: 2
  };

  var state = null;
  var baseUrl = null;
  var sequences = [];

  function byId(input) {
    return document.getElementById(input);
  }

  function byClass(input) {
    return document.getElementsByClassName(input);
  }

  function byTag(input) {
    return document.getElementsByTagName(input);
  }

  Element.prototype.byId = function(input) {
    return this.getElementById(input);
  };

  Element.prototype.byClass = function(input) {
    return this.getElementsByClassName(input);
  };

  Element.prototype.byTag = function(input) {
    return this.getElementsByTagName(input);
  };

  var casingHtml = '<select class="config"><option value="0">Lowercase</option><option value="1">Uppercase</option><option value="1">Mixed</option></select>';
  var paddingHtml = '<input class="config" type="number" value="PAD">';

  function addSequence(type, padding, casing, start) {
    var element = document.createElement("div");
    element.className = "sequence";
    element.innerHTML = '<select class="type"><option value="0">Alphabetical</option><option value="1">Numeric</option></select>
' +
      ' ' + (type === sequenceTypes.ALPHABETICAL ? casingHtml : paddingHtml.replace("PAD", padding)) +
      'Start at: <input type="text" class="start" value="' + (type === sequenceTypes.ALPHABETICAL ? "a" : "1") + '">';
    byId("sequences").appendChild(element);
    var sel = element.byClass("type")[0];
    sel.selectedIndex = type;
    sel.addEventListener("change", onTypeChange);
  }

  function addNewSequence() {
    addSequence(sequenceTypes.NUMERIC, 3, casings.LOWERCASE, 1);
  }

  function onTypeChange(e) {
      let elem = this.parentElement.byClass("config")[0];
      if (this.selectedIndex === sequenceTypes.ALPHABETICAL) {
        elem.outerHTML = casingHtml;
        this.parentElement.byClass("start")[0].value = "a";
      }
      else if (this.selectedIndex === sequenceTypes.NUMERIC) {
        elem.outerHTML = paddingHtml;
        this.parentElement.byClass("start")[0].value = "1";
      }
  }

  function removeSequence(index) {
    if (index > -1 && index < sequences.length) {
      sequences.splice(index, 1);
    }
  }

  function doNextSequence() {
    doSequence(++seqIndex);
  }

  function doPrevSequence() {
    doSequence(--seqIndex);
  }

  function doSequence() {
    if (sequences.length < 1) {
      alert("Error!");
    }
    loading = true;
    showMessage("Loading...");
    if (seqIndex < 0) {
      seqIndex = 0;
    }
    var seq = sequences[0];
    var image = byId("image");
    var src = baseUrl;
    var name = seqIndex.toString();
    while (name.length < seq.padding) {
      name = "0" + name;
    }
    src += name + ".jpg";
    image.src = src;
    image.alt = src;
    setTimeout(setImageSize, 100);
  }

  function onImageClick(e) {
    if (this.classList.contains("fit")) {
      this.classList.remove("fit");
      this.classList.add("full");
      this.removeAttribute("height");
      this.removeAttribute("width");
    }
    else {
      this.classList.add("fit");
      this.classList.remove("full");
      setImageSize();
    }
  }

  var loading = false;

  function start() {
    state = states.VIEW;
    buildSequences();
    byId("main").classList.add("hidden");
    byId("view").classList.remove("hidden");
    document.addEventListener("keydown", keyCheck);
    document.body.classList.add("view");
    window.addEventListener("resize", setImageSize);
    var image = byId("image");
    image.addEventListener("click", onImageClick);
    image.addEventListener("error", onImageError);
    image.addEventListener("load", onImageLoad);
    doSequence();
  }

  function onImageError(e) {
    showMessage("Error");
    loading = false;
  }

  function onImageLoad(e) {
    hideMessage();
    setImageSize();
    loading = false;
  }

  function showMessage(text) {
    var msg = byId("msg");
    if (text) {
      msg.innerHTML = text;
    }
    msg.classList.remove("hidden");
  }

  function hideMessage() {
    byId("msg").classList.add("hidden");
  }

  function setImageSize() {
    var image = byId("image");
    image.removeAttribute("height");
    image.removeAttribute("width");
    if (image.classList.contains("fit")) {
      let height = image.height;
      let width = image.width;
      if (height > width) {
        if (height > window.innerHeight) {
          constrainByHeight(image);
        }
        else if (width > window.innerWidth) {
          constrainByWidth(image);
        }
      }
      else {
        if (width > window.innerWidth) {
          constrainByWidth(image);
        }
        else if (height > window.innerHeight) {
          constrainByHeight(image);
        }
      }
    }
  }

  function constrainByWidth(image) {
    let height = image.height;
    let width = image.width;
    height = Math.floor(height * (window.innerWidth / width));
    width = window.innerWidth;
    image.setAttribute("height", height);
    image.setAttribute("width", width);
  }

  function constrainByHeight(image) {
    let height = image.height;
    let width = image.width;
    width = Math.floor(width * (window.innerHeight / height));
    height = window.innerHeight;
    image.setAttribute("height", height);
    image.setAttribute("width", width);
  }

  function keyCheck(e) {
    if (loading) {
      return;
    }
    if (e.keyCode === 39) {
      doNextSequence();
    }
    else if (e.keyCode === 37) {
      doPrevSequence();
    }
  }

  var seqIndex = 0;

  function buildSequences() {
    baseUrl = byId("base-url").value;
    sequences = [];
    var elems = byClass("sequence");
    for (let i = elems.length - 1; i >= 0; i--) {
      let elem = elems[i];
      let seq = {};
      let type = elem.byClass("type")[0].selectedIndex;
      seq.type = type;
      seq.start = elem.byClass("start")[0].value;
      if (type === sequenceTypes.ALPHABETICAL) {
        seq.padding = 0;
        seq.casing = elem.byClass("config")[0].selectedIndex;
      }
      else if (type === sequenceTypes.NUMERIC) {
        seq.padding = elem.byClass("config")[0].value;
        seq.casing = casings.LOWERCASE;
        seq.start = +seq.start;
      }
      sequences.push(seq);
    }
    seqIndex = sequences[0].start;
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    state = states.MAIN;
    byId("add-sequence").addEventListener("click", addNewSequence);
    byId("start").addEventListener("click", start);
    addNewSequence();
  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<commit_msg>Update img.js<commit_after>(function() {
  "use strict";
  var states = {
    MAIN: 0,
    VIEW: 1
  };

  var sequenceTypes = {
    ALPHABETICAL: 0,
    NUMERIC: 1
  };

  var casings = {
    LOWERCASE: 0,
    UPPERCASE: 1,
    MIXED: 2
  };

  var state = null;
  var baseUrl = null;
  var sequences = [];

  function byId(input) {
    return document.getElementById(input);
  }

  function byClass(input) {
    return document.getElementsByClassName(input);
  }

  function byTag(input) {
    return document.getElementsByTagName(input);
  }

  Element.prototype.byId = function(input) {
    return this.getElementById(input);
  };

  Element.prototype.byClass = function(input) {
    return this.getElementsByClassName(input);
  };

  Element.prototype.byTag = function(input) {
    return this.getElementsByTagName(input);
  };

  var casingHtml = '<select class="config"><option value="0">Lowercase</option><option value="1">Uppercase</option><option value="1">Mixed</option></select>';
  var paddingHtml = '<input class="config" type="number" value="PAD">';

  function addSequence(type, padding, casing, start) {
    var element = document.createElement("div");
    element.className = "sequence";
    element.innerHTML = '<select class="type"><option value="0">Alphabetical</option><option value="1">Numeric</option></select>
' +
      ' ' + (type === sequenceTypes.ALPHABETICAL ? casingHtml : paddingHtml.replace("PAD", padding)) +
      'Start at: <input type="text" class="start" value="' + (type === sequenceTypes.ALPHABETICAL ? "a" : "1") + '">';
    byId("sequences").appendChild(element);
    var sel = element.byClass("type")[0];
    sel.selectedIndex = type;
    sel.addEventListener("change", onTypeChange);
  }

  function addNewSequence() {
    addSequence(sequenceTypes.NUMERIC, 3, casings.LOWERCASE, 1);
  }

  function onTypeChange(e) {
      let elem = this.parentElement.byClass("config")[0];
      if (this.selectedIndex === sequenceTypes.ALPHABETICAL) {
        elem.outerHTML = casingHtml;
        this.parentElement.byClass("start")[0].value = "a";
      }
      else if (this.selectedIndex === sequenceTypes.NUMERIC) {
        elem.outerHTML = paddingHtml;
        this.parentElement.byClass("start")[0].value = "1";
      }
  }

  function removeSequence(index) {
    if (index > -1 && index < sequences.length) {
      sequences.splice(index, 1);
    }
  }

  function doNextSequence() {
    doSequence(++seqIndex);
  }

  function doPrevSequence() {
    doSequence(--seqIndex);
  }

  function doSequence() {
    if (sequences.length < 1) {
      alert("Error!");
    }
    loading = true;
    showMessage("Loading...");
    if (seqIndex < 0) {
      seqIndex = 0;
    }
    var seq = sequences[0];
    var image = byId("image");
    var src = baseUrl;
    var name = seqIndex.toString();
    while (name.length < seq.padding) {
      name = "0" + name;
    }
    src += name + ".jpg";
    var split = src.split("/");
    window.location.hash = split[split.length - 1].replace(/\./g, "_");
    image.src = src;
    image.alt = src;
    setTimeout(setImageSize, 100);
  }

  function onImageClick(e) {
    if (this.classList.contains("fit")) {
      this.classList.remove("fit");
      this.classList.add("full");
      this.removeAttribute("height");
      this.removeAttribute("width");
    }
    else {
      this.classList.add("fit");
      this.classList.remove("full");
      setImageSize();
    }
  }

  var loading = false;

  function start() {
    state = states.VIEW;
    buildSequences();
    byId("main").classList.add("hidden");
    byId("view").classList.remove("hidden");
    document.addEventListener("keydown", keyCheck);
    document.body.classList.add("view");
    window.addEventListener("resize", setImageSize);
    var image = byId("image");
    image.addEventListener("click", onImageClick);
    image.addEventListener("error", onImageError);
    image.addEventListener("load", onImageLoad);
    doSequence();
  }

  function onImageError(e) {
    showMessage("Error");
    loading = false;
  }

  function onImageLoad(e) {
    hideMessage();
    setImageSize();
    loading = false;
  }

  function showMessage(text) {
    var msg = byId("msg");
    if (text) {
      msg.innerHTML = text;
    }
    msg.classList.remove("hidden");
  }

  function hideMessage() {
    byId("msg").classList.add("hidden");
  }

  function setImageSize() {
    var image = byId("image");
    image.removeAttribute("height");
    image.removeAttribute("width");
    if (image.classList.contains("fit")) {
      let height = image.height;
      let width = image.width;
      if (height > width) {
        if (height > window.innerHeight) {
          constrainByHeight(image);
        }
        else if (width > window.innerWidth) {
          constrainByWidth(image);
        }
      }
      else {
        if (width > window.innerWidth) {
          constrainByWidth(image);
        }
        else if (height > window.innerHeight) {
          constrainByHeight(image);
        }
      }
    }
  }

  function constrainByWidth(image) {
    let height = image.height;
    let width = image.width;
    height = Math.floor(height * (window.innerWidth / width));
    width = window.innerWidth;
    image.setAttribute("height", height);
    image.setAttribute("width", width);
  }

  function constrainByHeight(image) {
    let height = image.height;
    let width = image.width;
    width = Math.floor(width * (window.innerHeight / height));
    height = window.innerHeight;
    image.setAttribute("height", height);
    image.setAttribute("width", width);
  }

  function keyCheck(e) {
    if (loading) {
      return;
    }
    if (e.keyCode === 39) {
      doNextSequence();
    }
    else if (e.keyCode === 37) {
      doPrevSequence();
    }
  }

  var seqIndex = 0;

  function buildSequences() {
    baseUrl = byId("base-url").value;
    sequences = [];
    var elems = byClass("sequence");
    for (let i = elems.length - 1; i >= 0; i--) {
      let elem = elems[i];
      let seq = {};
      let type = elem.byClass("type")[0].selectedIndex;
      seq.type = type;
      seq.start = elem.byClass("start")[0].value;
      if (type === sequenceTypes.ALPHABETICAL) {
        seq.padding = 0;
        seq.casing = elem.byClass("config")[0].selectedIndex;
      }
      else if (type === sequenceTypes.NUMERIC) {
        seq.padding = elem.byClass("config")[0].value;
        seq.casing = casings.LOWERCASE;
        seq.start = +seq.start;
      }
      sequences.push(seq);
    }
    seqIndex = sequences[0].start;
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    state = states.MAIN;
    byId("add-sequence").addEventListener("click", addNewSequence);
    byId("start").addEventListener("click", start);
    addNewSequence();
  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<|endoftext|>


<commit_before>
var canvasVideo;
var contextVideo;

var imageFilter;
var imageMemory;
var frameNumberForFPS = 0;
var frameNumber = 0;
var startTime = null;
var startCalibTime = null;
var calibSpan = 10000;//キャリブレーションを行う時間
var requestID;
var moveCount = 0;
var sumCount = 0;
var numFrame = 0;
var startTimeV=0;
var scoreMovie=0;//動画のによる得点
var brightThresh =10;//輝度差が閾値より10高ければ差分ありとする
var movePixelThresh = 0.02;//2%が動いていたら動いていることとする

//過去の画像を保存するためのクラス
function ImageMemory(iwidth, iheight){
  this.iwidth = iwidth;
  this.iheight = iheight;
  this.numPixel = iwidth*iheight;
  this.threshPixels = new Array(this.numPixel);
  this.lastPixels = new Array(this.numPixel);
  for(var i=0; i< this.numPixel; i++){
    this.threshPixels[i] = 0;
    this.lastPixels[i] = 0;
  }
};

//ロード時に呼ばれる関数
function videoInit(){
  startTimeV = getTime();
  setFilter(null);
  canvasVideo= document.getElementById('videoCanvas');
  contextVideo = canvasVideo.getContext("2d");
};

function calcScore(_moveCount, _sumCount){
  var ratio = _moveCount / _sumCount;
  ratio *= 250;
  if(ratio <= 1){
     return 0;
  }
  var saturation =  42 * Math.log10(ratio);
  if(saturation > 100){
     saturation = 100;
  }
  return Math.floor(saturation);
}

//フレームの処理
function update(){
  processVideoFrame();
  frameNumberForFPS++;
  if (startTime == null)
    startTime = (new Date).getTime();
  if (frameNumberForFPS >= 60) {
      var currentTime = (new Date).getTime();            // in milliseconds
      var deltaTime = (currentTime - startTime)/1000.0;  // in seconds
     if(sumCount>0){
        scoreMovie = calcScore(moveCount, sumCount);
        document.querySelector("#point").innerHTML = "動きの得点："+ scoreMovie;
      } else  {
        scoreMovie = 0;
        document.querySelector("#point").innerHTML = "準備中2・・・・";
      }
      startTime = currentTime;
      frameNumberForFPS = 0;
  }

  if(startCalibTime != null){
     var currentTime = (new Date).getTime();
     if(currentTime - startCalibTime > calibSpan){
        startCalibTime = null;
        cancelAnimationFrame(requestID);
        var audio = new Audio("");
        audio.autoplay = false;
        audio.src = "start.mp3";
        audio.load();
        audio.play();
        window.localStorage.setItem("threshPixels", ""+imageMemory.threshPixels)
        setFilter(dif);
     }
   }
};

//画像処理のフィルタをセットする関数
function setFilter(f) {
  frameNumber = -15;
  imageFilter = f;
};

//画像を処理する関数
function processImage() {
  if (canvasVideo.width > 0 && canvasVideo.height > 0) {
    if (imageFilter) {
      contextVideo.putImageData(imageFilter.apply(null, [contextVideo.getImageData(0, 0,
        canvasVideo.width, canvasVideo.height)]), 0, 0);
    }
  }
};

//キャリブレーション処理
calib = function(pixels, args) {
  var d = pixels.data;
  var avg = 0;
  if(frameNumber <= 0){
    for (var i = 0; i < imageMemory.numPixel; i ++) {
      imageMemory.lastPixels[i] = d[4 * i + 1];
      imageMemory.threshPixels[i] = 0;
    }
  }
  else{
    for (var i = 0; i < imageMemory.numPixel; i ++) {
      var pixVal = d[4 * i + 1];
      var dl = Math.abs(pixVal - imageMemory.lastPixels[i]);
      imageMemory.lastPixels[i] = pixVal;

      if(dl < 10){
         dl = 10;
       }
      imageMemory.threshPixels[i] = Math.max(imageMemory.threshPixels[i], dl);
      d[4 * i] = imageMemory.threshPixels[i];
      d[4 * i + 1] = imageMemory.threshPixels[i];
      d[4 * i + 2] = imageMemory.threshPixels[i];
    }
  }
  frameNumber++;
  return pixels;
};

//動画の処理を行う関数
function processVideoFrame() {
  if (contextVideo && video != null && video.videoWidth > 0 && video.videoHeight > 0) {
    // Resize the canvas to match the current video dimensions
    if( imageMemory == null){
      imageMemory = new ImageMemory(video.videoWidth, video.videoHeight);
    }
    if (canvasVideo.width != video.videoWidth)
      canvasVideo.width = video.videoWidth;
    if (canvasVideo.height != video.videoHeight)
      canvasVideo.height = video.videoHeight;

    contextVideo.drawImage(video, 0, 0, canvasVideo.width, canvasVideo.height);
    processImage(canvasVideo);
  }
};
// filter to make difference
dif = function (pixels, args) {
  var d = pixels.data;
  var avg = 0;
  var count = 0;
  if(frameNumber <= 0){
    for (var i = 0; i < imageMemory.numPixel; i ++) {
      imageMemory.lastPixels[i] = d[4 * i + 1];
    }
  }
  else{
    for (var i = 0; i < imageMemory.numPixel; i ++) {
      var pixVal = d[4 * i + 1];
      var dl = Math.abs(pixVal - imageMemory.lastPixels[i]);
      imageMemory.lastPixels[i] = pixVal;
      dl -= imageMemory.threshPixels[i];
      if(dl < 0){
        dl = 0;
      }
      else if(dl > brightThresh){
        count++;
      }
    }
  }
  if(count > imageMemory.numPixel * movePixelThresh){
     moveCount ++;
  }

  sumCount++;
  frameNumber ++;
  return pixels;
};

function videoAnimation(){
  var lastTimeV=getTime();
  //1秒ごとの処理
  var dT = 333;
  if(lastTimeV-startTimeV>dT){
    startTimeV=lastTimeV;
    update();
  }

}<commit_msg>reduce useless code<commit_after>
var canvasVideo;
var contextVideo;

var imageFilter;
var imageMemory;
var frameNumberForFPS = 0;
var frameNumber = 0;
var startTime = null;
var startCalibTime = null;
var calibSpan = 10000;//キャリブレーションを行う時間
var requestID;
var moveCount = 0;
var sumCount = 0;
var numFrame = 0;
var startTimeV=0;
var scoreMovie=0;//動画のによる得点
var brightThresh =10;//輝度差が閾値より10高ければ差分ありとする
var movePixelThresh = 0.02;//2%が動いていたら動いていることとする

//過去の画像を保存するためのクラス
function ImageMemory(iwidth, iheight){
  this.iwidth = iwidth;
  this.iheight = iheight;
  this.numPixel = iwidth*iheight;
  this.threshPixels = new Array(this.numPixel);
  this.lastPixels = new Array(this.numPixel);
  for(var i=0; i< this.numPixel; i++){
    this.threshPixels[i] = 0;
    this.lastPixels[i] = 0;
  }
};

//ロード時に呼ばれる関数
function videoInit(){
  startTimeV = getTime();
  setFilter(null);
  canvasVideo= document.getElementById('videoCanvas');
  contextVideo = canvasVideo.getContext("2d");
};

function calcScore(_moveCount, _sumCount){
  var ratio = _moveCount / _sumCount;
  ratio *= 250;
  if(ratio <= 1){
     return 0;
  }
  var saturation =  42 * Math.log10(ratio);
  if(saturation > 100){
     saturation = 100;
  }
  return Math.floor(saturation);
}

//フレームの処理
function update(){
  processVideoFrame();
  frameNumberForFPS++;
  if (startTime == null)
    startTime = (new Date).getTime();
  if (frameNumberForFPS >= 60) {
      var currentTime = (new Date).getTime();            // in milliseconds
      var deltaTime = (currentTime - startTime)/1000.0;  // in seconds
     if(sumCount>0){
        scoreMovie = calcScore(moveCount, sumCount);
        document.querySelector("#point").innerHTML = "動きの得点："+ scoreMovie;
      } else  {
        scoreMovie = 0;
        document.querySelector("#point").innerHTML = "準備中2・・・・";
      }
      startTime = currentTime;
      frameNumberForFPS = 0;
  }

  if(startCalibTime != null){
     var currentTime = (new Date).getTime();
     if(currentTime - startCalibTime > calibSpan){
        startCalibTime = null;
        //cancelAnimationFrame(requestID);
        window.localStorage.setItem("threshPixels", ""+imageMemory.threshPixels)
        setFilter(dif);
     }
   }
};

//画像処理のフィルタをセットする関数
function setFilter(f) {
  frameNumber = 0;
  imageFilter = f;
};

//画像を処理する関数
function processImage() {
  if (canvasVideo.width > 0 && canvasVideo.height > 0) {
    if (imageFilter) {
      contextVideo.putImageData(imageFilter.apply(null, [contextVideo.getImageData(0, 0,
        canvasVideo.width, canvasVideo.height)]), 0, 0);
    }
  }
};

//キャリブレーション処理
calib = function(pixels, args) {
  var d = pixels.data;
  var avg = 0;
  if(frameNumber == 0){
    for (var i = 0; i < imageMemory.numPixel; i ++) {
      imageMemory.lastPixels[i] = d[4 * i + 1];
      imageMemory.threshPixels[i] = 0;
    }
  }
  else{
    for (var i = 0; i < imageMemory.numPixel; i ++) {
      var pixVal = d[4 * i + 1];
      var dl = Math.abs(pixVal - imageMemory.lastPixels[i]);
      imageMemory.lastPixels[i] = pixVal;

      if(dl < 10){
         dl = 10;
       }
      imageMemory.threshPixels[i] = Math.max(imageMemory.threshPixels[i], dl);
      d[4 * i] = imageMemory.threshPixels[i];
      d[4 * i + 1] = imageMemory.threshPixels[i];
      d[4 * i + 2] = imageMemory.threshPixels[i];
    }
  }
  frameNumber++;
  return pixels;
};

//動画の処理を行う関数
function processVideoFrame() {
  if (contextVideo && video != null && video.videoWidth > 0 && video.videoHeight > 0) {
    // Resize the canvas to match the current video dimensions
    if( imageMemory == null){
      imageMemory = new ImageMemory(video.videoWidth, video.videoHeight);
    }
    if (canvasVideo.width != video.videoWidth)
      canvasVideo.width = video.videoWidth;
    if (canvasVideo.height != video.videoHeight)
      canvasVideo.height = video.videoHeight;

    contextVideo.drawImage(video, 0, 0, canvasVideo.width, canvasVideo.height);
    processImage(canvasVideo);
  }
};
// filter to make difference
dif = function (pixels, args) {
  var d = pixels.data;
  var avg = 0;
  var count = 0;
  if(frameNumber <= 0){
    for (var i = 0; i < imageMemory.numPixel; i ++) {
      imageMemory.lastPixels[i] = d[4 * i + 1];
    }
  }
  else{
    for (var i = 0; i < imageMemory.numPixel; i ++) {
      var pixVal = d[4 * i + 1];
      var dl = Math.abs(pixVal - imageMemory.lastPixels[i]);
      imageMemory.lastPixels[i] = pixVal;
      dl -= imageMemory.threshPixels[i];
      if(dl < 0){
        dl = 0;
      }
      else if(dl > brightThresh){
        count++;
      }
    }
  }
  if(count > imageMemory.numPixel * movePixelThresh){
     moveCount ++;
  }

  sumCount++;
  frameNumber ++;
  return pixels;
};

function videoAnimation(){
  var lastTimeV=getTime();
  //1秒ごとの処理
  var dT = 333;
  if(lastTimeV-startTimeV>dT){
    startTimeV=lastTimeV;
    update();
  }

}<|endoftext|>


<commit_before>module.exports = function (grunt) {

  var initConfig;

  // Loading external tasks
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-karma');

  /**
   * Custom task to inline a generated file at a certain moment...
   */
  grunt.registerTask('UGF', 'Use Generated Files.', function() {
    initConfig.meta.view.demoHTML= grunt.file.read(  grunt.template.process("<%= tmp %>/demos.html"));
  });

  // Default task.
  grunt.registerTask('default', ['jshint', 'karma:unit']);
  grunt.registerTask('build', ['concat:tmp', 'concat:modules', 'clean:rm_tmp', 'uglify']);
  grunt.registerTask('build-doc', ['build', 'concat:html_doc', 'UGF', 'clean:rm_tmp', 'copy']);
  grunt.registerTask('server', ['karma:start']);

  var testConfig = function(configFile, customOptions) {
    var options = { configFile: configFile, singleRun: true };
    var travisOptions = process.env.TRAVIS && { browsers: ['Firefox', 'PhantomJS'], reporters: ['dots'] };
    return grunt.util._.extend(options, customOptions, travisOptions);
  };

  // Project configuration.
  initConfig = {
    demo : 'demo',
    tmp : 'demo/tmp',
    dist : 'demo/out',
    pkg: grunt.file.readJSON('package.json'),
    meta: {
      banner: ['/**',
        ' * <%= pkg.name %> - <%= pkg.description %>',
        ' * @version v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>',
        ' * @link <%= pkg.homepage %>',
        ' * @license <%= pkg.license %>',
        ' */',
        ''].join('\n'),
      view : {
        humaName : "Input Directives",
        orgName : "thetrevdev",
        repoName : "input-directives",
        js : [
          'build/<%= meta.view.repoName %>.min.js'
        ]
      },
      destName : '<%= dist %>/build/<%= meta.view.repoName %>'
    },
    watch: {
      karma: {
        files: ['modules/**/*.js'],
        tasks: ['karma:unit:run'] //NOTE the :run flag
      }
    },
    karma: {
      unit: testConfig('test/karma.conf.js'),
      start: {configFile: 'test/karma.conf.js'}
    },
    concat: {
      html_doc: {
        options: {
          banner: ['',
            '
', ''
          ].join('\n  '),
          footer : '
'},
        src: [ 'modules/**/demo/index.html'],
        dest: '<%= tmp %>/demos.html'
      },
      tmp: {
        files: {  '<%= tmp %>/dep.js': [ 'modules/**/*.js', '!modules/input-directives.js', '!modules/ie-shiv/*.js', '!modules/**/test/*.js']}
      },
      modules: {
        options: {banner: '<%= meta.banner %>'},
        files: {
          '<%= meta.destName %>.js': ['<%= tmp %>/dep.js', 'modules/input-directives.js'],
          '<%= meta.destName %>-ieshiv.js' : ['modules/ie-shiv/*.js']
        }
      }
    },
    uglify: {
      options: {banner: '<%= meta.banner %>'},
      build: {
        files: {
          '<%= meta.destName %>.min.js': ['<%= meta.destName %>.js'],
          '<%= meta.destName %>-ieshiv.min.js': ['<%= meta.destName %>-ieshiv.js']
        }
      }
    },
    clean: {
      rm_tmp: {src: ['<%= tmp %>']}
    },
    jshint: {
      files:['modules/**/*.js', 'gruntFile.js', 'test/**/*Spec.js', 'demo/**/*.js'],
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        boss: true,
        eqnull: true,
        globals: {}
      }
    },
    copy: {
      main : {
        files : [
          {expand: true, cwd: '<%= demo %>/', src: [ '**', '!.**', '!out/**' ], dest: '<%= dist %>/'}
        ]
      },
      template : {
        options : {processContent : function(content){
          return grunt.template.process(content);
        }},
        files: [
          {src: ['<%= demo %>/.tmpl/index.tmpl'], dest: '<%= dist %>/index.html'}
        ]
      }
    }
  };
  grunt.initConfig(initConfig);

};<commit_msg>only jshint the core demo file<commit_after>module.exports = function (grunt) {

  var initConfig;

  // Loading external tasks
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-copy');
  grunt.loadNpmTasks('grunt-karma');

  /**
   * Custom task to inline a generated file at a certain moment...
   */
  grunt.registerTask('UGF', 'Use Generated Files.', function() {
    initConfig.meta.view.demoHTML= grunt.file.read(  grunt.template.process("<%= tmp %>/demos.html"));
  });

  // Default task.
  grunt.registerTask('default', ['jshint', 'karma:unit']);
  grunt.registerTask('build', ['concat:tmp', 'concat:modules', 'clean:rm_tmp', 'uglify']);
  grunt.registerTask('build-doc', ['build', 'concat:html_doc', 'UGF', 'clean:rm_tmp', 'copy']);
  grunt.registerTask('server', ['karma:start']);

  var testConfig = function(configFile, customOptions) {
    var options = { configFile: configFile, singleRun: true };
    var travisOptions = process.env.TRAVIS && { browsers: ['Firefox', 'PhantomJS'], reporters: ['dots'] };
    return grunt.util._.extend(options, customOptions, travisOptions);
  };

  // Project configuration.
  initConfig = {
    demo : 'demo',
    tmp : 'demo/tmp',
    dist : 'demo/out',
    pkg: grunt.file.readJSON('package.json'),
    meta: {
      banner: ['/**',
        ' * <%= pkg.name %> - <%= pkg.description %>',
        ' * @version v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>',
        ' * @link <%= pkg.homepage %>',
        ' * @license <%= pkg.license %>',
        ' */',
        ''].join('\n'),
      view : {
        humaName : "Input Directives",
        orgName : "thetrevdev",
        repoName : "input-directives",
        js : [
          'build/<%= meta.view.repoName %>.min.js'
        ]
      },
      destName : '<%= dist %>/build/<%= meta.view.repoName %>'
    },
    watch: {
      karma: {
        files: ['modules/**/*.js'],
        tasks: ['karma:unit:run'] //NOTE the :run flag
      }
    },
    karma: {
      unit: testConfig('test/karma.conf.js'),
      start: {configFile: 'test/karma.conf.js'}
    },
    concat: {
      html_doc: {
        options: {
          banner: ['',
            '
', ''
          ].join('\n  '),
          footer : '
'},
        src: [ 'modules/**/demo/index.html'],
        dest: '<%= tmp %>/demos.html'
      },
      tmp: {
        files: {  '<%= tmp %>/dep.js': [ 'modules/**/*.js', '!modules/input-directives.js', '!modules/ie-shiv/*.js', '!modules/**/test/*.js']}
      },
      modules: {
        options: {banner: '<%= meta.banner %>'},
        files: {
          '<%= meta.destName %>.js': ['<%= tmp %>/dep.js', 'modules/input-directives.js'],
          '<%= meta.destName %>-ieshiv.js' : ['modules/ie-shiv/*.js']
        }
      }
    },
    uglify: {
      options: {banner: '<%= meta.banner %>'},
      build: {
        files: {
          '<%= meta.destName %>.min.js': ['<%= meta.destName %>.js'],
          '<%= meta.destName %>-ieshiv.min.js': ['<%= meta.destName %>-ieshiv.js']
        }
      }
    },
    clean: {
      rm_tmp: {src: ['<%= tmp %>']}
    },
    jshint: {
      files:['modules/**/*.js', 'gruntFile.js', 'test/**/*Spec.js', 'demo/demo.js'],
      options: {
        curly: true,
        eqeqeq: true,
        immed: true,
        latedef: true,
        newcap: true,
        noarg: true,
        sub: true,
        boss: true,
        eqnull: true,
        globals: {}
      }
    },
    copy: {
      main : {
        files : [
          {expand: true, cwd: '<%= demo %>/', src: [ '**', '!.**', '!out/**' ], dest: '<%= dist %>/'}
        ]
      },
      template : {
        options : {processContent : function(content){
          return grunt.template.process(content);
        }},
        files: [
          {src: ['<%= demo %>/.tmpl/index.tmpl'], dest: '<%= dist %>/index.html'}
        ]
      }
    }
  };
  grunt.initConfig(initConfig);

};<|endoftext|>


<commit_before>/* global Rainbow */

/////////////////////////
// Helpers and globals //
/////////////////////////

const expect = chai.expect;

const genericPatterns = [{
    name: 'test',
    pattern: /test/gi
}];

const patternA = [{
    name: 'a',
    pattern: /here/gi
}];

const patternB = [{
    name: 'b',
    pattern: /is/gi
}];

////////////////
// Test suite //
////////////////

describe('Rainbow', () => {
    it('Basic things are defined', () => {
        expect(Rainbow).to.exist;
        expect(Rainbow.color).to.be.a('function');
        expect(Rainbow.extend).to.be.a('function');
        expect(Rainbow.onHighlight).to.be.a('function');
        expect(Rainbow.addAlias).to.be.a('function');
    });

    it('Should apply global class', (done) => {
        Rainbow.extend('generic', [{
            name: 'name',
            pattern: /Craig/gm
        }]);

        Rainbow.color('My name is Craig', { language: 'generic', globalClass: 'global' }, (result) => {
            expect(result).to.equal('My name is Craig');
            done();
        });
    });

    it('Should properly use patterns', (done) => {
        Rainbow.extend('generic', genericPatterns);

        Rainbow.color('here is a test', 'generic', (result) => {
            expect(result).to.equal('here is a test');
            done();
        });
    });

    it('Should properly extend generic patterns', (done) => {
        Rainbow.extend('newLanguage', patternA, 'generic');

        Rainbow.color('here is a test', 'newLanguage', (result) => {
            expect(result).to.equal('here is a test');
            done();
        });
    });

    it('Should properly extend other patterns that extend generic patterns', (done) => {
        Rainbow.extend('newLanguage', patternB);

        Rainbow.color('here is a test', 'newLanguage', (result) => {
            expect(result).to.equal('here is a test');
            done();
        });
    });

    it('Should properly apply aliases', (done) => {
        Rainbow.addAlias('new', 'newLanguage');

        Rainbow.color('here is a test', 'new', (result) => {
            expect(result).to.equal('here is a test');
            done();
        });
    });

    it('Should properly remove language', (done) => {
        Rainbow.extend('foo', genericPatterns);

        Rainbow.color('just a test', 'foo', (result) => {
            expect(result).to.equal('just a test');

            Rainbow.remove('foo');

            Rainbow.color('just a test', 'foo', (result2) => {
                expect(result2).to.equal('just a test');
                done();
            });
        });
    });
});
<commit_msg>Add test for non global regex matching<commit_after>/* global Rainbow */

/////////////////////////
// Helpers and globals //
/////////////////////////

const expect = chai.expect;

const genericPatterns = [{
    name: 'test',
    pattern: /test/gi
}];

const patternA = [{
    name: 'a',
    pattern: /here/gi
}];

const patternB = [{
    name: 'b',
    pattern: /is/gi
}];

////////////////
// Test suite //
////////////////

describe('Rainbow', () => {
    it('Basic things are defined', () => {
        expect(Rainbow).to.exist;
        expect(Rainbow.color).to.be.a('function');
        expect(Rainbow.extend).to.be.a('function');
        expect(Rainbow.onHighlight).to.be.a('function');
        expect(Rainbow.addAlias).to.be.a('function');
    });

    it('Should apply global class', (done) => {
        Rainbow.extend('generic', [{
            name: 'name',
            pattern: /Craig/gm
        }]);

        Rainbow.color('My name is Craig', { language: 'generic', globalClass: 'global' }, (result) => {
            expect(result).to.equal('My name is Craig');
            done();
        });
    });

    it('Should properly use patterns', (done) => {
        Rainbow.extend('generic', genericPatterns);

        Rainbow.color('here is a test', 'generic', (result) => {
            expect(result).to.equal('here is a test');
            done();
        });
    });

    it('Should properly extend generic patterns', (done) => {
        Rainbow.extend('newLanguage', patternA, 'generic');

        Rainbow.color('here is a test', 'newLanguage', (result) => {
            expect(result).to.equal('here is a test');
            done();
        });
    });

    it('Should properly extend other patterns that extend generic patterns', (done) => {
        Rainbow.extend('newLanguage', patternB);

        Rainbow.color('here is a test', 'newLanguage', (result) => {
            expect(result).to.equal('here is a test');
            done();
        });
    });

    it('Should properly apply aliases', (done) => {
        Rainbow.addAlias('new', 'newLanguage');

        Rainbow.color('here is a test', 'new', (result) => {
            expect(result).to.equal('here is a test');
            done();
        });
    });

    it('Should properly remove language', (done) => {
        Rainbow.extend('foo', genericPatterns);

        Rainbow.color('just a test', 'foo', (result) => {
            expect(result).to.equal('just a test');

            Rainbow.remove('foo');

            Rainbow.color('just a test', 'foo', (result2) => {
                expect(result2).to.equal('just a test');
                done();
            });
        });
    });

    // Not sure why anyone would want this behavior, but since we are faking
    // global regex matches we should make sure this works too.
    it('Should work with non global regex matches', (done) => {
        Rainbow.remove('foo');
        Rainbow.extend('foo', [
            {
                name: 'number',
                pattern: /\b\d+\b/
            }
        ]);

        Rainbow.color('123 456 789', 'foo', (result) => {
            expect(result).to.equal('123 456 789');
            done();
        });
    });
});
<|endoftext|>


<commit_before>(function() {
  "use strict";
  var states = {
    MAIN = 0,
    VIEW = 1
  };

  var sequenceTypes = {
    ALPHABETICAL = 0,
    NUMERIC = 1
  };

  var casings = {
    LOWERCASE = 0,
    UPPERCASE = 1,
    MIXED = 2
  };

  var state = null;
  var baseUrl = null;
  var sequences = [];

  function byId(input) {
    return document.getElementById(input);
  }

  function byClass(input) {
    return document.getElementsByClassName(input);
  }

  function byTag(input) {
    return document.getElementsByTagName(input);
  }

  Element.prototype.byId = function(input) {
      return this.getElementById(input);
  };

  Element.prototype.byClass = function(input) {
      return this.getElementsByClassName(input);
  };

  Element.prototype.byTag = function(input) {
      return this.getElementsByTagName(input);
  };

  function addAlphabeticalSequence(casing) {
    addSequence(sequenceTypes.ALPHABETICAL, 0, casing);
  }

  function addNumericSequence(padding) {
    addSequence(sequenceTypes.NUMERIC, padding, casing.MIXED);
  }

  function addSequence(type, padding, casing) {
    var sequence = {
      type: type,
      padding: padding,
      casing: casing
    };
    sequences.push(sequence);
    var element = document.createElement("div");
    element.innerHTML = '<select class="type"><option value="0">Alphabetical</option><option value="1">Numeric</option></select>
' +
      ' <select class="casing"><option value="0">Lowercase</option><option value="1">Uppercase</option><option value="1">Mixed</option></select>' +
      'Start at: <input type="text" class="start-at">';
    element.className = "sequence";
    byId("sequences").addChild(element);
    element.byClass("type").addEventListener("change", onTypeChange);
  }

  function onTypeChange(e) {
      alert(this.selectedIndex);
  }

  function removeSequence(index) {
    if (index > -1 && index < sequences.length) {
        sequences.splice(index, 1);
    }
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    state = states.MAIN;

  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<commit_msg>Update img.js<commit_after>(function() {
  "use strict";
  var states = {
    MAIN = 0,
    VIEW = 1
  };

  var sequenceTypes = {
    ALPHABETICAL = 0,
    NUMERIC = 1
  };

  var casings = {
    LOWERCASE = 0,
    UPPERCASE = 1,
    MIXED = 2
  };

  var state = null;
  var baseUrl = null;
  var sequences = [];

  function byId(input) {
    return document.getElementById(input);
  }

  function byClass(input) {
    return document.getElementsByClassName(input);
  }

  function byTag(input) {
    return document.getElementsByTagName(input);
  }

  Element.prototype.byId = function(input) {
      return this.getElementById(input);
  };

  Element.prototype.byClass = function(input) {
      return this.getElementsByClassName(input);
  };

  Element.prototype.byTag = function(input) {
      return this.getElementsByTagName(input);
  };

  function addAlphabeticalSequence(casing, start) {
    addSequence(sequenceTypes.ALPHABETICAL, 0, casing, start);
  }

  function addNumericSequence(padding, start) {
    addSequence(sequenceTypes.NUMERIC, padding, casing.MIXED, start);
  }

  function addSequence(type, padding, casing, start) {
    var sequence = {
      type: type,
      padding: padding,
      casing: casing,
      start: start
    };
    sequences.push(sequence);
    var element = document.createElement("div");
    element.innerHTML = '<select class="type"><option value="0">Alphabetical</option><option value="1">Numeric</option></select>
' +
      ' <select class="casing"><option value="0">Lowercase</option><option value="1">Uppercase</option><option value="1">Mixed</option></select>' +
      'Start at: <input type="text" class="start">';
    element.className = "sequence";
    byId("sequences").addChild(element);
    element.byClass("type").addEventListener("change", onTypeChange);
  }

  function addNewSequence() {
    addAlphabeticalSequence(casing.LOWERCASE, "a");
  }

  function onTypeChange(e) {
      alert(this.selectedIndex);
  }

  function removeSequence(index) {
    if (index > -1 && index < sequences.length) {
        sequences.splice(index, 1);
    }
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    state = states.MAIN;
    byId("add-sequence").addEventListener("click", addNewSequence);
  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<|endoftext|>


<commit_before>
var parse = require('..');

function arr(type, arr) {
  arr.type = type;
  return arr;
}

describe('parseRange(len, str)', function(){
  it('should parse range strings', function(){
    parse(200, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 199 }]));
    parse(1000, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 499 }]));
    parse(1000, 'bytes=40-80').should.eql(arr('bytes', [{ start: 40, end: 80 }]));
    parse(1000, 'bytes=-500').should.eql(arr('bytes', [{ start: 500, end: 999 }]));
    parse(1000, 'bytes=-400').should.eql(arr('bytes', [{ start: 600, end: 999 }]));
    parse(1000, 'bytes=500-').should.eql(arr('bytes', [{ start: 500, end: 999 }]));
    parse(1000, 'bytes=400-').should.eql(arr('bytes', [{ start: 400, end: 999 }]));
    parse(1000, 'bytes=0-0').should.eql(arr('bytes', [{ start: 0, end: 0 }]));
    parse(1000, 'bytes=-1').should.eql(arr('bytes', [{ start: 999, end: 999 }]));
    parse(1000, 'items=0-5').should.eql(arr('items', [{ start: 0, end: 5 }]));
    parse(1000, 'bytes=40-80,-1').should.eql(arr('bytes', [{ start: 40, end: 80 }, { start: 999, end: 999 }]));
  })
})<commit_msg>tests: add test for invalid range<commit_after>
var parse = require('..')
  , assert = require('assert');

function arr(type, arr) {
  arr.type = type;
  return arr;
}

describe('parseRange(len, str)', function(){
  it('should parse range strings', function(){
    assert(null == parse(200, 'bytes=500-20'));
    parse(200, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 199 }]));
    parse(1000, 'bytes=0-499').should.eql(arr('bytes', [{ start: 0, end: 499 }]));
    parse(1000, 'bytes=40-80').should.eql(arr('bytes', [{ start: 40, end: 80 }]));
    parse(1000, 'bytes=-500').should.eql(arr('bytes', [{ start: 500, end: 999 }]));
    parse(1000, 'bytes=-400').should.eql(arr('bytes', [{ start: 600, end: 999 }]));
    parse(1000, 'bytes=500-').should.eql(arr('bytes', [{ start: 500, end: 999 }]));
    parse(1000, 'bytes=400-').should.eql(arr('bytes', [{ start: 400, end: 999 }]));
    parse(1000, 'bytes=0-0').should.eql(arr('bytes', [{ start: 0, end: 0 }]));
    parse(1000, 'bytes=-1').should.eql(arr('bytes', [{ start: 999, end: 999 }]));
    parse(1000, 'items=0-5').should.eql(arr('items', [{ start: 0, end: 5 }]));
    parse(1000, 'bytes=40-80,-1').should.eql(arr('bytes', [{ start: 40, end: 80 }, { start: 999, end: 999 }]));
  })
})<|endoftext|>


<commit_before>var WicketAjaxDebug = {

	showResponseText : false,

	debugWindowId : "wicketAjaxDebugWindow",

	debugWindowDragHandleId : "wicketAjaxDebugWindowHandle",

	debugWindowLogId : "wicketAjaxDebugWindowLogId",

	getDebugWindow : function()
	{
	    wicketGet(WicketAjaxDebug.debugWindowId);
	},

	showDebugWindow : function() {
	    wicketShow(WicketAjaxDebug.debugWindowId);
	},

	hideDebugWindow : function() {
	    wicketHide(WicketAjaxDebug.debugWindowId);
	},

    log : function(msg) {
        var ta=wicketGet(WicketAjaxDebug.debugWindowLogId);
        ta.value=ta.value+"\n"+msg;
        ta.scrollTop = ta.scrollHeight;
    },

    logError : function(msg) {
        WicketAjaxDebug.log("ERROR: "+msg);
    },

    logInfo : function(msg) {
        WicketAjaxDebug.log(" INFO: "+msg);
    },

    clearLog : function() {
        var ta=wicketGet(WicketAjaxDebug.debugWindowLogId);
        ta.value=null;
    },

	init : function() {
        if ( wicketAjaxDebugEnabled() ) {
        	var wad=WicketAjaxDebug;
        	var dwid=wad.debugWindowId;
        	var dwdhid=wad.debugWindowDragHandleId;

            document.write(

        	 "

"

        	+"    "

        	+"        Wicket Ajax Debug Window (drag me here)"
        	+"    	"
        	+"    "
        	+"        clear | "
        	+"        close"
        	+"
"

        	+"    <form>"

        	+"        <textarea cols='60' rows='20' wrap='off' "
        	+"            name='"+WicketAjaxDebug.debugWindowLogId+"' id='"+WicketAjaxDebug.debugWindowLogId+"' "
        	+"            style='width:100%;' "
        	+"        ></textarea>"

        	+"    </form>"
        	+"

");

            WicketDrag.init(wicketGet(dwdhid), wicketGet(dwid));

            document.write(

             "
"
            +"    WICKET AJAX DEBUG"
            +"
");
        }
	}

};

WicketAjaxDebug.init();

<commit_msg>Improved debug console.<commit_after>var WicketAjaxDebug = {

	showResponseText : false,

	debugWindowId : "wicketAjaxDebugWindow",

	debugWindowDragHandleId : "wicketAjaxDebugWindowHandle",

	debugWindowLogId : "wicketAjaxDebugWindowLogId",

	getDebugWindow : function()
	{
	    wicketGet(WicketAjaxDebug.debugWindowId);
	},

	showDebugWindow : function() {
	    wicketShow(WicketAjaxDebug.debugWindowId);
	},

	hideDebugWindow : function() {
	    wicketHide(WicketAjaxDebug.debugWindowId);
	},

    log : function(msg) {
        var d = wicketGet(WicketAjaxDebug.debugWindowLogId);
        var c = document.createElement("div");
        msg = msg.replace(/</g, "<");
        msg = msg.replace(/>/g, ">");
        msg = msg.replace(/\n/g, "
");
        msg = msg.replace(/ /g, " ");
        msg = msg.replace(/\t/g, "    ");
        c.innerHTML = msg;
        c.setAttribute("style","font-size: 82%; margin: 0px; padding:0px");
        d.appendChild(c);
        d.scrollTop = d.scrollHeight;
    },

    logError : function(msg) {
        WicketAjaxDebug.log("ERROR: "+msg);
    },

    logInfo : function(msg) {
        WicketAjaxDebug.log(" INFO: "+msg);
    },

    clearLog : function() {
        var d = wicketGet(WicketAjaxDebug.debugWindowLogId);
		d.innerHTML = "";
    },

	init : function() {

        if ( wicketAjaxDebugEnabled()) {
        	var wad=WicketAjaxDebug;
        	var dwid=wad.debugWindowId;
        	var dwdhid=wad.debugWindowDragHandleId;

			var firstTime = document.getElementById(dwid) == null;

			if (firstTime)
	            document.write(
					"
"+
					"
"+
					"
"+
					"
"+
					"				clear | "+
					"				close"+
					"
"+
					"
"+
					"				Wicket Ajax Debug Window (drag me here)"+
					"
"+
					"
"+
					"
"+
					"
"+
					"
" +
					"
"
	            );
            WicketDrag.init(wicketGet(dwdhid), wicketGet(dwid));

			if (firstTime)
	            document.write(

	             "
"
	            +"    WICKET AJAX DEBUG"
	            +"
");
        }
	}

};

WicketAjaxDebug.init();

<|endoftext|>