<commit_before>Teikei.module("User", function(User, Teikei, Backbone, Marionette, $, _) {

  User.MenuView = Marionette.ItemView.extend({

    el: "#user-menu",

    template: "user/menu",

    ui: {
      signIn: "#signin",
      userName: "#user-menu-toggle",
      participateMenuItem: "#participate",
      myEntriesMenuItem: "#my-entries",
      newEntryMenuItem: "#new-entry",
      newEntryDropdown: "#new-entry .dropdown",
      userDropdown: ".account-menu .dropdown"
    },

    events: {
      "click #new-entry": "openNewEntryDropdown",
      "click #user-name": "openUserDropdown",
      "click #signup": "onSignUp",
      "click #add-farm": "addFarm",
      "click #add-depot": "addDepot",
      "click #my-entries": "showEntryList",
      "click #participate": "onParticipate"
    },

    triggers: {
      "click #signin": "signin:selected",
    },

    initialize: function() {
      this.bindUIElements();
      this.invalidate();
      Teikei.vent.on("user:signin:success", this.invalidate, this);
    },

    invalidate: function() {
      this.model = Teikei.currentUser;
      if (Teikei.currentUser) {
        this.renderSignedInState();
      }
      else {
        this.renderSignedOutState();
      }
    },

    openNewEntryDropdown: function() {
      this.openDropdown(this.ui.newEntryDropdown);
    },

    // TODO Merge function with duplicate in entryList.js
    openDropdown: function(dropdown) {
      dropdown.show();
      _.defer( function() {
        $("body").one("click", function() {
          dropdown.hide();
        });
      });
    },

    addFarm: function(event) {
      event.preventDefault();
      Teikei.vent.trigger("user:add:farm");
    },

    addDepot: function(event) {
      event.preventDefault();
      Teikei.vent.trigger("user:add:depot");
    },

    showEntryList: function(event) {
      event.preventDefault();
      Teikei.vent.trigger("user:show:entrylist");
    },

    onParticipate: function(event) {
      event.preventDefault();
      Teikei.vent.trigger("show:participate:1");
    },

    onSignUp: function(event) {
      event.preventDefault();
      this.trigger("signup:selected");
    },

    renderSignedInState: function() {
      this.render();
      this.ui.signIn.hide();
      this.ui.participateMenuItem.hide();
      this.ui.userName.show();
      this.ui.newEntryMenuItem.show();
      this.ui.myEntriesMenuItem.show();
    },

    renderSignedOutState: function() {
      this.render();
      this.ui.signIn.show();
      this.ui.participateMenuItem.show();
      this.ui.userName.hide();
      this.ui.newEntryMenuItem.hide();
      this.ui.myEntriesMenuItem.hide();
      this.ui.userDropdown.hide();
    }

  });
});
<commit_msg>Remove dead code from menu.js view.<commit_after>Teikei.module("User", function(User, Teikei, Backbone, Marionette, $, _) {

  User.MenuView = Marionette.ItemView.extend({

    el: "#user-menu",

    template: "user/menu",

    ui: {
      signIn: "#signin",
      myEntriesMenuItem: "#my-entries",
      newEntryMenuItem: "#new-entry",
      newEntryDropdown: "#new-entry .dropdown",
      userDropdown: ".account-menu .dropdown"
    },

    events: {
      "click #new-entry": "openNewEntryDropdown",
      "click #signup": "onSignUp",
      "click #add-farm": "addFarm",
      "click #add-depot": "addDepot",
      "click #my-entries": "showEntryList",
    },

    triggers: {
      "click #signin": "signin:selected",
    },

    initialize: function() {
      this.bindUIElements();
      this.invalidate();
      Teikei.vent.on("user:signin:success", this.invalidate, this);
    },

    invalidate: function() {
      this.model = Teikei.currentUser;
      if (Teikei.currentUser) {
        this.renderSignedInState();
      }
      else {
        this.renderSignedOutState();
      }
    },

    openNewEntryDropdown: function() {
      this.openDropdown(this.ui.newEntryDropdown);
    },

    // TODO Merge function with duplicate in entryList.js
    openDropdown: function(dropdown) {
      dropdown.show();
      _.defer( function() {
        $("body").one("click", function() {
          dropdown.hide();
        });
      });
    },

    addFarm: function(event) {
      event.preventDefault();
      Teikei.vent.trigger("user:add:farm");
    },

    addDepot: function(event) {
      event.preventDefault();
      Teikei.vent.trigger("user:add:depot");
    },

    showEntryList: function(event) {
      event.preventDefault();
      Teikei.vent.trigger("user:show:entrylist");
    },

    onSignUp: function(event) {
      event.preventDefault();
      this.trigger("signup:selected");
    },

    renderSignedInState: function() {
      this.render();
      this.ui.signIn.hide();
      this.ui.userName.show();
      this.ui.newEntryMenuItem.show();
      this.ui.myEntriesMenuItem.show();
    },

    renderSignedOutState: function() {
      this.render();
      this.ui.signIn.show();
      this.ui.userName.hide();
      this.ui.newEntryMenuItem.hide();
      this.ui.myEntriesMenuItem.hide();
      this.ui.userDropdown.hide();
    }

  });
});
<|endoftext|>


<commit_before>// ------------------------------ CRUD -------------------------------------
var Requests = {
  // Record create along ajax
	createByAjax: function(grid, continue_on) {
		var createFormElement = $('#new_' + grid.name);
		// clear all the error messages
		createFormElement.find(".field_error").text("");
		$.ajax({
   		type:'POST',
   		url: grid.path + '.json',
   		data: createFormElement.serialize() + "&authenticity_token=" + window._token,
   		success: function(request) {
			  var errors = "";

				if (request.success == true) {
					gridManager.createdIds.push(request.id);
					Ui.resetForm(grid.name);
					grid.loader.reloadData();
					if (!continue_on) { Ui.closeDialog(grid.name); }
				} else {
					for(key in request.error_message){
					  for(i in request.error_message[key]){
					    errors += (request.error_message[key][i] + " ")
					  }
					  createFormElement.find(".field[name=" + key + "]").find(".field_error").text(errors);
					}
				}
			}
 		});
	},

	// Delete rows along ajax
	deleteByAjax: function(grid, ids) {
		$.ajax({
			type: 'POST',
			url: grid.path + '/' + ids + '.json',
			data: decodeURIComponent($.param({_method: 'DELETE', authenticity_token: window._token})),
			success: function(msg) {
				if(msg.success == true) {
					grid.setSelectedRows([]);
					grid.loader.reloadData();
					Ui.flashNotice(ids, 'delete');
				} else {
					alert(msg.error_message);
				}
			}
		})
	},

	updateByAjax: function(grid, item) {
		delete item.slick_index;
		// format item data like time, date
		// format_data(item);
		// put ajax
		$.ajax({
			type: "POST",
			url: grid.path + "/" + item.id + ".json",
			data: decodeURIComponent($.param({_method: 'PUT', item: item, authenticity_token: window._token})),
			success: function(msg) {
				if(msg.success == true) {

				} else {
					alert(msg.error_message);
					grid.loader.reloadData();
				}
			}
		});
	},
}; // Requests<commit_msg>Error message js hander bug fix<commit_after>// ------------------------------ CRUD -------------------------------------
var Requests = {
  // Record create along ajax
	createByAjax: function(grid, continue_on) {
		var createFormElement = $('#new_' + grid.name);
		// clear all the error messages
		createFormElement.find(".field_error").text("");
		$.ajax({
   		type:'POST',
   		url: grid.path + '.json',
   		data: createFormElement.serialize() + "&authenticity_token=" + window._token,
   		success: function(request) {
				if (request.success == true) {
					gridManager.createdIds.push(request.id);
					Ui.resetForm(grid.name);
					grid.loader.reloadData();
					if (!continue_on) { Ui.closeDialog(grid.name); }
				} else {
					for(key in request.error_message){
					  createFormElement.find(".field[name=" + key + "]").find(".field_error").text(request.error_message[key].join());
					}
				}
			}
 		});
	},

	// Delete rows along ajax
	deleteByAjax: function(grid, ids) {
		$.ajax({
			type: 'POST',
			url: grid.path + '/' + ids + '.json',
			data: decodeURIComponent($.param({_method: 'DELETE', authenticity_token: window._token})),
			success: function(msg) {
				if(msg.success == true) {
					grid.setSelectedRows([]);
					grid.loader.reloadData();
					Ui.flashNotice(ids, 'delete');
				} else {
					alert(msg.error_message);
				}
			}
		})
	},

	updateByAjax: function(grid, item) {
		delete item.slick_index;
		// format item data like time, date
		// format_data(item);
		// put ajax
		$.ajax({
			type: "POST",
			url: grid.path + "/" + item.id + ".json",
			data: decodeURIComponent($.param({_method: 'PUT', item: item, authenticity_token: window._token})),
			success: function(msg) {
				if(msg.success == true) {

				} else {
					alert(msg.error_message);
					grid.loader.reloadData();
				}
			}
		});
	},
}; // Requests<|endoftext|>


<commit_before>// handles ajax search functionality
define(['util/util'],
	function(util) {
  'use strict';

  	// PRIVATE PROPERTIES
		// search parameter values
		var _keyword,
				_location;

		var _findBtn; // find button on homepage
		var _updateBtn; // update button on inside page

		var _callback; // function to execute when items are clicked

		// PUBLIC METHODS
		function init(callback)
		{
			_callback = callback;
			_keyword = document.getElementById("keyword");
			_location = document.getElementById("location");

			_findBtn = document.getElementById('find-btn');
			_updateBtn = document.getElementById('update-btn');

			// if no ajax callback is given, don't register ajax calls
			if (callback)
			{
				_updateBtn.addEventListener("click",_searchFormSubmittedHandler,false);
				_findBtn.addEventListener("click",_searchFormSubmittedHandler,false);
				_registerAjaxHooks();
			}
		}

		function refresh(scope)
		{
			_registerAjaxHooks(scope)
		}

		// getters and setters for keyword and location
		function getKeyword()
		{
			return _keyword.value;
		}

		function setKeyword(value)
		{
			_keyword.value = value;
		}

		function getLocation()
		{
			return _location.value;
		}

		function setLocation(value)
		{
			_location.value = value;
		}

		// PRIVATE METHODS

		// register all links with "ajax-link" class added as ajax-enabled links
		function _registerAjaxHooks(scope)
		{
			scope = scope || ""
			scope+=" .ajax-link";
			var lnks = document.querySelectorAll(scope);

			var curr;
			for (var l=0; l < lnks.length; l++)
			{
				curr = lnks[l];
				curr.addEventListener("click", _linkClickedHandler, false);
			}
		}

		function _searchFormSubmittedHandler(evt)
		{
			var params = util.getQueryParams(window.location.search);
			params.keyword = getKeyword();
			params.location = getLocation();
			params.page = 1;
			_callback.performSearch(params);

			evt.preventDefault();
			return false;
		}

		function _linkClickedHandler(evt)
		{
			var params = util.getQueryParams(this.search);
			var id = this.pathname.substring(this.pathname.lastIndexOf("/")+1, this.pathname.length);
			if (id != 'organizations')
				params.id = id;

			_callback.performSearch(params);

			evt.preventDefault();
			return false;
		}

	return {
		init:init,
		refresh:refresh,
		getKeyword:getKeyword,
		setKeyword:setKeyword,
		getLocation:getLocation,
		setLocation:setLocation
	};
});<commit_msg>Add checks for existence of button elements<commit_after>// handles ajax search functionality
define(['util/util'],
	function(util) {
  'use strict';

  	// PRIVATE PROPERTIES
		// search parameter values
		var _keyword,
				_location;

		var _findBtn; // find button on homepage
		var _updateBtn; // update button on inside page

		var _callback; // function to execute when items are clicked

		// PUBLIC METHODS
		function init(callback)
		{
			_callback = callback;
			_keyword = document.getElementById("keyword");
			_location = document.getElementById("location");

			_findBtn = document.getElementById('find-btn');
			_updateBtn = document.getElementById('update-btn');

			// if no ajax callback is given, don't register ajax calls
			if (callback)
			{
				if (_updateBtn) _updateBtn.addEventListener("click",_searchFormSubmittedHandler,false);
				if (_findBtn) _findBtn.addEventListener("click",_searchFormSubmittedHandler,false);
				_registerAjaxHooks();
			}
		}

		function refresh(scope)
		{
			_registerAjaxHooks(scope)
		}

		// getters and setters for keyword and location
		function getKeyword()
		{
			return _keyword.value;
		}

		function setKeyword(value)
		{
			_keyword.value = value;
		}

		function getLocation()
		{
			return _location.value;
		}

		function setLocation(value)
		{
			_location.value = value;
		}

		// PRIVATE METHODS

		// register all links with "ajax-link" class added as ajax-enabled links
		function _registerAjaxHooks(scope)
		{
			scope = scope || ""
			scope+=" .ajax-link";
			var lnks = document.querySelectorAll(scope);

			var curr;
			for (var l=0; l < lnks.length; l++)
			{
				curr = lnks[l];
				curr.addEventListener("click", _linkClickedHandler, false);
			}
		}

		function _searchFormSubmittedHandler(evt)
		{
			var params = util.getQueryParams(window.location.search);
			params.keyword = getKeyword();
			params.location = getLocation();
			params.page = 1;
			_callback.performSearch(params);

			evt.preventDefault();
			return false;
		}

		function _linkClickedHandler(evt)
		{
			var params = util.getQueryParams(this.search);
			var id = this.pathname.substring(this.pathname.lastIndexOf("/")+1, this.pathname.length);
			if (id != 'organizations')
				params.id = id;

			_callback.performSearch(params);

			evt.preventDefault();
			return false;
		}

	return {
		init:init,
		refresh:refresh,
		getKeyword:getKeyword,
		setKeyword:setKeyword,
		getLocation:getLocation,
		setLocation:setLocation
	};
});<|endoftext|>


