var contentPosSet = false;
var topPosition;
var heightLessFooter;
var where='';
var val;
var mon=1;
var mouseX = 0;
var mouseY = 0;
var defMonth = 0;
var d = new Date();
var nowMonth = d.getMonth() + 1;
$(document).mousemove( function(e) {
mouseX = e.pageX;
mouseY = e.pageY;
});
/**params for CDA to by pass js errors**/
var city_prefix='chicago';
var default_zip='60601';
function isValidZipCode(){ return true; }
$(document).ready(function() {
defMonth = $('#homicideapp').attr('data-currmonth');
$(window).scroll(function(){
if($('.leaflet-popup-content-wrapper').length > -1){
$('.leaflet-popup-content-wrapper').remove();
$('.leaflet-popup-tip-container').remove();
}
})
$(".murder-modal").css("display","block");
// App Model
var AppState = Backbone.Model.extend({
defaults: {
mapboxID: 'dnainfo',
mapboxBaseLayer: 'map-fo2sfxjw',
cartodbID: 'dnainfo',
//cartodbTable: 'chicago_homicide'
cartodbTable: table_prefix + 'homicide_20130104_di'
}
});
var map_zoom = false;
/**
* Helper class to create sql statements with conditions based on input from user filters.
* - querystart - everything in the query BEFORE the where clauses.
* - queryend - everything in the query AFTER the where clauses.
* - whereClauses - optional array of where clauses to inject into query.
*/
function getParameterByName(name){
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function DnaInfoQueryBuilder(querystart, queryend, whereClauses) {
if (!_.isArray(whereClauses)) {
whereClauses = new Array();
}
if (getQueryVariable('neighborhood')) {
var neighborhood = getQueryVariable('neighborhood');
neighborhood = neighborhood.replace(/\+/g, ' ');
whereClauses.push(table_prefix + 'homicide_20130104_di.neighborhood = \'' + _.escape(neighborhood) + '\'');
where = "where neighborhood='"+neighborhood+"'";
}
if (getQueryVariable('cause')) {
var cause = getQueryVariable('cause');
cause = cause.replace(/\+/g, ' ');
if(cause=='Other'){
whereClauses.push(table_prefix + "homicide_20130104_di.cause not in ('Stabbing','Strangulation','Shooting','Assault')");
}else{
whereClauses.push(table_prefix + 'homicide_20130104_di.cause = \'' + _.escape(cause) + '\'');
}
}
var raceGroups = ['B', 'W', 'H', 'O', 'U'];
if (getQueryVariable('race')) {
var race = getQueryVariable('race');
whereClauses.push(table_prefix + 'homicide_20130104_di.race = \'' + raceGroups[race] + '\'');
}
var ageGroups = {
'0': {
'min': 0,
'max': 12
},
'1': {
'min': 13,
'max': 17
},
'2': {
'min': 18,
'max': 24
},
'3': {
'min': 25,
'max': 34
},
'4': {
'min': 35,
'max': 44
},
'5': {
'min': 45,
'max': 54
},
'6': {
'min': 55,
'max': 64
},
'7': {
'min': 65,
'max': 130
}
};
if (getQueryVariable('age')) {
var ageGroupId = getQueryVariable('age');
if (ageGroups[ageGroupId]) {
whereClauses.push(table_prefix + 'homicide_20130104_di.age >= \'' + ageGroups[ageGroupId].min + '\'');
whereClauses.push(table_prefix + 'homicide_20130104_di.age <= \'' + ageGroups[ageGroupId].max + '\'');
}
}
whereClauses.push(timeclause);
var whereQueryString = '';
if (whereClauses && whereClauses.length) {
whereQueryString = 'WHERE ' + whereClauses.join(' AND ');
}
return querystart + whereQueryString + queryend;
}
/**
* MapView
*/
var last_hood = '';
var hood_lat_lon = '';
var MapView = Backbone.View.extend({
popup: undefined,
initialize: function() {
var that = this;
_.bindAll(this, 'render', 'openIndividualPopup');
var file_link='';
var cause = getQueryVariable('cause');
if(cause){
cause = cause.replace('+', '');
file_link = '/css/chicago-murders/mapstyle_'+cause+'.carto';
}else{
file_link = '/css/chicago-murders/mapstyle.carto';
}
$.get(file_link, function(data) {
that.cartoStyle = data;
that.render();
}, 'text');
this.collection.bind('add', this.render);
},
renderWidePopup: function(ev, latlng, pos, data) {
if (this.map.getZoom() < 12) {
var homicide_text = 'homicide';
var avg_dis_text = data.avg_distance;
if(data.homicide_count > 1){
homicide_text = 'homicides';
}
if(last_hood!=data.neighborhood_name ){
hood_lat_lon = latlng;
last_hood=data.neighborhood_name;
}
if(data.avg_age==0) data.avg_age = 'N/A';
avg_dis_text = data.avg_distance+' mi.';
var content = "
" + data.neighborhood_name + "
" + data.homicide_count + " " + homicide_text + "
Avg. Age: " + data.avg_age + "
Avg. Distance From Home: " + avg_dis_text + "
";
if (!this.popup && !map_zoom) {
//this.popup = L.popup().setLatLng(latlng).setContent(content).openOn(this.map);
this.popup = L.popup({autoPan:true}).setLatLng(hood_lat_lon).setContent(content).openOn(this.map);
if(mouseX > 0)
{
$('.leaflet-popup-content-wrapper').appendTo('#homicideapp');
$('.leaflet-popup-content-wrapper').css('position','fixed');
$('.leaflet-popup-content-wrapper').css('top',mouseY-$(window).scrollTop()-165 + 'px');
$('.leaflet-popup-content-wrapper').css('left',mouseX-105 + 'px');
$('.leaflet-popup-content-wrapper').css('z-index','9999');
$('.leaflet-popup-tip-container').appendTo('#homicideapp');
$('.leaflet-popup-tip-container').css('position','fixed');
$('.leaflet-popup-tip-container').css('top',mouseY-$(window).scrollTop()-35+18+ 'px');
$('.leaflet-popup-tip-container').css('left',mouseX-20 + 'px');
$('.leaflet-popup-tip-container').css('z-index','9999');
this.map.on('popupclose', function(e){
if($('.leaflet-popup-content-wrapper').length > -1){
$('.leaflet-popup-content-wrapper').remove();
$('.leaflet-popup-tip-container').remove();
}
});
}
}
else {
//this.popup.setContent(content).setLatLng(latlng);
this.popup.setContent(content).setLatLng(hood_lat_lon);
if(mouseX > 0)
{
$('.leaflet-popup-content-wrapper').appendTo('#homicideapp');
$('.leaflet-popup-content-wrapper').css('position','fixed');
$('.leaflet-popup-content-wrapper').css('top',mouseY-165-$(window).scrollTop() + 'px');
$('.leaflet-popup-content-wrapper').css('left',mouseX-105 + 'px');
$('.leaflet-popup-content-wrapper').css('z-index','9999');
$('.leaflet-popup-tip-container').appendTo('#homicideapp');
$('.leaflet-popup-tip-container').css('position','fixed');
$('.leaflet-popup-tip-container').css('top',mouseY-$(window).scrollTop()-35 +18+ 'px');
$('.leaflet-popup-tip-container').css('left',mouseX-20 + 'px');
$('.leaflet-popup-tip-container').css('z-index','9999');
this.map.on('popupclose', function(e){
if($('.leaflet-popup-content-wrapper').length > -1){
$('.leaflet-popup-content-wrapper').remove();
$('.leaflet-popup-tip-container').remove();
}
});
}
}
}
},
render: function() {
var that = this;
$(this.el).css('height', '685px');
if (_.isString(this.cartoStyle) && _.isUndefined(this.map)) {
var legend_type;
var cause = getQueryVariable('cause');
switch(cause){
case 'Shooting':
legend_type = '_gunshot';
break;
case 'Stabbing':
legend_type = '_stabbings';
break;
case 'Assault':
legend_type = '_assault';
break;
case 'Strangulation':
legend_type = '_stranglings';
break;
case 'Other':
legend_type = '_auto';
break;
default:
legend_type = '';
break;
}
this.map = L.map(this.el, {
minZoom: 10,
maxZoom: 16,
maxBounds: new L.LatLngBounds(new L.LatLng(42.5, -88.45), new L.LatLng(41.3, -86.75)),
doubleClickZoom: false
}).setView([41.802355184289396, -87.79066782637711], 11);
var baseLayer = L.tileLayer('https://{s}.tiles.mapbox.com/v3/' + App.appState.get('mapboxID') + '.' + App.appState.get('mapboxBaseLayer') + '/{z}/{x}/{y}.png', {
attribution: 'Mapbox Streets',
maxZoom: 13
});
this.map.addLayer(baseLayer);
$(this.el).after('');
this.homicideWideView = new L.CartoDBLayer({
map: this.map,
user_name: App.appState.get('mapboxID'),
table_name: table_prefix + 'chicago_neighborhoods',
minZoom: 10,
maxZoom: 13,
query: DnaInfoQueryBuilder("SELECT COUNT(" + table_prefix + "homicide_20130104_di.the_geom_webmercator) AS homicide_count, round(avg(" + table_prefix + "homicide_20130104_di.age::decimal),0) as avg_age, round(avg(" + table_prefix + "homicide_20130104_di.distance::decimal),1) as avg_distance, " + table_prefix + "chicago_neighborhoods.the_geom_webmercator, " + table_prefix + "chicago_neighborhoods.name AS neighborhood_name FROM " + table_prefix + "homicide_20130104_di," + table_prefix + "chicago_neighborhoods ", " GROUP BY " + table_prefix + "chicago_neighborhoods.the_geom_webmercator, neighborhood_name", ["ST_Contains(" + table_prefix + "chicago_neighborhoods.the_geom_webmercator, " + table_prefix + "homicide_20130104_di.the_geom_webmercator) AND " + table_prefix + "homicide_20130104_di.age ~ '\\d+'"]),
tile_style: (this.cartoStyle) ? this.cartoStyle : '',
interactivity: "homicide_count, neighborhood_name, avg_age, avg_distance",
featureClick: function(ev, latlng, pos, data) {
that.renderWidePopup(ev, latlng, pos, data);
},
featureOver: function(ev, latlng, pos, data){
that.renderWidePopup(ev, latlng, pos, data);
},
featureOut: function(ev, latlng, pos, data){
if (that.popup) {
that.popup._close();
that.popup = undefined;
}
},
attribution: "CartoDB",
auto_bound: false
});
this.map.addLayer(this.homicideWideView);
if (getQueryVariable('neighborhood')) {
this.homicideWideView.setBounds('SELECT * FROM ' + table_prefix + 'chicago_neighborhoods WHERE name = \'' + getQueryVariable('neighborhood') + "'");
}
this.homicideNarrowView = new L.CartoDBLayer({
map: this.map,
user_name: App.appState.get('mapboxID'),
table_name: App.appState.get('cartodbTable'),
minZoom: 12,
maxZoom: 14,
query: DnaInfoQueryBuilder("SELECT * FROM {{table_name}} ", ""),
tile_style: (this.cartoStyle) ? this.cartoStyle : '',
interactivity: "cartodb_id,gdoc_id",
featureClick: function(ev, latlng, pos, data) {
if (data.cartodb_id != that.individualPopup) {
var aHomicideModel = that.collection.where({gdoc_id: data.cartodb_id})[0];
if (aHomicideModel) {
that.openIndividualPopup(aHomicideModel);
}
}
},
featureOver: function(ev, latlng, pos, data) {
document.body.style.cursor = 'pointer';
if (data.cartodb_id != that.individualPopup) {
var aHomicideModel = that.collection.where({gdoc_id: data.cartodb_id})[0];
if (aHomicideModel) {
that.openIndividualPopup(aHomicideModel);
}
}
},
featureOut: function(ev, latlng, pos, data) {
document.body.style.cursor = 'default';
},
attribution: "CartoDB",
auto_bound: false
});
this.map.on('zoomstart', function(e) {
map_zoom = true;
if($('.leaflet-popup-content-wrapper').length > -1){
$('.leaflet-popup-content-wrapper').remove();
$('.leaflet-popup-tip-container').remove();
}
});
this.map.on('zoomend', function(e) {
map_zoom = false;
if (this.getZoom() < 12) {
this.removeLayer(that.homicideNarrowView);
} else {
this.addLayer(that.homicideNarrowView);
}
});
var center = this.map.getCenter();
var bounds = this.map.getBounds();
var minimap = L.map('mini-map', {
zoomControl: false,
attributionControl: false,
worldCopyJump: false,
center: center,
zoom: 9,
dragging: false,
touchZoom: false
});
var baseLayer2 = L.tileLayer('https://{s}.tiles.mapbox.com/v3/' + App.appState.get('mapboxID') + '.' + App.appState.get('mapboxBaseLayer') + '/{z}/{x}/{y}.png', {
attribution: 'Mapbox Streets',
maxZoom: 13
});
minimap.addLayer(baseLayer2);
var rectangle = L.rectangle(bounds, {color: '#f00', weight: 1});
// alert(getQueryVariable('cause'))
switch(getQueryVariable('cause')){
case 'Stabbing':
rectangle = L.rectangle(bounds, {color: '#2951ff', weight: 1});
break;
case 'Assault':
rectangle = L.rectangle(bounds, {color: '#ff681e', weight: 1});
break;
case 'Strangulation':
rectangle = L.rectangle(bounds, {color: '#743591', weight: 1});
break;
case 'Shooting':
rectangle = L.rectangle(bounds, {color: '#efd440', weight: 1});
break;
case 'Other':
rectangle = L.rectangle(bounds, {color: '#368859', weight: 1});
break;
}
rectangle.dragging = new L.Handler.PolyDrag(rectangle);
minimap.addLayer(rectangle);
rectangle.dragging.enable();
rectangle.on('dragend', function() {
var bounds = rectangle.getBounds();
// that.map.panTo(bounds.getCenter());
// alert(bounds.getCenter())
});
this.map.on('moveend', function(e) {
rectangle.setBounds(this.getBounds());
});
this.map.on('viewreset', function(e) {
rectangle.setBounds(this.getBounds());
});
}
if (this.itemID) {
var aHomicideModel = this.collection.where({gdoc_id: this.itemID})[0];
if (aHomicideModel) {
this.openIndividualPopup(aHomicideModel);
}
}
},
openIndividualPopup: function(aHomicideModel) {
this.individualPopup = aHomicideModel.get('gdoc_id');
var aHomicideView = new HomicideView({model: aHomicideModel});
var latlng = new L.LatLng(aHomicideModel.get('lat'), aHomicideModel.get('lon'));
//this.map.setView(latlng, 13);
this.map.on('drag', function(e){
$('.leaflet-popup-content-wrapper').remove();
$('.leaflet-popup-tip-container').remove();
});
var popup = L.popup({autoPan:true}).setLatLng(latlng).setContent(aHomicideView.render().el).openOn(this.map);
if(mouseX > 0)
{
$('.leaflet-popup-content-wrapper').appendTo('#homicideapp');
if(mouseX < 1)
{
var r_x=this.map.latLngToLayerPoint(latlng).x;
var r_y=this.map.latLngToLayerPoint(latlng).y;
}
if(mouseX > 0)
{
var yDiff = mouseY;
var margin = ($(document).width()-964)/2;
var yPan = 0;
var xPan = 0;
if((mouseX-135) < margin){
xPan = (margin - (mouseX-135))+40;
}
if((mouseX+135) > (margin+964)){
xPan = (margin+964)-(mouseX+135)-20;
}
if(yDiff-258 < 340){
yPan = 340-(yDiff-258);
}
$('.leaflet-popup-content-wrapper').css('position','fixed');
$('.leaflet-popup-content-wrapper').css('top',mouseY-$(window).scrollTop()-255+yPan + 'px');
$('.leaflet-popup-content-wrapper').css('left',mouseX-165 + xPan + 'px');
$('.leaflet-popup-content-wrapper').css('z-index','9999');
$('.leaflet-popup-content-wrapper').css('height','258px');
$('.leaflet-popup-content-wrapper').css('width','370px');
$('.leaflet-popup-tip-container').appendTo('#homicideapp');
$('.leaflet-popup-tip-container').css('position','fixed');
$('.leaflet-popup-tip-container').css('top',mouseY-$(window).scrollTop() -15+yPan + 'px');
$('.leaflet-popup-tip-container').css('left',mouseX-20 + xPan + 'px');
$('.leaflet-popup-tip-container').css('z-index','9999');
}
this.map.on('popupclose', function(e){
if($('.leaflet-popup-content-wrapper').length > -1){
$('.leaflet-popup-content-wrapper').remove();
$('.leaflet-popup-tip-container').remove();
}
});
}
}
});
/**
* MapFilterView
*/
var MapFilterView = Backbone.View.extend({
initialize: function() {
var that = this;
$.ajax({
url: DnaInfoQueryBuilder(cdaSettings.cartodb.base_url+"?q=SELECT COUNT(" + table_prefix + "homicide_20130104_di.the_geom_webmercator) AS homicide_count, " + table_prefix + "chicago_neighborhoods.the_geom_webmercator, " + table_prefix + "chicago_neighborhoods.name AS neighborhood_name FROM " + table_prefix + "homicide_20130104_di," + table_prefix + "chicago_neighborhoods ", " GROUP BY " + table_prefix + "chicago_neighborhoods.the_geom_webmercator, neighborhood_name", ["ST_Contains(" + table_prefix + "chicago_neighborhoods.the_geom_webmercator, " + table_prefix + "homicide_20130104_di.the_geom_webmercator) "])+"&api_key="+cdaSettings.cartodb.api_key,
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
if (data.rows.length == 0) {
$(that.el).after('No incidents found.
');
}
}
});
},
render: function() {
var that = this;
var ageGroups = [
'12 or younger',
'13-17',
'18-24',
'25-34',
'35-44',
'45-54',
'55-64',
'65+'
];
var raceGroups = ['Black','White','Hispanic','Other','Unknown'];
$(this.el).html('');
// populate age select form
$.each(ageGroups, function(i, item) {
var ageGroupId = getQueryVariable('age');
var selectedAttribute = '';
if (i === parseInt(ageGroupId)) {
selectedAttribute = 'selected="selected"';
}
$('select[name="age"]').append('');
});
// populate race select form
$.each(raceGroups, function(i, item) {
var raceGroupId = getQueryVariable('race');
var selectedAttribute = '';
if (i === parseInt(raceGroupId)) {
selectedAttribute = 'selected="selected"';
}
$('select[name="race"]').append('');
});
// populate neighborhood select form
var currentNeighborhood = getQueryVariable('neighborhood');
if (currentNeighborhood) {
currentNeighborhood = currentNeighborhood.replace('+', ' ');
}
$.ajax({
url: cdaSettings.cartodb.base_url+'?q=SELECT * FROM ' + table_prefix + 'chicago_neighborhoods ORDER BY name'+"&api_key="+cdaSettings.cartodb.api_key,
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
$.each(data.rows, function(i, datum) {
var neighborhoodSelectedAttribute = '';
if (currentNeighborhood == datum.name) {
neighborhoodSelectedAttribute = 'selected="selected"';
}
//$('select[name="neighborhood"]', that.el).append('');
});
//$('select[name="neighborhood"]', that.el).chosen();
}
});
$('.btn-clear').click(function(e) {
$('select[name="neighborhood"]', that.el).val('');
$('select[name="age"]', that.el).val('');
$('select[name="race"]', that.el).val('');
});
},
renderNoResults: function() {
alert(this.collection.length);
}
});
/**
* HomicideModel
*/
var HomicideModel = Backbone.Model.extend({
defaults: {
gdoc_id: -1,
name: '',
address: '',
age: '',
date: '',
neighborhood: '',
cause: '',
lat:'',
lon:'',
story_link: '',
image_link: '',
image_tag:'',
age_tag:'',
cause_tag:''
},
initialize: function() {
var myDate = new Date(this.get('date'));
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var daysOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
this.set('formatted_date', months[myDate.getMonth()] + ' ' + myDate.getDate() + ', ' + myDate.getFullYear());
}
});
/**
* NeighborhoodsCollection
*/
var NeighborhoodsCollection = Backbone.Collection.extend({
initialize: function() {
var that = this;
$('#hoods').append('All Neighborhoods');
$.ajax({
url: cdaSettings.cartodb.base_url+"?q=SELECT neighborhood FROM " + table_prefix + "homicide_20130104_di where neighborhood!='' group by neighborhood order by neighborhood"+"&api_key="+cdaSettings.cartodb.api_key,
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
_.each(data.rows, function(datum) {
//alert(datum.neighborhood)
$('#hoods').append(''+datum.neighborhood+'');
});
}
});
}
});
/**
* HomicideCollection
*/
var HomicideCollection = Backbone.Collection.extend({
model: HomicideModel,
initialize: function() {
where = 'where ';
if(getQueryVariable('mon')){
mon = (getQueryVariable('mon') >=1 && getQueryVariable('mon') <= 12)? getQueryVariable('mon') : defMonth;
//where += "extract(month from date::timestamp)="+mon+ " AND ";
}
where += timeclause;
$('#hero').html(timeline_year + ' DEATH TOLL : ');
var that = this;
$.ajax({
url: cdaSettings.cartodb.base_url+"?q=SELECT *, ST_AsGeoJSON(the_geom) AS geom_raw ,time,(select count(*) from " + table_prefix + "homicide_20130104_di " + where + ") as death_toll FROM " + table_prefix + "homicide_20130104_di "+where+" order by date_backup,name"+"&api_key="+cdaSettings.cartodb.api_key,
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
$('#hero').html(timeline_year + ' DEATH TOLL : '+data.rows[0].death_toll);
_.each(data.rows, function(datum) {
var geomDataRaw = JSON.parse(datum.geom_raw);
var homicide = new HomicideModel({
gdoc_id: datum.cartodb_id,
name: datum.name,
address: datum.address_of_occurrence,
age: datum.age,
age_type: datum.age_type,
date: datum.date,
neighborhood: datum.neighborhood,
murder_lat: datum.lat,
murder_lon: datum.lon,
cause: datum.cause,
time: datum.time,
race: datum.race,
story_link: datum.story_link,
image_link: datum.image_link,
lat: (geomDataRaw) ? geomDataRaw.coordinates[1] : undefined,
lon: (geomDataRaw) ? geomDataRaw.coordinates[0] : undefined
});
that.add(homicide);
$('.murder-modal').css('display','none');
});
}
});
}
});
/**
* HomicideView
*/
var HomicideView = Backbone.View.extend({
tagName: 'div',
className: 'homicide',
template: _.template($('#homicide_template').html()),
initialize: function() {
_.bindAll(this, 'render');
},
render: function(options) {
var values = this.model.toJSON();
values = _(values).extend(options);
if(values.time){
values.time = 'Time: '+values.time+'';
}
if (!values.image_link) {
values.iam=4;
this.$el.addClass('no-image');
}
else {
this.$el.addClass('image');
if(values.image_link!=''){
values.image_tag= "
";
if(values.story_link!="")
values.image_tag = "
";
}
}
if(values.age == null || values.age==0 || values.age==''){
values.age_tag = ''
}else if(values.name=='Emonie Star-Beasley Brown'){
values.age_tag = 'Age: 3 weeks';
}else{
if(values.age_type == null || values.age_type == 'years')
{
if(values.age <= 1)
{
values.age_type = 'year';
}
else
{
values.age_type = 'years';
}
}
else if(values.age_type == 'months')
{
values.age = Math.round(Number(values.age)*12);
if(values.age <= 1)
{
values.age_type = 'month';
}
}
else if(values.age_type == 'weeks')
{
values.age = truncate(values.age * 52);
if(values.age <= 1)
{
values.age_type = 'week';
}
}
values.age_tag = 'Age: '+values.age+ ' ' + values.age_type;
}
if(values.cause==''){
values.cause_tag =''
}else{
values.cause_tag = 'Cause: '+values.cause;
}
if(values.name){
values.title = values.name;
}
if(values.story_link){
values.title = "" + values.name + '';
values.story_link ='';
}
var clean_name = values.name.replace(/ /g,"");
if (values.position) {
this.$el.addClass('span6');
this.$el.attr('id',clean_name);
this.$el.addClass(values.position);
}
this.$el.html(this.template(values));
return this;
}
});
/**
* TimelineView
*/
var TimelineView = Backbone.View.extend({
id: 'timeline',
initialize: function() {
$('#timeline-wrapper').show()
$('#timeline-mon-nav').show()
$('#timeline-menu-wrapper').show()
this.positionCounter = 0;
this.m = (getQueryVariable('mon')&&getQueryVariable('mon')>=0)?getQueryVariable('mon')-1:(defMonth-1);
this.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
this.monthIncidentCounter = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
_.bindAll(this, 'render', 'appendItem'); // every function that uses 'this' as the current object should be in here
this.collection.bind('add', this.appendItem);
this.render();
},
render: function() {
var that = this;
//set current button
$('.mon:eq('+this.m+')').addClass('current');
//add days red dot
var days=new Date(timeline_year, this.m+1, 0).getDate();
var day_div = '';
for(var i=1;i<=days;i++){
var day= ''+i.toString().lpad(0,2)+'
';
day_div += day;
}
$(that.el).append(''+
'
= 1 person
'+
'
'+this.months[this.m].toUpperCase()+'
'+
day_div+
'
'+
'
');
$('#timeline-wrapper').show();
$('#timeline-mon-nav').show();
//Obtain list of years
$.ajax({
url: cdaSettings.cartodb.base_url+"?q=SELECT date_backup FROM " + table_prefix + "homicide_20130104_di order by date_backup desc LIMIT 1"+"&api_key="+cdaSettings.cartodb.api_key, //Query here,
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
_.each(data.rows, function(datum) {
var darray = datum.date_backup.split('T');
var darray = darray[0].split('-');
var thisyear = darray[0];
if ((thisyear - 2012) > 0)
{
for(var i = 0; i < (thisyear - 2012);i++)
{
var nextyear = 2012 + (i+1);
years.push(nextyear);
var myclass = '';
if(timeline_year == nextyear)
{
myclass = 'class="active"';
}
$('.yearselector').append('' + nextyear + '');
}
}
var current = ($('.months .current').index() < 0)? 0:$('.months .current').index() + 1;
if((current > 1 || timeline_year > 2012))
{
$('#timeline-mon-nav .prev').removeClass('deactivated');
}
//Gray out the dates that have no data
$.ajax({
url: cdaSettings.cartodb.base_url+"?q=SELECT date_backup FROM " + table_prefix + "homicide_20130104_di where date_backup <= '" + timeline_year + "-12-31' and date_backup >= '" + timeline_year + "-01-01' order by date_backup desc LIMIT 1"+"&api_key="+cdaSettings.cartodb.api_key, //Query here,
dataType: 'jsonp',
crossDomain: true,
success: function(data) {
var month = -1;
_.each(data.rows, function(datum) {
var darray = datum.date_backup.split('T');
var darray = darray[0].split('-');
month = darray[1];
month = Number(month);
var yearhtml = '';
for(var i = 0; i < month;i++)
{
$('#mon' + (i+1)).removeClass('deactive');
$('#mon' + (i+1)).attr('href','/chicago/'+timeline_year+'-chicago-murders/timeline?mon=' + (i+1));
yearhtml += '' + montha[i] + '';
}
$('#yearbox .dropdown-menu').html(yearhtml);
});
if(getQueryVariable('mon')){
if(month == -1)
month = 1;
var currMonth = getQueryVariable('mon');
}
else
{
$('#yearbox .default_val').html('January');
var currMonth = nowMonth;
}
var current = ($('.months .current').index() < 0)? 0:$('.months .current').index()+1;
var currIndex = 0;
if((Number(month)) < currMonth)
{
location.href = '/chicago/' + timeline_year + '-chicago-murders/timeline?mon=' + (Number(month)); //IE
}
if((current < (Number(month)) || timeline_year < years[years.length-1]))
{
$('#timeline-mon-nav .next').removeClass('deactivated');
}
var mymonth = montha[currMonth-1];
$('#yearbox .default_val').html(mymonth);
}
});
});
}
});
},
appendItem: function(item) {
var homicideView = new HomicideView({
model: item,
});
var position = (this.positionCounter % 2 == 0) ? 'pull-left' : 'pull-right';
var itemDate = new Date(item.get('date'));
var itemMonth = itemDate.getMonth();
this.monthIncidentCounter[itemMonth]++;
$('.' + this.months[itemMonth].toLowerCase() + ' h1.date a').text(this.months[itemMonth] + ' (' + this.monthIncidentCounter[itemMonth] + ')');
$('.' + this.months[itemMonth].toLowerCase() + ' .content', this.el).append(homicideView.render({position: position}).el);
$('.' + this.months[itemMonth].toLowerCase() + ' .murder-content-nav .murder-by-day .day',this.el).eq(itemDate.getDate()-1).append('')
if($('.' + this.months[itemMonth].toLowerCase() + ' .content .homicide').length==2){
// $('#'+item.get('name').replace(/ /g,"")).css('margin-top','100px');
}
if(this.positionCounter==1){
$('.' + this.months[itemMonth].toLowerCase() +' .homicide:eq(1)').addClass('margin-pad');
}
this.positionCounter++;
}
});
var MyRouter = Backbone.Router.extend({
routes: {
"": "index",
"map": "map",
"map?id=:id": "map",
"timeline": "timeline",
"timeline?mon=:mon": "timeline",
"explore-data": "exploreData"
},
initialize: function() {
this.main = $('#main');
this.appState = new AppState();
this.homicideCollection = new HomicideCollection();
},
index: function() {
this.timeline();
},
map: function(id) {
this.mapView = new MapView({el: $('#map-wrapper'), collection: this.homicideCollection});
if (!this.mapFormView) {
this.mapFilterView = new MapFilterView({el: $('#map-form'), collection: this.homicideCollection});
}
if (id) {
this.mapView.itemID = parseInt(id);
}
else {
this.mapView.itemID = undefined;
}
},
timeline: function() {
var timeline = $('#timeline');
if (!this.timelineView) {
this.timelineView = new TimelineView({el: $('#timeline-wrapper'), collection: this.homicideCollection});
}
},
exploreData: function() {
//hoods nav
var hoods = new NeighborhoodsCollection();
//diagrams
}
});
var App = new MyRouter();
Backbone.history.start({pushState: true, root: '/chicago/' + timeline_year + '-chicago-murders'});
//
/** timeline-wrapper go-next go-prev**/
$('#timeline-mon-nav div').click(function(e){
var current = ($('.months .current').index() < 0)? 0:$('.months .current').index();
if($(this).hasClass('prev')){
// $('.months .mon:eq('+(current==0?11:(current-1))+')').click();
if(current == 0)
{
if(timeline_year > 2012)
{
location.href = '/chicago/' + (Number(timeline_year)-1) + '-chicago-murders/timeline?mon=12'; //IE
}
}
else
{
location.href = $('.months .mon:eq('+(current==0?11:(current-1))+')').attr('href'); //IE8
}
}
if($(this).hasClass('next')){
// $('.months .mon:eq('+(current==11?0:(current+1))+')').click();
if(current == 11)
{
var maxyear = years[years.length-1];
if(timeline_year < maxyear)
{
location.href = '/chicago/' + (Number(timeline_year)+1) + '-chicago-murders/timeline?mon=1'; //IE
}
}
else
{
location.href = $('.months .mon:eq('+(current==11?0:(current+1))+')').attr('href'); //IE8
}
}
})
});
String.prototype.lpad = function(padString, length) {
var str = this;
while (str.length < length)
str = padString + str;
return str;
}
String.prototype.repeat = function(times) {
return (new Array(times + 1)).join(this);
}
function getQueryVariable(variable) {
var url = window.location.toString();
var query = url.replace(/^([^\?]*)/, '');
query = query.replace(/^\?/, '');
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return unescape(pair[1]);
}
}
return false;
}
var small_default = function()
{
if($('#timeline-wrapper').length < 1)
{
var mon = 1;
if(getQueryVariable('mon')){
mon = (getQueryVariable('mon') >=1 && getQueryVariable('mon') <= 12)? getQueryVariable('mon') : 1;
}
else
{
var myDate = new Date(this.get('date'));
mon = myDate.getMonth();
}
location.href = '/chicago/' + timeline_year + '-chicago-murders/timeline?mon=' + mon; //IE
}
};
init_funcs['small'].push([small_default,'']);
function truncate(n) {
return n | 0; // bitwise operators convert operands to 32-bit integers
}