<commit_before>
/******************************
         Graphing.js
 ******************************/

drawPoints = function(map, data) {
  var pointTypes = d3.map(),
      points = data,
      lastSelectedPoint;

  var drawPointTypeSelection = function() {

    labels = d3.select('#toggles').selectAll('input')
      .data(pointTypes.values())
      .enter().append("label");

    labels.append("input")
      .attr('type', 'checkbox')

      // Enable all
      .property('checked', function(d) { return true; })
      .attr("value", function(d) { return d.type; })
      .on("change", drawWithLoading);

    labels.append("span")
      .attr('class', 'key')
      .style('background-color', function(d) { return '#' + d.color; });

    labels.append("span")
      .text(function(d) { return d.type; });
  }

  var selectedTypes = function() {
    return d3.selectAll('#toggles input[type=checkbox]')[0].filter(function(elem) {
      return elem.checked;
    }).map(function(elem) {
      return elem.value;
    })
  }

  var pointsFilteredToSelectedTypes = function() {
    var currentSelectedTypes = d3.set(selectedTypes());
    return points.filter(function(item){
      return currentSelectedTypes.has(item.type);
    });
  }

  var drawWithLoading = function(e){
    d3.select('#loading').classed('visible', true);
    if (e && e.type == 'viewreset') {
      d3.select('#overlay').remove();
    }
    setTimeout(function(){
      draw();

      // Add Date Filter
      if($("#month").val() != "All Months" && $("#day").val() != "All Days"){
        filter($("#month").val(), $("#day").val());
      }

      d3.select('#loading').classed('visible', false);
    }, 0);
  }

  var draw = function() {
    d3.select('#overlay').remove();

    var bounds = map.getBounds(),
        topLeft = map.latLngToLayerPoint(bounds.getNorthWest()),
        bottomRight = map.latLngToLayerPoint(bounds.getSouthEast()),
        existing = d3.set(),
        drawLimit = bounds.pad(0.4);

    filteredPoints = pointsFilteredToSelectedTypes().filter(function(d) {
      var latlng = new L.LatLng(d.latitude, d.longitude);

      if (!drawLimit.contains(latlng)) { return false };

      var point = map.latLngToLayerPoint(latlng);

      key = point.toString();
      if (existing.has(key)) { return false };
      existing.add(key);

      d.x = point.x;
      d.y = point.y;
      return true;
    });

    var svg = d3.select(map.getPanes().overlayPane).append("svg")
      .attr('id', 'overlay')
      .attr("class", "leaflet-zoom-hide")
      .style("width", map.getSize().x + 'px')
      .style("height", map.getSize().y + 'px')
      .style("margin-left", topLeft.x + "px")
      .style("margin-top", topLeft.y + "px");

    var g = svg.append("g")
      .attr("transform", "translate(" + (-topLeft.x) + "," + (-topLeft.y) + ")")
      .attr("pointer-events", "all");

    var svgPoints = g.attr("class", "points")
      .selectAll("g")
      .data(filteredPoints)
      .enter().append("g")
      .attr("class", "point")
      .style("z-index", 999);

    svgPoints.append("path")
      .attr("class", "point-cell")
      .on('click', function(d){ console.log(d) })
      .classed("selected", function(d) { return lastSelectedPoint == d} );

    // Add circles for each point
    svgPoints.append("circle")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .style('fill', function(d) { return '#' + d.color } )
      .attr("date", function(d) { return d.date })
      .attr("r", 7)
      .attr("pointer-events", "all")
      .attr("opacity", .1);

    // Draw point-to-point connections
    svgPoints.each(function(){
      if($(this).next().length == 1){
        var this_transform = $(this).children("circle").attr("transform"),
            next_transform = $(this).next().children("circle").attr("transform"),
            this_position = this_transform.substring(10, this_transform.length - 1).split(","),
            next_position = next_transform.substring(10, next_transform.length - 1).split(",");

        d3.select(this).append("line")
          .attr("x1", this_position[0])
          .attr("y1", this_position[1])
          .attr("x2", next_position[0])
          .attr("y2", next_position[1])
          .style("stroke", "rgb(255,0,0)")
          .style("stroke-width", 5)
          .style("opacity", 0);
      }
    });

    addTrackingLines();

    // Provides a tracing highlight of user
    // activiity for sequential points on hover
    function addTrackingLines(){

      $("g").each(function(){
        $(this).hover(function(){

          var lines = [$(this).children("line"), $(this).next().children("line")],
              lines2 = [$(this).prev().children("line")];

          for(i=1; i < 5; i++){
            lines.push(lines[i].parent().next().children("line"));
          }

          for(i=0; i < 4; i++){
            lines2.push(lines2[i].parent().prev().children("line"));
          }

          lines = lines.concat(lines2);

          for(var x in lines){
            lines[x].css("opacity", .4); // Set HOVER .4
          }
        },

        function(){
          var lines = [$(this).children("line"), $(this).next().children("line")],
              lines2 = [$(this).prev().children("line")];

          for(i=1; i < 5; i++){
            lines.push(lines[i].parent().next().children("line"));
          }

          for(i=0; i < 4; i++){
            lines2.push(lines2[i].parent().prev().children("line"));
          }

          lines = lines.concat(lines2);

          for(var x in lines){
            lines[x].css("opacity", 0);
          }
        });
      });
    }

  }

  var mapLayer = {
    onAdd: function(map) {
      map.on('viewreset moveend', drawWithLoading);
      drawWithLoading();
    }
  }

  map.on('ready', function() {
      points.forEach(function(point) {
        pointTypes.set(point.type, {type: point.type, color: point.color});
      })

      drawPointTypeSelection();

      map.addLayer(mapLayer);
    })

}<commit_msg>Remove opacity from plot points<commit_after>
/******************************
         Graphing.js
 ******************************/

drawPoints = function(map, data) {
  var pointTypes = d3.map(),
      points = data,
      lastSelectedPoint;

  var drawPointTypeSelection = function() {

    labels = d3.select('#toggles').selectAll('input')
      .data(pointTypes.values())
      .enter().append("label");

    labels.append("input")
      .attr('type', 'checkbox')

      // Enable all
      .property('checked', function(d) { return true; })
      .attr("value", function(d) { return d.type; })
      .on("change", drawWithLoading);

    labels.append("span")
      .attr('class', 'key')
      .style('background-color', function(d) { return '#' + d.color; });

    labels.append("span")
      .text(function(d) { return d.type; });
  }

  var selectedTypes = function() {
    return d3.selectAll('#toggles input[type=checkbox]')[0].filter(function(elem) {
      return elem.checked;
    }).map(function(elem) {
      return elem.value;
    })
  }

  var pointsFilteredToSelectedTypes = function() {
    var currentSelectedTypes = d3.set(selectedTypes());
    return points.filter(function(item){
      return currentSelectedTypes.has(item.type);
    });
  }

  var drawWithLoading = function(e){
    d3.select('#loading').classed('visible', true);
    if (e && e.type == 'viewreset') {
      d3.select('#overlay').remove();
    }
    setTimeout(function(){
      draw();

      // Add Date Filter
      if($("#month").val() != "All Months" && $("#day").val() != "All Days"){
        filter($("#month").val(), $("#day").val());
      }

      d3.select('#loading').classed('visible', false);
    }, 0);
  }

  var draw = function() {
    d3.select('#overlay').remove();

    var bounds = map.getBounds(),
        topLeft = map.latLngToLayerPoint(bounds.getNorthWest()),
        bottomRight = map.latLngToLayerPoint(bounds.getSouthEast()),
        existing = d3.set(),
        drawLimit = bounds.pad(0.4);

    filteredPoints = pointsFilteredToSelectedTypes().filter(function(d) {
      var latlng = new L.LatLng(d.latitude, d.longitude);

      if (!drawLimit.contains(latlng)) { return false };

      var point = map.latLngToLayerPoint(latlng);

      key = point.toString();
      if (existing.has(key)) { return false };
      existing.add(key);

      d.x = point.x;
      d.y = point.y;
      return true;
    });

    var svg = d3.select(map.getPanes().overlayPane).append("svg")
      .attr('id', 'overlay')
      .attr("class", "leaflet-zoom-hide")
      .style("width", map.getSize().x + 'px')
      .style("height", map.getSize().y + 'px')
      .style("margin-left", topLeft.x + "px")
      .style("margin-top", topLeft.y + "px");

    var g = svg.append("g")
      .attr("transform", "translate(" + (-topLeft.x) + "," + (-topLeft.y) + ")")
      .attr("pointer-events", "all");

    var svgPoints = g.attr("class", "points")
      .selectAll("g")
      .data(filteredPoints)
      .enter().append("g")
      .attr("class", "point")
      .style("z-index", 999);

    svgPoints.append("path")
      .attr("class", "point-cell")
      .on('click', function(d){ console.log(d) })
      .classed("selected", function(d) { return lastSelectedPoint == d} );

    // Add circles for each point
    svgPoints.append("circle")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .style('fill', function(d) { return '#' + d.color } )
      .attr("date", function(d) { return d.date })
      .attr("r", 7)
      .attr("pointer-events", "all")
      .attr("opacity", 1);

    // Draw point-to-point connections
    svgPoints.each(function(){
      if($(this).next().length == 1){
        var this_transform = $(this).children("circle").attr("transform"),
            next_transform = $(this).next().children("circle").attr("transform"),
            this_position = this_transform.substring(10, this_transform.length - 1).split(","),
            next_position = next_transform.substring(10, next_transform.length - 1).split(",");

        d3.select(this).append("line")
          .attr("x1", this_position[0])
          .attr("y1", this_position[1])
          .attr("x2", next_position[0])
          .attr("y2", next_position[1])
          .style("stroke", "rgb(255,0,0)")
          .style("stroke-width", 5)
          .style("opacity", 0);
      }
    });

    addTrackingLines();

    // Provides a tracing highlight of user
    // activiity for sequential points on hover
    function addTrackingLines(){

      $("g").each(function(){
        $(this).hover(function(){

          var lines = [$(this).children("line"), $(this).next().children("line")],
              lines2 = [$(this).prev().children("line")];

          for(i=1; i < 5; i++){
            lines.push(lines[i].parent().next().children("line"));
          }

          for(i=0; i < 4; i++){
            lines2.push(lines2[i].parent().prev().children("line"));
          }

          lines = lines.concat(lines2);

          for(var x in lines){
            lines[x].css("opacity", .4); // Set HOVER .4
          }
        },

        function(){
          var lines = [$(this).children("line"), $(this).next().children("line")],
              lines2 = [$(this).prev().children("line")];

          for(i=1; i < 5; i++){
            lines.push(lines[i].parent().next().children("line"));
          }

          for(i=0; i < 4; i++){
            lines2.push(lines2[i].parent().prev().children("line"));
          }

          lines = lines.concat(lines2);

          for(var x in lines){
            lines[x].css("opacity", 0);
          }
        });
      });
    }

  }

  var mapLayer = {
    onAdd: function(map) {
      map.on('viewreset moveend', drawWithLoading);
      drawWithLoading();
    }
  }

  map.on('ready', function() {
      points.forEach(function(point) {
        pointTypes.set(point.type, {type: point.type, color: point.color});
      })

      drawPointTypeSelection();

      map.addLayer(mapLayer);
    })

}<|endoftext|>