<commit_before>$(document).ready(function(){
  // todos for this file
  // make it OO
  drawChartAjaxCall();
});

function draw(response) {
  function UserShowTempChartSvg(response) {
        this.w = window.innerWidth;
        this.h = 450;
        this.maxDataPointsForDots = 500;
        this.transitionDuration = 1000;
        this.violations = 0;
        this.margin = 40;
        this.pointRadius = 4;
        this.data = this.setData(response);
        this.max = d3.max(this.data, function(d) { return Math.max( d.temp, d.outdoor_temp ) }) + 1;
        this.min = this.setMin();
        this.x = d3.time.scale().range([0, this.w - this.margin * 2]).domain([this.data[0].date, this.data[this.data.length - 1].date]);
        this.y = d3.scale.linear().range([this.h - this.margin * 2, 0]).domain([this.min, this.max]);
        this.xAxis = d3.svg.axis().scale(this.x).tickSize(this.h - this.margin * 2).tickPadding(0).ticks(this.data.length);
        this.yAxis = d3.svg.axis().scale(this.y).orient('left').tickSize(-this.w + this.margin * 2).tickPadding(0).ticks(5);
        this.strokeWidth = this.w / this.data.length;
        this.svg = this.setSvg();
        this.t = this.setT();
        this.yAxisGroup = null;
        this.xAxisGroup = null;
        this.dataCirclesGroup = null;
        this.dataLinesGroup = null;
        this.dataLines = null;
        this.line = null;
        this.garea = null;
        this.$fillArea = null;
        this.circles = null;
      }

  // Date constants
  UserShowTempChartSvg.prototype.DAYS = [ 'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday' ];
  UserShowTempChartSvg.prototype.MONTHS = [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
    "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ];
  UserShowTempChartSvg.prototype.ABBREVIATED_MONTHS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];

  UserShowTempChartSvg.prototype.setData = function(dataArrWithObjs) {
    var self = this;
    dataArrWithObjs.forEach(function(obj){
      obj.date = new Date(obj.created_at);
      obj.isDay = obj.date.getHours() >= 6 && obj.date.getHours() <= 22;
      if(/live_update/.test(document.URL)){
        obj.violation = true;
      }
      if( obj.violation ){ self.violations += 1; }
    });
    return dataArrWithObjs;
  }

  UserShowTempChartSvg.prototype.setMin = function() {
    if ( d3.min(this.data, function(d) { return d.outdoor_temp }) ){
      return d3.min(this.data, function(d) { return Math.min( d.temp ) }) - 5;
    } else {
      return d3.min(this.data, function(d) { return Math.min( d.temp, d.outdoor_temp ) }) - 10;
    }
  }

  UserShowTempChartSvg.prototype.setSvg = function(){
    return d3.select('#d3-chart')
      .append('svg:svg')
      .attr('width', this.w)
      .attr('height', this.h)
      .attr('class', 'viz')
      .append('svg:g')
      .attr('transform', 'translate(' + this.margin + ',' + this.margin + ')');
  }

  UserShowTempChartSvg.prototype.setT = function(){
    return this.svg.transition().duration(this.transitionDuration);
  }
  var chartProperties = new UserShowTempChartSvg(response);

  function function_name(argument) {
    // body...
  }
  function addLineStlyingToXTicks(){
    var $lines = $(".xTick .tick line"),
        length = chartProperties.data.length,
        date,
        newText,
        $textEl;

    for(var i = 0; i < length; i++){
      if(chartProperties.data[i].isDay === false){
        $($lines[i]).attr(
          { 'stroke-width': chartProperties.strokeWidth, 'stroke': '#90ABB0' }
        );
        if(i === 0){
          $($lines[i]).attr({ 'stroke-width': chartProperties.strokeWidth * 1.9 });
        }
      }
      else {
        // add dates to bottom of graph
        if ( chartProperties.data[i].date.getHours() === 16 ) {
          date = chartProperties.data[i].date;
          newText = chartProperties.ABBREVIATED_MONTHS[date.getMonth()] + " "
            + date.getDate() + ", " + (date.getYear() + 1900);
          $textEl = $($(".xTick .tick text")[i]);
          $textEl.text(newText);
          $textEl.show();
          $textEl.attr({"x": -15, "y": 380});
        }
      }
    }
  }

// x ticks and labels gets placed first
  // x ticks and labels
  function setXAxisGroup(){
    if (!chartProperties.xAxisGroup) {
      chartProperties.xAxisGroup = chartProperties.svg.append('svg:g')
        .attr('class', 'xTick')
        .call(chartProperties.xAxis);
    }
    else {
      chartProperties.t.select('.xTick').call(chartProperties.xAxis);
    }
  }

  setXAxisGroup();
  addLineStlyingToXTicks();

// y ticks and labels gets placed second
  // y ticks and labels
  function setYAxisGroup() {
    if (!chartProperties.yAxisGroup) {
      chartProperties.yAxisGroup = chartProperties.svg.append('svg:g')
        .attr('class', 'yTick')
        .call(chartProperties.yAxis);
      // fixes x value for text
      $(".yTick .tick text").attr("x", "-5")
    }
    else {
      t.select('.yTick').call(chartProperties.yAxis);
    }
  }

  setYAxisGroup();

// y ticks and labels gets placed third
  // Draw the lines
  function setDataLinesGroup(){
    if (!chartProperties.dataLinesGroup) {
      chartProperties.dataLinesGroup = chartProperties.svg.append('svg:g');
    }
  }
  setDataLinesGroup();

  chartProperties.dataLines = chartProperties.dataLinesGroup.selectAll('.data-line').data([chartProperties.data]);

  function setLine(){
    chartProperties.line = d3.svg.line()
    // assign the X function to plot our line as we wish
    .x(function(d,i) {
      return chartProperties.x(d.date);
    })
    .y(function(d) {
      return chartProperties.y(d.temp);
    })
    .interpolate("linear");
  }
  setLine();

  function setGroupArea(){
    chartProperties.garea = d3.svg.area()
      .interpolate("linear")
      .x(function(d) { return chartProperties.x(d.date); })
      .y0(chartProperties.h - chartProperties.margin * 2)
      .y1(function(d) { return chartProperties.y(d.outdoor_temp); });
  }
  setGroupArea();

  function createAreaClassForGroupArea(){
    chartProperties.dataLines
      .enter()
      .append('svg:path')
      .attr("class", "area");
  }
  createAreaClassForGroupArea();

  function addDataLineWithoutTransitions() {
    chartProperties.dataLines.enter().append('path')
      .attr('class', 'data-line')
      .attr("d", chartProperties.line(data))
  }

  function addDataLineWithTransitions() {
    chartProperties.dataLines.enter().append('path')
      .attr('class', 'data-line')
      .style('opacity', 0.3)
      .attr("d", chartProperties.line(chartProperties.data))
      .transition()
      .delay(chartProperties.transitionDuration / 2)
      .duration(chartProperties.transitionDuration)
      .style('opacity', 1);
  }
  addDataLineWithTransitions();

  function addGroupArea(){
    d3.selectAll(".area").attr("d", chartProperties.garea(chartProperties.data));
    // move the area to the back of the graph
    chartProperties.$fillArea = $(".area");
    $("#d3-chart svg > g").prepend(chartProperties.$fillArea)
  }
  addGroupArea();

  function addViolationCountToLegend() {
    $("#violations span").text($("#violations span")
      .text().replace(/\d+/, chartProperties.violations));
  }
  addViolationCountToLegend();

  if (chartProperties.violations) {
  // Draw the circles if there are any violations
    function setDataCirclesGroup() {
      if (!chartProperties.dataCirclesGroup) {
        chartProperties.dataCirclesGroup = chartProperties.svg.append('svg:g');
      }
    }
    setDataCirclesGroup();

    function setCircles() {
      chartProperties.circles = chartProperties.dataCirclesGroup.selectAll('.data-point').data(chartProperties.data);
    }
    setCircles();

    function addCircles(){
      chartProperties.circles.enter()
        .append('svg:circle')
        .attr('class', 'data-point')
        .style('opacity', 1)
        .attr('cx', function(d) { return chartProperties.x(d.date) })
        .attr('cy', function() { return chartProperties.y(0) })
        .attr('r', function(d) {
          return d.violation ? chartProperties.pointRadius : 0;
        })
        .transition()
        .duration(chartProperties.transitionDuration)
        .style('opacity', 1)
        .attr('cx', function(d) { return chartProperties.x(d.date) })
        .attr('cy', function(d) { return chartProperties.y(d.temp) });
    }
    addCircles();

  }

  function legalMinimumFor(reading){
    if(reading.isDay === true){
      return '68';
    }else{
      return '55';
    }
  }

  function getCivilianTime(reading){
    if (reading.getHours() > 12){
      return (reading.getHours() - 12) + ":"
        + (reading.getMinutes() >= 10 ?
          reading.getMinutes() : "0" + reading.getMinutes())
        + " PM";
    }else{
      return reading.getHours() + ":"
        + (reading.getMinutes() >= 10 ?
          reading.getMinutes() : "0" + reading.getMinutes())
        + " AM";
    }
  }

  // only add tooltips if it is not a live demo
  if(!/live_update/.test(document.URL)){
    $('svg circle').tipsy({
      gravity: 's',
      html: true,
      topOffset: 2.8,
      leftOffset: 0.3,
      opacity: 1,
      title: function() {
        var d = this.__data__;
        var pDate = d.date;
        return pDate.getDate() + ' '
          + chartProperties.MONTHS[pDate.getMonth()] + ' '
          + pDate.getFullYear() + '
'
          + chartProperties.DAYS[ pDate.getDay() ] + ' at '
          + getCivilianTime(pDate) + '
'
          + 'Temperature in Violation
'
          + '
Temperature in Apt: ' + d.temp + '°'
          + '
Temperature Outside: ' + d.outdoor_temp + '°'
          + '
Legal minimum: ' + legalMinimumFor(d) + '°';
      }
    });
  }
}

