New Speed Evidence /themes/speed/js/speed.js

Language Javascript Lines 497
MD5 Hash 8444a7b637db90b4b3c4777bca2a16a8
Repository https://bitbucket.org/builtbyclick/new-speed-evidence.git View Raw File View Project SPDX
| Open JSFiddle
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
Backbone.View.prototype.close = function(){
	this.remove();
	this.unbind();
	if (this.onClose){
		this.onClose();
	}
}

var Report = Backbone.Model.extend({
	forView: function () {
		var modes = {
			1: 'Web',
			2: 'SMS',
			3: 'Email',
			4: 'Twitter'
		};

		var context = this.toJSON();
		context.id = context.incident.incidentid;
		context.link = baseURL + "/reports/view/"+context.incident.incidentid;
		context.name = context.incident.incidenttitle;
		context.description = $("<div>"+context.incident.incidentdescription+"</div>").text();
		context.date = moment(context.incident.incidentdate, "YYYY-MM-DD HH:mm:ss");
		context.site = context.incident.sharingsourceid;
		context.source = modes[context.incident.incidentmode];

		context.category = [];
		_.each(context.categories, function (c) { context.category.push(c.category.title); });
		context.category = context.category.join(', ');

		context.thumbnail = false;
		_.each(context.media, function (m) { if (m.type == 1 && ! context.thumbnail) context.thumbnail = m.link_url; });

		// Source Icon
		context.icon = 'icon-globe';
		if (context.incident.incidentmode == 4)
		{
			context.icon = 'icon-twitter';
		}
		else if (context.incident.incidentmode == 3)
		{
			context.icon = 'icon-envelope';
		}
		else if (context.incident.incidentmode == 2)
		{
			context.icon = 'icon-mobile-phone';
		}
		else if (context.incident.incidentmode == 1)
		{
			context.icon = 'icon-globe';
			_.each(context.media, function (m)
			{
				if (m.type == 2) context.icon = 'icon-facetime-video';
				if (m.type == 1 && (context.icon == 'icon-globe' || context.icon == 'icon-file-text')) context.icon = 'icon-camera';
				if (m.type == 4 && context.icon == 'icon-globe') context.icon = 'icon-rss';
			});
		}

		if (context.site && context.site !== 'main')
		{
			context.url = baseURL + '/reports/sharing/view/'+context.id;
		}
		else
		{
			context.url = baseURL + '/reports/view/'+context.id;
		}

		return context;
	}
});


var ReportCollection = Backbone.Collection.extend(
{
	model : Report,
	initialize : function (models, options)
	{

	},
});
/*
 *  Report list view
 */
var ReportListView = Backbone.View.extend(
{
	template : _.template($("#reports-list-template").html()),
	emptyItemTemplate : _.template($("#empty-item-template").html()),
	initialize : function(options) {
		_.bindAll(this, "addReport", "addAll", 'loading', 'saveFilter', 'removeReport');
		this.model.bind('add', this.addReport);
		this.model.bind('remove', this.removeReport);
		this.model.bind('reset', this.addAll);

		this.container = $(options.container);
		this.liveReports = options.liveReports;
	},
	events : {
		'click .paused' : function () { this.liveReports.toggle(); },
		'click .filter-button' : function() { $('#middle').toggleClass('filterOpen'); },
		'submit form' : 'saveFilter',
		'click form input#reset' : function (e) {
			liveReports.filter({ c:null, m:null, mode:null, q:null, sharing:null });
			liveReports.updateFormFromFilter();

			//e.preventDefault();
		}
	},
	render : function() {
		this.$el.html(this.template({}));
		this.reportList = this.$('ul.reports-list');
		if (this.model.length > 0)
		{
			this.addAll();
		}
		else
		{
			this.reportList.append(this.emptyItemTemplate());
		}

		this.container.html(this.el);

		return this;
	},
	addReport : function(report) {
		var view = new ReportListLiView(
		{
			model : report,
			id : 'update_' + report.id,
			parent : this
		});

		this.reportList.append(view.render().el);
		report.view = view;
		// Remove no reports box
		this.$('li.no-reports').remove();
	},
	removeReport : function() {
		// If we have an empty collection, show 'no reports' message
		if (this.model.length == 0)
		{
			this.reportList.empty();
			this.reportList.append(this.emptyItemTemplate());
		}
	},
	addAll : function() {
		this.reportList.empty();
		this.model.each(this.addReport);
	},
	onClose : function() {
		this.model.unbind('add', this.addReport);
		this.model.unbind('reset', this.addAll);
		// Destroy report views
		this.model.each(function(model) { model.view.close() });
	},
	loading : function(show) {
		if (show)
		{
			this.$('.loading').show();
			this.$('li.no-reports').hide();
		}
		else
		{
			this.$('.loading').hide();
			this.$('li.no-reports').hide();
		}
	},
	saveFilter : function(event) {
		filter = $('#latest-updates form').toJSON();

		// Defaults
		filter = _.extend({ c:[], m:[], mode:[], q:null, sharing:null }, filter);

		delete filter.form_auth_token;

		liveReports.filter(filter);

		event.preventDefault();
	}
});