<commit_before>  var ns=$.fn.wipeImages,factory=ns.wipeFactory;
  $.fn.wipeImages.wipes=$.extend($.fn.wipeImages.wipes,{

    diagTopLeft:function(el){
      var opts={
        cols:8,rows:4
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupDiagonally(opts.rows,opts.cols);
      wipe.isGrouped=true;
      wipe.run();
    },
    diagTopRight:function(el){
      var opts={
        cols:8,rows:4
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupDiagonally(opts.rows,opts.cols,true).reverse();
      wipe.isGrouped=true;
      wipe.run();
    },
    diagBottomRight:function(el){
      var opts={
        cols:8,rows:4
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupDiagonally(opts.rows,opts.cols).reverse();
      wipe.isGrouped=true;
      wipe.run();
    },
    diagBottomLeft:function(el){
      var opts={
        cols:8,rows:4
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupDiagonally(opts.rows,opts.cols,true);
      wipe.isGrouped=true;
      wipe.run();
    },
    fromCenter:function(el){
      var opts={
        cols:10,rows:1
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols);
      wipe.isGrouped=true;
      wipe.run();
    },
    toCenter:function(el){
      var opts={
        cols:9,rows:1
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols).reverse();
      wipe.isGrouped=true;
      wipe.run();
    },
    pyramidInvertedCollapse:function(el){
      var endHeight=el.height(),opts={
        cols:19,rows:1,
        from:{
          height:"0px"
        },
        to:{
          height:endHeight + "px"
        }
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols);
      wipe.isGrouped=true;
      wipe.run();
    },
    pyramidCollapse:function(el){
      var endHeight=el.height(),opts={
        cols:19,rows:1,
        from:{
          height:"0px"
        },
        to:{
          height:endHeight + "px"
        }
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols).reverse();
      wipe.isGrouped=true;
      wipe.run();
    },
    pyramidInvertedGrow:function(el){
      var endHeight=el.height(),opts={
        cols:19,rows:1,
        from:{
          height:"0px",
          bottom:"0px",
          top:"auto"
        },
        to:{
          height:endHeight + "px"
        }
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols).reverse();
      wipe.isGrouped=true;
      wipe.run();
    },
    pyramidGrow:function(el){
      var endHeight=el.height(),opts={
        cols:19,rows:1,
        from:{
          height:"0px",
          bottom:"0px",
          top:"auto"
        },
        to:{
          height:endHeight + "px"
        }
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols);
      wipe.isGrouped=true;
      wipe.run();
    }

  });
<commit_msg>File size optimizations for extended wipes<commit_after>
  var ns=$.fn.wipeImages,factory=ns.wipeFactory;

  //Diagonal Fade Animations
  function diagonals(){
    var opts={
      cols:8,rows:4
    },wipe;
    function _run(wipe,rev1,rev2){
      wipe.isGrouped=true;
      wipe.groups=groupDiagonally(opts.rows,opts.cols,rev1);
      if(rev2) {wipe.groups.reverse();}
      wipe.run();
    }
    return {
      diagTopLeft:function(el){
        wipe=new factory(el,opts);
        _run(wipe);
      },
      diagTopRight:function(el){
        wipe=new factory(el,opts);
        _run(wipe,true,true);
      },
      diagBottomRight:function(el){
        wipe=new factory(el,opts);
        _run(wipe,false,true);
      },
      diagBottomLeft:function(el){
        wipe=new factory(el,opts);
        _run(wipe,true,false);
      }
    };
  }

  ns.wipes=$.extend(ns.wipes,diagonals());

  //From Center Fade Animations
  function fromCenters(){
    var opts={
      cols:10,rows:1
    },wipe;
    function _run(wipe,rev){
      wipe.isGrouped=true;
      wipe.groups=groupCentrally(opts.rows,opts.cols,rev);
      if(rev) {wipe.groups.reverse();}
      wipe.run();
    }
    return {
      fromCenter:function(el){
        wipe=new factory(el,opts);
        _run(wipe);
      },
      toCenter:function(el){
        opts.cols=9;
        wipe=new factory(el,opts);
        _run(wipe,true);
      }
    };
  }

  ns.wipes=$.extend(ns.wipes,fromCenters());

  $.fn.wipeImages.wipes=$.extend($.fn.wipeImages.wipes,{

    pyramidInvertedCollapse:function(el){
      var endHeight=el.height(),opts={
        cols:19,rows:1,
        from:{
          height:"0px"
        },
        to:{
          height:endHeight + "px"
        }
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols);
      wipe.isGrouped=true;
      wipe.run();
    },
    pyramidCollapse:function(el){
      var endHeight=el.height(),opts={
        cols:19,rows:1,
        from:{
          height:"0px"
        },
        to:{
          height:endHeight + "px"
        }
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols).reverse();
      wipe.isGrouped=true;
      wipe.run();
    },
    pyramidInvertedGrow:function(el){
      var endHeight=el.height(),opts={
        cols:19,rows:1,
        from:{
          height:"0px",
          bottom:"0px",
          top:"auto"
        },
        to:{
          height:endHeight + "px"
        }
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols).reverse();
      wipe.isGrouped=true;
      wipe.run();
    },
    pyramidGrow:function(el){
      var endHeight=el.height(),opts={
        cols:19,rows:1,
        from:{
          height:"0px",
          bottom:"0px",
          top:"auto"
        },
        to:{
          height:endHeight + "px"
        }
      };
      var wipe=new factory(el,opts);
      wipe.groups=groupCentrally(opts.rows,opts.cols);
      wipe.isGrouped=true;
      wipe.run();
    }

  });
<|endoftext|>


<commit_before>/*!
 * Layzr.js 1.4.2 - A small, fast, modern, and dependency-free library for lazy loading.
 * Copyright (c) 2015 Michael Cavalea - http://callmecavs.github.io/layzr.js/
 * License: MIT
 */

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.Layzr = factory();
  }
}(this, function() {
'use strict';

// CONSTRUCTOR

function Layzr(options) {
  // debounce
  this._lastScroll = 0;
  this._ticking    = false;

  // options
  options = options || {};

  this._optionsContainer  = document.querySelector(options.container) || window;
  this._optionsSelector   = options.selector || '[data-layzr]';
  this._optionsAttr       = options.attr || 'data-layzr';
  this._optionsAttrRetina = options.retinaAttr || 'data-layzr-retina';
  this._optionsAttrBg     = options.bgAttr || 'data-layzr-bg';
  this._optionsAttrHidden = options.hiddenAttr || 'data-layzr-hidden';
  this._optionsThreshold  = options.threshold || 0;
  this._optionsCallback   = options.callback || null;

  // properties
  this._retina  = window.devicePixelRatio > 1;
  this._srcAttr = this._retina ? this._optionsAttrRetina : this._optionsAttr;

  // nodelist
  this._nodes = document.querySelectorAll(this._optionsSelector);

  // scroll and resize handler
  this._handlerBind = this._requestScroll.bind(this);

  // call to create
  this._create();
}

// DEBOUNCE HELPERS
// adapted from: http://www.html5rocks.com/en/tutorials/speed/animations/

Layzr.prototype._requestScroll = function() {
  if(this._optionsContainer === window) {
    this._lastScroll = window.pageYOffset;
  }
  else {
    this._lastScroll = this._optionsContainer.scrollTop + this._getOffset(this._optionsContainer);
  }

  this._requestTick();
};

Layzr.prototype._requestTick = function() {
  if(!this._ticking) {
    requestAnimationFrame(this.update.bind(this));
    this._ticking = true;
  }
};

// OFFSET HELPER
// remember, getBoundingClientRect is relative to the viewport

Layzr.prototype._getOffset = function(node) {
  return node.getBoundingClientRect().top + window.pageYOffset;
};

// HEIGHT HELPER

Layzr.prototype._getContainerHeight = function() {
  return this._optionsContainer.innerHeight
      || this._optionsContainer.offsetHeight;
}

// LAYZR METHODS

Layzr.prototype._create = function() {
  // fire scroll event once
  this._handlerBind();

  // bind scroll and resize event
  this._optionsContainer.addEventListener('scroll', this._handlerBind, false);
  this._optionsContainer.addEventListener('resize', this._handlerBind, false);
};

Layzr.prototype._destroy = function() {
  // unbind scroll and resize event
  this._optionsContainer.removeEventListener('scroll', this._handlerBind, false);
  this._optionsContainer.removeEventListener('resize', this._handlerBind, false);
};

Layzr.prototype._inViewport = function(node) {
  // get viewport top and bottom offset
  var viewportTop = this._lastScroll;
  var viewportBottom = viewportTop + this._getContainerHeight();

  // get node top and bottom offset
  var nodeTop = this._getOffset(node);
  var nodeBottom = nodeTop + this._getContainerHeight();

  // calculate threshold, convert percentage to pixel value
  var threshold = (this._optionsThreshold / 100) * window.innerHeight;

  // return if node in viewport
  return nodeBottom >= viewportTop - threshold
      && nodeTop <= viewportBottom + threshold
      && !node.hasAttribute(this._optionsAttrHidden);
};

Layzr.prototype._reveal = function(node) {
  // get node source
  var source = node.getAttribute(this._srcAttr) || node.getAttribute(this._optionsAttr);

  // set node src or bg image
  if(node.hasAttribute(this._optionsAttrBg)) {
    node.style.backgroundImage = 'url(' + source + ')';
  }
  else {
    node.setAttribute('src', source);
  }

  // call the callback
  if(typeof this._optionsCallback === 'function') {
    // "this" will be the node in the callback
    this._optionsCallback.call(node);
  }

  // remove node data attributes
  node.removeAttribute(this._optionsAttr);
  node.removeAttribute(this._optionsAttrRetina);
  node.removeAttribute(this._optionsAttrBg);
  node.removeAttribute(this._optionsAttrHidden);
  node.style.display = 'block';
};

Layzr.prototype.updateSelector = function() {
  // update cached list of nodes matching selector
  this._nodes = document.querySelectorAll(this._optionsSelector);
};

Layzr.prototype.update = function() {
  // cache nodelist length
  var nodesLength = this._nodes.length;

  // loop through nodes
  for(var i = 0; i < nodesLength; i++) {
    // cache node
    var node = this._nodes[i];

    // check if node has mandatory attribute
    if(node.hasAttribute(this._optionsAttr)) {
      // check if node in viewport
      if(this._inViewport(node)) {
        // reveal node
        this._reveal(node);
      }
    }
  }

  // allow for more animation frames
  this._ticking = false;
};

return Layzr;
}));
<commit_msg>Update lazyload.js<commit_after>/*!
 * Layzr.js 1.4.2 - A small, fast, modern, and dependency-free library for lazy loading.
 * Copyright (c) 2015 Michael Cavalea - http://callmecavs.github.io/layzr.js/
 * License: MIT
 */

(function(root, factory) {
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof exports === 'object') {
    module.exports = factory();
  } else {
    root.Layzr = factory();
  }
}(this, function() {
'use strict';

// CONSTRUCTOR

function Layzr(options) {
  // debounce
  this._lastScroll = 0;
  this._ticking    = false;

  // options
  options = options || {};

  this._optionsContainer  = document.querySelector(options.container) || window;
  this._optionsSelector   = options.selector || '[data-layzr]';
  this._optionsAttr       = options.attr || 'data-layzr';
  this._optionsAttrRetina = options.retinaAttr || 'data-layzr-retina';
  this._optionsAttrBg     = options.bgAttr || 'data-layzr-bg';
  this._optionsAttrHidden = options.hiddenAttr || 'data-layzr-hidden';
  this._optionsThreshold  = options.threshold || 0;
  this._optionsCallback   = options.callback || null;

  // properties
  this._retina  = window.devicePixelRatio > 1;
  this._srcAttr = this._retina ? this._optionsAttrRetina : this._optionsAttr;

  // nodelist
  this._nodes = document.querySelectorAll(this._optionsSelector);

  // scroll and resize handler
  this._handlerBind = this._requestScroll.bind(this);

  // call to create
  this._create();
}

// DEBOUNCE HELPERS
// adapted from: http://www.html5rocks.com/en/tutorials/speed/animations/

Layzr.prototype._requestScroll = function() {
  if(this._optionsContainer === window) {
    this._lastScroll = window.pageYOffset;
  }
  else {
    this._lastScroll = this._optionsContainer.scrollTop + this._getOffset(this._optionsContainer);
  }

  this._requestTick();
};

Layzr.prototype._requestTick = function() {
  if(!this._ticking) {
    requestAnimationFrame(this.update.bind(this));
    this._ticking = true;
  }
};

// OFFSET HELPER
// remember, getBoundingClientRect is relative to the viewport

Layzr.prototype._getOffset = function(node) {
  return node.getBoundingClientRect().top + window.pageYOffset;
};

// HEIGHT HELPER

Layzr.prototype._getContainerHeight = function() {
  return this._optionsContainer.innerHeight
      || this._optionsContainer.offsetHeight;
}

// LAYZR METHODS

Layzr.prototype._create = function() {
  // fire scroll event once
  this._handlerBind();

  // bind scroll and resize event
  this._optionsContainer.addEventListener('scroll', this._handlerBind, false);
  this._optionsContainer.addEventListener('resize', this._handlerBind, false);
};

Layzr.prototype._destroy = function() {
  // unbind scroll and resize event
  this._optionsContainer.removeEventListener('scroll', this._handlerBind, false);
  this._optionsContainer.removeEventListener('resize', this._handlerBind, false);
};

Layzr.prototype._inViewport = function(node) {
  // get viewport top and bottom offset
  var viewportTop = this._lastScroll;
  var viewportBottom = viewportTop + this._getContainerHeight();

  // get node top and bottom offset
  var nodeTop = this._getOffset(node);
  var nodeBottom = nodeTop + this._getContainerHeight();

  // calculate threshold, convert percentage to pixel value
  var threshold = (this._optionsThreshold / 100) * window.innerHeight;

  // return if node in viewport
  return nodeBottom >= viewportTop - threshold
      && nodeTop <= viewportBottom + threshold
      && !node.hasAttribute(this._optionsAttrHidden);
};

Layzr.prototype._reveal = function(node) {
  // get node source
  var source = node.getAttribute(this._srcAttr) || node.getAttribute(this._optionsAttr);

  // set node src or bg image
  if(node.hasAttribute(this._optionsAttrBg)) {
    node.style.backgroundImage = 'url(' + source + ')';
  }
  else {
    node.setAttribute('src', source);
  }

  // call the callback
  if(typeof this._optionsCallback === 'function') {
    // "this" will be the node in the callback
    this._optionsCallback.call(node);
  }

  // remove node data attributes
  node.removeAttribute(this._optionsAttr);
  node.removeAttribute(this._optionsAttrRetina);
  node.removeAttribute(this._optionsAttrBg);
  node.removeAttribute(this._optionsAttrHidden);
  node.style.opacity = '1';
};

Layzr.prototype.updateSelector = function() {
  // update cached list of nodes matching selector
  this._nodes = document.querySelectorAll(this._optionsSelector);
};

Layzr.prototype.update = function() {
  // cache nodelist length
  var nodesLength = this._nodes.length;

  // loop through nodes
  for(var i = 0; i < nodesLength; i++) {
    // cache node
    var node = this._nodes[i];

    // check if node has mandatory attribute
    if(node.hasAttribute(this._optionsAttr)) {
      // check if node in viewport
      if(this._inViewport(node)) {
        // reveal node
        this._reveal(node);
      }
    }
  }

  // allow for more animation frames
  this._ticking = false;
};

return Layzr;
}));
<|endoftext|>