function drawChartBasedOnScreenSize(chartData){
  if ( $('#live-update') !== undefined ) {
    $('.temp-num').html(chartData[chartData.length - 1].temp + '°')
  }

  if (window.innerWidth < 450) {
    var quarterReadings = chartData.slice(119, 167);
    $("#d3-chart").html("")
    draw(quarterReadings);
  }else if(window.innerWidth < 720){
    var halfReadings = chartData.slice(71, 167);
    $("#d3-chart").html("")
    draw(halfReadings);
  }else if(window.innerWidth < 1080){
    var threeQuarterReadings = chartData.slice(23, 167);
    $("#d3-chart").html("")
    draw(threeQuarterReadings);
  }else{
    $("#d3-chart").html("")
    draw(chartData);
  }
}

function drawChartAjaxCall(){
  if($("#d3-chart").length > 0){
    if(/collaborations/.test(document.URL)){
      var URL = /\/users\/\d+\/collaborations\/\d+/.exec(document.URL)[0];
      // returns /user/11/collaborations/35
    } else if ( /live_update/.test(document.URL) ){
      var URL = /\/users\/\d+\/live_update/.exec(document.URL)[0];
      //returns /user/13/live_update
    } else {
      var URL = /\/users\/\d+/.exec(document.URL)[0];
    }
    $.ajax({
      url: URL,
      dataType: "JSON",
      success: function(response){
        if( response.length > 0 ){
          drawChartBasedOnScreenSize(response);
          var resizeTimer = 0;
          window.onresize = function(){
            if (resizeTimer){
              clearTimeout(resizeTimer);
            }
            resizeTimer = setTimeout(function(){
              drawChartBasedOnScreenSize(response);
            }, 50);
          };
        }
      },
      error: function(response){
        console.log("error");
        console.log(response);
      }
    });
  }
}
<commit_msg>creates xAxisGroup<commit_after>$(document).ready(function(){
  // todos for this file
  // make it OO
  drawChartAjaxCall();
});

function draw(response) {
  function UserShowTempChartSvg(response) {
        this.w = window.innerWidth;
        this.h = 450;
        this.maxDataPointsForDots = 500;
        this.transitionDuration = 1000;
        this.violations = 0;
        this.margin = 40;
        this.pointRadius = 4;
        this.data = this.setData(response);
        this.max = d3.max(this.data, function(d) { return Math.max( d.temp, d.outdoor_temp ) }) + 1;
        this.min = this.setMin();
        this.x = d3.time.scale().range([0, this.w - this.margin * 2]).domain([this.data[0].date, this.data[this.data.length - 1].date]);
        this.y = d3.scale.linear().range([this.h - this.margin * 2, 0]).domain([this.min, this.max]);
        this.xAxis = d3.svg.axis().scale(this.x).tickSize(this.h - this.margin * 2).tickPadding(0).ticks(this.data.length);
        this.yAxis = d3.svg.axis().scale(this.y).orient('left').tickSize(-this.w + this.margin * 2).tickPadding(0).ticks(5);
        this.strokeWidth = this.w / this.data.length;
        this.svg = this.setSvg();
        this.t = this.setT();
        this.yAxisGroup = null;
        this.xAxisGroup = null;
        this.dataCirclesGroup = null;
        this.dataLinesGroup = null;
        this.dataLines = null;
        this.line = null;
        this.garea = null;
        this.$fillArea = null;
        this.circles = null;
      }

  // Date constants
  UserShowTempChartSvg.prototype.DAYS = [ 'Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday' ];
  UserShowTempChartSvg.prototype.MONTHS = [ "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE",
    "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" ];

  UserShowTempChartSvg.prototype.setData = function(dataArrWithObjs) {
    var self = this;
    dataArrWithObjs.forEach(function(obj){
      obj.date = new Date(obj.created_at);
      obj.isDay = obj.date.getHours() >= 6 && obj.date.getHours() <= 22;
      if(/live_update/.test(document.URL)){
        obj.violation = true;
      }
      if( obj.violation ){ self.violations += 1; }
    });
    return dataArrWithObjs;
  }

  UserShowTempChartSvg.prototype.setMin = function() {
    if ( d3.min(this.data, function(d) { return d.outdoor_temp }) ){
      return d3.min(this.data, function(d) { return Math.min( d.temp ) }) - 5;
    } else {
      return d3.min(this.data, function(d) { return Math.min( d.temp, d.outdoor_temp ) }) - 10;
    }
  }

  UserShowTempChartSvg.prototype.setSvg = function(){
    return d3.select('#d3-chart')
      .append('svg:svg')
      .attr('width', this.w)
      .attr('height', this.h)
      .attr('class', 'viz')
      .append('svg:g')
      .attr('transform', 'translate(' + this.margin + ',' + this.margin + ')');
  }

  UserShowTempChartSvg.prototype.setT = function(){
    return this.svg.transition().duration(this.transitionDuration);
  }
  var chartProperties = new UserShowTempChartSvg(response);

  function UserShowTempChartXAxisGroup(svgObj) {
    this.data = svgObj.data;
    this.length = svgObj.length;
    this.svg = svgObj.svg;
    this.xAxis = svgObj.xAxis;
    this.strokeWidth = svgObj.strokeWidth;
  }

  UserShowTempChartXAxisGroup.prototype.ABBREVIATED_MONTHS = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];

  UserShowTempChartXAxisGroup.prototype.addLineStlyingToXTicks = function(){
    var $lines = $(".xTick .tick line"),
        length = this.data.length,
        date,
        newText,
        $textEl;

    for(var i = 0; i < length; i++){
      if(this.data[i].isDay === false){
        $($lines[i]).attr(
          { 'stroke-width': this.strokeWidth, 'stroke': '#90ABB0' }
        );
        if(i === 0){
          $($lines[i]).attr({ 'stroke-width': this.strokeWidth * 1.9 });
        }
      }
      else {
        // add dates to bottom of graph
        if ( this.data[i].date.getHours() === 16 ) {
          date = this.data[i].date;
          newText = this.ABBREVIATED_MONTHS[date.getMonth()] + " "
            + date.getDate() + ", " + (date.getYear() + 1900);
          $textEl = $($(".xTick .tick text")[i]);
          $textEl.text(newText);
          $textEl.show();
          $textEl.attr({"x": -15, "y": 380});
        }
      }
    }
  }

// x ticks and labels gets placed first
  // x ticks and labels
  UserShowTempChartXAxisGroup.prototype.setXAxisGroup = function(){
    if (!this.xAxisGroup) {
      this.xAxisGroup = this.svg.append('svg:g')
        .attr('class', 'xTick')
        .call(this.xAxis);
    }
    else {
      chartProperties.t.select('.xTick').call(this.xAxis);
    }
  }

  var testXGroup = new UserShowTempChartXAxisGroup(chartProperties);
  testXGroup.setXAxisGroup();
  testXGroup.addLineStlyingToXTicks();

// y ticks and labels gets placed second
  // y ticks and labels
  function setYAxisGroup() {
    if (!chartProperties.yAxisGroup) {
      chartProperties.yAxisGroup = chartProperties.svg.append('svg:g')
        .attr('class', 'yTick')
        .call(chartProperties.yAxis);
      // fixes x value for text
      $(".yTick .tick text").attr("x", "-5")
    }
    else {
      t.select('.yTick').call(chartProperties.yAxis);
    }
  }

  setYAxisGroup();

// y ticks and labels gets placed third
  // Draw the lines
  function setDataLinesGroup(){
    if (!chartProperties.dataLinesGroup) {
      chartProperties.dataLinesGroup = chartProperties.svg.append('svg:g');
    }
  }
  setDataLinesGroup();

  chartProperties.dataLines = chartProperties.dataLinesGroup.selectAll('.data-line').data([chartProperties.data]);

  function setLine(){
    chartProperties.line = d3.svg.line()
    // assign the X function to plot our line as we wish
    .x(function(d,i) {
      return chartProperties.x(d.date);
    })
    .y(function(d) {
      return chartProperties.y(d.temp);
    })
    .interpolate("linear");
  }
  setLine();

  function createAreaClassForGroupArea(){
    chartProperties.dataLines
      .enter()
      .append('svg:path')
      .attr("class", "area");
  }
  createAreaClassForGroupArea();

  function addDataLineWithoutTransitions() {
    chartProperties.dataLines.enter().append('path')
      .attr('class', 'data-line')
      .attr("d", chartProperties.line(data))
  }

  function addDataLineWithTransitions() {
    chartProperties.dataLines.enter().append('path')
      .attr('class', 'data-line')
      .style('opacity', 0.3)
      .attr("d", chartProperties.line(chartProperties.data))
      .transition()
      .delay(chartProperties.transitionDuration / 2)
      .duration(chartProperties.transitionDuration)
      .style('opacity', 1);
  }
  addDataLineWithTransitions();

  function setGroupArea(){
    chartProperties.garea = d3.svg.area()
      .interpolate("linear")
      .x(function(d) { return chartProperties.x(d.date); })
      .y0(chartProperties.h - chartProperties.margin * 2)
      .y1(function(d) { return chartProperties.y(d.outdoor_temp); });
  }
  setGroupArea();

  function addGroupArea(){
    d3.selectAll(".area").attr("d", chartProperties.garea(chartProperties.data));
    // move the area to the back of the graph
    chartProperties.$fillArea = $(".area");
    $("#d3-chart svg > g").prepend(chartProperties.$fillArea)
  }
  addGroupArea();

  function addViolationCountToLegend() {
    $("#violations span").text($("#violations span")
      .text().replace(/\d+/, chartProperties.violations));
  }
  addViolationCountToLegend();

  if (chartProperties.violations) {
  // Draw the circles if there are any violations
    function setDataCirclesGroup() {
      if (!chartProperties.dataCirclesGroup) {
        chartProperties.dataCirclesGroup = chartProperties.svg.append('svg:g');
      }
    }
    setDataCirclesGroup();

    function setCircles() {
      chartProperties.circles = chartProperties.dataCirclesGroup.selectAll('.data-point').data(chartProperties.data);
    }
    setCircles();

    function addCircles(){
      chartProperties.circles.enter()
        .append('svg:circle')
        .attr('class', 'data-point')
        .style('opacity', 1)
        .attr('cx', function(d) { return chartProperties.x(d.date) })
        .attr('cy', function() { return chartProperties.y(0) })
        .attr('r', function(d) {
          return d.violation ? chartProperties.pointRadius : 0;
        })
        .transition()
        .duration(chartProperties.transitionDuration)
        .style('opacity', 1)
        .attr('cx', function(d) { return chartProperties.x(d.date) })
        .attr('cy', function(d) { return chartProperties.y(d.temp) });
    }
    addCircles();

  }

  function legalMinimumFor(reading){
    if(reading.isDay === true){
      return '68';
    }else{
      return '55';
    }
  }

  function getCivilianTime(reading){
    if (reading.getHours() > 12){
      return (reading.getHours() - 12) + ":"
        + (reading.getMinutes() >= 10 ?
          reading.getMinutes() : "0" + reading.getMinutes())
        + " PM";
    }else{
      return reading.getHours() + ":"
        + (reading.getMinutes() >= 10 ?
          reading.getMinutes() : "0" + reading.getMinutes())
        + " AM";
    }
  }

  // only add tooltips if it is not a live demo
  if(!/live_update/.test(document.URL)){
    $('svg circle').tipsy({
      gravity: 's',
      html: true,
      topOffset: 2.8,
      leftOffset: 0.3,
      opacity: 1,
      title: function() {
        var d = this.__data__;
        var pDate = d.date;
        return pDate.getDate() + ' '
          + chartProperties.MONTHS[pDate.getMonth()] + ' '
          + pDate.getFullYear() + '
'
          + chartProperties.DAYS[ pDate.getDay() ] + ' at '
          + getCivilianTime(pDate) + '
'
          + 'Temperature in Violation
'
          + '
Temperature in Apt: ' + d.temp + '°'
          + '
Temperature Outside: ' + d.outdoor_temp + '°'
          + '
Legal minimum: ' + legalMinimumFor(d) + '°';
      }
    });
  }
}

