blob: 6552d70cf1d420b827b26154014eed1cd2fcc425 [file] [log] [blame]
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001$(function() {
2
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07003 // Initialize connection to AsterixDB. Just one connection is needed and contains
4 // logic for connecting to each API endpoint. This object A is reused throughout the
5 // code but does not store information about any individual API call.
6 A = new AsterixDBConnection({
7
8 // We will be using the twitter dataverse, which we can configure either like this
9 // or by following our AsterixDBConnection with a dataverse call, like so:
10 // A = new AsterixDBConnection().dataverse("twitter");
11 "dataverse" : "twitter",
12
13 // Due to the setup of this demo using the Bottle server, it is necessary to change the
14 // default endpoint of API calls. The proxy server handles the call to http://localhost:19002
15 // for us, and we reconfigure this connection to connect to the proxy server.
16 "endpoint_root" : "/",
17
18 // Finally, we want to make our error function nicer so that we show errors with a call to the
19 // reportUserMessage function. Update the "error" property to do that.
20 "error" : function(data) {
21 // For an error, data will look like this:
22 // {
23 // "error-code" : [error-number, error-text]
24 // "stacktrace" : ...stack trace...
25 // "summary" : ...summary of error...
26 // }
27 // We will report this as an Asterix REST API Error, an error code, and a reason message.
28 // Note the method signature: reportUserMessage(message, isPositiveMessage, target). We will provide
29 // an error message to display, a positivity value (false in this case, errors are bad), and a
30 // target html element in which to report the message.
31 var showErrorMessage = "Asterix Error #" + data["error-code"][0] + ": " + data["error-code"][1];
32 var isPositive = false;
33 var showReportAt = "report-message";
34
35 reportUserMessage(showErrorMessage, isPositive, showReportAt);
36 }
37 });
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070038
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -070039 // This little bit of code manages period checks of the asynchronous query manager,
40 // which holds onto handles asynchornously received. We can set the handle update
41 // frequency using seconds, and it will let us know when it is ready.
42 var intervalID = setInterval(
43 function() {
44 asynchronousQueryIntervalUpdate();
45 },
46 asynchronousQueryGetInterval()
47 );
48
49
50 // Initialize data structures
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070051 APIqueryTracker = {};
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -070052 asyncQueryManager = {};
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070053 drilldown_data_map = {};
54 drilldown_data_map_vals = {};
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -070055
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070056 map_cells = [];
57 map_tweet_markers = [];
genia.likes.science@gmail.com65e04182013-10-04 04:31:41 -070058 map_info_windows = {};
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -070059
60 review_mode_tweetbooks = [];
61 getAllDataverseTweetbooks();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070062
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -070063 // Legend Container
64 // Create a rainbow from a pretty color scheme.
65 // http://www.colourlovers.com/palette/292482/Terra
66 rainbow = new Rainbow();
67 rainbow.setSpectrum("#E8DDCB", "#CDB380", "#036564", "#033649", "#031634");
68 buildLegend();
69
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -070070 // Initialization of demo datastructures, map, tabs
71 initDemoPrepareTabs();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070072
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -070073 // UI Elements - Creates Map, Location Auto-Complete, Selection Rectangle
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070074 var mapOptions = {
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -070075 center: new google.maps.LatLng(38.89, -77.03),
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070076 zoom: 4,
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -070077 mapTypeId: google.maps.MapTypeId.ROADMAP,
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070078 streetViewControl: false,
79 draggable : false
80 };
81 map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
82
83 var input = document.getElementById('location-text-box');
84 var autocomplete = new google.maps.places.Autocomplete(input);
85 autocomplete.bindTo('bounds', map);
86
87 google.maps.event.addListener(autocomplete, 'place_changed', function() {
88 var place = autocomplete.getPlace();
89 if (place.geometry.viewport) {
90 map.fitBounds(place.geometry.viewport);
91 } else {
92 map.setCenter(place.geometry.location);
93 map.setZoom(17); // Why 17? Because it looks good.
94 }
95 var address = '';
96 if (place.address_components) {
97 address = [(place.address_components[0] && place.address_components[0].short_name || ''),
98 (place.address_components[1] && place.address_components[1].short_name || ''),
99 (place.address_components[2] && place.address_components[2].short_name || '') ].join(' ');
100 }
101 });
102
103 // UI Elements - Selection Rectangle Drawing
104 shouldDraw = false;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700105 selectionRect = null;
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700106 var startLatLng;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700107 var selectionRadio = $("#selection-button");
108 var firstClick = true;
109
110 google.maps.event.addListener(map, 'mousedown', function (event) {
111 // only allow drawing if selection is selected
112 if (selectionRadio.hasClass("active")) {
113 startLatLng = event.latLng;
114 shouldDraw = true;
115 }
116 });
117
118 google.maps.event.addListener(map, 'mousemove', drawRect);
119 function drawRect (event) {
120 if (shouldDraw) {
121 if (!selectionRect) {
122 var selectionRectOpts = {
123 bounds: new google.maps.LatLngBounds(startLatLng, event.latLng),
124 map: map,
125 strokeWeight: 1,
126 strokeColor: "2b3f8c",
127 fillColor: "2b3f8c"
128 };
129 selectionRect = new google.maps.Rectangle(selectionRectOpts);
130 google.maps.event.addListener(selectionRect, 'mouseup', function () {
131 shouldDraw = false;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700132 });
133 } else {
genia.likes.science@gmail.com4ada78c2013-09-07 13:53:48 -0700134
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700135 if (startLatLng.lng() < event.latLng.lng()) {
136 selectionRect.setBounds(new google.maps.LatLngBounds(startLatLng, event.latLng));
137 } else {
138 selectionRect.setBounds(new google.maps.LatLngBounds(event.latLng, startLatLng));
139 }
140 }
141 }
142 };
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700143
144
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700145
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700146
147 // Open about tab to start user on a tutorial
148 //$('#mode-tabs a:first').tab('show') // Select first tab
149
150
151 // UI Elements - A button to clear current map and query data
152 $("#clear-button").click(mapWidgetResetMap);
153
154 var updateSliderDisplay = function(event, ui) {
155 if (event.target.id == "grid-lat-slider") {
156 $("#gridlat").text(""+ui.value);
157 } else {
158 $("#gridlng").text(""+ui.value);
159 }
160 };
161
162 sliderOptions = {
163 max: 10,
164 min: 1.5,
165 step: .1,
166 value: 2.0,
167 slidechange: updateSliderDisplay,
168 slide: updateSliderDisplay,
169 start: updateSliderDisplay,
170 stop: updateSliderDisplay
171 };
172
173 $("#gridlat").text(""+sliderOptions.value);
174 $("#gridlng").text(""+sliderOptions.value);
175 $(".grid-slider").slider(sliderOptions);
176
177 // UI Elements - Date Pickers
178 var dateOptions = {
179 dateFormat: "yy-mm-dd",
180 defaultDate: "2012-01-02",
181 navigationAsDateFormat: true,
182 constrainInput: true
183 };
184 var start_dp = $("#start-date").datepicker(dateOptions);
185 start_dp.val(dateOptions.defaultDate);
186 dateOptions['defaultDate'] = "2012-12-31";
187 var end_dp= $("#end-date").datepicker(dateOptions);
188 end_dp.val(dateOptions.defaultDate);
189
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700190 // UI Elements - Toggle location search style by location or by map selection
191 $('#selection-button').on('click', function (e) {
192 $("#location-text-box").attr("disabled", "disabled");
193 if (selectionRect) {
194 selectionRect.setMap(map);
195 }
196 });
197 $('#location-button').on('click', function (e) {
198 $("#location-text-box").removeAttr("disabled");
199 if (selectionRect) {
200 selectionRect.setMap(null);
201 }
202 });
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700203 $("#selection-button").button('toggle');
204
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700205 $('#new-tweetbook-button').on('click', function (e) {
206 onCreateNewTweetBook($('#new-tweetbook-entry').val());
207
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700208 $('#new-tweetbook-entry').val("");
209 $('#new-tweetbook-entry').attr("placeholder", "Name a new tweetbook");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700210 });
211
212 // UI Element - Query Submission
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700213 $("#submit-button").on("click", function () {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700214
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700215 var kwterm = $("#keyword-textbox").val();
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700216 if (kwterm == "") {
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700217 reportUserMessage("Please enter a search term!", false, "report-message");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700218 } else {
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700219
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700220 $("#report-message").html('');
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700221 $("#submit-button").attr("disabled", true);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700222
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700223 var startdp = $("#start-date").datepicker("getDate");
224 var enddp = $("#end-date").datepicker("getDate");
225 var startdt = $.datepicker.formatDate("yy-mm-dd", startdp)+"T00:00:00Z";
226 var enddt = $.datepicker.formatDate("yy-mm-dd", enddp)+"T23:59:59Z";
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700227
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700228 var formData = {
229 "keyword": kwterm,
230 "startdt": startdt,
231 "enddt": enddt,
232 "gridlat": $("#grid-lat-slider").slider("value"),
233 "gridlng": $("#grid-lng-slider").slider("value")
234 };
235
236 // Get Map Bounds
237 var bounds;
238 if ($('#selection-button').hasClass("active") && selectionRect) {
239 bounds = selectionRect.getBounds();
240 } else {
241 bounds = map.getBounds();
242 }
243
244 var swLat = Math.abs(bounds.getSouthWest().lat());
245 var swLng = Math.abs(bounds.getSouthWest().lng());
246 var neLat = Math.abs(bounds.getNorthEast().lat());
247 var neLng = Math.abs(bounds.getNorthEast().lng());
248
249 formData["swLat"] = Math.min(swLat, neLat);
250 formData["swLng"] = Math.max(swLng, neLng);
251 formData["neLat"] = Math.max(swLat, neLat);
252 formData["neLng"] = Math.min(swLng, neLng);
253
254 var build_cherry_mode = "synchronous";
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700255
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700256 if ($('#asbox').is(":checked")) {
257 build_cherry_mode = "asynchronous";
258 $('#show-query-button').attr("disabled", false);
259 } else {
260 $('#show-query-button').attr("disabled", true);
261 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700262
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700263 var f = buildAQLQueryFromForm(formData);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700264
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700265 APIqueryTracker = {
266 "query" : "use dataverse twitter;\n" + f.val(),
267 "data" : formData
268 };
genia.likes.science@gmail.com233fe972013-09-07 13:57:46 -0700269
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700270 // TODO Make dialog work correctly.
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700271 //$('#dialog').html(APIqueryTracker["query"]);
genia.likes.science@gmail.com233fe972013-09-07 13:57:46 -0700272
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700273 if (build_cherry_mode == "synchronous") {
274 A.query(f.val(), cherryQuerySyncCallback, build_cherry_mode);
275 } else {
276 A.query(f.val(), cherryQueryAsyncCallback, build_cherry_mode);
277 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700278
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700279 // Clears selection rectangle on query execution, rather than waiting for another clear call.
280 if (selectionRect) {
281 selectionRect.setMap(null);
282 selectionRect = null;
283 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700284 }
285 });
286});
287
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700288/**
289* Builds AsterixDB REST Query from explore mode form.
290*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700291function buildAQLQueryFromForm(parameters) {
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700292
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700293 var bounds = {
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700294 "ne" : { "lat" : parameters["neLat"], "lng" : -1*parameters["neLng"]},
295 "sw" : { "lat" : parameters["swLat"], "lng" : -1*parameters["swLng"]}
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700296 };
297
298 var rectangle =
299 new FunctionExpression("create-rectangle",
300 new FunctionExpression("create-point", bounds["sw"]["lat"], bounds["sw"]["lng"]),
301 new FunctionExpression("create-point", bounds["ne"]["lat"], bounds["ne"]["lng"]));
302
303
304 var aql = new FLWOGRExpression()
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700305 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700306 .LetClause("$keyword", new AExpression('"' + parameters["keyword"] + '"'))
307 .LetClause("$region", rectangle)
308 .WhereClause().and(
309 new FunctionExpression("spatial-intersect", "$t.sender-location", "$region"),
310 new AExpression('$t.send-time > datetime("' + parameters["startdt"] + '")'),
311 new AExpression('$t.send-time < datetime("' + parameters["enddt"] + '")'),
312 new FunctionExpression("contains", "$t.message-text", "$keyword")
313 )
314 .GroupClause(
315 "$c",
316 new FunctionExpression("spatial-cell", "$t.sender-location",
317 new FunctionExpression("create-point", "24.5", "-125.5"),
318 parameters["gridlat"].toFixed(1), parameters["gridlng"].toFixed(1)),
319 "with",
320 "$t"
321 )
322 .ReturnClause({ "cell" : "$c", "count" : "count($t)" });
323
324 return aql;
325}
326
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700327/**
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700328* getAllDataverseTweetbooks
329*
330* no params
331*
332* Returns all datasets of type TweetbookEntry, populates review_mode_tweetbooks
333*/
334function getAllDataverseTweetbooks(fn_tweetbooks) {
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700335
336 // This creates a query to the Metadata for datasets of type
337 // TweetBookEntry. Note that if we throw in a WhereClause (commented out below)
338 // there is an odd error. This is being fixed and will be removed from this demo.
339 var getTweetbooksQuery = new FLWOGRExpression()
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700340 .ForClause("$ds", new AExpression("dataset Metadata.Dataset"))
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700341 //.WhereClause(new AExpression('$ds.DataTypeName = "TweetbookEntry"'))
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700342 .ReturnClause({
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700343 "DataTypeName" : "$ds.DataTypeName",
344 "DatasetName" : "$ds.DatasetName"
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700345 });
346
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700347 // Now create a function that will be called when tweetbooks succeed.
348 // In this case, we want to parse out the results object from the Asterix
349 // REST API response.
350 var tweetbooksSuccess = function(r) {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700351 // Parse tweetbook metadata results
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700352 $.each(r.results, function(i, data) {
353 if ($.parseJSON(data)["DataTypeName"] == "TweetbookEntry") {
354 review_mode_tweetbooks.push($.parseJSON(data)["DatasetName"]);
355 }
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700356 });
357
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700358 // Now, if any tweetbooks already exist, opulate review screen.
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700359 $('#review-tweetbook-titles').html('');
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700360 $.each(review_mode_tweetbooks, function(i, tweetbook) {
361 addTweetBookDropdownItem(tweetbook);
362 });
363 };
364
365 // Now, we are ready to run a query.
366 A.meta(getTweetbooksQuery.val(), tweetbooksSuccess);
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700367}
368
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700369/** Asynchronous Query Management **/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700370
371/**
372* Checks through each asynchronous query to see if they are ready yet
373*/
374function asynchronousQueryIntervalUpdate() {
375 for (var handle_key in asyncQueryManager) {
376 if (!asyncQueryManager[handle_key].hasOwnProperty("ready")) {
377 asynchronousQueryGetAPIQueryStatus( asyncQueryManager[handle_key]["handle"], handle_key );
378 }
379 }
380}
381
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700382/**
383* Returns current time interval to check for asynchronous query readiness
384* @returns {number} milliseconds between asychronous query checks
385*/
386function asynchronousQueryGetInterval() {
387 var seconds = 10;
388 return seconds * 1000;
389}
390
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700391/**
392* Retrieves status of an asynchronous query, using an opaque result handle from API
393* @param {Object} handle, an object previously returned from an async call
394* @param {number} handle_id, the integer ID parsed from the handle object
395*/
396function asynchronousQueryGetAPIQueryStatus (handle, handle_id) {
397
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700398 A.query_status(
399 {
400 "handle" : JSON.stringify(handle)
401 },
402 function (res) {
403 if (res["status"] == "SUCCESS") {
404 // We don't need to check if this one is ready again, it's not going anywhere...
405 // Unless the life cycle of handles has changed drastically
406 asyncQueryManager[handle_id]["ready"] = true;
407
408 // Indicate success.
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700409 $('#handle_' + handle_id).removeClass("btn-disabled").prop('disabled', false).addClass("btn-success");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700410 }
411 }
412 );
413}
414
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700415/**
416* On-success callback after async API query
417* @param {object} res, a result object containing an opaque result handle to Asterix
418*/
419function cherryQueryAsyncCallback(res) {
420
421 // Parse handle, handle id and query from async call result
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700422 var handle_query = APIqueryTracker["query"];
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700423 var handle = res;
424 var handle_id = res["handle"].toString().split(',')[0];
425
426 // Add to stored map of existing handles
427 asyncQueryManager[handle_id] = {
428 "handle" : handle,
429 "query" : handle_query,
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700430 "data" : APIqueryTracker["data"]
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700431 };
432
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700433 // Create a container for this async query handle
434 $('<div/>')
435 .css("margin-left", "1em")
436 .css("margin-bottom", "1em")
437 .css("display", "block")
438 .attr({
439 "class" : "btn-group",
440 "id" : "async_container_" + handle_id
441 })
442 .appendTo("#async-handle-controls");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700443
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700444 // Adds the main button for this async handle
445 var handle_action_button = '<button class="btn btn-disabled" id="handle_' + handle_id + '">Handle ' + handle_id + '</button>';
446 $('#async_container_' + handle_id).append(handle_action_button);
447 $('#handle_' + handle_id).prop('disabled', true);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700448 $('#handle_' + handle_id).on('click', function (e) {
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700449
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700450 // make sure query is ready to be run
451 if (asyncQueryManager[handle_id]["ready"]) {
452
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700453 APIqueryTracker = {
454 "query" : asyncQueryManager[handle_id]["query"],
455 "data" : asyncQueryManager[handle_id]["data"]
456 };
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700457 // TODO
458 //$('#dialog').html(APIqueryTracker["query"]);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700459
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -0700460 if (!asyncQueryManager[handle_id].hasOwnProperty("result")) {
461 // Generate new Asterix Core API Query
462 A.query_result(
463 { "handle" : JSON.stringify(asyncQueryManager[handle_id]["handle"]) },
464 function(res) {
465 asyncQueryManager[handle_id]["result"] = res;
466 cherryQuerySyncCallback(res);
467 }
468 );
469 } else {
470 cherryQuerySyncCallback(asyncQueryManager[handle_id]["result"]);
471 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700472 }
473 });
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700474
475 // Adds a removal button for this async handle
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700476 var asyncDeleteButton = addDeleteButton(
477 "trashhandle_" + handle_id,
478 "async_container_" + handle_id,
479 function (e) {
480 $('#async_container_' + handle_id).remove();
481 delete asyncQueryManager[handle_id];
482 }
483 );
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700484
485 $('#async_container_' + handle_id).append('<br/>');
486
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700487 $("#submit-button").attr("disabled", false);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700488}
489
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700490/**
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700491* cleanJSON
492*
493* @param json, a JSON string that is not correctly formatted.
494*
495* Quick and dirty little function to clean up an Asterix JSON quirk.
496*/
497function cleanJSON(json) {
498 return json
499 .replace("rectangle", '"rectangle"')
500 .replace("point:", '"point":')
501 .replace("point:", '"point":')
502 .replace("int64", '"int64"');
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700503}
504
505/**
506* A spatial data cleaning and mapping call
507* @param {Object} res, a result object from a cherry geospatial query
508*/
509function cherryQuerySyncCallback(res) {
genia.likes.science@gmail.comd42b4022013-08-09 05:05:23 -0700510
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700511 // Initialize coordinates and weights, to store
512 // coordinates of map cells and their weights
513 // TODO these are all included in coordinates already...
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700514 var coordinates = [];
515 var weights = [];
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700516 var maxWeight = 0;
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700517 var minWeight = Number.MAX_VALUE;
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700518
519 // Parse resulting JSON objects. Here is an example record:
520 // { "cell": { rectangle: [{ point: [22.5, 64.5]}, { point: [24.5, 66.5]}]}, "count": { int64: 5 }}
521 $.each(res.results, function(i, data) {
522
523 // First, parse a JSON object from a cleaned up string.
524 var record = $.parseJSON(cleanJSON(data));
525
526 // Parse Coordinates and Weights into a record
527 var sw = record.cell.rectangle[0].point;
528 var ne = record.cell.rectangle[1].point;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700529
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700530 var coordinate = {
531 "latSW" : sw[0],
532 "lngSW" : sw[1],
533 "latNE" : ne[0],
534 "lngNE" : ne[1],
535 "weight" : record.count.int64
536 }
537
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700538 maxWeight = Math.max(coordinate["weight"], maxWeight);
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700539 minWeight = Math.min(coordinate["weight"], minWeight);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700540 coordinates.push(coordinate);
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700541 });
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700542
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700543 triggerUIUpdate(coordinates, maxWeight, minWeight);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700544}
545
546/**
547* Triggers a map update based on a set of spatial query result cells
548* @param [Array] mapPlotData, an array of coordinate and weight objects
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700549* @param [Array] plotWeights, a list of weights of the spatial cells - e.g., number of tweets
550*/
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700551function triggerUIUpdate(mapPlotData, maxWeight, minWeight) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700552 /** Clear anything currently on the map **/
553 mapWidgetClearMap();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700554
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700555 // Initialize info windows.
genia.likes.science@gmail.com65e04182013-10-04 04:31:41 -0700556 map_info_windows = {};
557
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700558 $.each(mapPlotData, function (m) {
559
560 var point_center = new google.maps.LatLng(
561 (mapPlotData[m].latSW + mapPlotData[m].latNE)/2.0,
562 (mapPlotData[m].lngSW + mapPlotData[m].lngNE)/2.0);
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700563
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700564 var map_circle_options = {
565 center: point_center,
566 anchorPoint: point_center,
567 radius: mapWidgetComputeCircleRadius(mapPlotData[m], maxWeight),
568 map: map,
569 fillOpacity: 0.85,
570 fillColor: rainbow.colourAt(Math.ceil(100 * (mapPlotData[m].weight / maxWeight))),
571 clickable: true
572 };
573 var map_circle = new google.maps.Circle(map_circle_options);
574 map_circle.val = mapPlotData[m];
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700575
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700576 map_info_windows[m] = new google.maps.InfoWindow({
577 content: mapPlotData[m].weight + " tweets",
578 position: point_center
579 });
580
581 // Clicking on a circle drills down map to that value, hovering over it displays a count
582 // of tweets at that location.
583 google.maps.event.addListener(map_circle, 'click', function (event) {
584 $.each(map_info_windows, function(i) {
585 map_info_windows[i].close();
genia.likes.science@gmail.comec46c772013-09-07 18:13:00 -0700586 });
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700587 onMapPointDrillDown(map_circle.val);
588 });
genia.likes.science@gmail.comec46c772013-09-07 18:13:00 -0700589
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700590 google.maps.event.addListener(map_circle, 'mouseover', function(event) {
591 if (!map_info_windows[m].getMap()) {
592 map_info_windows[m].setPosition(map_circle.center);
593 map_info_windows[m].open(map);
594 }
595 });
596
597 // Add this marker to global marker cells
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700598 map_cells.push(map_circle);
599
600 // Show legend
601 $("#legend-min").html(minWeight);
602 $("#legend-max").html(maxWeight);
603 $("#rainbow-legend-container").show();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700604 });
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700605}
606
607/**
608* prepares an Asterix API query to drill down in a rectangular spatial zone
609*
610* @params {object} marker_borders [LEGACY] a set of bounds for a region from a previous api result
611*/
612function onMapPointDrillDown(marker_borders) {
613 var zoneData = APIqueryTracker["data"];
614
615 var zswBounds = new google.maps.LatLng(marker_borders.latSW, marker_borders.lngSW);
616 var zneBounds = new google.maps.LatLng(marker_borders.latNE, marker_borders.lngNE);
617
618 var zoneBounds = new google.maps.LatLngBounds(zswBounds, zneBounds);
619 zoneData["swLat"] = zoneBounds.getSouthWest().lat();
620 zoneData["swLng"] = zoneBounds.getSouthWest().lng();
621 zoneData["neLat"] = zoneBounds.getNorthEast().lat();
622 zoneData["neLng"] = zoneBounds.getNorthEast().lng();
623 var zB = {
624 "sw" : {
625 "lat" : zoneBounds.getSouthWest().lat(),
626 "lng" : zoneBounds.getSouthWest().lng()
627 },
628 "ne" : {
629 "lat" : zoneBounds.getNorthEast().lat(),
630 "lng" : zoneBounds.getNorthEast().lng()
631 }
632 };
633
634 mapWidgetClearMap();
635
636 var customBounds = new google.maps.LatLngBounds();
637 var zoomSWBounds = new google.maps.LatLng(zoneData["swLat"], zoneData["swLng"]);
638 var zoomNEBounds = new google.maps.LatLng(zoneData["neLat"], zoneData["neLng"]);
639 customBounds.extend(zoomSWBounds);
640 customBounds.extend(zoomNEBounds);
641 map.fitBounds(customBounds);
642
643 var df = getDrillDownQuery(zoneData, zB);
644
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700645 APIqueryTracker = {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700646 "query_string" : "use dataverse twitter;\n" + df.val(),
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700647 "marker_path" : "static/img/mobile2.png",
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700648 "on_clean_result" : onCleanTweetbookDrilldown,
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700649 };
650
651 A.query(df.val(), onTweetbookQuerySuccessPlot);
652}
653
654function getDrillDownQuery(parameters, bounds) {
655
656 var zoomRectangle = new FunctionExpression("create-rectangle",
657 new FunctionExpression("create-point", bounds["sw"]["lat"], bounds["sw"]["lng"]),
658 new FunctionExpression("create-point", bounds["ne"]["lat"], bounds["ne"]["lng"]));
659
660 var drillDown = new FLWOGRExpression()
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700661 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700662 .LetClause("$keyword", new AExpression('"' + parameters["keyword"] + '"'))
663 .LetClause("$region", zoomRectangle)
664 .WhereClause().and(
665 new FunctionExpression('spatial-intersect', '$t.sender-location', '$region'),
666 new AExpression().set('$t.send-time > datetime("' + parameters["startdt"] + '")'),
667 new AExpression().set('$t.send-time < datetime("' + parameters["enddt"] + '")'),
668 new FunctionExpression('contains', '$t.message-text', '$keyword')
669 )
670 .ReturnClause({
671 "tweetId" : "$t.tweetid",
672 "tweetText" : "$t.message-text",
673 "tweetLoc" : "$t.sender-location"
674 });
675
676 return drillDown;
677}
678
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700679function onDrillDownAtLocation(tO) {
680
681 var tweetId = tO["tweetEntryId"];
682 var tweetText = tO["tweetText"];
683
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700684 // First, set tweet in drilldown modal to be this tweet's text
685 $('#modal-body-tweet').html('Tweet #' + tweetId + ": " + tweetText);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700686
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700687 // Next, empty any leftover tweetbook comments or error/success messages
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700688 $("#modal-body-add-to").val('');
689 $("#modal-body-add-note").val('');
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700690 $("#modal-body-message-holder").html("");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700691
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700692 // Next, if there is an existing tweetcomment reported, show it.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700693 if (tO.hasOwnProperty("tweetComment")) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700694
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700695 // Show correct panel
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700696 $("#modal-existing-note").show();
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700697 $("#modal-save-tweet-panel").hide();
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700698
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700699 // Fill in existing tweet comment
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700700 $("#modal-body-tweet-note").val(tO["tweetComment"]);
701
702 // Change Tweetbook Badge
703 $("#modal-current-tweetbook").val(APIqueryTracker["active_tweetbook"]);
704
705 // Add deletion functionality
706 $("#modal-body-trash-icon").on('click', function () {
707 // Send comment deletion to asterix
708 var deleteTweetCommentOnId = '"' + tweetId + '"';
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700709 var toDelete = new DeleteStatement(
710 "$mt",
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700711 APIqueryTracker["active_tweetbook"],
712 new AExpression("$mt.tweetid = " + deleteTweetCommentOnId.toString())
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700713 );
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700714 A.update(
715 toDelete.val()
716 );
717
718 // Hide comment from map
719 $('#drilldown_modal').modal('hide');
720
721 // Replot tweetbook
722 onPlotTweetbook(APIqueryTracker["active_tweetbook"]);
723 });
724
725 } else {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700726 // Show correct panel
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700727 $("#modal-existing-note").hide();
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700728 $("#modal-save-tweet-panel").show();
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700729
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700730 // Now, when adding a comment on an available tweet to a tweetbook
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700731 $('#save-comment-tweetbook-modal').unbind('click');
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700732 $("#save-comment-tweetbook-modal").on('click', function(e) {
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700733
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700734 // Stuff to save about new comment
735 var save_metacomment_target_tweetbook = $("#modal-body-add-to").val();
736 var save_metacomment_target_comment = '"' + $("#modal-body-add-note").val() + '"';
737 var save_metacomment_target_tweet = '"' + tweetId + '"';
738
739 // Make sure content is entered, and then save this comment.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700740 if ($("#modal-body-add-note").val() == "") {
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700741
742 reportUserMessage("Please enter a comment about the tweet", false, "report-message");
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700743
744 } else if ($("#modal-body-add-to").val() == "") {
745
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700746 reportUserMessage("Please enter a tweetbook.", false, "report-message");
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700747
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700748 } else {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700749
750 // Check if tweetbook exists. If not, create it.
751 if (!(existsTweetbook(save_metacomment_target_tweetbook))) {
752 onCreateNewTweetBook(save_metacomment_target_tweetbook);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700753 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700754
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700755 var toInsert = new InsertStatement(
756 save_metacomment_target_tweetbook,
757 {
758 "tweetid" : save_metacomment_target_tweet.toString(),
759 "comment-text" : save_metacomment_target_comment
760 }
761 );
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700762
763 A.update(toInsert.val(), function () {
764 var successMessage = "Saved comment on <b>Tweet #" + tweetId +
765 "</b> in dataset <b>" + save_metacomment_target_tweetbook + "</b>.";
766 reportUserMessage(successMessage, true, "report-message");
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700767
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700768 $("#modal-body-add-to").val('');
769 $("#modal-body-add-note").val('');
770 $('#save-comment-tweetbook-modal').unbind('click');
771
772 // Close modal
773 $('#drilldown_modal').modal('hide');
774 });
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700775 }
776 });
777 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700778}
779
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700780/**
781* Adds a new tweetbook entry to the menu and creates a dataset of type TweetbookEntry.
782*/
783function onCreateNewTweetBook(tweetbook_title) {
784
785 var tweetbook_title = tweetbook_title.split(' ').join('_');
786
787 A.ddl(
788 "create dataset " + tweetbook_title + "(TweetbookEntry) primary key tweetid;",
789 function () {}
790 );
791
792 if (!(existsTweetbook(tweetbook_title))) {
793 review_mode_tweetbooks.push(tweetbook_title);
794 addTweetBookDropdownItem(tweetbook_title);
795 }
796}
797
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700798function onDropTweetBook(tweetbook_title) {
799
800 // AQL Call
801 A.ddl(
802 "drop dataset " + tweetbook_title + " if exists;",
803 function () {}
804 );
805
806 // Removes tweetbook from review_mode_tweetbooks
807 var remove_position = $.inArray(tweetbook_title, review_mode_tweetbooks);
808 if (remove_position >= 0) review_mode_tweetbooks.splice(remove_position, 1);
809
810 // Clear UI with review tweetbook titles
811 $('#review-tweetbook-titles').html('');
812 for (r in review_mode_tweetbooks) {
813 addTweetBookDropdownItem(review_mode_tweetbooks[r]);
814 }
815}
816
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700817function addTweetBookDropdownItem(tweetbook) {
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700818 // Add placeholder for this tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700819 $('<div/>')
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700820 .attr({
821 "class" : "btn-group",
822 "id" : "rm_holder_" + tweetbook
823 }).appendTo("#review-tweetbook-titles");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700824
825 // Add plotting button for this tweetbook
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700826 var plot_button = '<button class="btn btn-default" id="rm_plotbook_' + tweetbook + '">' + tweetbook + '</button>';
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700827 $("#rm_holder_" + tweetbook).append(plot_button);
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700828 $("#rm_plotbook_" + tweetbook).width("200px");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700829 $("#rm_plotbook_" + tweetbook).on('click', function(e) {
830 onPlotTweetbook(tweetbook);
831 });
832
833 // Add trash button for this tweetbook
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700834 var onTrashTweetbookButton = addDeleteButton(
835 "rm_trashbook_" + tweetbook,
836 "rm_holder_" + tweetbook,
837 function(e) {
838 onDropTweetBook(tweetbook);
839 }
840 );
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700841}
842
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700843function onPlotTweetbook(tweetbook) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700844
845 // Clear map for this one
846 mapWidgetResetMap();
847
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700848 var plotTweetQuery = new FLWOGRExpression()
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700849 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700850 .ForClause("$m", new AExpression("dataset " + tweetbook))
851 .WhereClause(new AExpression("$m.tweetid = $t.tweetid"))
852 .ReturnClause({
853 "tweetId" : "$m.tweetid",
854 "tweetText" : "$t.message-text",
855 "tweetLoc" : "$t.sender-location",
856 "tweetCom" : "$m.comment-text"
857 });
858
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700859 APIqueryTracker = {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700860 "query_string" : "use dataverse twitter;\n" + plotTweetQuery.val(),
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700861 "marker_path" : "static/img/mobile_green2.png",
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700862 "on_clean_result" : onCleanPlotTweetbook,
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700863 "active_tweetbook" : tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700864 };
865
866 A.query(plotTweetQuery.val(), onTweetbookQuerySuccessPlot);
867}
868
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700869function onTweetbookQuerySuccessPlot (res) {
870
871 var records = res["results"];
872
873 var coordinates = [];
874 map_tweet_markers = [];
875 map_tweet_overlays = [];
876 drilldown_data_map = {};
877 drilldown_data_map_vals = {};
878
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700879 var micon = APIqueryTracker["marker_path"];
880 var marker_click_function = onClickTweetbookMapMarker;
881 var clean_result_function = APIqueryTracker["on_clean_result"];
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700882
883 coordinates = clean_result_function(records);
884
885 for (var dm in coordinates) {
886 var keyLat = coordinates[dm].tweetLat.toString();
887 var keyLng = coordinates[dm].tweetLng.toString();
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700888
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700889 if (!drilldown_data_map.hasOwnProperty(keyLat)) {
890 drilldown_data_map[keyLat] = {};
891 }
892 if (!drilldown_data_map[keyLat].hasOwnProperty(keyLng)) {
893 drilldown_data_map[keyLat][keyLng] = [];
894 }
895 drilldown_data_map[keyLat][keyLng].push(coordinates[dm]);
896 drilldown_data_map_vals[coordinates[dm].tweetEntryId.toString()] = coordinates[dm];
897 }
898
899 $.each(drilldown_data_map, function(drillKeyLat, valuesAtLat) {
900 $.each(drilldown_data_map[drillKeyLat], function (drillKeyLng, valueAtLng) {
901
902 // Get subset of drilldown position on map
903 var cposition = new google.maps.LatLng(parseFloat(drillKeyLat), parseFloat(drillKeyLng));
904
905 // Create a marker using the snazzy phone icon
906 var map_tweet_m = new google.maps.Marker({
907 position: cposition,
908 map: map,
909 icon: micon,
910 clickable: true,
911 });
912
913 // Open Tweet exploration window on click
914 google.maps.event.addListener(map_tweet_m, 'click', function (event) {
915 marker_click_function(drilldown_data_map[drillKeyLat][drillKeyLng]);
916 });
917
918 // Add marker to index of tweets
919 map_tweet_markers.push(map_tweet_m);
920
921 });
922 });
923}
924
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700925function existsTweetbook(tweetbook) {
926 if (parseInt($.inArray(tweetbook, review_mode_tweetbooks)) == -1) {
927 return false;
928 } else {
929 return true;
930 }
931}
932
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700933function onCleanPlotTweetbook(records) {
934 var toPlot = [];
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700935
936 // An entry looks like this:
937 // { "tweetId": "273589", "tweetText": " like verizon the network is amazing", "tweetLoc": { point: [37.78, 82.27]}, "tweetCom": "hooray comments" }
938
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700939 for (var entry in records) {
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700940
941 var points = records[entry].split("point:")[1].match(/[-+]?[0-9]*\.?[0-9]+/g);
942
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700943 var tweetbook_element = {
944 "tweetEntryId" : parseInt(records[entry].split(",")[0].split(":")[1].split('"')[1]),
945 "tweetText" : records[entry].split("tweetText\": \"")[1].split("\", \"tweetLoc\":")[0],
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700946 "tweetLat" : parseFloat(points[0]),
947 "tweetLng" : parseFloat(points[1]),
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700948 "tweetComment" : records[entry].split("tweetCom\": \"")[1].split("\"")[0]
949 };
950 toPlot.push(tweetbook_element);
951 }
952
953 return toPlot;
954}
955
956function onCleanTweetbookDrilldown (rec) {
957
958 var drilldown_cleaned = [];
959
960 for (var entry = 0; entry < rec.length; entry++) {
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700961
962 // An entry looks like this:
963 // { "tweetId": "105491", "tweetText": " hate verizon its platform is OMG", "tweetLoc": { point: [30.55, 71.44]} }
964 var points = rec[entry].split("point:")[1].match(/[-+]?[0-9]*\.?[0-9]+/g);
965
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700966 var drill_element = {
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700967 "tweetEntryId" : parseInt(rec[entry].split(",")[0].split(":")[1].replace('"', '')),
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700968 "tweetText" : rec[entry].split("tweetText\": \"")[1].split("\", \"tweetLoc\":")[0],
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700969 "tweetLat" : parseFloat(points[0]),
970 "tweetLng" : parseFloat(points[1])
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700971 };
972 drilldown_cleaned.push(drill_element);
973 }
974 return drilldown_cleaned;
975}
976
977function onClickTweetbookMapMarker(tweet_arr) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700978 // Clear existing display
979 $.each(tweet_arr, function (t, valueT) {
980 var tweet_obj = tweet_arr[t];
981 onDrillDownAtLocation(tweet_obj);
982 });
983
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700984 $('#drilldown_modal').modal();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700985}
986
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700987/**
988* Explore mode: Initial map creation and screen alignment
989*/
990function onOpenExploreMap () {
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700991 var explore_column_height = $('#explore-well').height();
992 var right_column_width = $('#right-col').width();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700993 $('#map_canvas').height(explore_column_height + "px");
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700994 $('#map_canvas').width(right_column_width + "px");
995
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700996 $('#review-well').height(explore_column_height + "px");
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700997 $('#review-well').css('max-height', explore_column_height + "px");
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700998 $('#right-col').height(explore_column_height + "px");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700999}
1000
1001/**
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001002* initializes demo - adds some extra events when review/explore
1003* mode are clicked, initializes tabs, aligns map box, moves
1004* active tab to about tab
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001005*/
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001006function initDemoPrepareTabs() {
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -07001007
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001008 // Tab behavior for About, Explore, and Demo
1009 $('#mode-tabs a').click(function (e) {
1010 e.preventDefault()
1011 $(this).tab('show')
1012 })
1013
1014 // Explore mode should show explore-mode query-builder UI
1015 $('#explore-mode').click(function(e) {
1016 $('#review-well').hide();
1017 $('#explore-well').show();
1018 mapWidgetResetMap();
1019 });
1020
1021 // Review mode should show review well and hide explore well
1022 $('#review-mode').click(function(e) {
1023 $('#explore-well').hide();
1024 $('#review-well').show();
1025 mapWidgetResetMap();
1026 });
1027
1028 // Does some alignment necessary for the map canvas
1029 onOpenExploreMap();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001030}
1031
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001032/**
1033* Creates a delete icon button using default trash icon
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001034* @param {String} id, id for this element
1035* @param {String} attachTo, id string of an element to which I can attach this button.
1036* @param {Function} onClick, a function to fire when this icon is clicked
1037*/
1038function addDeleteButton(iconId, attachTo, onClick) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001039
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001040 var trashIcon = '<button class="btn btn-default" id="' + iconId + '"><span class="glyphicon glyphicon-trash"></span></button>';
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001041 $('#' + attachTo).append(trashIcon);
1042
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001043 // When this trash button is clicked, the function is called.
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001044 $('#' + iconId).on('click', onClick);
1045}
1046
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001047/**
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001048* Creates a message and attaches it to data management area.
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001049* @param {String} message, a message to post
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001050* @param {Boolean} isPositiveMessage, whether or not this is a positive message.
1051* @param {String} target, the target div to attach this message.
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001052*/
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001053function reportUserMessage(message, isPositiveMessage, target) {
1054 // Clear out any existing messages
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001055 $('#' + target).html('');
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001056
1057 // Select appropriate alert-type
1058 var alertType = "alert-success";
1059 if (!isPositiveMessage) {
1060 alertType = "alert-danger";
1061 }
1062
1063 // Append the appropriate message
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001064 $('<div/>')
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001065 .attr("class", "alert " + alertType)
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001066 .html('<button type="button" class="close" data-dismiss="alert">&times;</button>' + message)
1067 .appendTo('#' + target);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001068}
1069
1070/**
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001071* mapWidgetResetMap
1072*
1073* [No Parameters]
1074*
1075* Clears ALL map elements - plotted items, overlays, then resets position
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001076*/
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001077function mapWidgetResetMap() {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001078
1079 if (selectionRect) {
1080 selectionRect.setMap(null);
1081 selectionRect = null;
1082 }
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001083
1084 mapWidgetClearMap();
1085
1086 // Reset map center and zoom
1087 map.setCenter(new google.maps.LatLng(38.89, -77.03));
1088 map.setZoom(4);
1089}
1090
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001091/**
1092* mapWidgetClearMap
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001093* Removes data/markers
1094*/
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001095function mapWidgetClearMap() {
1096
1097 // Remove previously plotted data/markers
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001098 for (c in map_cells) {
1099 map_cells[c].setMap(null);
1100 }
1101 map_cells = [];
genia.likes.science@gmail.com65e04182013-10-04 04:31:41 -07001102
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001103 $.each(map_info_windows, function(i) {
1104 map_info_windows[i].close();
1105 });
1106 map_info_windows = {};
1107
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001108 for (m in map_tweet_markers) {
1109 map_tweet_markers[m].setMap(null);
1110 }
1111 map_tweet_markers = [];
Eugenia Gabrielova12de0302013-10-18 02:25:39 -07001112
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -07001113 $("#rainbow-legend-container").hide();
1114
Eugenia Gabrielova12de0302013-10-18 02:25:39 -07001115 $("#submit-button").attr("disabled", false);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001116}
1117
1118/**
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001119* buildLegend
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001120*
1121* Generates gradient, button action for legend bar
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001122*/
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001123function buildLegend() {
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -07001124
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001125 // Fill in legend area with colors
1126 var gradientColor;
1127
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -07001128 for (i = 0; i<100; i++) {
1129 //$("#rainbow-legend-container").append("" + rainbow.colourAt(i));
1130 $("#legend-gradient").append('<div style="display:inline-block; max-width:2px; background-color:#' + rainbow.colourAt(i) +';">&nbsp;</div>');
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001131 }
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001132
1133 // Window clear button closes all info count windows
1134 $("#windows-off-btn").on("click", function(e) {
1135 $.each(map_info_windows, function(i) {
1136 map_info_windows[i].close();
1137 });
1138 });
1139}
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001140
1141/**
1142* Computes radius for a given data point from a spatial cell
1143* @param {Object} keys => ["latSW" "lngSW" "latNE" "lngNE" "weight"]
1144* @returns {number} radius between 2 points in metres
1145*/
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001146function mapWidgetComputeCircleRadius(spatialCell, wLimit) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001147
1148 // Define Boundary Points
1149 var point_center = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
1150 var point_left = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, spatialCell.lngSW);
1151 var point_top = new google.maps.LatLng(spatialCell.latNE, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
1152
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001153 // Circle scale modifier =
1154 var scale = 500 + 500*(spatialCell.weight / wLimit);
1155
1156 // Return proportionate value so that circles mostly line up.
1157 return scale * Math.min(distanceBetweenPoints_(point_center, point_left), distanceBetweenPoints_(point_center, point_top));
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001158}
1159
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001160/**
1161 * Calculates the distance between two latlng locations in km.
1162 * @see http://www.movable-type.co.uk/scripts/latlong.html
1163 *
1164 * @param {google.maps.LatLng} p1 The first lat lng point.
1165 * @param {google.maps.LatLng} p2 The second lat lng point.
1166 * @return {number} The distance between the two points in km.
1167 * @private
1168*/
1169function distanceBetweenPoints_(p1, p2) {
1170 if (!p1 || !p2) {
1171 return 0;
1172 }
1173
1174 var R = 6371; // Radius of the Earth in km
1175 var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
1176 var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
1177 var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
1178 Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
1179 Math.sin(dLon / 2) * Math.sin(dLon / 2);
1180 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1181 var d = R * c;
1182 return d;
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001183};