var ReportListLiView = Backbone.View.extend({
	initialize : function(params) {
		_.bindAll(this, "update", "remove", "close", "togglePopup");
		this.model.bind('change', this.update);
		this.model.bind('remove', this.close);
		this.parent = params.parent;

		// Add events to close popups when clicking anywhere outside the popup
		$(document).on('click', function(e) {
			params.parent.$('ul.reports-list li').popover('destroy').removeClass('popped');
		});
		// Stop clicks on popup closing it.
		$('.popover').on('click', function(e) { e.stopPropagation(); });
	},
	tagName : 'li',
	className : 'clearfix',
	events : {
		'click' : 'togglePopup'
	},
	attributes : function () {
		var context = this.model.forView();
		return {
			'data-placement':'right',
			'title' : context.name,
			'data-content' : _.template($("#report-popover-template").html(), context)
		}
	},
	template : _.template($("#report-item-template").html()),
	render : function() {
		var context = this.model.forView();
		this.$el.html(this.template(context));
		return this;
	},
	remove : function() {
		this.$el.popover('destroy');
		this.$el.remove();
	},
	update : function(report) {
		this.render();
	},
	onClose : function() {
		this.model.unbind('change', this.update);
		this.model.unbind('remove', this.remove);
	},
	togglePopup: function (e) {
		// when clicking on an element which has a popover, hide
		// them all except the current one being hovered upon
		var $popover = this.$el;
		if (! $popover.hasClass('popped'))
		{
			this.parent.$('ul.reports-list li').not('#' + $popover.attr('id')).popover('destroy').removeClass('popped');
			$popover.popover({html : 'true', trigger : 'manual'}).popover('show').addClass('popped');
		}
		else
		{
			$popover.popover('destroy').removeClass('popped');
		}

		e.stopPropagation();
	}
});