function drawChartBasedOnScreenSize(chartData){
  if ( $('#live-update') !== undefined ) {
    $('.temp-num').html(chartData[chartData.length - 1].temp + '°')
  }

  if (window.innerWidth < 450) {
    var quarterReadings = chartData.slice(119, 167);
    $("#d3-chart").html("")
    draw(quarterReadings);
  }else if(window.innerWidth < 720){
    var halfReadings = chartData.slice(71, 167);
    $("#d3-chart").html("")
    draw(halfReadings);
  }else if(window.innerWidth < 1080){
    var threeQuarterReadings = chartData.slice(23, 167);
    $("#d3-chart").html("")
    draw(threeQuarterReadings);
  }else{
    $("#d3-chart").html("")
    draw(chartData);
  }
}

function drawChartAjaxCall(){
  if($("#d3-chart").length > 0){
    if(/collaborations/.test(document.URL)){
      var URL = /\/users\/\d+\/collaborations\/\d+/.exec(document.URL)[0];
      // returns /user/11/collaborations/35
    } else if ( /live_update/.test(document.URL) ){
      var URL = /\/users\/\d+\/live_update/.exec(document.URL)[0];
      //returns /user/13/live_update
    } else {
      var URL = /\/users\/\d+/.exec(document.URL)[0];
    }
    $.ajax({
      url: URL,
      dataType: "JSON",
      success: function(response){
        if( response.length > 0 ){
          drawChartBasedOnScreenSize(response);
          var resizeTimer = 0;
          window.onresize = function(){
            if (resizeTimer){
              clearTimeout(resizeTimer);
            }
            resizeTimer = setTimeout(function(){
              drawChartBasedOnScreenSize(response);
            }, 50);
          };
        }
      },
      error: function(response){
        console.log("error");
        console.log(response);
      }
    });
  }
}
<|endoftext|>


<commit_before>/**
 * The SidebarNavView view.
 */
define([
  'jquery',
  'backbone',
  'underscore',
  'mps'
], function($,Backbone, _,mps) {

  'use strict';

  var SidebarNavModel = Backbone.Model.extend({
    defaults: {
      offset: null,
      height: null
    }
  });

  var SidebarNavView = Backbone.View.extend({

    el: '#sidebarNavView',

    events: {
      'click .nav-item' : 'updateSource',
      'click .nav-title' : 'scrollTo',
      'click #back-btn' : 'returnBack',
      'click .source_header' : 'toggleSources',
      'click .source_dropdown_header' : 'toggleDropdown',
      'click .source_dropdown_menu a' : 'showSubContent'
    },

    initialize: function() {
      if (!this.$el.length) {
        return
      }
      //CACHE
      this.$window = $(window);
      this.$document = $(document);
      this.$htmlbody = $('html,body');
      this.$headerH1 = $('#headerView').find('h1');
      this.$backBtn = $('#back-btn');
      this.$navItem = this.$el.find('.nav-item');
      this.$sideBarAside = $('#sidebarAside');
      this.$sideBarBox = $('#sources-box');
      this.$sourceArticle = $('.source-article');
      this.$sourceHeader = $('.source_header');
      this.$sourceBody = $('.source_body');
      this.$cut = $('#cut');
      this.$sourceSpinner = $('#sources-spinner');

      //VARS
      this.padding = 40;
      this.first = true;
      this.mobile = (this.$window.width() > 850) ? false : true;

      //INIT
      this.setListeners();
    },

    setListeners: function(){
      this.calculateOffsets();
      this.scrollDocument();
      this.$document.on('scroll',_.bind(this.scrollDocument,this));
      this.$window.on('resize',_.bind(this.calculateOffsets,this));

      mps.subscribe('SourceStatic/change',_.bind(this.changeSource,this));
      mps.subscribe('SubItem/change',_.bind(this.calculateOffsets,this));
    },

    toggleDropdown: function(e){
      e && e.preventDefault();
      $(e.currentTarget).parents('.source_dropdown').find('.source_dropdown_menu').toggle(0);
    },

    showSubContent:function(e){
      e && e.preventDefault();
      $(e.currentTarget).parents('.source_dropdown').find('.source_dropdown_menu').hide(0);

      var text = $(e.currentTarget).text();
      var id = $(e.currentTarget).data('slug');
      $(e.currentTarget).parents('.source_dropdown').find('.source_dropdown_header').find('.overview_title').children('span').text(text);

      $('.source_dropdown_body').hide(0);
      $('#'+id).show(0);

      this.calculateOffsets();

    },

    toggleSources: function(e){
      var top;
      this.$sourceBody.hide(0);

      if ($(e.currentTarget).hasClass('active')) {
        this.$sourceBody.removeClass('active');
        $(e.currentTarget).removeClass('active');
      } else {
        this.$sourceHeader.removeClass('active');
        top = $(e.currentTarget).offset().top;
        $(e.currentTarget).addClass('active');
        $(e.currentTarget).parent().children('.source_body').show(0);
      }

      setTimeout(_.bind(function(){
        this.calculateOffsets(top);
      },this),50);
    },

    calculateOffsets: function(top){
      this.$sideBarBox.css({'min-height': this.$sideBarAside.height() });
      this.offset = this.$el.offset().top + parseInt(this.$el.css('paddingTop'), 10);
      this.offsetBottom = this.$cut.offset().top - this.$sideBarAside.height() - this.padding;
      (top) ? this.$htmlbody.animate({ scrollTop: top },250) : this.$htmlbody.animate({ scrollTop: this.$sideBarBox.offset().top - this.padding },0);
    },

    scrollDocument: function(e){
      var scrollTop = this.$document.scrollTop();
      if (scrollTop > this.offset) {
        this.$sideBarBox.addClass('fixed');
        this.firstFixed = false;
        if(scrollTop < this.offsetBottom) {
          this.$sideBarAside.removeClass('bottom').addClass('fixed');
        }else{
          this.$sideBarAside.removeClass('fixed').addClass('bottom');
        }
      }else{
        this.$sideBarAside.removeClass('fixed bottom');
        this.$sideBarBox.removeClass('fixed');
        this.firstFixed = true;
      }
    },

    updateSource: function(e){
      e && e.preventDefault();

      var params = {
        section: $(e.currentTarget).data('slug'),
        interesting: $(e.currentTarget).data('interesting')
      }

      mps.publish('SourceStatic/update',[params]);
    },

    changeSource: function(params){
      //spinner
      this.$sourceSpinner.removeClass('start');

      if (params.section) {
        var posY = (this.mobile) ? this.$document.scrollTop() : this.$sideBarBox.offset().top - this.padding;
        this.$htmlbody.animate({ scrollTop: posY },0, _.bind(function(){
            this.changeHelper(params.section);
        },this));
        mps.publish('Interesting/update',[params.interesting]);
      }else{
        if (!this.mobile) {
          var section = this.$navItem.eq(0).data('slug');
          this.changeHelper(section);
        }
        var interesting = this.$navItem.eq(0).data('interesting');
        mps.publish('Interesting/update',[interesting]);
      }

    },

    changeHelper: function(section){
      this.$sideBarBox.addClass('active');
      this.$backBtn.addClass('active');
      //aside
      this.$navItem.removeClass('selected');
      $('.'+section).addClass('selected');

      //section
      this.$sourceArticle.removeClass('selected');
      $('#'+section).addClass('selected');

      if(this.mobile) {
        this.$sideBarBox.animate({ scrollTop: 0 },0);
        this.$headerH1.addClass('active');
      }

      setTimeout(_.bind(function(){
        this.calculateOffsets();
      },this),50);

      setTimeout(_.bind(function(){

        //htmlbody
        if(this.mobile) {
          this.$sideBarBox.addClass('animate');
          this.$htmlbody.addClass('active');
        }
      },this),500);
    },

    returnBack: function(e){
      e && e.preventDefault();

      this.$headerH1.removeClass('active');
      this.$sideBarBox.removeClass('active');
      this.$backBtn.removeClass('active');
      this.$navItem.removeClass('selected');

      this.$htmlbody.removeClass('active').animate({ scrollTop: this.$sideBarAside.offset().top },0);

    },

    scrollTo: function(e){
      e && e.preventDefault();
      this.$htmlbody.animate({ scrollTop: 0 },500);
    }

  });

  return SidebarNavView;

});
<commit_msg>General: sidebar scroll fix<commit_after>/**
 * The SidebarNavView view.
 */