<commit_before>/**
 * GoJS 1.0.0
 * https://github.com/Lanfei/GoJS
 * A JavaScript module loader following CMD standard
 * [Common Module Definition](https://github.com/cmdjs/specification/blob/master/draft/module.md)
 */

(function(global, undefined) {

	// global
	if (global.gojs) {
		return;
	}

	var gojs = global.gojs = {
		version: '1.0.0'
	};

	// path
	var DOT_RE = /\/\.\//g;
	var MULTI_SLASH_RE = /([^:/])\/+\//g;
	var DOUBLE_DOT_RE = /\/[^/]+\/\.\.\//;

	function normPath(path) {
		path = path.replace(DOT_RE, '/');

		path = path.replace(MULTI_SLASH_RE, '$1/');

		while (path.match(DOUBLE_DOT_RE)) {
			path = path.replace(DOUBLE_DOT_RE, '/');
		}
		return path;
	}

	function dirname(path) {
		return path.match(/[^?#]*\//)[0];
	}

	function absSrc(script) {
		return script.hasAttribute ? script.src : script.getAttribute('src', 4);
	}

	// config
	var config = {
			base: undefined,
			main: undefined,
			charset: 'utf-8'
		},
		scripts = document.scripts,
		goScript = scripts[scripts.length - 1],
		data = goScript.dataset;

	gojs.config = function(data) {
		if (data) {
			for (var key in config) {
				config[key] = data[key] || config[key];
			}
			if (config['base'] === undefined) {
				config['base'] = dirname(absSrc(goScript));
			}
			if (config['base'] && config['base'].slice(-1) !== '/') {
				config['base'] += '/';
			}
		}
		return config;
	};

	if (!data) {
		data = {};
		var attrs = goScript.attributes;
		for (var i = 0, l = attrs.length; i < l; ++i) {
			var item = attrs[i],
				nodeName = item.nodeName,
				nodeValue = item.nodeValue;

			if (nodeName.indexOf('data-') === 0) {
				data[nodeName.replace('data-', '')] = nodeValue;
			}
		}
	}

	gojs.config(data);

	// loader
	var modules = {},
		fetchingList = [],
		asyncList = [],
		currentScript = '',
		isSync = false,
		syncQueue = [],
		head = document.head || document.getElementsByTagName('head')[0];

	function getCurrentScript() {
		var scripts = head.getElementsByTagName('script');

		// Chrome
		if (document.currentScript) {
			return absSrc(document.currentScript);
		}

		// Safari, etc.
		if (isSync) {
			return currentScript;
		}

		// Opera 9, etc.
		try {
			throwAnError();
		} catch (e) {
			var stack = e.stack;
			// Opera 9 or lower
			if (e.stacktrace) {
				stack = e.toString();
			}
			if (stack) {
				var reg = /(http|https|file):\/\/[^ ]+\.js/g;
				var matches = stack.match(reg);
				return matches.pop();
			}
		}

		// IE 6-9
		for (var i = 0, l = scripts.length; i < l; ++i) {
			var script = scripts[i];
			if (script.readyState === 'interactive') {
				return absSrc(script);
			}
		}

		isSync = true;

		return currentScript;
	}

	function loadModule(id) {
		var uri = id2Uri(id);
		if (modules[uri]) {
			return;
		}
		var script = document.createElement('script');
		script.src = uri;
		script.charset = config.charset;
		script.async = true;
		// Sync
		if (getCurrentScript() && isSync) {
			syncQueue.push(id);
			return;
		}
		currentScript = uri;
		// setTimeout: IE6
		setTimeout(function() {
			script.onload = script.onreadystatechange = function() {
				if (!script.readyState || /loaded|complete/.test(script.readyState)) {
					script.onload = script.onreadystatechange = null;
					head.removeChild(script);
					script = null;
				}
				currentScript = '';
				if (isSync && syncQueue.length) {
					loadModule(syncQueue.shift());
				}
			};
			head.insertBefore(script, head.firstChild);
		});
	}

	function id2Uri(id) {
		var uri = id;
		if (!/^(http|https|file):\/\//.test(id)) {
			uri = normPath(dirname(document.location.href) + config.base + id);
		}
		if (uri.slice(-3) !== '.js') {
			uri += '.js';
		}
		return uri;
	}

	function uri2Id(uri) {
		var base = normPath(dirname(document.location.href) + config.base);
		var id = uri.replace(base, '');
		if (id.slice(-3) === '.js') {
			id = id.substring(0, id.length - 3);
		}
		return id;
	}

	function require(id) {
		return modules[id2Uri(id)];
	}

	require.async = function(ids, callback) {
		var deps = [];
		if (typeof ids == 'string') {
			ids = [ids];
		}
		for (var i = 0, l = ids.length; i < l; ++i) {
			deps.push(id2Uri(ids[i]));
			loadModule(ids[i]);
		}
		asyncList.push({
			deps: deps,
			callback: callback
		});
		// checkAsync();
	};

	require.resolve = id2Uri;

	function checkAsync() {
		for (var i = 0, l = asyncList.length; i < l; ++i) {
			var args = [],
				deps = asyncList[i].deps,
				callback = asyncList[i].callback;
			for (var j = 0, depLen = deps.length; j < depLen; ++j) {
				var factory = modules[deps[j]];
				if (factory) {
					args.push(factory);
				} else {
					break;
				}
			}
			if (args.length === depLen) {
				callback.apply(null, args);
				asyncList.splice(i, 1);
				--i;
				--l;
			}
		}
	}

	function resolveDeps() {
		var len = fetchingList.length;
		if (!len) {
			return;
		}
		var loaded, module, uri, factory, deps, exports;
		for (var i = len - 1; i >= 0; --i) {
			loaded = true;
			module = fetchingList[i];
			uri = module.uri;
			factory = module.factory;
			deps = module.dependencies;
			for (var j = 0, l = deps.length; j < l; ++j) {
				var depUri = id2Uri(deps[j]);
				if (!modules[depUri]) {
					loaded = false;
					break;
				}
			}
			if (loaded) {
				exports = factory(require, module.exports, module);
				modules[uri] = exports || module.exports;
				fetchingList.splice(i, 1);
				checkAsync();
				resolveDeps();
				return;
			}
		}
	}

	function parseDeps(code) {
		var re = /(^|\b)(?!_)require\( *[\'\"][^\'\"]+[\'\"] *\)/g,
			// matches = code.replace(/\/\/.*/g, '').match(re) || [],
			matches = code.match(re) || [],
			deps = [];
		for (var i = 0, l = matches.length; i < l; ++i) {
			matches[i] = matches[i].replace(/require\( *[\'\"]([^\'\"]+)[\'\"] *\)/, '$1');
		}
		return matches;
	}

	global.define = function(factory) {
		var uri = getCurrentScript();
		if (typeof factory === 'function') {
			var module = {},
				deps = parseDeps(factory.toString());
			module.id = uri2Id(uri);
			module.uri = uri;
			module.exports = {};
			module.factory = factory;
			module.dependencies = deps;
			for (var i = 0, l = deps.length; i < l; ++i) {
				loadModule(deps[i]);
			}
			fetchingList.push(module);
		} else {
			modules[uri] = factory;
			checkAsync();
		}
		resolveDeps();
	};

	global.define.cmd = {};

	if (config.main) {
		loadModule(config.main);
	}

})(this);<commit_msg>Optimized<commit_after>/**
 * GoJS 1.0.0
 * https://github.com/Lanfei/GoJS
 * A JavaScript module loader following CMD standard
 * [Common Module Definition](https://github.com/cmdjs/specification/blob/master/draft/module.md)
 */

(function(global, undefined) {

	// global
	if (global.gojs) {
		return;
	}

	var gojs = global.gojs = {
		version: '1.0.0'
	};

	// path
	var DOT_RE = /\/\.\//g;
	var MULTI_SLASH_RE = /([^:/])\/+\//g;
	var DOUBLE_DOT_RE = /\/[^/]+\/\.\.\//;

	function normPath(path) {
		path = path.replace(DOT_RE, '/');

		path = path.replace(MULTI_SLASH_RE, '$1/');

		while (path.match(DOUBLE_DOT_RE)) {
			path = path.replace(DOUBLE_DOT_RE, '/');
		}
		return path;
	}

	function dirname(path) {
		return path.match(/[^?#]*\//)[0];
	}

	function absSrc(script) {
		return script.hasAttribute ? script.src : script.getAttribute('src', 4);
	}

	// config
	var config = {
			base: undefined,
			main: undefined,
			charset: 'utf-8'
		},
		scripts = document.scripts,
		goScript = scripts[scripts.length - 1],
		data = goScript.dataset;

	gojs.config = function(data) {
		if (data) {
			for (var key in config) {
				config[key] = data[key] || config[key];
			}
			if (config['base'] === undefined) {
				config['base'] = dirname(absSrc(goScript));
			}
			if (config['base'] && config['base'].slice(-1) !== '/') {
				config['base'] += '/';
			}
		}
		return config;
	};

	if (!data) {
		data = {};
		var attrs = goScript.attributes;
		for (var i = 0, l = attrs.length; i < l; ++i) {
			var item = attrs[i],
				nodeName = item.nodeName,
				nodeValue = item.nodeValue;

			if (nodeName.indexOf('data-') === 0) {
				data[nodeName.replace('data-', '')] = nodeValue;
			}
		}
	}

	gojs.config(data);

	// loader
	var modules = {},
		fetchingList = [],
		asyncList = [],
		currentScript = '',
		isSync = false,
		syncQueue = [],
		head = document.head || document.getElementsByTagName('head')[0];

	function getCurrentScript() {
		var scripts = head.getElementsByTagName('script');

		// Chrome
		if (document.currentScript) {
			return absSrc(document.currentScript);
		}

		// Safari, etc.
		if (isSync) {
			return currentScript;
		}

		// Opera 9, etc.
		try {
			throwAnError();
		} catch (e) {
			var stack = e.stack;
			// Opera 9 or lower
			if (e.stacktrace) {
				stack = e.toString();
			}
			if (stack) {
				var reg = /(http|https|file):\/\/[^ ]+\.js/g;
				var matches = stack.match(reg);
				return matches.pop();
			}
		}

		// IE 6-9
		for (var i = 0, l = scripts.length; i < l; ++i) {
			var script = scripts[i];
			if (script.readyState === 'interactive') {
				return absSrc(script);
			}
		}

		isSync = true;

		return currentScript;
	}

	function loadModule(id) {
		var uri = id2Uri(id);
		if (modules[uri]) {
			return;
		}
		var script = document.createElement('script');
		script.src = uri;
		script.charset = config.charset;
		script.async = true;
		// Sync
		if (getCurrentScript() && isSync) {
			syncQueue.push(id);
			return;
		}
		currentScript = uri;
		// setTimeout: IE6
		setTimeout(function() {
			script.onload = script.onreadystatechange = function() {
				if (!script.readyState || /loaded|complete/.test(script.readyState)) {
					script.onload = script.onreadystatechange = null;
					head.removeChild(script);
					script = null;
				}
				currentScript = '';
				if (isSync && syncQueue.length) {
					loadModule(syncQueue.shift());
				}
			};
			head.insertBefore(script, head.firstChild);
		});
	}

	function id2Uri(id) {
		var uri = id;
		if (!/^(http|https|file):\/\//.test(id)) {
			uri = normPath(dirname(document.location.href) + config.base + id);
		}
		if (uri.slice(-3) !== '.js') {
			uri += '.js';
		}
		return uri;
	}

	function uri2Id(uri) {
		var base = normPath(dirname(document.location.href) + config.base);
		var id = uri.replace(base, '');
		if (id.slice(-3) === '.js') {
			id = id.substring(0, id.length - 3);
		}
		return id;
	}

	function require(id) {
		return modules[id2Uri(id)];
	}

	require.async = function(ids, callback) {
		var deps = [];
		if (typeof ids == 'string') {
			ids = [ids];
		}
		for (var i = 0, l = ids.length; i < l; ++i) {
			deps.push(id2Uri(ids[i]));
			loadModule(ids[i]);
		}
		asyncList.push({
			deps: deps,
			callback: callback
		});
		// checkAsync();
	};

	require.resolve = id2Uri;

	function checkAsync() {
		for (var i = 0, l = asyncList.length; i < l; ++i) {
			var args = [],
				deps = asyncList[i].deps,
				callback = asyncList[i].callback;
			for (var j = 0, depLen = deps.length; j < depLen; ++j) {
				var factory = modules[deps[j]];
				if (!factory) {
					break;
				}
				args.push(factory);
				if (args.length === depLen) {
					break;
				}
			}
			if (args.length === depLen) {
				callback.apply(null, args);
				asyncList.splice(i, 1);
				--i;
				--l;
			}
		}
	}

	function resolveDeps() {
		var len = fetchingList.length;
		if (!len) {
			return;
		}
		var loaded, module, uri, factory, deps, exports;
		for (var i = len - 1; i >= 0; --i) {
			loaded = true;
			module = fetchingList[i];
			uri = module.uri;
			factory = module.factory;
			deps = module.dependencies;
			for (var j = 0, l = deps.length; j < l; ++j) {
				var depUri = id2Uri(deps[j]);
				if (!modules[depUri]) {
					loaded = false;
					break;
				}
			}
			if (loaded) {
				exports = factory(require, module.exports, module);
				modules[uri] = exports || module.exports;
				fetchingList.splice(i, 1);
				checkAsync();
				resolveDeps();
				return;
			}
		}
	}

	function parseDeps(code) {
		var re = /(^|\b)(?!_)require\( *[\'\"][^\'\"]+[\'\"] *\)/g,
			// matches = code.replace(/\/\/.*/g, '').match(re) || [],
			matches = code.match(re) || [],
			deps = [];
		for (var i = 0, l = matches.length; i < l; ++i) {
			matches[i] = matches[i].replace(/require\( *[\'\"]([^\'\"]+)[\'\"] *\)/, '$1');
		}
		return matches;
	}

	global.define = function(factory) {
		var uri = getCurrentScript();
		if (typeof factory === 'function') {
			var module = {},
				deps = parseDeps(factory.toString());
			module.id = uri2Id(uri);
			module.uri = uri;
			module.exports = {};
			module.factory = factory;
			module.dependencies = deps;
			for (var i = 0, l = deps.length; i < l; ++i) {
				loadModule(deps[i]);
			}
			fetchingList.push(module);
		} else {
			modules[uri] = factory;
			checkAsync();
		}
		resolveDeps();
	};

	global.define.cmd = {};

	if (config.main) {
		loadModule(config.main);
	}

})(this);<|endoftext|>


<commit_before>
var body;

var imageEls;
var lightbox;
var lightboxImg;
var lightboxVis;

var btnLeft;
var btnRight;
var btnClose;

var imgIndex;
var imgLength;

window.addEventListener('load', function () {
  setTimeout(getImages(), 1000);
  // getImages();
});

var imageSrcs = []
function getImages() {

  body = document.getElementsByTagName('body')[0];
  imageEls = document.querySelectorAll('.artPagesImgContainer')[0].getElementsByTagName('img');
  imgLength = imageEls.length;
  lightbox = document.getElementById('lightbox');
  lightboxImg = document.getElementById('lightbox-img');

  btnLeft = document.getElementById('lightbox-left');
  btnRight = document.getElementById('lightbox-right');
  btnClose = document.getElementById('lightbox-close');

  btnLeft.addEventListener('click', function () {
    incrementIndex(-1);
  });

  btnRight.addEventListener('click', function () {
    incrementIndex(1);
  });

  btnClose.addEventListener('click', function () {
    lightboxToggle();
  });

  lightboxVis = lightbox.classList.contains('lightbox-visible');
  lightbox.addEventListener('click', function (event) {
    if (event.target == lightbox) {
      lightboxToggle();
    }
  });

  for (var i = 0; i < imageEls.length; i++) {
    imageEls[i].addEventListener('click', function (event) {
      imgIndex = getIndex(event);
      lightboxToggle();
    });
    imageSrcs[i] = imageEls[i].src;
  }

  document.addEventListener('keydown', function (event) {
    console.log(lightboxVis);
    console.log(event.keyCode);
    if (lightboxVis) {

      if (event.keyCode == 27) {
        lightboxToggle();
        return;
      }

      if (event.keyCode == 37 || event.keyCode == 65) {
        incrementIndex(-1);
      } else if (event.keyCode == 39 || event.keyCode == 68) {
        incrementIndex(1);
      }
    }
  });

  console.log('images loaded');
}

function incrementIndex(amount) {
  imgIndex += amount;

  if (imgIndex < 0) {
    imgIndex = imgLength - 1;
  }

  if (imgIndex >= imgLength) {
    imgIndex = 0;
  }

  console.log(imgIndex);
  setLightboxImage(imgIndex);
}

function getIndex(event) {
  var target = event.target;

  for (var i = 0; i < imageEls.length; i++) {
    if (imageEls[i] == target) {
      console.log("index is " + i);
      return i;
    }
  }
}

function lightboxToggle() {
  if (lightboxVis) {
    lightbox.classList.add('lightbox-hidden');
    lightbox.classList.remove('lightbox-visible');

    body.classList.remove('no-scroll');

    lightboxVis = false;
  } else {
    lightbox.classList.add('lightbox-visible');
    lightbox.classList.remove('lightbox-hidden');

    body.classList.add('no-scroll');

    lightboxVis = true;

    setLightboxImage();
  }
}

function setLightboxImage() {
  lightboxImg.src = imageSrcs[imgIndex];
}
<commit_msg>added delay in getting images<commit_after>
var body;

var imageEls;
var lightbox;
var lightboxImg;
var lightboxVis;

var btnLeft;
var btnRight;
var btnClose;

var imgIndex;
var imgLength;

window.addEventListener('load', function () {
  setTimeout( function () { getImages(); }, 1000);
  // getImages();
});

var imageSrcs = []
function getImages() {

  body = document.getElementsByTagName('body')[0];
  imageEls = document.querySelectorAll('.artPagesImgContainer')[0].getElementsByTagName('img');
  imgLength = imageEls.length;
  lightbox = document.getElementById('lightbox');
  lightboxImg = document.getElementById('lightbox-img');

  btnLeft = document.getElementById('lightbox-left');
  btnRight = document.getElementById('lightbox-right');
  btnClose = document.getElementById('lightbox-close');

  btnLeft.addEventListener('click', function () {
    incrementIndex(-1);
  });

  btnRight.addEventListener('click', function () {
    incrementIndex(1);
  });

  btnClose.addEventListener('click', function () {
    lightboxToggle();
  });

  lightboxVis = lightbox.classList.contains('lightbox-visible');
  lightbox.addEventListener('click', function (event) {
    if (event.target == lightbox) {
      lightboxToggle();
    }
  });

  for (var i = 0; i < imageEls.length; i++) {
    imageEls[i].addEventListener('click', function (event) {
      imgIndex = getIndex(event);
      lightboxToggle();
    });
    imageSrcs[i] = imageEls[i].src;
  }

  document.addEventListener('keydown', function (event) {
    console.log(lightboxVis);
    console.log(event.keyCode);
    if (lightboxVis) {

      if (event.keyCode == 27) {
        lightboxToggle();
        return;
      }

      if (event.keyCode == 37 || event.keyCode == 65) {
        incrementIndex(-1);
      } else if (event.keyCode == 39 || event.keyCode == 68) {
        incrementIndex(1);
      }
    }
  });

  console.log('images loaded');
}

function incrementIndex(amount) {
  imgIndex += amount;

  if (imgIndex < 0) {
    imgIndex = imgLength - 1;
  }

  if (imgIndex >= imgLength) {
    imgIndex = 0;
  }

  console.log(imgIndex);
  setLightboxImage(imgIndex);
}

function getIndex(event) {
  var target = event.target;

  for (var i = 0; i < imageEls.length; i++) {
    if (imageEls[i] == target) {
      console.log("index is " + i);
      return i;
    }
  }
}

function lightboxToggle() {
  if (lightboxVis) {
    lightbox.classList.add('lightbox-hidden');
    lightbox.classList.remove('lightbox-visible');

    body.classList.remove('no-scroll');

    lightboxVis = false;
  } else {
    lightbox.classList.add('lightbox-visible');
    lightbox.classList.remove('lightbox-hidden');

    body.classList.add('no-scroll');

    lightboxVis = true;

    setLightboxImage();
  }
}

function setLightboxImage() {
  lightboxImg.src = imageSrcs[imgIndex];
}
<|endoftext|>


<commit_before>console.log("hello")
getLocation();
google.maps.event.addDomListener(window, 'load', initialize);

var map;
var infowindow;
var latitude;
var longitude;

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setLatLong);
    } else {
        window.alert("Geolocation is not supported by this browser.");
    }
}

function setLatLong(position) {
  latitude = position.coords.latitude;
  longitude = position.coords.longitude;
  var myLatLng = new google.maps.LatLng(latitude, longitude);
  var myLocation = new google.maps.Marker({
    position: myLatLng,
    map: map,
  });
}

function initialize() {
  var pyrmont = new google.maps.LatLng(37.7613981, -122.40302159999999);

  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: pyrmont,
    zoom: 12
  });

  var request = {
    location: pyrmont,
    radius: 8000,
    types: ['bar'],
    open_now: 'true',
  };
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var image = './imgs/beer_icon.png';
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
    icon: image
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name + ", " + place.rating + " stars");
    infowindow.open(map, this);
  });
}

<commit_msg>update map to center<commit_after>console.log("hello")
getLocation();
google.maps.event.addDomListener(window, 'load', initialize);

var map;
var infowindow;
var latitude;
var longitude;

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(setLatLong);
    } else {
        window.alert("Geolocation is not supported by this browser.");
    }
}

function setLatLong(position) {
  latitude = position.coords.latitude;
  longitude = position.coords.longitude;
  var myLatLng = new google.maps.LatLng(latitude, longitude);
  var myLocation = new google.maps.Marker({
    position: myLatLng,
    map: map,
  });
}

function initialize() {
  var pyrmont = new google.maps.LatLng(latitude, longitude);

  map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: pyrmont,
    zoom: 12
  });

  var request = {
    location: pyrmont,
    radius: 8000,
    types: ['bar'],
    open_now: 'true',
  };
  infowindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      createMarker(results[i]);
    }
  }
}