var liveReports = {
	request : null,
	pollTimeout: null,
	loaded: null,
	// Latest report ID we pulled
	latestid: 0,
	// Update frequence in ms
	delay: 20000,
	// Current filter
	filters: {},

	initialize : function(params) {
		_.bindAll(this, 'fetch', 'startPolling', 'update', 'stopPolling', 'toggle', 'updateFormFromFilter');
		// Deferred object for tracking fetch process
		dfd = $.Deferred();
		this.request = dfd.promise();
		dfd.resolve();

		this.loaded = $.Deferred();

		try {
			var filters = JSON.parse(localStorage.getItem("updateFilters"));
		} catch (e) {
			filters = {};
		}

		filters = _.extend({ c:[], m:[], mode:[] }, filters);
		this.filters = filters;

		// Create collection
		this.reports = new ReportCollection();
		// Render list view
		this.listView = new ReportListView({
			model : this.reports,
			container : '#latest-updates',
			liveReports : this
		});
		this.listView.render();
		this.reports.view = this.listView;

		this.updateFormFromFilter();

		// Show loading text, hide after first load
		this.listView.loading(true);
		liveReports.loaded.done(_.bind(function () {
			this.listView.loading(false);
		}, this));

		params = _.extend({}, params);
		if (typeof params.delay !== 'undefined')
		{
			this.delay == params.delay;
		}
	},

	// Fetch data from the server
	fetch : function() {
		// Clear timeout
		this.clearPollingTimeout();

		// Check if fetch is already running
		if (this.request.state() == 'pending') return this.request;

		// need to handle race conditions so
		// 1. we're never running multiple syncs at once
		//    handled in poll or fetch
		// 2. we can trigger events when a sync finishes
		//    this.fetching.done( somefunc )
		// 3. we can tell if a sync is running now?
		//    this.fetching.state == 'pending'
		// 4. we can say 'sync now or ignore if already syncing'
		//    this.startPolling(0) is pretty close

		// Build request url
		var fetchURL = baseURL + '/api?task=incidents&limit=20';
		//var fetchURL = '/json/index';

		var params = [];
		for (var _key in this.filters) {
			if (this.filters[_key] != null)
			{
				params.push(_key + '=' + this.filters[_key]);
			}
		}

		if (fetchURL.indexOf("?") !== -1) {
			var index = fetchURL.indexOf("?");
			var args = fetchURL.substr(index+1, fetchURL.length).split("&");
			fetchURL = fetchURL.substring(0, index);

			for (var i=0; i<args.length; i++) {
				params.push(args[i]);
			}
		}

		// Update the fetch URL with parameters
		fetchURL += (params.length > 0) ? '?' + params.join('&') : '';

		dfd = $.getJSON(fetchURL)
			.done(this.update)
			.always(_.bind(function () {
				this.startPolling();
				this.loaded.resolve();
			}, this));
		this.request = dfd.promise();

		// Returning promise object when done
		return this.request;
	},

	// Start timer for polling server
	startPolling : function(delay) {
		// Only reset polling if we're not polling already OR delay is passed
		if (this.pollTimeout == null || typeof delay !== 'undefined')
		{
			delay = typeof delay !== 'undefined' ? delay : this.delay;

			// Clear existing timeout
			this.clearPollingTimeout();
			this.pollTimeout = _.delay(this.fetch, delay);

			// Update pause/resume display
			$('#latest-updates .paused .pause').show();
			$('#latest-updates .paused .resume').hide();
		}
	},

	// Clear timer for polling server
	clearPollingTimeout : function() {
		clearTimeout(this.pollTimeout);
		this.pollTimeout = null;
	},

	// Clear timer for polling server
	stopPolling : function() {
		this.clearPollingTimeout();

		// Update pause/resume display
		$('#latest-updates .paused .pause').hide();
		$('#latest-updates .paused .resume').show();
	},

	isPolling : function()
	{
		if (this.pollTimeout == null) return false;
		return true;
	},

	// Set filter
	// @todo save filters in local storage?
	filter: function(filters) {
		if (filters == undefined) {
			throw "Missing filters";
		}

		var hasChanged = false;

		// Overwrite the current set of filters with the new values
		$.each(filters, _.bind(function(filter, value) {
			var currentValue = this.filters[filter];
			if ((currentValue == undefined && currentValue == null) ||
				currentValue !== value) {
				hasChanged = true;
				this.filters[filter] = value;
			}
		}, this));

		localStorage.setItem("updateFilters", JSON.stringify(this.filters));

		// Have the filters changed
		if (hasChanged) {
			this.startPolling(0);
		}
	},

	// Update display with new data
	update: function (data) {
		var context = this;
		if (typeof data.payload != 'undefined')
		{
			if (typeof data.payload.incidents != 'undefined')
			{
				// Set id field
				_.each(data.payload.incidents, function (item, i) { data.payload.incidents[i].id = item.incident.incidentid; });
				// Set up collection
				this.reports.set(data.payload.incidents);
			}
			else
			{
				this.reports.set([]);
			}
		}
	},

	// Toggle polling
	toggle: function (event) {
		if (this.pollTimeout == null) this.startPolling();
		else this.stopPolling();

		event.preventDefault();
	},
	// @todo move to view
	updateFormFromFilter : function () {
		var filters = this.filters

		$('#latest-updates form input').attr('checked', false);


		if (typeof filters.q !== 'undefined' ) $("#latest-updates form #q").val(filters.q);
		//if (typeof filters.q !== 'undefined' ) $("#latest-updates form #q").val(filters.q);
		if (typeof filters.m !== 'undefined' ) {
			_.each(filters.m, function(v) {
				$('#latest-updates form input[name="m[]"][value="'+v+'"]').attr('checked','checked');
			});
		}
		if (typeof filters.mode !== 'undefined' ) {
			_.each(filters.mode, function(v) {
				$('#latest-updates form input[name="mode[]"][value="'+v+'"]').attr('checked','checked');
			});
		}
		if (typeof filters.c !== 'undefined' ) {
			_.each(filters.c, function(v) {
				$('#latest-updates form input[name="c[]"][value="'+v+'"]').attr('checked','checked');
			});
		}
		if (typeof filters.sharing !== 'undefined' ) {
			_.each(filters.sharing, function(v) {
				$('#latest-updates form input[name="sharing[]"][value="'+v+'"]').attr('checked','checked');
			});
		}
	}
};

$(document).ready(function () {
	liveReports.initialize();

	// Bind events
	// @todo only after first load
	// @todo move to view or something
	liveReports.loaded.done(function () {
		var pausedState = false;
		$('#latest-updates').hover(function () {
			$('#latest-updates .paused').show();
			$('#latest-updates .filter-button').show();
			pausedState = liveReports.isPolling();
			liveReports.stopPolling();
		}, function () {
			$('#latest-updates .paused').hide();
			$('#latest-updates .filter-button').hide();
			if (pausedState) liveReports.startPolling();
		});
	});

	liveReports.startPolling(0);
});
Back to Top