define([
  'jquery',
  'backbone',
  'underscore',
  'mps'
], function($,Backbone, _,mps) {

  'use strict';

  var SidebarNavModel = Backbone.Model.extend({
    defaults: {
      offset: null,
      height: null
    }
  });

  var SidebarNavView = Backbone.View.extend({

    el: '#sidebarNavView',

    events: {
      'click .nav-item' : 'updateSource',
      'click .nav-title' : 'scrollTo',
      'click #back-btn' : 'returnBack',
      'click .source_header' : 'toggleSources',
      'click .source_dropdown_header' : 'toggleDropdown',
      'click .source_dropdown_menu a' : 'showSubContent'
    },

    initialize: function() {
      if (!this.$el.length) {
        return
      }
      //CACHE
      this.$window = $(window);
      this.$document = $(document);
      this.$htmlbody = $('html,body');
      this.$headerH1 = $('#headerView').find('h1');
      this.$backBtn = $('#back-btn');
      this.$navItem = this.$el.find('.nav-item');
      this.$sideBarAside = $('#sidebarAside');
      this.$sideBarBox = $('#sources-box');
      this.$sourceArticle = $('.source-article');
      this.$sourceHeader = $('.source_header');
      this.$sourceBody = $('.source_body');
      this.$cut = $('#cut');
      this.$sourceSpinner = $('#sources-spinner');

      //VARS
      this.padding = 40;
      this.first = true;
      this.mobile = (this.$window.width() > 850) ? false : true;

      //INIT
      this.setListeners();
    },

    setListeners: function(){
      this.calculateOffsets();
      this.scrollDocument();
      this.$document.on('scroll',_.bind(this.scrollDocument,this));
      this.$window.on('resize',_.bind(this.calculateOffsets,this));

      mps.subscribe('SourceStatic/change',_.bind(this.changeSource,this));
      mps.subscribe('SubItem/change',_.bind(this.calculateOffsets,this));
    },

    toggleDropdown: function(e){
      e && e.preventDefault();
      $(e.currentTarget).parents('.source_dropdown').find('.source_dropdown_menu').toggle(0);
    },

    showSubContent:function(e){
      e && e.preventDefault();
      $(e.currentTarget).parents('.source_dropdown').find('.source_dropdown_menu').hide(0);

      var text = $(e.currentTarget).text();
      var id = $(e.currentTarget).data('slug');
      $(e.currentTarget).parents('.source_dropdown').find('.source_dropdown_header').find('.overview_title').children('span').text(text);

      $('.source_dropdown_body').hide(0);
      $('#'+id).show(0);

      this.calculateOffsets();

    },

    toggleSources: function(e){
      var top;
      this.$sourceBody.hide(0);

      if ($(e.currentTarget).hasClass('active')) {
        this.$sourceBody.removeClass('active');
        $(e.currentTarget).removeClass('active');
      } else {
        this.$sourceHeader.removeClass('active');
        top = $(e.currentTarget).offset().top;
        $(e.currentTarget).addClass('active');
        $(e.currentTarget).parent().children('.source_body').show(0);
      }

      setTimeout(_.bind(function(){
        this.calculateOffsets();
        (top) ? this.$htmlbody.animate({ scrollTop: top },250) : this.$htmlbody.animate({ scrollTop: this.$sideBarBox.offset().top - this.padding },0);
      },this),50);
    },

    calculateOffsets: function(){
      this.$sideBarBox.css({'min-height': this.$sideBarAside.height() });
      this.offset = this.$el.offset().top + parseInt(this.$el.css('paddingTop'), 10);
      this.offsetBottom = this.$cut.offset().top - this.$sideBarAside.height() - this.padding;
    },

    scrollDocument: function(e){
      var scrollTop = this.$document.scrollTop();
      if (scrollTop > this.offset) {
        this.$sideBarBox.addClass('fixed');
        this.firstFixed = false;
        if(scrollTop < this.offsetBottom) {
          this.$sideBarAside.removeClass('bottom').addClass('fixed');
        }else{
          this.$sideBarAside.removeClass('fixed').addClass('bottom');
        }
      }else{
        this.$sideBarAside.removeClass('fixed bottom');
        this.$sideBarBox.removeClass('fixed');
        this.firstFixed = true;
      }
    },

    updateSource: function(e){
      e && e.preventDefault();

      var params = {
        section: $(e.currentTarget).data('slug'),
        interesting: $(e.currentTarget).data('interesting')
      }

      mps.publish('SourceStatic/update',[params]);
    },

    changeSource: function(params){
      //spinner
      this.$sourceSpinner.removeClass('start');

      if (params.section) {
        var posY = (this.mobile) ? this.$document.scrollTop() : this.$sideBarBox.offset().top - this.padding;
        this.$htmlbody.animate({ scrollTop: posY },0, _.bind(function(){
            this.changeHelper(params.section);
        },this));
        mps.publish('Interesting/update',[params.interesting]);
      }else{
        if (!this.mobile) {
          var section = this.$navItem.eq(0).data('slug');
          this.changeHelper(section);
        }
        var interesting = this.$navItem.eq(0).data('interesting');
        mps.publish('Interesting/update',[interesting]);
      }

    },

    changeHelper: function(section){
      this.$sideBarBox.addClass('active');
      this.$backBtn.addClass('active');
      //aside
      this.$navItem.removeClass('selected');
      $('.'+section).addClass('selected');

      //section
      this.$sourceArticle.removeClass('selected');
      $('#'+section).addClass('selected');

      if(this.mobile) {
        this.$sideBarBox.animate({ scrollTop: 0 },0);
        this.$headerH1.addClass('active');
      }

      setTimeout(_.bind(function(){
        this.calculateOffsets();
      },this),50);

      setTimeout(_.bind(function(){

        //htmlbody
        if(this.mobile) {
          this.$sideBarBox.addClass('animate');
          this.$htmlbody.addClass('active');
        }
      },this),500);
    },

    returnBack: function(e){
      e && e.preventDefault();

      this.$headerH1.removeClass('active');
      this.$sideBarBox.removeClass('active');
      this.$backBtn.removeClass('active');
      this.$navItem.removeClass('selected');

      this.$htmlbody.removeClass('active').animate({ scrollTop: this.$sideBarAside.offset().top },0);

    },

    scrollTo: function(e){
      e && e.preventDefault();
      this.$htmlbody.animate({ scrollTop: 0 },500);
    }

  });

  return SidebarNavView;

});
<|endoftext|>


<commit_before>Slipmat.Views.Header = Backbone.View.extend({

  tagName: "header",
  className: "header",
  template: JST["layouts/header/header"],

  initialize: function (options) {
    this.results = new Slipmat.Collections.SearchResults();
    this.resultTemplate = JST["layouts/header/_searchResult"];

    this.listenTo(Slipmat.currentUser, "sync", this.renderPanel);
    this.listenTo(Slipmat.currentUser, "signIn signOut", this.togglePanel);
    this.listenTo(this.results, "sync", this.renderSearchResults);
  },

  events: {
    "input input": "handleInput",
    "submit #search": "search",
    "click #signOut": "signOut",
    "click #register": "register"
  },

  render: function () {
    var content = this.template({ currentUser: Slipmat.currentUser });
    this.$el.html(content);
    this.togglePanel(Slipmat.currentUser);

    return this;
  },

  renderPanel: function () {
    if (!Slipmat.currentUser.isSignedIn()) { return; }

    var userPanel = JST["layouts/header/_signedInPanel"];
    this.$(".header-user-list").html(userPanel());
  },

  togglePanel: function () {
    var userPanel;

    if (Slipmat.currentUser.isSignedIn()) {
      userPanel = JST["layouts/header/_signedInPanel"];
    } else {
      userPanel = JST["layouts/header/_signedOutPanel"];
    }
    this.$(".header-user-list").html(userPanel());
  },

  handleInput: function (e) {
    e.preventDefault();

    var userInput = $(e.currentTarget).val();
    var query = {
      query: userInput,
      limit: 10
    };

    this.results.fetch({ data: query });
  },

  renderSearchResults: function () {
    var header = this;
    var $results = this.$(".search-results").empty();

    if (!this.results.length) {
      $results.hide();
    } else {
      $results.show();

      var results = this.results.slice(0, 10);
      results.forEach(function (result) {
        var $result = header.resultTemplate({ result: result });
        $results.append($result);
      });
    }
  },

  search: function (e) {
    e.preventDefault();

    var query = $(e.currentTarget).find("input").val();
    Backbone.history.navigate("/search?query=" + query, { trigger: true });
  },

  register: function (e) {
    e.preventDefault();

    Backbone.history.navigate("/register", { trigger: true });
  },

  signOut: function (e) {
    e.preventDefault();

    Slipmat.currentUser.signOut();
  }

});
<commit_msg>Redirect to root URL in case of blank search query<commit_after>Slipmat.Views.Header = Backbone.View.extend({

  tagName: "header",
  className: "header",
  template: JST["layouts/header/header"],

  initialize: function (options) {
    this.results = new Slipmat.Collections.SearchResults();
    this.resultTemplate = JST["layouts/header/_searchResult"];

    this.listenTo(Slipmat.currentUser, "sync", this.renderPanel);
    this.listenTo(Slipmat.currentUser, "signIn signOut", this.togglePanel);
    this.listenTo(this.results, "sync", this.renderSearchResults);
  },

  events: {
    "input input": "handleInput",
    "submit #search": "search",
    "click #signOut": "signOut",
    "click #register": "register"
  },

  render: function () {
    var content = this.template({ currentUser: Slipmat.currentUser });
    this.$el.html(content);
    this.togglePanel(Slipmat.currentUser);

    return this;
  },

  renderPanel: function () {
    if (!Slipmat.currentUser.isSignedIn()) { return; }

    var userPanel = JST["layouts/header/_signedInPanel"];
    this.$(".header-user-list").html(userPanel());
  },

  togglePanel: function () {
    var userPanel;

    if (Slipmat.currentUser.isSignedIn()) {
      userPanel = JST["layouts/header/_signedInPanel"];
    } else {
      userPanel = JST["layouts/header/_signedOutPanel"];
    }
    this.$(".header-user-list").html(userPanel());
  },

  handleInput: function (e) {
    e.preventDefault();

    var userInput = $(e.currentTarget).val();
    var query = {
      query: userInput,
      limit: 10
    };

    this.results.fetch({ data: query });
  },

  renderSearchResults: function () {
    var header = this;
    var $results = this.$(".search-results").empty();

    if (!this.results.length) {
      $results.hide();
    } else {
      $results.show();

      var results = this.results.slice(0, 10);
      results.forEach(function (result) {
        var $result = header.resultTemplate({ result: result });
        $results.append($result);
      });
    }
  },

  search: function (e) {
    e.preventDefault();
    this.$(".search-results").empty();

    var query = $(e.currentTarget).find("input").val();
    var fragment = (query.length ? "/search?query=" + query : "");

    Backbone.history.navigate(fragment, { trigger: true });
  },

  register: function (e) {
    e.preventDefault();

    Backbone.history.navigate("/register", { trigger: true });
  },

  signOut: function (e) {
    e.preventDefault();

    Slipmat.currentUser.signOut();
  }

});
<|endoftext|>


<commit_before>'use strict';
import React, { PropTypes as T } from 'react';
import { connect } from 'react-redux';
import widont from '../utils/widont';
import _ from 'lodash';
import c from 'classnames';
import { Dropdown } from 'openaq-design-system';

import ConnectFold from '../components/connect-fold';
import CommunityCard from '../components/community-card';
import content from '../../content/content.json';
import QsState from '../utils/qs-state';

// Values for the filters.
const filterData = {
  type: {
    values: _(content.projects)
      .values()
      .map(o => o.type)
      .filter(Boolean)
      .uniq()
      .value(),
    label: 'types'
  },

  location: {
    values: _(content.projects)
      .values()
      .map(o => o.location)
      .filter(Boolean)
      .uniq()
      .value(),
    label: 'locations'
  }
};

class CommunityProjects extends React.Component {
  constructor (props) {
    super(props);

    this.qsState = new QsState({
      type: {
        accessor: 'filter.type',
        default: null
      },
      location: {
        accessor: 'filter.location',
        default: null
      }
    });

    this.state = this.qsState.getState(props.location.search.substr(1));
  }

  onFilterSelect (what, value, e) {
    e.preventDefault();
    this.setState({
      filter: Object.assign({}, this.state.filter, {
        [what]: value
      })
    }, () => {
      const qObj = this.qsState.getQueryObject(this.state);
      this.props.history.push(Object.assign({}, this.props.location, { query: qObj }));
    });
  }

  renderFilterDropdown (what) {
    const values = filterData[what].values;
    const label = `All ${filterData[what].label}`;
    const current = this.state.filter[what];

    return (
      <Dropdown
        triggerElement='a'
        triggerTitle={`Filter by ${what}`}
        triggerText={current || label} >

            {label}

          {values.map(o => (

              <a className={c('drop__menu-item', {'drop__menu-item--active': current === o})} href='#' target='_blank' title={`Filter by ${o}`} data-hook='dropdown:close' onClick={this.onFilterSelect.bind(this, what, o)}>{o}

          ))}

      </Dropdown>
    );
  }

  renderProjects () {
    const {type, location} = this.state.filter;

    let cards = _(content.projects).values();

    // Apply filters if they're set
    if (type || location) {
      cards = cards.filter(o => {
        if (type && o.type !== type) {
          return false;
        }
        if (location && o.location !== location) {
          return false;
        }
        return true;
      });
    }

    cards = cards.map(o => {
      return (
        <CommunityCard
          key={_.kebabCase(o.title)}
          horizontal={true}
          title={o.title}
          linkTitle='View this community contribution'
          url={o.url}
          imageNode={}
          type={o.type}
          location={o.location}
          logo={o.logo}
        >

        </CommunityCard>
      );
    })
    .value();

    return (

Projects

Filter by

Type

              {this.renderFilterDropdown('type')}

Location

              {this.renderFilterDropdown('location')}

Showing {cards.length} projects

            {cards.length ? cards : (

No projects found for the given filters

            )}

    );
  }