function createMarker(place) {
  var image = './imgs/beer_icon.png';
  var placeLoc = place.geometry.location;
  var marker = new google.maps.Marker({
    map: map,
    position: place.geometry.location,
    icon: image
  });

  google.maps.event.addListener(marker, 'click', function() {
    infowindow.setContent(place.name + ", " + place.rating + " stars");
    infowindow.open(map, this);
  });
}

<|endoftext|>


<commit_before>"use strict";

window.me = window.me || {};

me.MenuBar = (function() {
	var TOGGLE_SCRIPT_EDITOR = "toggle_script_editor";

	var updateExportButtonsVisibility = function() {
		if (this.map_path) {
			this.export_file_btn.style.display = 'inline-block'
			this.export_file_as_btn.style.display = 'inline-block'
		} else {
			this.export_file_btn.style.display = 'none'
			this.export_file_as_btn.style.display = 'none'
		}
	}

	var clazz = function(map_io, map_exporter) {
		var self = this;
		self.map_io = map_io;
		self.map_exporter = map_exporter;

		self.save_file = document.getElementById('save_file');
		self.save_file.addEventListener('change', function() {
			if (this.value) {
				self.save(this.value);
			}
		});

		self.save_file_btn = document.getElementById('save_file_btn');
		self.save_file_btn.addEventListener('click', function(e) {
			if (self.map_path) {
				self.save(self.map_path);
			} else {
				me.utils.triggerEvent(self.save_file, 'click');
			}
		});

		self.save_file_as_btn = document.getElementById('save_file_as_btn');
		self.save_file_as_btn.addEventListener('click', function(e) {
			self.save_file.value = null;
			me.utils.triggerEvent(self.save_file, 'click');
		});

		self.open_file = document.getElementById('open_file');
		self.open_file.addEventListener('change', function() {
			if (this.value) {
				self.open(this.value);
			}
		});

		self.open_file_btn = document.getElementById('open_file_btn');
		self.open_file_btn.addEventListener('click', function(e) {
			self.open_file.value = null;
			me.utils.triggerEvent(self.open_file, 'click');
		});

		self.export_file = document.getElementById('export_file');
		self.export_file.addEventListener('change', function() {
			if (this.value) {
				self.map_io.map.export_path = this.value;
				self.save(self.map_path);
				self.export(this.value);
			}
		});

		self.export_file_btn = document.getElementById('export_file_btn');
		self.export_file_btn.addEventListener('click', function(e) {
			if (self.export_path || (self.export_path = self.map_io.map.export_path)) {
				self.save(self.map_path);
				self.export(self.export_path);
			} else {
				me.utils.triggerEvent(self.export_file, 'click');
			}
		});

		self.export_file_as_btn = document.getElementById('export_file_as_btn');
		self.export_file_as_btn.addEventListener('click', function(e) {
			self.export_file.value = null;
			me.utils.triggerEvent(self.export_file, 'click');
		});

		self.toogle_script_editor_btn = document.getElementById('map_script_toggle_btn');
		self.toogle_script_editor_btn.addEventListener('click', function(e) {
			self.emitter.emit(TOGGLE_SCRIPT_EDITOR);
		});
	};

	clazz.prototype = {
		save: function(path) {
			try {
				this.map_io.save(path);
				this.map_path = path;
				updateExportButtonsVisibility.call(this);
			} catch (e) {
				alert('Error while saving map: ' + e);
			}
		},

		open: function(path) {
			try {
				this.map_io.open(path);
				this.map_path = path;
				updateExportButtonsVisibility.call(this);
			} catch (e) {
				alert('Error while loading map: ' + e);
			}
		},

		export: function(path) {
			try {
				this.map_exporter.exportMap(path);
				this.export_path = path;
			} catch (e) {
				alert('Error while exporting map: ' + e);
			}
		}
	};

	clazz.TOGGLE_SCRIPT_EDITOR = TOGGLE_SCRIPT_EDITOR;

	return clazz;
})();
<commit_msg>Removed redundant code.<commit_after>"use strict";