  render () {
    return (

Community Impact

{widont('Projects of our community using the data to fight air inquality in the most exciting ways.')}

          {this.renderProjects()}
          <ConnectFold />

    );
  }
}

CommunityProjects.propTypes = {
  location: T.object,
  history: T.object
};

// /////////////////////////////////////////////////////////////////// //
// Connect functions

// Connect to access router.
module.exports = connect()(CommunityProjects);
<commit_msg>Order location and type dropdown. Fix #306<commit_after>'use strict';
import React, { PropTypes as T } from 'react';
import { connect } from 'react-redux';
import widont from '../utils/widont';
import _ from 'lodash';
import c from 'classnames';
import { Dropdown } from 'openaq-design-system';

import ConnectFold from '../components/connect-fold';
import CommunityCard from '../components/community-card';
import content from '../../content/content.json';
import QsState from '../utils/qs-state';

// Values for the filters.
const filterData = {
  type: {
    values: _(content.projects)
      .values()
      .map(o => o.type)
      .filter(Boolean)
      .uniq()
      .sortBy()
      .value(),
    label: 'types'
  },

  location: {
    values: _(content.projects)
      .values()
      .map(o => o.location)
      .filter(Boolean)
      .uniq()
      .sortBy()
      .value(),
    label: 'locations'
  }
};

class CommunityProjects extends React.Component {
  constructor (props) {
    super(props);

    this.qsState = new QsState({
      type: {
        accessor: 'filter.type',
        default: null
      },
      location: {
        accessor: 'filter.location',
        default: null
      }
    });

    this.state = this.qsState.getState(props.location.search.substr(1));
  }

  onFilterSelect (what, value, e) {
    e.preventDefault();
    this.setState({
      filter: Object.assign({}, this.state.filter, {
        [what]: value
      })
    }, () => {
      const qObj = this.qsState.getQueryObject(this.state);
      this.props.history.push(Object.assign({}, this.props.location, { query: qObj }));
    });
  }

  renderFilterDropdown (what) {
    const values = filterData[what].values;
    const label = `All ${filterData[what].label}`;
    const current = this.state.filter[what];

    return (
      <Dropdown
        triggerElement='a'
        triggerTitle={`Filter by ${what}`}
        triggerText={current || label} >

            {label}

          {values.map(o => (

              <a className={c('drop__menu-item', {'drop__menu-item--active': current === o})} href='#' target='_blank' title={`Filter by ${o}`} data-hook='dropdown:close' onClick={this.onFilterSelect.bind(this, what, o)}>{o}

          ))}

      </Dropdown>
    );
  }

  renderProjects () {
    const {type, location} = this.state.filter;

    let cards = _(content.projects).values();

    // Apply filters if they're set
    if (type || location) {
      cards = cards.filter(o => {
        if (type && o.type !== type) {
          return false;
        }
        if (location && o.location !== location) {
          return false;
        }
        return true;
      });
    }

    cards = cards.map(o => {
      return (
        <CommunityCard
          key={_.kebabCase(o.title)}
          horizontal={true}
          title={o.title}
          linkTitle='View this community contribution'
          url={o.url}
          imageNode={}
          type={o.type}
          location={o.location}
          logo={o.logo}
        >

        </CommunityCard>
      );
    })
    .value();

    return (

Projects

Filter by

Type

              {this.renderFilterDropdown('type')}

Location

              {this.renderFilterDropdown('location')}

Showing {cards.length} projects

            {cards.length ? cards : (

No projects found for the given filters

            )}

    );
  }

  render () {
    return (

Community Impact

{widont('Projects of our community using the data to fight air inquality in the most exciting ways.')}

          {this.renderProjects()}
          <ConnectFold />

    );
  }
}

CommunityProjects.propTypes = {
  location: T.object,
  history: T.object
};

// /////////////////////////////////////////////////////////////////// //
// Connect functions

// Connect to access router.
module.exports = connect()(CommunityProjects);
<|endoftext|>


<commit_before>const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const path = require('path');
const chalk = require('chalk');
const _ = require('lodash');

const coreConfig = require('./webpack.core');
const helpers = require('./helpers');

const isCI = process.argv.indexOf('--ci') !== -1;

if (isCI) {
  console.log(chalk.bgBlue('CI flag is on'));
} else {
  console.log(chalk.bgGreen('CI flag is off'))
}