window.me = window.me || {};

me.MenuBar = (function() {
	var TOGGLE_SCRIPT_EDITOR = "toggle_script_editor";

	var updateExportButtonsVisibility = function() {
		if (this.map_path) {
			this.export_file_btn.style.display = 'inline-block'
			this.export_file_as_btn.style.display = 'inline-block'
		} else {
			this.export_file_btn.style.display = 'none'
			this.export_file_as_btn.style.display = 'none'
		}
	}

	var clazz = function(map_io, map_exporter) {
		var self = this;
		self.map_io = map_io;
		self.map_exporter = map_exporter;

		self.save_file = document.getElementById('save_file');
		self.save_file.addEventListener('change', function() {
			if (this.value) {
				self.save(this.value);
			}
		});

        self.open_file = document.getElementById('open_file');
		self.open_file.addEventListener('change', function() {
			if (this.value) {
				self.open(this.value);
			}
		});

        self.export_file = document.getElementById('export_file');
		self.export_file.addEventListener('change', function() {
			if (this.value) {
				self.map_io.map.export_path = this.value;
				self.save(self.map_path);
				self.export(this.value);
			}
		});

        var addButton = function(id, callback) {
            var button = document.getElementById(id);
            button.addEventListener('click', callback);
            return button;
        };

		self.save_file_btn = addButton('save_file_btn', function(e) {
			if (self.map_path) {
				self.save(self.map_path);
			} else {
				me.utils.triggerEvent(self.save_file, 'click');
			}
		});

		self.save_file_as_btn = addButton('save_file_as_btn', function(e) {
			self.save_file.value = null;
			me.utils.triggerEvent(self.save_file, 'click');
		});

		self.open_file_btn = addButton('open_file_btn', function(e) {
			self.open_file.value = null;
			me.utils.triggerEvent(self.open_file, 'click');
		});

		self.export_file_btn = addButton('export_file_btn', function(e) {
			if (self.export_path || (self.export_path = self.map_io.map.export_path)) {
				self.save(self.map_path);
				self.export(self.export_path);
			} else {
				me.utils.triggerEvent(self.export_file, 'click');
			}
		});

		self.export_file_as_btn = addButton('export_file_as_btn', function(e) {
			self.export_file.value = null;
			me.utils.triggerEvent(self.export_file, 'click');
		});

		self.toogle_script_editor_btn = addButton('map_script_toggle_btn', function(e) {
			self.emitter.emit(TOGGLE_SCRIPT_EDITOR);
		});
	};

	clazz.prototype = {
		save: function(path) {
			try {
				this.map_io.save(path);
				this.map_path = path;
				updateExportButtonsVisibility.call(this);
			} catch (e) {
				alert('Error while saving map: ' + e);
			}
		},

		open: function(path) {
			try {
				this.map_io.open(path);
				this.map_path = path;
				updateExportButtonsVisibility.call(this);
			} catch (e) {
				alert('Error while loading map: ' + e);
			}
		},

		export: function(path) {
			try {
				this.map_exporter.exportMap(path);
				this.export_path = path;
			} catch (e) {
				alert('Error while exporting map: ' + e);
			}
		}
	};

	clazz.TOGGLE_SCRIPT_EDITOR = TOGGLE_SCRIPT_EDITOR;

	return clazz;
})();
<|endoftext|>


<commit_before>// window.checkAdLoad = function(){
//   var checkAdLoadfunction = function(){
//     var msg = "Ad unit is not present";
//     if($("._teraAdContainer")){
//       console.log("Ad unit is present")
//       msg = "Ad unit is present";
//     }
//     return msg;
//   }
//   checkAdLoadfunction()
//   console.log(checkAdLoadfunction);
//   var validateAd = new CustomEvent("trackAdLoad", { "detail": checkAdLoadfunction});
//   window.dispatchEvent(validateAd);
// }

window.sayHello = function(name){
console.log("Hey "+name);
}

t$(document).ready(function(){
  console.log("Checking the AdInstances.");

  checkAdLoadfunction = function(){
    if(t$("._abmMainAdContainer")){
      console.log("Ad unit is present");
      t$('div').mouseover(function(){
        t$(this).find('._abmAdContainer')
        console.log('Hoverred mouse over tera ad unit')
      });
    }

    setInterval(function(){

      var adLoaded = checkAdLoad();
      console.log("HE")
      console.log(adLoaded)
      console.log("HE")
      var validateAd = new CustomEvent("adLoaded", { "info": adLoaded,"detail":adLoaded});

      window.dispatchEvent(validateAd);
    }, 3000);

  }
});
<commit_msg>JS change<commit_after>// window.checkAdLoad = function(){
//   var checkAdLoadfunction = function(){
//     var msg = "Ad unit is not present";
//     if($("._teraAdContainer")){
//       console.log("Ad unit is present")
//       msg = "Ad unit is present";
//     }
//     return msg;
//   }
//   checkAdLoadfunction()
//   console.log(checkAdLoadfunction);
//   var validateAd = new CustomEvent("trackAdLoad", { "detail": checkAdLoadfunction});
//   window.dispatchEvent(validateAd);
// }

window.sayHello = function(name){
console.log("Hey "+name);
}

function checkAdLoad(){
  if(t$("._abmMainAdContainer")){
    return "Ad is Present";
  } else {
    return "Ad is Absent"
  }
}

setInterval(function(){

  var adLoaded = checkAdLoad();
  console.log(adLoaded)
  console.log("HE")
  var validateAd = new CustomEvent("adLoaded", { "info": adLoaded,"detail":adLoaded});

  window.dispatchEvent(validateAd);
}, 3000);

t$(document).ready(function(){
  console.log("Checking the AdInstances.");
  window.checkAdLoadfunction = function(){
    if(t$("._abmMainAdContainer")){
      console.log("Ad unit is present");
      t$('div').mouseover(function(){
        t$(this).find('._abmAdContainer')
        console.log('Hoverred mouse over tera ad unit')
      });
    }
  }
});
<|endoftext|>


<commit_before>var map,
    dropbox = document.getElementById('map-canvas'),
    log = document.getElementById('log'),
    stat_div = document.getElementById('status'),
    curr_info,
    done = 0,
    processing = 0,
    reader = new FileReader(),
    img = new Image(),
    maxWidth = 100,
    maxHeight = 100;

function addInfoWindow(marker, thumbnail_data, width, height, lat, lon) {
  var infoWindow = new google.maps.InfoWindow({
    content: '' +
              '
Lat: ' + lat + '
Lon: ' + lon + '
'
  });

  google.maps.event.addListener(marker, 'click', function () {
    if(curr_info) curr_info.close();
    infoWindow.open(map, marker);
    curr_info = infoWindow;
  });
}