module.exports = webpackMerge(coreConfig, {
  devtool: 'inline-source-map',

  // entry: 'src/app/main.ts',
  entry: function(){return {}} ,

  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'awesome-typescript-loader',
        query: {
          module: 'commonjs',
          sourceMap: !isCI,
          inlineSourceMap: isCI,
          forkChecker: true
        }
      },
      {
        test: /\.ts$/,
        use: 'angular2-template-loader'
      },
      {
        test: /\.html$/,
        use: 'html-loader'

      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)/,
        use: 'null-loader'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        use: 'null-loader'
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        use: 'raw-loader'
      }
    ]
    .concat(!isCI ? [] : [
      {
        test: /\.(js|ts)$/,
        enforce: 'post',
        use: 'istanbul-instrumenter-loader',
        include: helpers.root('src'),
        exclude: [
          /\.(e2e|spec)\.ts$/,
          /node_modules/
        ]
      }
    ])
  }
});
<commit_msg>karma webpack conf fix (refs #30)<commit_after>const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const path = require('path');
const chalk = require('chalk');
const _ = require('lodash');

const coreConfig = require('./webpack.core');
const helpers = require('./helpers');

const isCI = process.argv.indexOf('--ci') !== -1;

if (isCI) {
  console.log(chalk.bgBlue('CI flag is on'));
} else {
  console.log(chalk.bgGreen('CI flag is off'))
}

module.exports = webpackMerge(coreConfig, {
  devtool: 'inline-source-map',

  // entry: 'src/app/main.ts',
  entry: function(){return {}} ,

  module: {
    rules: [
      {
        test: /\.ts$/,
        loader: 'awesome-typescript-loader',
        query: {
          module: 'commonjs',
          sourceMap: !isCI,
          inlineSourceMap: isCI,
          forkChecker: true
        }
      },
      {
        test: /\.ts$/,
        use: 'angular2-template-loader'
      },
      {
        test: /\.html$/,
        use: 'html-loader'

      },
      {
        test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)/,
        use: 'null-loader'
      },
      {
        test: /\.css$/,
        exclude: helpers.root('src', 'app'),
        use: 'null-loader'
      },
      {
        test: /\.css$/,
        include: helpers.root('src', 'app'),
        use: 'raw-loader'
      }
    ]
    .concat(!isCI ? [] : [
      {
        test: /\.(js|ts)$/,
        enforce: 'post',
        use: 'istanbul-instrumenter-loader',
        include: helpers.root('src'),
        exclude: [
          /\.(e2e|spec)\.ts$/,
          /node_modules/
        ]
      }
    ])
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import Relay from 'react-relay';

import BuildState from '../../icons/BuildState';

import BuildTooltip from './build-tooltip';

class Status extends React.Component {
  static propTypes = {
    pipeline: React.PropTypes.shape({
      id: React.PropTypes.string.isRequired,
      builds: React.PropTypes.shape({
        edges: React.PropTypes.arrayOf(
          React.PropTypes.shape({
            node: React.PropTypes.shape({
              state: React.PropTypes.string.isRequired,
              url: React.PropTypes.string.isRequired
            }).isRequired
          }).isRequired
        )
      }).isRequired
    }).isRequired
  };

  state = {
    hover: false
  }

  render() {
    const buildEdge = this.props.pipeline.builds.edges[0];

    if (buildEdge) {
      const build = buildEdge.node;

      return (

          <BuildState state={build.state} />
          <BuildTooltip build={build} visible={this.state.hover} left={-8} top={44} />

      );
    } else {
      return (
        <BuildState state="pending" />
      );
    }
  }

  handleMouseOver = () => {
    this.setState({ hover: true });
  }

  handleMouseOut = () => {
    this.setState({ hover: false });
  }
}

export default Relay.createContainer(Status, {
  fragments: {
    pipeline: () => Relay.QL`
      fragment on Pipeline {
        id
        builds(first: 1, branch: "%default", state: [ BUILD_STATE_RUNNING, BUILD_STATE_PASSED, BUILD_STATE_FAILED, BUILD_STATE_CANCELED, BUILD_STATE_BLOCKED ]) {
          edges {
            node {
              state
              url
              ${BuildTooltip.getFragment('build')}
            }
          }
        }
      }
    `
  }
});
<commit_msg>Show scheduled builds as featured<commit_after>import React from 'react';
import Relay from 'react-relay';

import BuildState from '../../icons/BuildState';

import BuildTooltip from './build-tooltip';

class Status extends React.Component {
  static propTypes = {
    pipeline: React.PropTypes.shape({
      id: React.PropTypes.string.isRequired,
      builds: React.PropTypes.shape({
        edges: React.PropTypes.arrayOf(
          React.PropTypes.shape({
            node: React.PropTypes.shape({
              state: React.PropTypes.string.isRequired,
              url: React.PropTypes.string.isRequired
            }).isRequired
          }).isRequired
        )
      }).isRequired
    }).isRequired
  };

  state = {
    hover: false
  }

  render() {
    const buildEdge = this.props.pipeline.builds.edges[0];

    if (buildEdge) {
      const build = buildEdge.node;

      return (

          <BuildState state={build.state} />
          <BuildTooltip build={build} visible={this.state.hover} left={-8} top={44} />

      );
    } else {
      return (
        <BuildState state="pending" />
      );
    }
  }

  handleMouseOver = () => {
    this.setState({ hover: true });
  }

  handleMouseOut = () => {
    this.setState({ hover: false });
  }
}

export default Relay.createContainer(Status, {
  fragments: {
    pipeline: () => Relay.QL`
      fragment on Pipeline {
        id
        builds(first: 1, branch: "%default", state: [ BUILD_STATE_SCHEDULED, BUILD_STATE_RUNNING, BUILD_STATE_PASSED, BUILD_STATE_FAILED, BUILD_STATE_CANCELED, BUILD_STATE_BLOCKED ]) {
          edges {
            node {
              state
              url
              ${BuildTooltip.getFragment('build')}
            }
          }
        }
      }
    `
  }
});
<|endoftext|>


<commit_before>import React from 'react';
import styled from 'styled-components';
import * as _ from 'lodash';

// @TODO: Move each of the following styled components into separate files.
const Title = styled.h1`
  font-size: 40px;
  font-weight: 900;
  margin: 0;
  padding: 0;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const Subtitle = styled.h2`
  font-size: 20px;
  font-weight: 500;
  opacity: 0.7;
  margin: 0;
  padding: 0;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const TextWrapper = styled.div`
  align-self: center;
  margin-right: 15px;
`;

const RowWrapper = styled.div`
  background: #FFCC00;
  color: #5F288D;
  padding: 25px;
  height: 100%;
`;

const Wrapper = styled.div`
  padding: 10px 20px;
  box-sizing: border-box;

  &:nth-child(-n+1) > .row-wrap {
    background: #5F288D;
    color: #FFF;
    > .text-wrap > .item-title {
      font-size: 50px;
    }
  }
`;

export default function CountsItem(props) {
  return (
    <Wrapper className="col-md-12 col-xs-12">
      <RowWrapper className="row row-wrap">
        <TextWrapper className="text-wrap" >
          <Title className="item-title"> {_.first(props.counts).incidentsCount} </Title>
        </TextWrapper>

        <TextWrapper>
          <Subtitle> {_.first(props.counts).countyName} </Subtitle>

            {_.tail(props.counts).map((item, index) =>

                {item.countyName},
                ( {item.incidentsCount} )

            )}

        </TextWrapper>
      </RowWrapper>
    </Wrapper>
  );
}

CountsItem.propTypes = {
  counts: React.PropTypes.array,
};
<commit_msg>More styling for stats page<commit_after>import React from 'react';
import styled from 'styled-components';
import * as _ from 'lodash';

// @TODO: Move each of the following styled components into separate files.
const Title = styled.h1`
  font-size: 40px;
  font-weight: 900;
  margin: 0;
  padding: 0;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const Subtitle = styled.h2`
  font-size: 20px;
  font-weight: 500;
  opacity: 0.7;
  margin: 0;
  padding: 0;
  overflow: hidden;
  text-overflow: ellipsis;
`;

const TextWrapper = styled.div`
  align-self: center;
  margin-right: 15px;
`;

const RowWrapper = styled.div`
  background: #FFCC00;
  color: #5F288D;
  padding: 25px;
  height: 100%;
`;

const Wrapper = styled.div`
  padding: 10px 20px;
  box-sizing: border-box;

  &:nth-child(-n+1) > .row-wrap {
    background: #5F288D;
    color: #FFF;
    > .text-wrap > .item-title {
      font-size: 50px;
    }
  }
`;

export default function CountsItem(props) {
  return (
    <Wrapper className="col-md-12 col-xs-12">
      <RowWrapper className="row row-wrap">
        <TextWrapper className="text-wrap" >
          <Title className="item-title"> {_.first(props.counts).countyName} </Title>
        </TextWrapper>

        <TextWrapper>
          <Subtitle> {_.first(props.counts).incidentsCount} </Subtitle>
        </TextWrapper>

          {_.tail(props.counts).map((item, index) =>

               {item.countyName}
              ({item.incidentsCount}),

          )}

      </RowWrapper>
    </Wrapper>
  );
}

CountsItem.propTypes = {
  counts: React.PropTypes.array,
};
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies
 */
var mapsPolicy = require('../policies/maps.server.policy');
var maps = require('../controllers/maps.server.controller');
var Register = require('../../../registers/server/models/register.server.model');
var User = require('../../../users/server/models/user.server.model');

module.exports = function(app) {
  // Maps Routes
  // app.route('/api/maps').all(mapsPolicy.isAllowed)
  //   .get(maps.list)
  //   .post(maps.create);

  // app.route('/api/maps/:mapId').all(mapsPolicy.isAllowed)
  //   .get(maps.read)
  //   .put(maps.update)
  //   .delete(maps.delete);

  // // Finish by binding the Map middleware
  // app.param('mapId', maps.mapByID);

  app.post('api/maps', function(req,res){
    var i,j,k

    var ar_der = req.body.ar_der,
        ar_izq = req.body.ar_izq,
        ab_der = req.body.ab_der,
        ab_izq = req.body.ab_izq,
        fecha = req.body.fecha,
        cant = req.body.cant;

    //  medida de la pantalla
    var largo = ar_der.lng - ar_izq.lng;
    var alto = ar_izq.lat - ab_izq.lat;

    //espaciados para cuadrados(regiones)
    var espaciadoX = largo/cant
    var espaciadoY = alto/cant

    //esaciado para marcadores
    var espaciadoXmarcador = largo/(cant*2)
    var espaciadoYmarcador = alto/(cant*2)

    //array correlativo lonjitudes/latitudes se relacionan con el lugar en el array que ocupan
    var lat[];
    var lng[];

    //array de marcadores a pasar en el front-end
    var latMarc[];
    var lngMarc[];

    //llenando array de longitudes y latitudes
    for (i = 0; i <= cant; i++) {
      push.lng(ab_izq.lng + (i * espaciadoX));
      push.lat(ab_izq.lat + (i * espaciadoY));
    }

    //llenado de lat y lng de marcadores a enviar
    for (i = 0; i < cant; i++) {
      push.lngMarc(lng[i] + (i * espaciadoXmarcador));
      push.latMarc(lat[i] + (i * espaciadoYmarcador++));
    }

    //arreglo de objetos a enviar
    var respuesta = [];

    //contadores y sumadores para sacar promedio
    var contTos[], sumTos[];
    var contDifResp[], sumDifResp[];
    var contEstornudos[], sumEstornudos[];
    var contSibilancia[], sumSibilancia[];
    var contCatarro[], sumCatarro[];

    //contadores de situacion personal de las regiones
    var cantFuma, cantAlergico, cantTrabajoPeligroso, cantHipertiroides, cantCeliaco, cantDiabetes1, cantDiabetes2;

    //consulta a mongoDB restringiendo las lat y lng al cuadrado del mapa a pantalla completa
    User
      .find({
          pos.lat: { $gt: ab_izq.lat, $lt: ab_lng.lat },
          pos.lng: { $gt: ab_izq.lng, $lt: ar_izq.lng },
          'create_at': fecha
      })
      //relacionando las personas con los registros
      .populate('register')
      .exec( function(err, doc){
        if (err) return handleError(err);

        //recorro todos los datos
        doc.forEach(function(l, reg){

          //recorro las latitudes
          for (i = 0; i < cant; i++) {
            if (reg.pos.lat <= lat[i]){
              //recorro las longitudes
              for (j = 0; j < cant; j++) {
                if (reg.pos.lng <= lng[j]){

                  //arreglo bidimensional representando coordenadas (x,y)

                  //contadores para sacar promedio
                  contTos[i][j] ++;
                  contDifResp[i][j] ++;
                  contEstornudos[i][j] ++;
                  contSibilancia[i][j] ++;
                  contCatarro[i][j] ++;

                  //sumador para sacar promedio
                  sumTos[i][j] +=reg.tos;
                  sumDifResp[i][j] +=reg.dificultadRespiratoria;
                  sumEstornudos[i][j] +=reg.estornudos;
                  sumSibilancia[i][j] +=reg.sibilancia;
                  sumCatarro[i][j] +=reg.catarro;

                  //estadisticas de personas
                  cantFuma[i][j] += reg.fuma ? 1 : 0;
                  cantAlergico[i][j] += reg.alergico ? 1 : 0;
                  cantTrabajoPeligroso[i][j] += reg.trabajoPeligroso ? 1 : 0;
                  cantHipertiroides[i][j] += reg.hipertiroides ? 1 : 0;
                  cantCeliaco[i][j] += reg.celiaco ? 1 : 0;
                  cantDiabetes1[i][j] += ((reg.diabetes.tiene) && (reg.diabetes.tipo == 1)) ? 1 : 0;
                  cantDiabetes2[i][j] += ((reg.diabetes.tiene) && (reg.diabetes.tipo == 2)) ? 1 : 0;

                  break;
                }
              }
            }
          }

        });

    });

    for (k = 1 ; k <= (cant*cant) ; k++) {
        for (i = 0; i < cant; i++) {
          for (j = 0; j < cant; j++) {

            respuesta[k] = {
              promedioTos: (sumTos[i][j]/contTos[i][j]),
              promedioDificultadRespiratoria: (sumDifResp[i][j]/contDifResp[i][j]),
              promedioEstornudo: (sumEstornudos[i][j]/contEstornudos[i][j]),
              promedioSibilancia: (sumSibilancia[i][j]/contSibilancia[i][j]),
              promedioCatarro: (sumCatarro[i][j]/contCatarro[i][j]),
              cantidadFumadores: cantFuma[i][j],
              cantidadAlergicos: cantAlergico[i][j],
              cantidadTrabajoPeligroso: cantTrabajoPeligroso[i][j],
              cantidadHipertiroides: cantHipertiroides[i][j],
              cantidadCeliaco: cantCeliaco[i][j],
              cantidadDiabetes1: cantDiabetes1[i][j],
              cantidadDiabetees2: cantDiabetes2[i][j],
              latMarcador: latMarc[k],
              lngMarcador: lngMarc[k],
            }

          }
        }
    }
    res.json(respuesta);

  });

  // app.post('api/maps', function(req,res){
    /*
    var ar_der = req.body.ar_der,
        ar_izq = req.body.ar_izq,
        ab_der = req.body.ab_der,
        ab_izq = req.body.ab_izq,
        fecha = req.body.fecha,
        cant = 3;

    //  medida de la pantalla
    var largo = ar_der.lat - ar_izq.lat;
    var alto = ar_izq.lng - ab_izq.lng;

    //espaciados
    var espaciadoX = largo/cant
    var espaciadoY = alto/cant

    //array correlativo
    var lat[];
    var lng[];

    for (var i = 0; i <= cant; i++) {
      push.lat(ab_izq.lat + (i * espaciadoX));
      push.lng(ab_izq.lng + (i * espaciadoY));
    }

    var respuesta = [];

    User
      .find(pos.lat: { $gt: ab_izq.lat, $lt: ab_lng.lat }, pos.lng: { $gt: ab_izq.lng, $lt: ar_izq.lng })
      .populate('register')
      .exec( function(err, doc){
        if (err) return handleError(err);

        doc.forEach(function(i, reg){

          for (var i = 1; i <= cant; i++) {
            if (reg.pos.lat <= lat[i]){
              for (var j = 1; j <= cant; j++) {
                if (reg.pos.lng <= lng[i]){

                }
              }
            }
          }

        });

    });

  });
  */
};
<commit_msg>fix ;<commit_after>'use strict';

/**
 * Module dependencies
 */
var mapsPolicy = require('../policies/maps.server.policy');
var maps = require('../controllers/maps.server.controller');
var Register = require('../../../registers/server/models/register.server.model');
var User = require('../../../users/server/models/user.server.model');

module.exports = function(app) {
  // Maps Routes
  // app.route('/api/maps').all(mapsPolicy.isAllowed)
  //   .get(maps.list)
  //   .post(maps.create);

  // app.route('/api/maps/:mapId').all(mapsPolicy.isAllowed)
  //   .get(maps.read)
  //   .put(maps.update)
  //   .delete(maps.delete);

  // // Finish by binding the Map middleware
  // app.param('mapId', maps.mapByID);

  app.post('api/maps', function(req,res) {
    var i,j,k;

    var ar_der = req.body.ar_der,
        ar_izq = req.body.ar_izq,
        ab_der = req.body.ab_der,
        ab_izq = req.body.ab_izq,
        fecha = req.body.fecha,
        cant = req.body.cant;

    //  medida de la pantalla
    var largo = ar_der.lng - ar_izq.lng;
    var alto = ar_izq.lat - ab_izq.lat;

    //espaciados para cuadrados(regiones)
    var espaciadoX = largo/cant;
    var espaciadoY = alto/cant;

    //esaciado para marcadores
    var espaciadoXmarcador = largo/(cant*2);
    var espaciadoYmarcador = alto/(cant*2);

    //array correlativo lonjitudes/latitudes se relacionan con el lugar en el array que ocupan
    var lat = [];
    var lng = [];

    //array de marcadores a pasar en el front-end
    var latMarc = [];
    var lngMarc = [];

    //llenando array de longitudes y latitudes
    for (i = 0; i <= cant; i++) {
      lng.push(ab_izq.lng + (i * espaciadoX));
      lat.push(ab_izq.lat + (i * espaciadoY));
    }

    //llenado de lat y lng de marcadores a enviar
    for (i = 0; i < cant; i++) {
      lngMarc.push(lng[i] + (i * espaciadoXmarcador));
      latMarc.push(lat[i] + (i * espaciadoYmarcador));
    }

    //arreglo de objetos a enviar
    var respuesta = [];

    //contadores y sumadores para sacar promedio
    var contTos = [][], sumTos = [][];
    var contDifResp = [][], sumDifResp = [][];
    var contEstornudos = [][], sumEstornudos = [][];
    var contSibilancia = [][], sumSibilancia = [][];
    var contCatarro = [][], sumCatarro = [][];

    //contadores de situacion personal de las regiones
    var cantFuma = [][],
        cantAlergico = [][],
        cantTrabajoPeligroso = [][],
        cantHipertiroides = [][],
        cantCeliaco = [][],
        cantDiabetes1 = [][],
        cantDiabetes2 = [][];

    //consulta a mongoDB restringiendo las lat y lng al cuadrado del mapa a pantalla completa
    User
      .find({
          pos.lat: { $gt: ab_izq.lat, $lt: ab_izq.lat },
          pos.lng: { $gt: ab_izq.lng, $lt: ar_der.lng }
      })
      //relacionando las personas con los registros
      .populate('register')
      .where({'create_at': fecha})
      .exec( function(err, doc){
        if (err) return handleError(err);

        //recorro todos los datos
        doc.forEach(function(l, reg){

          //recorro las latitudes
          for (i = 0; i < cant; i++) {
            if (reg.pos.lat <= lat[i]){
              //recorro las longitudes
              for (j = 0; j < cant; j++) {
                if (reg.pos.lng <= lng[j]){

              //arreglo bidimensional representando coordenadas (x,y)

                  //contadores para sacar promedio
                  contTos[i][j] += (reg.tos > 0) ? 1 : 0;
                  contDifResp[i][j] += (reg.dificultadRespiratoria) > 0 ? 1 : 0;
                  contEstornudos[i][j] += (reg.estornudos > 0) ? 1 : 0;
                  contSibilancia[i][j] += (reg.sibilancia > 0) ? 1 : 0;
                  contCatarro[i][j] += (reg.catarro > 0) ? 1 : 0;

                  //sumador para sacar promedio
                  sumTos[i][j] += (reg.tos > 0) ? reg.tos : 0;
                  sumDifResp[i][j] +=(reg.dificultadRespiratoria > 0) ? reg.dificultadRespiratoria : 0;
                  sumEstornudos[i][j] += (reg.estornudos > 0) ? reg.estornudos : 0;
                  sumSibilancia[i][j] += (reg.sibilancia > 0) ? reg.sibilancia : 0;
                  sumCatarro[i][j] += (reg.catarro > 0) ? reg.catarro : 0;

                  //estadisticas de personas
                  cantFuma[i][j] += reg.fuma ? 1 : 0;
                  cantAlergico[i][j] += reg.alergico ? 1 : 0;
                  cantTrabajoPeligroso[i][j] += reg.trabajoPeligroso ? 1 : 0;
                  cantHipertiroides[i][j] += reg.hipertiroides ? 1 : 0;
                  cantCeliaco[i][j] += reg.celiaco ? 1 : 0;
                  cantDiabetes[i][j] += (reg.diabetes) ? 1 : 0;

                }
              }
            }
          }

        });
      });//fin exec

    //llenando un array de objetos para enviar
    for (k = 1 ; k <= (cant*cant) ; k++) {

        //for anidados para recorrer arrays bidimensionales y asignarlos al array de objetos
        for (i = 0; i < cant; i++) {
          for (j = 0; j < cant; j++) {

            respuesta[k] = {
              promedioTos: (sumTos[i][j]/contTos[i][j]), //promedios
              promedioDificultadRespiratoria: (sumDifResp[i][j]/contDifResp[i][j]), //promedios
              promedioEstornudo: (sumEstornudos[i][j]/contEstornudos[i][j]), //promedios
              promedioSibilancia: (sumSibilancia[i][j]/contSibilancia[i][j]), //promedios
              promedioCatarro: (sumCatarro[i][j]/contCatarro[i][j]), //promedios
              cantidadFumadores: cantFuma[i][j],
              cantidadAlergicos: cantAlergico[i][j],
              cantidadTrabajoPeligroso: cantTrabajoPeligroso[i][j],
              cantidadHipertiroides: cantHipertiroides[i][j],
              cantidadCeliaco: cantCeliaco[i][j],
              cantidadDiabetes1: cantDiabetes1[i][j],
              cantidadDiabetees2: cantDiabetes2[i][j],
              latMarcador: latMarc[k],
              lngMarcador: lngMarc[k],
            }

          }
        }
    }

    res.json(respuesta);

  });

};
<|endoftext|>


<commit_before>import PropTypes from "prop-types";
import React, { useEffect, useMemo, useState, useRef } from "react";
import styled from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import Button from "@agir/front/genericComponents/Button";
import ModalWrapper from "@agir/front/genericComponents/Modal";

const StyledModalBody = styled.div`
  h4 {
    margin-top: 0;
    margin-bottom: 1rem;
    font-size: 1rem;
    font-weight: 600;
    line-height: 1.5;
  }

  p {
    margin: 0;
    padding: 0;
    font-size: 0.875rem;
    line-height: 1.5;

    strong {
      font-weight: 600;
    }
  }

  p + p {
    margin-top: 0.25rem;
  }
`;
const StyledModalFooter = styled.footer`
  display: flex;
  margin-top: 1.5rem;
  flex-flow: ${({ $inline }) => ($inline ? "row nowrap" : "column nowrap")};

  ${Button} {
    flex: 1 1 auto;
    justify-content: center;
    transition: opacity 250ms ease-in-out;
  }

  ${Button} + ${Button} {
    margin: ${({ $inline }) => ($inline ? "0 0 0 .5rem" : ".5rem 0 0")};
  }
`;
const StyledModalContent = styled.div`
  max-width: 415px;
  margin: 40px auto;
  background-color: ${style.white};
  border-radius: 8px;
  padding: 1rem;

  @media (max-width: ${style.collapse}px) {
    margin: 0;
    border-radius: 0;
    max-width: 100%;
    min-height: 100vh;
  }
`;

const Steps = {
  delete: [
    ({ isLoading, onClose, onDelete }) => (
      <>

      </>
    ),
    ({ isLoading, onClose, onReport }) => (
      <>

      </>
    ),
    ({ onClose }) => (
      <>

      </>
    ),
  ],
  report: [
    ({ isLoading, onClose, onReport }) => (
      <>

      </>
    ),
    ({ isLoading, onClose, onDelete }) => (
      <>

      </>
    ),
    ({ onClose }) => (
      <>

      </>
    ),
  ],
};

const MessageActionModal = (props) => {
  const {
    action,
    shouldShow,
    onClose,
    onDelete,
    onReport,
    isLoading,
    error,
  } = props;
  const [step, setStep] = useState(0);
  const nextStep = useRef(0);
  const lastStep = useRef(null);

  const Step = useMemo(() => {
    const Step =
      action && Steps[action] ? Steps[action][step] : lastStep.current;
    lastStep.current = Step;
    return Step;
  }, [action, step]);

  const handleDelete = useMemo(
    () =>
      typeof onDelete === "function"
        ? () => {
            nextStep.current += 1;
            onDelete();
          }
        : undefined,
    [onDelete]
  );

  const handleReport = useMemo(
    () =>
      typeof onReport === "function"
        ? () => {
            nextStep.current += 1;
            onReport();
          }
        : undefined,
    [onReport]
  );

  useEffect(() => {
    if (!isLoading && step !== nextStep.current) {
      if (!error) {
        setStep(nextStep.current);
      } else {
        nextStep.current = step;
      }
    }
  }, [isLoading, error, step]);

  useEffect(() => {
    if (shouldShow) {
      setStep(0);
      nextStep.current = 0;
    }
  }, [shouldShow]);

  return (
    <ModalWrapper
      shouldShow={shouldShow && !!Step}
      onClose={isLoading ? undefined : onClose}
      noScroll
    >

    </ModalWrapper>
  );
};
MessageActionModal.propTypes = {
  action: PropTypes.oneOf(Object.keys(Steps)),
  error: PropTypes.string,
  isLoading: PropTypes.bool,
  shouldShow: PropTypes.bool,
  onClose: PropTypes.func,
  onDelete: PropTypes.func,
  onReport: PropTypes.func,
};
export default MessageActionModal;
<commit_msg>fix: update MessageActionModal second step dismiss button text<commit_after>import PropTypes from "prop-types";
import React, { useEffect, useMemo, useState, useRef } from "react";
import styled from "styled-components";

import style from "@agir/front/genericComponents/_variables.scss";

import Button from "@agir/front/genericComponents/Button";
import ModalWrapper from "@agir/front/genericComponents/Modal";

const StyledModalBody = styled.div`
  h4 {
    margin-top: 0;
    margin-bottom: 1rem;
    font-size: 1rem;
    font-weight: 600;
    line-height: 1.5;
  }

  p {
    margin: 0;
    padding: 0;
    font-size: 0.875rem;
    line-height: 1.5;

    strong {
      font-weight: 600;
    }
  }

  p + p {
    margin-top: 0.25rem;
  }
`;
const StyledModalFooter = styled.footer`
  display: flex;
  margin-top: 1.5rem;
  flex-flow: ${({ $inline }) => ($inline ? "row nowrap" : "column nowrap")};

  ${Button} {
    flex: 1 1 auto;
    justify-content: center;
    transition: opacity 250ms ease-in-out;
  }

  ${Button} + ${Button} {
    margin: ${({ $inline }) => ($inline ? "0 0 0 .5rem" : ".5rem 0 0")};
  }
`;
const StyledModalContent = styled.div`
  max-width: 415px;
  margin: 40px auto;
  background-color: ${style.white};
  border-radius: 8px;
  padding: 1rem;

  @media (max-width: ${style.collapse}px) {
    margin: 0;
    border-radius: 0;
    max-width: 100%;
    min-height: 100vh;
  }
`;

const Steps = {
  delete: [
    ({ isLoading, onClose, onDelete }) => (
      <>

      </>
    ),
    ({ isLoading, onClose, onReport }) => (
      <>

      </>
    ),
    ({ onClose }) => (
      <>

      </>
    ),
  ],
  report: [
    ({ isLoading, onClose, onReport }) => (
      <>

      </>
    ),
    ({ isLoading, onClose, onDelete }) => (
      <>

      </>
    ),
    ({ onClose }) => (
      <>

      </>
    ),
  ],
};

const MessageActionModal = (props) => {
  const {
    action,
    shouldShow,
    onClose,
    onDelete,
    onReport,
    isLoading,
    error,
  } = props;
  const [step, setStep] = useState(0);
  const nextStep = useRef(0);
  const lastStep = useRef(null);

  const Step = useMemo(() => {
    const Step =
      action && Steps[action] ? Steps[action][step] : lastStep.current;
    lastStep.current = Step;
    return Step;
  }, [action, step]);

  const handleDelete = useMemo(
    () =>
      typeof onDelete === "function"
        ? () => {
            nextStep.current += 1;
            onDelete();
          }
        : undefined,
    [onDelete]
  );

  const handleReport = useMemo(
    () =>
      typeof onReport === "function"
        ? () => {
            nextStep.current += 1;
            onReport();
          }
        : undefined,
    [onReport]
  );

  useEffect(() => {
    if (!isLoading && step !== nextStep.current) {
      if (!error) {
        setStep(nextStep.current);
      } else {
        nextStep.current = step;
      }
    }
  }, [isLoading, error, step]);

  useEffect(() => {
    if (shouldShow) {
      setStep(0);
      nextStep.current = 0;
    }
  }, [shouldShow]);

  return (
    <ModalWrapper
      shouldShow={shouldShow && !!Step}
      onClose={isLoading ? undefined : onClose}
      noScroll
    >

    </ModalWrapper>
  );
};
MessageActionModal.propTypes = {
  action: PropTypes.oneOf(Object.keys(Steps)),
  error: PropTypes.string,
  isLoading: PropTypes.bool,
  shouldShow: PropTypes.bool,
  onClose: PropTypes.func,
  onDelete: PropTypes.func,
  onReport: PropTypes.func,
};
export default MessageActionModal;
<|endoftext|>