function initialize() {
  var mapOptions = {
    zoom: 2,
    center: new google.maps.LatLng(45.012143, 16.347125),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function updateStatus() {
  if(done == processing) {
    done = processing = 0;
    stat_div.innerHTML = "";
  }
  else stat_div.innerHTML = "(Processing... " + done + "/" + processing + ")";
}

// Handle each file that was dropped (you can drop multiple at once)
function drop(e) {
  no_bubble(e);
  var files = e.target.files || e.dataTransfer.files;
  processing = files.length;
  updateStatus();
  process_file(files, 0, files.length);
  return false;
}

// Prevent event from bubbling up
function no_bubble(e) {
  e.stopPropagation();
  e.preventDefault();
}

/**
 * Extracts information from the i'th file
 * of files and posts on map. Uses recursion
 * for enforcing 1-by-1 processing.
 * @param  {Array}        files files list to process
 * @param  {Number} i     index of file in files to process
 * @param  {Number} n     number of files in files
 * @return {Undefined}    undefined
 */
function process_file(files, i, n) {
  if(i == n) return;
  var file = files[i],
      marker = new google.maps.Marker({
        map: map,
        flat: true
      });

  if (file.slice) {
    filePart = file.slice(0, 131072);
  } else if (file.webkitSlice) {
      filePart = file.webkitSlice(0, 131072);
  } else if (file.mozSlice) {
      filePart = file.mozSlice(0, 131072);
  } else {
    filePart = file;
  }

  reader.readAsBinaryString(filePart);

  reader.onloadend = function (event) {
    var exif_data = EXIF.readFromBinaryFile(new BinaryFile(event.target.result));

    if(!exif_data || !exif_data.GPSLatitude || !exif_data.GPSLongitude) {
      // No GPS data available
      done++;
      updateStatus();
      process_file(files, i+1, n); // process next file
    }
    else {
      var lat = exif_data.GPSLatitude;
      var lon = exif_data.GPSLongitude;
      var lat_deg = (lat[0] + (lat[1]/60.0) + (lat[2]/3600.0)).toFixed(6);
      var lon_deg = (lon[0] + (lon[1]/60.0) + (lon[2]/3600.0)).toFixed(6);

      if(exif_data.GPSLatitudeRef.indexOf("S") != -1) lat_deg *= -1;
      if(exif_data.GPSLongitudeRef.indexOf("W") != -1) lon_deg *= -1;
      marker.setPosition(new google.maps.LatLng(lat_deg, lon_deg));

      var imageWidth = exif_data.PixelXDimension,
          imageHeight = exif_data.PixelYDimension;

        if (imageWidth > imageHeight) {
          if (imageWidth > maxWidth) {
            imageHeight *= maxWidth / imageWidth;
            imageWidth = maxWidth;
          }
        }
        else {
          if (imageHeight > maxHeight) {
            imageWidth *= maxHeight / imageHeight;
            imageHeight = maxHeight;
          }
        }

      if(exif_data.thumbnail) {
        // yay! thumbnail found!
        addInfoWindow(marker, exif_data.thumbnail, imageWidth, imageHeight, lat_deg, lon_deg);
        done++;
        updateStatus();
        process_file(files, i+1, n); // process next file
      }
      else {
        // load image fully for thumbnail --> slow! :(
        reader.onloadend = function (event) {
          img.src = event.target.result;
          img.onload = function() { // image loaded in img?

            var canvas = document.createElement('canvas');
            canvas.width = imageWidth;
            canvas.height = imageHeight;

            var ctx = canvas.getContext("2d");
            // redraw smaller
            ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
            var thumbnail_data = canvas.toDataURL("image/jpeg");
            addInfoWindow(marker, thumbnail_data, imageWidth, imageHeight, lat_deg, lon_deg);

            done++;
            updateStatus();
            process_file(files, i+1, n); // process next file
          };
        };
        reader.readAsDataURL(file); //read original file
      }
    }
  };
}

dropbox.addEventListener("drop", drop, false);
dropbox.addEventListener("dragleave", no_bubble, false);
dropbox.addEventListener("dragexit", no_bubble, false);
dropbox.addEventListener("dragover", no_bubble, false);

google.maps.event.addDomListener(window, 'load', initialize);
<commit_msg>Improve initial maps location<commit_after>var map,
    dropbox = document.getElementById('map-canvas'),
    log = document.getElementById('log'),
    stat_div = document.getElementById('status'),
    curr_info,
    done = 0,
    processing = 0,
    reader = new FileReader(),
    img = new Image(),
    maxWidth = 100,
    maxHeight = 100;

function addInfoWindow(marker, thumbnail_data, width, height, lat, lon) {
  var infoWindow = new google.maps.InfoWindow({
    content: '' +
              '
Lat: ' + lat + '
Lon: ' + lon + '
'
  });

  google.maps.event.addListener(marker, 'click', function () {
    if(curr_info) curr_info.close();
    infoWindow.open(map, marker);
    curr_info = infoWindow;
  });
}

function initialize() {
  var mapOptions = {
    zoom: 2,
    center: new google.maps.LatLng(51.985511, 34.628375),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function updateStatus() {
  if(done == processing) {
    done = processing = 0;
    stat_div.innerHTML = "";
  }
  else stat_div.innerHTML = "(Processing... " + done + "/" + processing + ")";
}

// Handle each file that was dropped (you can drop multiple at once)
function drop(e) {
  no_bubble(e);
  var files = e.target.files || e.dataTransfer.files;
  processing = files.length;
  updateStatus();
  process_file(files, 0, files.length);
  return false;
}

// Prevent event from bubbling up
function no_bubble(e) {
  e.stopPropagation();
  e.preventDefault();
}

/**
 * Extracts information from the i'th file
 * of files and posts on map. Uses recursion
 * for enforcing 1-by-1 processing.
 * @param  {Array}        files files list to process
 * @param  {Number} i     index of file in files to process
 * @param  {Number} n     number of files in files
 * @return {Undefined}    undefined
 */
function process_file(files, i, n) {
  if(i == n) return;
  var file = files[i],
      marker = new google.maps.Marker({
        map: map,
        flat: true
      });

  if (file.slice) {
    filePart = file.slice(0, 131072);
  } else if (file.webkitSlice) {
      filePart = file.webkitSlice(0, 131072);
  } else if (file.mozSlice) {
      filePart = file.mozSlice(0, 131072);
  } else {
    filePart = file;
  }

  reader.readAsBinaryString(filePart);

  reader.onloadend = function (event) {
    var exif_data = EXIF.readFromBinaryFile(new BinaryFile(event.target.result));

    if(!exif_data || !exif_data.GPSLatitude || !exif_data.GPSLongitude) {
      // No GPS data available
      done++;
      updateStatus();
      process_file(files, i+1, n); // process next file
    }
    else {
      var lat = exif_data.GPSLatitude;
      var lon = exif_data.GPSLongitude;
      var lat_deg = (lat[0] + (lat[1]/60.0) + (lat[2]/3600.0)).toFixed(6);
      var lon_deg = (lon[0] + (lon[1]/60.0) + (lon[2]/3600.0)).toFixed(6);

      if(exif_data.GPSLatitudeRef.indexOf("S") != -1) lat_deg *= -1;
      if(exif_data.GPSLongitudeRef.indexOf("W") != -1) lon_deg *= -1;
      marker.setPosition(new google.maps.LatLng(lat_deg, lon_deg));

      var imageWidth = exif_data.PixelXDimension,
          imageHeight = exif_data.PixelYDimension;

        if (imageWidth > imageHeight) {
          if (imageWidth > maxWidth) {
            imageHeight *= maxWidth / imageWidth;
            imageWidth = maxWidth;
          }
        }
        else {
          if (imageHeight > maxHeight) {
            imageWidth *= maxHeight / imageHeight;
            imageHeight = maxHeight;
          }
        }

      if(exif_data.thumbnail) {
        // yay! thumbnail found!
        addInfoWindow(marker, exif_data.thumbnail, imageWidth, imageHeight, lat_deg, lon_deg);
        done++;
        updateStatus();
        process_file(files, i+1, n); // process next file
      }
      else {
        // load image fully for thumbnail --> slow! :(
        reader.onloadend = function (event) {
          img.src = event.target.result;
          img.onload = function() { // image loaded in img?

            var canvas = document.createElement('canvas');
            canvas.width = imageWidth;
            canvas.height = imageHeight;

            var ctx = canvas.getContext("2d");
            // redraw smaller
            ctx.drawImage(this, 0, 0, imageWidth, imageHeight);
            var thumbnail_data = canvas.toDataURL("image/jpeg");
            addInfoWindow(marker, thumbnail_data, imageWidth, imageHeight, lat_deg, lon_deg);

            done++;
            updateStatus();
            process_file(files, i+1, n); // process next file
          };
        };
        reader.readAsDataURL(file); //read original file
      }
    }
  };
}

dropbox.addEventListener("drop", drop, false);
dropbox.addEventListener("dragleave", no_bubble, false);
dropbox.addEventListener("dragexit", no_bubble, false);
dropbox.addEventListener("dragover", no_bubble, false);

google.maps.event.addDomListener(window, 'load', initialize);
<|endoftext|>


<commit_before>var testData = {
  "001": { "num":"001", "name":"Bulbasuar"},
  "002": { "num":"002", "name":"Ivysaur"},
  "003": { "num":"003", "name":"Venusaur"},
  "004": { "num":"004", "name":"Charmander"},
  "005": { "num":"005", "name":"Charmeleon"},
  "006": { "num":"006", "name":"Charizard"},
  "007": { "num":"007", "name":"Squirtle"},
  "008": { "num":"008", "name":"Wartortle"},
  "009": { "num":"009", "name":"Blastoise"}
}<commit_msg>add more items<commit_after>var testData = var testData = {
  "001": { "num":"001", "name":"Bulbasaur"},
  "002": { "num":"002", "name":"Ivysaur"},
  "003": { "num":"003", "name":"Venusaur"},
  "004": { "num":"004", "name":"Charmander"},
  "005": { "num":"005", "name":"Charmeleon"},
  "006": { "num":"006", "name":"Charizard"},
  "007": { "num":"007", "name":"Squirtle"},
  "008": { "num":"008", "name":"Wartortle"},
  "009": { "num":"009", "name":"Blastoise"},
  "010": { "num":"010", "name":"Caterpie"},
  "011": { "num":"011", "name":"Metapod"},
  "012": { "num":"012", "name":"Butterfree"},
  "013": { "num":"013", "name":"Weedle"},
  "014": { "num":"014", "name":"Kakuna"},
  "015": { "num":"015", "name":"Beedrill"},
  "016": { "num":"016", "name":"Pidgey"},
  "017": { "num":"017", "name":"Pidgeotto"},
  "018": { "num":"018", "name":"Pidgeot"},
  "019": { "num":"019", "name":"Rattata"},
  "020": { "num":"020", "name":"Raticate"},
  "021": { "num":"021", "name":"Spearow"},
  "022": { "num":"022", "name":"Fearow"},
  "023": { "num":"023", "name":"Ekans"},
  "024": { "num":"024", "name":"Arbok"},
  "025": { "num":"025", "name":"Pikachu"},
  "026": { "num":"026", "name":"Raichu"},
  "027": { "num":"027", "name":"Sandshrew"},
  "028": { "num":"028", "name":"Sandslash"},
  "029": { "num":"029", "name":"Nidoran ♀"},
  "030": { "num":"030", "name":"Nidorina"},
  "031": { "num":"031", "name":"Nidoqueen"},
  "032": { "num":"032", "name":"Nidoran ♂"},
  "033": { "num":"033", "name":"Nidorino"},
  "034": { "num":"034", "name":"Nidoking"},
  "035": { "num":"035", "name":"Clefairy"}
}
<|endoftext|>


<commit_before>var projects_table;
        // Set this up like this to make it easier to dev this locally -- evz
        var data_host = 'http://codeforamerica.org/api/organizations/Code-for-San-Francisco/projects';
        // var data_host = 'http://civic-json.datamade.dev.work'

        // helper function for displaying messages when submitting projects
        function displayMessage(message, type) {
          $( "#submit-message" ).fadeOut(function() {
            $( "#submit-message" ).attr('class', 'alert alert-' + type);
            $( "#submit-message" ).html(message);
          });
          $( "#submit-message" ).fadeIn();
        }

        $('#share-toggle').click(function(){
          $('#share-project').slideToggle();
          return false;
        });

        $('#project-needs').click(function(){
          projects_table.fnFilter( 'project needs' );
          $.address.parameter('search', 'project needs');
          $('#hack-night-projects').ScrollTo();
          return false;
        });

        // AJAX form submission to civic-json-worker
        // https://github.com/open-city/civic-json-worker
        $('#submit-project').click(function(){

          $.post(
            data_host + '/add-project/',
            data={'project_url': $('#github-url').val()},
            function(resp){
              displayMessage( "Your project has been submitted! It should display below within 5 minutes.", 'success' );
              $("#github-url").val("");
            }
            ).fail(function() {
              displayMessage( "Error submitting your project! Check that the URL is correct.", 'danger' );
            });

            return false;
          });

        // handle the case where someone hits the 'enter' key insted of the submit button
        $("#github-url").keydown(function(e){
          var key =  e.keyCode ? e.keyCode : e.which;
          if(key == 13) {
            $('#submit-project').click();
            return false;
          }
        });

        // this is a template used for mustache.js. Each one represents a table row.
        var template = "\

\
        \

{{name}}
\
        {{#homepage}}\
        Website\
        {{/homepage}}\

Created\
        {{created_at_formatted}}\
        {{#language}}\

Language\
        {{language}}\
        {{/language}}\

\
        {{#participation_percent}}\

{{.}}%
\
        {{/participation_percent}}\
        	\
        \

{{description}}
\

Contributors
\

\
        {{#owner}}\
        \
        {{login}}\
        {{/owner}}\
        {{#contributors}}\
        {{^owner}}\
        \
        {{login}}\
        {{/owner}}\
        {{/contributors}}\

\
        {{#has_project_needs}}\

Project needs
\
        {{#project_needs}}\
        {{title}}\
        {{/project_needs}}\
        {{/has_project_needs}}\
        	\
        \
        {{recent_commits}} \
        	\
        \
        {{watchers_count}} \
        	\
        \
        {{forks_count}} \
        	\
        \
        {{open_issues}} \
        	\

\
        ";

        $('#hack-night-projects tbody').spin({top: '40px'}); //show a spinner while loading data

        // The projects list to display
        var projects = []

        // Show off the projects
        function showProjects(data, textStatus, jqXHR){

          // Fill up the projects list
          projects = projects.concat(data.objects);

          // Follow next page links
          if (data.pages.next) {
            $.when( $.getJSON(data.pages.next) ).then(showProjects);

          } else {

            // update project count at the top of the page
            $('#project-count').html(Object.keys(projects).length);
            // loop through our json data
            $.each(projects, function(i, json){
              json=json.github_details;
              var participation = [];
              var max_participation = 50;
              if (json['participation']) {
                for (var i = 0; i < json['participation'].length; i++) {
                  var val = ((json['participation'][i] + 1) / parseFloat(max_participation)) * 100;
                  if (val > 100) val = 100;
                  participation.push(val)
                }
                json['participation_percent'] = participation;

                var recent_commits = 0;
                var recent_commits_arr = json['participation'].splice(48,4); // get the last 4 weeks
                $.each(recent_commits_arr, function() {
                  recent_commits += this;
                });

                json['recent_commits'] = recent_commits;
              }

              // to display text like 'x days ago' we use moment.js's awesome fromNow function
              // http://momentjs.com/docs/#/displaying/fromnow/
              json['created_at_formatted'] = moment(json['created_at']).fromNow();
              json['updated_at_formatted'] = moment(json['updated_at']).fromNow();
              json['has_project_needs'] = (json['project_needs'].length > 0);

              // check to make sure all our URL's have http:// in front of them
              // otherwise they won't link properly
              var prefix_regex = /^https?:\/\/.*/;
              var homepage = json['homepage'];
              if (homepage != null && !prefix_regex.test(homepage))
                json['homepage_formatted'] = "http://" + homepage;
              else
                json['homepage_formatted'] = homepage;

              // using the template above, add the project as a new row to our table
              $("#hack-night-projects tbody").append(Mustache.render(template, json));
            })

            // initialize datatables for sorting and searching
            // http://datatables.net/
            projects_table = $('#hack-night-projects').dataTable( {
              "aaSorting": [ [2,'desc'], [3, 'desc'] ],
              "aoColumns": [
              null,
              null,
              { "sType": "num-html" },
              { "sType": "num-html" },
              { "sType": "num-html" },
              { "sType": "num-html" }
              ],
              "bInfo": false,
              "bPaginate": false,
              "autoWidth": false,
              "columnDefs": [
                { "width": "345px", "targets": 0}
              ]
            } );

            // allows linking directly to searches
            if ($.address.parameter('search') != undefined)
              projects_table.fnFilter( $.address.parameter('search') );

            // when someone types a search value, it updates the URL
            $('#hack-night-projects_filter input').keyup(function(e){
              $.address.parameter('search', $('#hack-night-projects_filter input').val());
            });
          }
        }

        // Go get projects! Then show them off.
        $.when( $.getJSON(data_host) ).then(showProjects);<commit_msg>Uses the full /projects response, not just github_issues. Also includes issues as project needs<commit_after>var projects_table;
        // Set this up like this to make it easier to dev this locally -- evz
        var data_host = 'http://codeforamerica.org/api/organizations/Code-for-San-Francisco/projects';
        // var data_host = 'http://civic-json.datamade.dev.work'

        // helper function for displaying messages when submitting projects
        function displayMessage(message, type) {
          $( "#submit-message" ).fadeOut(function() {
            $( "#submit-message" ).attr('class', 'alert alert-' + type);
            $( "#submit-message" ).html(message);
          });
          $( "#submit-message" ).fadeIn();
        }

        $('#share-toggle').click(function(){
          $('#share-project').slideToggle();
          return false;
        });

        $('#project-needs').click(function(){
          projects_table.fnFilter( 'project needs' );
          $.address.parameter('search', 'project needs');
          $('#hack-night-projects').ScrollTo();
          return false;
        });

        // AJAX form submission to civic-json-worker
        // https://github.com/open-city/civic-json-worker
        $('#submit-project').click(function(){

          $.post(
            data_host + '/add-project/',
            data={'project_url': $('#github-url').val()},
            function(resp){
              displayMessage( "Your project has been submitted! It should display below within 5 minutes.", 'success' );
              $("#github-url").val("");
            }
            ).fail(function() {
              displayMessage( "Error submitting your project! Check that the URL is correct.", 'danger' );
            });

            return false;
          });

        // handle the case where someone hits the 'enter' key insted of the submit button
        $("#github-url").keydown(function(e){
          var key =  e.keyCode ? e.keyCode : e.which;
          if(key == 13) {
            $('#submit-project').click();
            return false;
          }
        });

        // this is a template used for mustache.js. Each one represents a table row.
        var template = "\

\
        \

{{name}}
\
        {{#github_details.homepage}}\
        Website\
        {{/github_details.homepage}}\

Created\
        {{github_details.created_at_formatted}}\
        {{#github_details.language}}\

Language\
        {{github_details.language}}\
        {{/github_details.language}}\

\
        {{#github_details.participation_percent}}\

{{.}}%
\
        {{/github_details.participation_percent}}\
        	\
        \

{{github_details.description}}
\

Contributors
\

\
        {{#github_details.owner}}\
        \
        {{login}}\
        {{/github_details.owner}}\
        {{#github_details.contributors}}\
        {{^owner}}\
        \
        {{login}}\
        {{/owner}}\
        {{/github_details.contributors}}\

\
        {{#has_project_needs}}\

Project needs
\
        {{#issues}}\
        {{title}}\
        {{/issues}}\
        {{/has_project_needs}}\
        	\
        \
        {{github_details.recent_commits}} \
        	\
        \
        {{github_details.watchers_count}} \
        	\
        \
        {{github_details.forks_count}} \
        	\
        \
        {{github_details.open_issues}} \
        	\

\
        ";

        $('#hack-night-projects tbody').spin({top: '40px'}); //show a spinner while loading data

        // The projects list to display
        var projects = []

        // Show off the projects
        function showProjects(data, textStatus, jqXHR){

          // Fill up the projects list
          projects = projects.concat(data.objects);

          // Follow next page links
          if (data.pages.next) {
            $.when( $.getJSON(data.pages.next) ).then(showProjects);

          } else {

            // update project count at the top of the page
            $('#project-count').html(Object.keys(projects).length);
            // loop through our json data
            $.each(projects, function(i, json){

              var participation = [];
              var max_participation = 50;
              if (json['github_details']['participation']) {
                for (var i = 0; i < json['github_details']['participation'].length; i++) {
                  var val = ((json['github_details']['participation'][i] + 1) / parseFloat(max_participation)) * 100;
                  if (val > 100) val = 100;
                  participation.push(val)
                }
                json['github_details']['participation_percent'] = participation;

                var recent_commits = 0;
                var recent_commits_arr = json['github_details']['participation'].splice(48,4); // get the last 4 weeks
                $.each(recent_commits_arr, function() {
                  recent_commits += this;
                });

                json['github_details']['recent_commits'] = recent_commits;
              }

              // to display text like 'x days ago' we use moment.js's awesome fromNow function
              // http://momentjs.com/docs/#/displaying/fromnow/
              json['github_details']['created_at_formatted'] = moment(json['github_details']['created_at']).fromNow();
              json['github_details']['updated_at_formatted'] = moment(json['github_details']['updated_at']).fromNow();
              json['has_project_needs'] = (json['issues'].length > 0);

              // check to make sure all our URL's have http:// in front of them
              // otherwise they won't link properly
              var prefix_regex = /^https?:\/\/.*/;
              var homepage = json['link_url'];
              if (homepage != null && !prefix_regex.test(homepage))
                json['homepage_formatted'] = "http://" + homepage;
              else
                json['homepage_formatted'] = homepage;

              // using the template above, add the project as a new row to our table
              $("#hack-night-projects tbody").append(Mustache.render(template, json));
            })

            // initialize datatables for sorting and searching
            // http://datatables.net/
            projects_table = $('#hack-night-projects').dataTable( {
              "aaSorting": [ [2,'desc'], [3, 'desc'] ],
              "aoColumns": [
              null,
              null,
              { "sType": "num-html" },
              { "sType": "num-html" },
              { "sType": "num-html" },
              { "sType": "num-html" }
              ],
              "bInfo": false,
              "bPaginate": false,
              "autoWidth": false,
              "columnDefs": [
                { "width": "345px", "targets": 0}
              ]
            } );

            // allows linking directly to searches
            if ($.address.parameter('search') != undefined)
              projects_table.fnFilter( $.address.parameter('search') );

            // when someone types a search value, it updates the URL
            $('#hack-night-projects_filter input').keyup(function(e){
              $.address.parameter('search', $('#hack-night-projects_filter input').val());
            });
          }
        }

        // Go get projects! Then show them off.
        $.when( $.getJSON(data_host) ).then(showProjects);<|endoftext|>


<commit_before>(function() { // TODO: generate the requerd wrappers and styles for scrolling
  var Scroller = this.Scroller = function() {
    return this._init.apply(this, arguments);
  },
  p = Scroller.prototype;

  p._init = function(el) {
    this.$el = $(el);

    this.lastCurY = this.prevY = this.curY = 0;
    this.$el.on('mousedown touchstart', this._start.bind(this));
    this.$el.on('touchmove mousemove', this._move.bind(this));
    $(window).on('mouseup touchend touchcancel', this._end.bind(this)); // stop scrolling if mouse lifted outside of the window

    return this.$el;
  }

  p._start = function(e) {
    this.mouseClick = true;
    this.prevY = this._getPositionY(e);
    this.lastCurY = this.curY;
    this.$el.trigger('scroll:start');
    e.preventDefault();
  }

  p._move = function(e) {
    if((!e.touches || !e.touches.length) && !this.mouseClick)
      return;

    // mobile doesn't have start event
    if(!this.prevY)
      this._start(e);

    this._updateCurY(e);

    // TODO: do this whithin requestAnimationFrame or even better my game loop, hmm maybe browser handling the transform request internaly and u dont need requestAnimationFrame
    this.$el.css('-webkit-transform', 'translateY(' + this.curY + 'px)');
    this.$el.css('-moz-transform', 'translateY(' + this.curY + 'px)');

    this.$el.trigger('scroll:move');
  }

  p._end = p._cancel = function(e) {
    this.$el.trigger('scroll:end');

    // trigger click only when mouse moved less then 1 px
    if(Math.abs(this.lastCurY - this.curY) < 1)
      this.$el.trigger('scroll:click', e);

    this.mouseClick = false;
    this.prevY = null;
  }

  p._updateCurY = function(e) {
    this.y = this._getPositionY(e);
    this.curY += this.y - this.prevY;
    this.viewPortY = this.$el.height() - $(window).height();

    // make sure we stay in the boundaries of the device
    this.curY = this.curY > 0 ? 0 : (this.curY < -this.viewPortY ? -this.viewPortY : this.curY);
    this.prevY = this.y;
  }

  p._getPositionY = function(e) {
    return e.screenY || e.touches[0].screenY;
  }
})();
<commit_msg>minor fix<commit_after>(function() { // TODO: generate the requerd wrappers and styles for scrolling
  var Scroller = this.Scroller = function() {
    return this._init.apply(this, arguments);
  },
  p = Scroller.prototype;

  p._init = function(el) {
    this.$el = $(el);

    this.lastCurY = this.prevY = this.curY = 0;
    this.$el.on('mousedown touchstart', this._start.bind(this));
    this.$el.on('touchmove mousemove', this._move.bind(this));
    $(window).on('mouseup touchend touchcancel', this._end.bind(this)); // stop scrolling if mouse lifted outside of the window

    return this.$el;
  }

  p._start = function(e) {
    this.mouseClick = true;
    this.prevY = this._getPositionY(e);
    this.lastCurY = this.curY;
    this.$el.trigger('scroll:start');
    e.preventDefault();
  }

  p._move = function(e) {
    if((!e.touches || !e.touches.length) && !this.mouseClick)
      return;

    // mobile doesn't have start event
    if(!this.prevY)
      this._start(e);

    this._updateCurY(e);

    // TODO: do this whithin requestAnimationFrame or even better my game loop, hmm maybe browser handling the transform request internaly and u dont need requestAnimationFrame
    this.$el.css('-webkit-transform', 'translateY(' + this.curY + 'px)');
    this.$el.css('-moz-transform', 'translateY(' + this.curY + 'px)');

    this.$el.trigger('scroll:move');
  }

  p._end = p._cancel = function(e) {
    if(!this.mouseClick && !this.prevY)
      return;

    this.$el.trigger('scroll:end');

    // trigger click only when mouse moved less then 1 px
    if(Math.abs(this.lastCurY - this.curY) < 1)
      this.$el.trigger('scroll:click', e);

    this.mouseClick = false;
    this.prevY = null;
  }

  p._updateCurY = function(e) {
    this.y = this._getPositionY(e);
    this.curY += this.y - this.prevY;
    this.viewPortY = this.$el.height() - $(window).height();

    // make sure we stay in the boundaries of the device
    this.curY = this.curY > 0 ? 0 : (this.curY < -this.viewPortY ? -this.viewPortY : this.curY);
    this.prevY = this.y;
  }

  p._getPositionY = function(e) {
    return e.screenY || e.touches[0].screenY;
  }
})();
<|endoftext|>