blob: b63b6762afd83b27f14f50fc57bb4c85350a5e88 [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 );
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070048
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -070049 // Legend Container
50 // Create a rainbow from a pretty color scheme.
51 // http://www.colourlovers.com/palette/292482/Terra
52 rainbow = new Rainbow();
53 rainbow.setSpectrum("#E8DDCB", "#CDB380", "#036564", "#033649", "#031634");
54 buildLegend();
55
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -070056 // Initialization of UI Tabas
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -070057 initDemoPrepareTabs();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070058
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -070059 // UI Elements - Creates Map, Location Auto-Complete, Selection Rectangle
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070060 var mapOptions = {
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -070061 center: new google.maps.LatLng(38.89, -77.03),
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070062 zoom: 4,
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -070063 mapTypeId: google.maps.MapTypeId.ROADMAP,
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070064 streetViewControl: false,
Eugenia Gabrielovae11965b2013-10-29 19:07:42 -070065 draggable : false,
66 mapTypeControl: false
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070067 };
68 map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
69
70 var input = document.getElementById('location-text-box');
71 var autocomplete = new google.maps.places.Autocomplete(input);
72 autocomplete.bindTo('bounds', map);
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -070073
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070074 google.maps.event.addListener(autocomplete, 'place_changed', function() {
75 var place = autocomplete.getPlace();
76 if (place.geometry.viewport) {
77 map.fitBounds(place.geometry.viewport);
78 } else {
79 map.setCenter(place.geometry.location);
80 map.setZoom(17); // Why 17? Because it looks good.
81 }
82 var address = '';
83 if (place.address_components) {
84 address = [(place.address_components[0] && place.address_components[0].short_name || ''),
85 (place.address_components[1] && place.address_components[1].short_name || ''),
86 (place.address_components[2] && place.address_components[2].short_name || '') ].join(' ');
87 }
88 });
89
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -070090 // Drawing Manager for selecting map regions. See documentation here:
91 // https://developers.google.com/maps/documentation/javascript/reference#DrawingManager
92 rectangleManager = new google.maps.drawing.DrawingManager({
93 drawingMode : google.maps.drawing.OverlayType.RECTANGLE,
94 drawingControl : false,
95 rectangleOptions : {
96 strokeWeight: 1,
97 clickable: false,
98 editable: true,
99 strokeColor: "2b3f8c",
100 fillColor: "2b3f8c",
101 zIndex: 1
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700102 }
103 });
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -0700104 rectangleManager.setMap(map);
105 selectionRectangle = null;
106
107 // Drawing Manager: Just one editable rectangle!
108 google.maps.event.addListener(rectangleManager, 'rectanglecomplete', function(rectangle) {
109 selectionRectangle = rectangle;
110 rectangleManager.setDrawingMode(null);
111 });
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700112
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700113 // Initialize data structures
114 APIqueryTracker = {};
115 asyncQueryManager = {};
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700116 map_cells = [];
117 map_tweet_markers = [];
118 map_info_windows = {};
119 review_mode_tweetbooks = [];
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700120
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700121 getAllDataverseTweetbooks();
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700122 initDemoUIButtonControls();
Eugenia Gabrielovae11965b2013-10-29 19:07:42 -0700123
124 google.maps.event.addListenerOnce(map, 'idle', function(){
125 // Show tutorial tab only the first time the map is loaded
126 $('#mode-tabs a:first').tab('show');
127 });
128
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700129});
130
131function initDemoUIButtonControls() {
132
133 // Explore Mode - Update Sliders
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700134 var updateSliderDisplay = function(event, ui) {
135 if (event.target.id == "grid-lat-slider") {
136 $("#gridlat").text(""+ui.value);
137 } else {
138 $("#gridlng").text(""+ui.value);
139 }
140 };
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700141 sliderOptions = {
142 max: 10,
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700143 min: 2.0,
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700144 step: .1,
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700145 value: 3.0,
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700146 slidechange: updateSliderDisplay,
147 slide: updateSliderDisplay,
148 start: updateSliderDisplay,
149 stop: updateSliderDisplay
150 };
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700151 $("#gridlat").text(""+sliderOptions.value);
152 $("#gridlng").text(""+sliderOptions.value);
153 $(".grid-slider").slider(sliderOptions);
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700154
155 // Explore Mode - Query Builder Date Pickers
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700156 var dateOptions = {
157 dateFormat: "yy-mm-dd",
158 defaultDate: "2012-01-02",
159 navigationAsDateFormat: true,
160 constrainInput: true
161 };
162 var start_dp = $("#start-date").datepicker(dateOptions);
163 start_dp.val(dateOptions.defaultDate);
164 dateOptions['defaultDate'] = "2012-12-31";
165 var end_dp= $("#end-date").datepicker(dateOptions);
166 end_dp.val(dateOptions.defaultDate);
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700167
168 // Explore Mode: Toggle Selection/Location Search
Eugenia Gabrielova3d7bfe52013-10-28 02:36:44 -0700169 $('#selection-button').on('change', function (e) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700170 $("#location-text-box").attr("disabled", "disabled");
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -0700171 rectangleManager.setMap(map);
172 if (selectionRectangle) {
173 selectionRectangle.setMap(null);
174 selectionRectangle = null;
175 } else {
176 rectangleManager.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700177 }
178 });
Eugenia Gabrielova3d7bfe52013-10-28 02:36:44 -0700179 $('#location-button').on('change', function (e) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700180 $("#location-text-box").removeAttr("disabled");
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -0700181 rectangleManager.setMap(null);
Eugenia Gabrielovae11965b2013-10-29 19:07:42 -0700182 selectionRectangle = null;
183 rectangleManager.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700184 });
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700185 $("#selection-button").trigger("click");
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700186
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700187 // Review Mode: New Tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700188 $('#new-tweetbook-button').on('click', function (e) {
189 onCreateNewTweetBook($('#new-tweetbook-entry').val());
190
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700191 $('#new-tweetbook-entry').val("");
192 $('#new-tweetbook-entry').attr("placeholder", "Name a new tweetbook");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700193 });
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700194
195 // Explore Mode - Clear Button
196 $("#clear-button").click(mapWidgetResetMap);
197
198 // Explore Mode: Query Submission
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700199 $("#submit-button").on("click", function () {
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700200
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700201 $("#report-message").html('');
202 $("#submit-button").attr("disabled", true);
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -0700203 rectangleManager.setDrawingMode(null);
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700204
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700205 var kwterm = $("#keyword-textbox").val();
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700206 var startdp = $("#start-date").datepicker("getDate");
207 var enddp = $("#end-date").datepicker("getDate");
208 var startdt = $.datepicker.formatDate("yy-mm-dd", startdp)+"T00:00:00Z";
209 var enddt = $.datepicker.formatDate("yy-mm-dd", enddp)+"T23:59:59Z";
210
211 var formData = {
212 "keyword": kwterm,
213 "startdt": startdt,
214 "enddt": enddt,
215 "gridlat": $("#grid-lat-slider").slider("value"),
216 "gridlng": $("#grid-lng-slider").slider("value")
217 };
218
219 // Get Map Bounds
220 var bounds;
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -0700221 if ($('#selection-label').hasClass("active") && selectionRectangle) {
222 bounds = selectionRectangle.getBounds();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700223 } else {
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700224 bounds = map.getBounds();
225 }
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700226
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700227 var swLat = Math.abs(bounds.getSouthWest().lat());
228 var swLng = Math.abs(bounds.getSouthWest().lng());
229 var neLat = Math.abs(bounds.getNorthEast().lat());
230 var neLng = Math.abs(bounds.getNorthEast().lng());
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700231
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700232 formData["swLat"] = Math.min(swLat, neLat);
233 formData["swLng"] = Math.max(swLng, neLng);
234 formData["neLat"] = Math.max(swLat, neLat);
235 formData["neLng"] = Math.min(swLng, neLng);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700236
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700237 var build_cherry_mode = "synchronous";
238 if ($('#asbox').is(":checked")) {
239 build_cherry_mode = "asynchronous";
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700240 }
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700241
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700242 var f = buildAQLQueryFromForm(formData);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700243
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700244 APIqueryTracker = {
245 "query" : "use dataverse twitter;\n" + f.val(),
246 "data" : formData
247 };
genia.likes.science@gmail.com233fe972013-09-07 13:57:46 -0700248
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700249 if (build_cherry_mode == "synchronous") {
250 A.query(f.val(), cherryQuerySyncCallback, build_cherry_mode);
251 } else {
252 A.query(f.val(), cherryQueryAsyncCallback, build_cherry_mode);
253 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700254
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700255 // Clears selection rectangle on query execution, rather than waiting for another clear call.
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -0700256 if (selectionRectangle) {
257 selectionRectangle.setMap(null);
258 selectionRectangle = null;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700259 }
260 });
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700261}
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700262
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700263/**
264* Builds AsterixDB REST Query from explore mode form.
265*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700266function buildAQLQueryFromForm(parameters) {
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700267
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700268 var bounds = {
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700269 "ne" : { "lat" : parameters["neLat"], "lng" : -1*parameters["neLng"]},
270 "sw" : { "lat" : parameters["swLat"], "lng" : -1*parameters["swLng"]}
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700271 };
272
273 var rectangle =
274 new FunctionExpression("create-rectangle",
275 new FunctionExpression("create-point", bounds["sw"]["lat"], bounds["sw"]["lng"]),
276 new FunctionExpression("create-point", bounds["ne"]["lat"], bounds["ne"]["lng"]));
277
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700278 // You can chain these all together, but let's take them one at a time.
279 // Let's start with a ForClause. Here we go through each tweet $t in the
280 // dataset TweetMessageShifted.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700281 var aql = new FLWOGRExpression()
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700282 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"));
283
284 // We know we have bounds for our region, so we can add that LetClause next.
285 aql = aql.LetClause("$region", rectangle);
286
287 // Now, let's change it up. The keyword term doesn't always show up, so it might be blank.
288 // We'll attach a new let clause for it, and then a WhereClause.
289 if (parameters["keyword"].length > 0) {
290 aql = aql
291 .LetClause("$keyword", new AExpression('"' + parameters["keyword"] + '"'))
292 .WhereClause().and(
293 new FunctionExpression("spatial-intersect", "$t.sender-location", "$region"),
294 new AExpression('$t.send-time > datetime("' + parameters["startdt"] + '")'),
295 new AExpression('$t.send-time < datetime("' + parameters["enddt"] + '")'),
296 new FunctionExpression("contains", "$t.message-text", "$keyword")
297 );
298 } else {
299 aql = aql
300 .WhereClause().and(
301 new FunctionExpression("spatial-intersect", "$t.sender-location", "$region"),
302 new AExpression('$t.send-time > datetime("' + parameters["startdt"] + '")'),
303 new AExpression('$t.send-time < datetime("' + parameters["enddt"] + '")')
304 );
305 }
306
307 // Finally, we'll group our results into spatial cells.
308 aql = aql.GroupClause(
309 "$c",
310 new FunctionExpression("spatial-cell", "$t.sender-location",
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700311 new FunctionExpression("create-point", "24.5", "-125.5"),
312 parameters["gridlat"].toFixed(1), parameters["gridlng"].toFixed(1)),
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700313 "with",
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700314 "$t"
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700315 );
316
317 // ...and return a resulting cell and a count of results in that cell.
318 aql = aql.ReturnClause({ "cell" : "$c", "count" : "count($t)" });
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700319
320 return aql;
321}
322
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700323/**
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700324* getAllDataverseTweetbooks
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700325*
326* Returns all datasets of type TweetbookEntry, populates review_mode_tweetbooks
327*/
328function getAllDataverseTweetbooks(fn_tweetbooks) {
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700329
330 // This creates a query to the Metadata for datasets of type
331 // TweetBookEntry. Note that if we throw in a WhereClause (commented out below)
332 // there is an odd error. This is being fixed and will be removed from this demo.
333 var getTweetbooksQuery = new FLWOGRExpression()
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700334 .ForClause("$ds", new AExpression("dataset Metadata.Dataset"))
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700335 //.WhereClause(new AExpression('$ds.DataTypeName = "TweetbookEntry"'))
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700336 .ReturnClause({
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700337 "DataTypeName" : "$ds.DataTypeName",
338 "DatasetName" : "$ds.DatasetName"
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700339 });
340
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700341 // Now create a function that will be called when tweetbooks succeed.
342 // In this case, we want to parse out the results object from the Asterix
343 // REST API response.
344 var tweetbooksSuccess = function(r) {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700345 // Parse tweetbook metadata results
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700346 $.each(r.results, function(i, data) {
347 if ($.parseJSON(data)["DataTypeName"] == "TweetbookEntry") {
348 review_mode_tweetbooks.push($.parseJSON(data)["DatasetName"]);
349 }
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700350 });
351
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700352 // Now, if any tweetbooks already exist, opulate review screen.
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700353 $('#review-tweetbook-titles').html('');
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700354 $.each(review_mode_tweetbooks, function(i, tweetbook) {
355 addTweetBookDropdownItem(tweetbook);
356 });
357 };
358
359 // Now, we are ready to run a query.
360 A.meta(getTweetbooksQuery.val(), tweetbooksSuccess);
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700361}
362
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700363/**
364* Checks through each asynchronous query to see if they are ready yet
365*/
366function asynchronousQueryIntervalUpdate() {
367 for (var handle_key in asyncQueryManager) {
368 if (!asyncQueryManager[handle_key].hasOwnProperty("ready")) {
369 asynchronousQueryGetAPIQueryStatus( asyncQueryManager[handle_key]["handle"], handle_key );
370 }
371 }
372}
373
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700374/**
375* Returns current time interval to check for asynchronous query readiness
376* @returns {number} milliseconds between asychronous query checks
377*/
378function asynchronousQueryGetInterval() {
379 var seconds = 10;
380 return seconds * 1000;
381}
382
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700383/**
384* Retrieves status of an asynchronous query, using an opaque result handle from API
385* @param {Object} handle, an object previously returned from an async call
386* @param {number} handle_id, the integer ID parsed from the handle object
387*/
388function asynchronousQueryGetAPIQueryStatus (handle, handle_id) {
389
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700390 A.query_status(
391 {
392 "handle" : JSON.stringify(handle)
393 },
394 function (res) {
395 if (res["status"] == "SUCCESS") {
396 // We don't need to check if this one is ready again, it's not going anywhere...
397 // Unless the life cycle of handles has changed drastically
398 asyncQueryManager[handle_id]["ready"] = true;
399
400 // Indicate success.
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700401 $('#handle_' + handle_id).removeClass("btn-disabled").prop('disabled', false).addClass("btn-success");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700402 }
403 }
404 );
405}
406
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700407/**
408* On-success callback after async API query
409* @param {object} res, a result object containing an opaque result handle to Asterix
410*/
411function cherryQueryAsyncCallback(res) {
412
413 // Parse handle, handle id and query from async call result
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700414 var handle_query = APIqueryTracker["query"];
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700415 var handle = res;
416 var handle_id = res["handle"].toString().split(',')[0];
417
418 // Add to stored map of existing handles
419 asyncQueryManager[handle_id] = {
420 "handle" : handle,
Eugenia Gabrielovae11965b2013-10-29 19:07:42 -0700421 "query" : handle_query, // This will show up when query control button is clicked.
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700422 "data" : APIqueryTracker["data"]
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700423 };
424
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700425 // Create a container for this async query handle
426 $('<div/>')
427 .css("margin-left", "1em")
428 .css("margin-bottom", "1em")
429 .css("display", "block")
430 .attr({
431 "class" : "btn-group",
432 "id" : "async_container_" + handle_id
433 })
434 .appendTo("#async-handle-controls");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700435
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700436 // Adds the main button for this async handle
437 var handle_action_button = '<button class="btn btn-disabled" id="handle_' + handle_id + '">Handle ' + handle_id + '</button>';
438 $('#async_container_' + handle_id).append(handle_action_button);
439 $('#handle_' + handle_id).prop('disabled', true);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700440 $('#handle_' + handle_id).on('click', function (e) {
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700441
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700442 // make sure query is ready to be run
443 if (asyncQueryManager[handle_id]["ready"]) {
444
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700445 APIqueryTracker = {
446 "query" : asyncQueryManager[handle_id]["query"],
447 "data" : asyncQueryManager[handle_id]["data"]
448 };
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700449
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -0700450 if (!asyncQueryManager[handle_id].hasOwnProperty("result")) {
451 // Generate new Asterix Core API Query
452 A.query_result(
453 { "handle" : JSON.stringify(asyncQueryManager[handle_id]["handle"]) },
454 function(res) {
455 asyncQueryManager[handle_id]["result"] = res;
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700456
457 var resultTransform = {
458 "results" : res.results[0]
459 };
460
461 cherryQuerySyncCallback(resultTransform);
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -0700462 }
463 );
464 } else {
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700465
466 var resultTransform = {
467 "results" : asyncQueryManager[handle_id]["result"].results[0]
468 };
469
470 cherryQuerySyncCallback(resultTransform);
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -0700471 }
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/**
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700491* A spatial data cleaning and mapping call
492* @param {Object} res, a result object from a cherry geospatial query
493*/
494function cherryQuerySyncCallback(res) {
genia.likes.science@gmail.comd42b4022013-08-09 05:05:23 -0700495
Eugenia Gabrielovae11965b2013-10-29 19:07:42 -0700496 // First, we check if any results came back in.
497 // If they didn't, return.
498 if (!res.hasOwnProperty("results")) {
499 reportUserMessage("Oops, no results found for those parameters.", false, "report-message");
500 return;
501 }
502
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700503 // Initialize coordinates and weights, to store
504 // coordinates of map cells and their weights
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700505 var coordinates = [];
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700506 var maxWeight = 0;
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700507 var minWeight = Number.MAX_VALUE;
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700508
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700509 // Parse resulting JSON objects. Here is an example record:
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700510 // { "cell": rectangle("21.5,-98.5 24.5,-95.5"), "count": 78i64 }
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700511 $.each(res.results, function(i, data) {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700512
513 // We need to clean the JSON a bit to parse it properly in javascript
514 var cleanRecord = $.parseJSON(data
515 .replace('rectangle(', '')
516 .replace(')', '')
517 .replace('i64', ''));
518
519 var recordCount = cleanRecord["count"];
520 var rectangle = cleanRecord["cell"]
521 .replace(' ', ',')
522 .split(',')
523 .map( parseFloat );
524
525 // Now, using the record count and coordinates, we can create a
526 // coordinate system for this spatial cell.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700527 var coordinate = {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700528 "latSW" : rectangle[0],
529 "lngSW" : rectangle[1],
530 "latNE" : rectangle[2],
531 "lngNE" : rectangle[3],
532 "weight" : recordCount
533 };
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700534
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700535 // We track the minimum and maximum weight to support our legend.
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700536 maxWeight = Math.max(coordinate["weight"], maxWeight);
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700537 minWeight = Math.min(coordinate["weight"], minWeight);
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700538
539 // Save completed coordinate and move to next one.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700540 coordinates.push(coordinate);
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700541 });
Eugenia Gabrielovacacc9f82013-10-21 14:10: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*
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700610* @params {object} marker_borders a set of bounds for a region from a previous api result
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700611*/
612function onMapPointDrillDown(marker_borders) {
Eugenia Gabrielovaf29a55f2013-10-28 03:18:18 -0700613
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700614 var zoneData = APIqueryTracker["data"];
615
616 var zswBounds = new google.maps.LatLng(marker_borders.latSW, marker_borders.lngSW);
617 var zneBounds = new google.maps.LatLng(marker_borders.latNE, marker_borders.lngNE);
618
619 var zoneBounds = new google.maps.LatLngBounds(zswBounds, zneBounds);
620 zoneData["swLat"] = zoneBounds.getSouthWest().lat();
621 zoneData["swLng"] = zoneBounds.getSouthWest().lng();
622 zoneData["neLat"] = zoneBounds.getNorthEast().lat();
623 zoneData["neLng"] = zoneBounds.getNorthEast().lng();
624 var zB = {
625 "sw" : {
626 "lat" : zoneBounds.getSouthWest().lat(),
627 "lng" : zoneBounds.getSouthWest().lng()
628 },
629 "ne" : {
630 "lat" : zoneBounds.getNorthEast().lat(),
631 "lng" : zoneBounds.getNorthEast().lng()
632 }
633 };
634
635 mapWidgetClearMap();
636
637 var customBounds = new google.maps.LatLngBounds();
638 var zoomSWBounds = new google.maps.LatLng(zoneData["swLat"], zoneData["swLng"]);
639 var zoomNEBounds = new google.maps.LatLng(zoneData["neLat"], zoneData["neLng"]);
640 customBounds.extend(zoomSWBounds);
641 customBounds.extend(zoomNEBounds);
642 map.fitBounds(customBounds);
643
644 var df = getDrillDownQuery(zoneData, zB);
645
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700646 APIqueryTracker = {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700647 "query_string" : "use dataverse twitter;\n" + df.val(),
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700648 "marker_path" : "static/img/mobile2.png"
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700649 };
650
651 A.query(df.val(), onTweetbookQuerySuccessPlot);
652}
653
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700654/**
655* Generates an aql query for zooming on a spatial cell and obtaining tweets contained therein.
656* @param parameters, the original query parameters
657* @param bounds, the bounds of the zone to zoom in on.
658*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700659function getDrillDownQuery(parameters, bounds) {
660
661 var zoomRectangle = new FunctionExpression("create-rectangle",
662 new FunctionExpression("create-point", bounds["sw"]["lat"], bounds["sw"]["lng"]),
663 new FunctionExpression("create-point", bounds["ne"]["lat"], bounds["ne"]["lng"]));
664
665 var drillDown = new FLWOGRExpression()
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700666 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700667 .LetClause("$region", zoomRectangle);
668
669 if (parameters["keyword"].length == 0) {
670 drillDown = drillDown
671 .WhereClause().and(
672 new FunctionExpression('spatial-intersect', '$t.sender-location', '$region'),
673 new AExpression().set('$t.send-time > datetime("' + parameters["startdt"] + '")'),
674 new AExpression().set('$t.send-time < datetime("' + parameters["enddt"] + '")')
675 );
676 } else {
677 drillDown = drillDown
678 .LetClause("$keyword", new AExpression('"' + parameters["keyword"] + '"'))
679 .WhereClause().and(
680 new FunctionExpression('spatial-intersect', '$t.sender-location', '$region'),
681 new AExpression().set('$t.send-time > datetime("' + parameters["startdt"] + '")'),
682 new AExpression().set('$t.send-time < datetime("' + parameters["enddt"] + '")'),
683 new FunctionExpression('contains', '$t.message-text', '$keyword')
684 );
685 }
686
687 drillDown = drillDown
688 .ReturnClause({
689 "tweetId" : "$t.tweetid",
690 "tweetText" : "$t.message-text",
691 "tweetLoc" : "$t.sender-location"
692 });
693
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700694 return drillDown;
695}
696
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700697/**
698* Given a location where a tweet exists, opens a modal to examine or update a tweet's content.
699* @param t0, a tweetobject that has a location, text, id, and optionally a comment.
700*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700701function onDrillDownAtLocation(tO) {
702
703 var tweetId = tO["tweetEntryId"];
704 var tweetText = tO["tweetText"];
705
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700706 // First, set tweet in drilldown modal to be this tweet's text
707 $('#modal-body-tweet').html('Tweet #' + tweetId + ": " + tweetText);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700708
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700709 // Next, empty any leftover tweetbook comments or error/success messages
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700710 $("#modal-body-add-to").val('');
711 $("#modal-body-add-note").val('');
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700712 $("#modal-body-message-holder").html("");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700713
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700714 // Next, if there is an existing tweetcomment reported, show it.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700715 if (tO.hasOwnProperty("tweetComment")) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700716
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700717 // Show correct panel
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700718 $("#modal-existing-note").show();
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700719 $("#modal-save-tweet-panel").hide();
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700720
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700721 // Fill in existing tweet comment
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700722 $("#modal-body-tweet-note").val(tO["tweetComment"]);
723
724 // Change Tweetbook Badge
725 $("#modal-current-tweetbook").val(APIqueryTracker["active_tweetbook"]);
726
727 // Add deletion functionality
728 $("#modal-body-trash-icon").on('click', function () {
729 // Send comment deletion to asterix
730 var deleteTweetCommentOnId = '"' + tweetId + '"';
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700731 var toDelete = new DeleteStatement(
732 "$mt",
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700733 APIqueryTracker["active_tweetbook"],
734 new AExpression("$mt.tweetid = " + deleteTweetCommentOnId.toString())
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700735 );
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700736 A.update(
737 toDelete.val()
738 );
739
740 // Hide comment from map
741 $('#drilldown_modal').modal('hide');
742
743 // Replot tweetbook
744 onPlotTweetbook(APIqueryTracker["active_tweetbook"]);
745 });
746
747 } else {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700748 // Show correct panel
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700749 $("#modal-existing-note").hide();
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700750 $("#modal-save-tweet-panel").show();
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700751
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700752 // Now, when adding a comment on an available tweet to a tweetbook
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700753 $('#save-comment-tweetbook-modal').unbind('click');
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700754 $("#save-comment-tweetbook-modal").on('click', function(e) {
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700755
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700756 // Stuff to save about new comment
757 var save_metacomment_target_tweetbook = $("#modal-body-add-to").val();
758 var save_metacomment_target_comment = '"' + $("#modal-body-add-note").val() + '"';
759 var save_metacomment_target_tweet = '"' + tweetId + '"';
760
761 // Make sure content is entered, and then save this comment.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700762 if ($("#modal-body-add-note").val() == "") {
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700763
764 reportUserMessage("Please enter a comment about the tweet", false, "report-message");
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700765
766 } else if ($("#modal-body-add-to").val() == "") {
767
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700768 reportUserMessage("Please enter a tweetbook.", false, "report-message");
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700769
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700770 } else {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700771
772 // Check if tweetbook exists. If not, create it.
773 if (!(existsTweetbook(save_metacomment_target_tweetbook))) {
774 onCreateNewTweetBook(save_metacomment_target_tweetbook);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700775 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700776
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700777 var toInsert = new InsertStatement(
778 save_metacomment_target_tweetbook,
779 {
780 "tweetid" : save_metacomment_target_tweet.toString(),
781 "comment-text" : save_metacomment_target_comment
782 }
783 );
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700784
785 A.update(toInsert.val(), function () {
786 var successMessage = "Saved comment on <b>Tweet #" + tweetId +
787 "</b> in dataset <b>" + save_metacomment_target_tweetbook + "</b>.";
788 reportUserMessage(successMessage, true, "report-message");
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700789
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700790 $("#modal-body-add-to").val('');
791 $("#modal-body-add-note").val('');
792 $('#save-comment-tweetbook-modal').unbind('click');
793
794 // Close modal
795 $('#drilldown_modal').modal('hide');
796 });
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700797 }
798 });
799 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700800}
801
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700802/**
803* Adds a new tweetbook entry to the menu and creates a dataset of type TweetbookEntry.
804*/
805function onCreateNewTweetBook(tweetbook_title) {
806
807 var tweetbook_title = tweetbook_title.split(' ').join('_');
808
809 A.ddl(
810 "create dataset " + tweetbook_title + "(TweetbookEntry) primary key tweetid;",
811 function () {}
812 );
813
814 if (!(existsTweetbook(tweetbook_title))) {
815 review_mode_tweetbooks.push(tweetbook_title);
816 addTweetBookDropdownItem(tweetbook_title);
817 }
818}
819
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700820/**
821* Removes a tweetbook from both demo and from
822* dataverse metadata.
823*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700824function onDropTweetBook(tweetbook_title) {
825
826 // AQL Call
827 A.ddl(
828 "drop dataset " + tweetbook_title + " if exists;",
829 function () {}
830 );
831
832 // Removes tweetbook from review_mode_tweetbooks
833 var remove_position = $.inArray(tweetbook_title, review_mode_tweetbooks);
834 if (remove_position >= 0) review_mode_tweetbooks.splice(remove_position, 1);
835
836 // Clear UI with review tweetbook titles
837 $('#review-tweetbook-titles').html('');
838 for (r in review_mode_tweetbooks) {
839 addTweetBookDropdownItem(review_mode_tweetbooks[r]);
840 }
841}
842
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700843/**
844* Adds a tweetbook action button to the dropdown box in review mode.
845* @param tweetbook, a string representing a tweetbook
846*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700847function addTweetBookDropdownItem(tweetbook) {
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700848 // Add placeholder for this tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700849 $('<div/>')
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700850 .attr({
851 "class" : "btn-group",
852 "id" : "rm_holder_" + tweetbook
853 }).appendTo("#review-tweetbook-titles");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700854
855 // Add plotting button for this tweetbook
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700856 var plot_button = '<button class="btn btn-default" id="rm_plotbook_' + tweetbook + '">' + tweetbook + '</button>';
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700857 $("#rm_holder_" + tweetbook).append(plot_button);
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700858 $("#rm_plotbook_" + tweetbook).width("200px");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700859 $("#rm_plotbook_" + tweetbook).on('click', function(e) {
860 onPlotTweetbook(tweetbook);
861 });
862
863 // Add trash button for this tweetbook
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700864 var onTrashTweetbookButton = addDeleteButton(
865 "rm_trashbook_" + tweetbook,
866 "rm_holder_" + tweetbook,
867 function(e) {
868 onDropTweetBook(tweetbook);
869 }
870 );
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700871}
872
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700873/**
874* Generates AsterixDB query to plot existing tweetbook commnets
875* @param tweetbook, a string representing a tweetbook
876*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700877function onPlotTweetbook(tweetbook) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700878
879 // Clear map for this one
Eugenia Gabrielovae11965b2013-10-29 19:07:42 -0700880 mapWidgetClearMap();
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700881
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700882 var plotTweetQuery = new FLWOGRExpression()
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700883 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700884 .ForClause("$m", new AExpression("dataset " + tweetbook))
885 .WhereClause(new AExpression("$m.tweetid = $t.tweetid"))
886 .ReturnClause({
887 "tweetId" : "$m.tweetid",
888 "tweetText" : "$t.message-text",
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700889 "tweetCom" : "$m.comment-text",
890 "tweetLoc" : "$t.sender-location"
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700891 });
892
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700893 APIqueryTracker = {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700894 "query_string" : "use dataverse twitter;\n" + plotTweetQuery.val(),
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700895 "marker_path" : "static/img/mobile_green2.png",
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700896 "active_tweetbook" : tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700897 };
898
899 A.query(plotTweetQuery.val(), onTweetbookQuerySuccessPlot);
900}
901
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700902/**
903* Given an output response set of tweet data,
904* prepares markers on map to represent individual tweets.
905* @param res, a JSON Object
906*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700907function onTweetbookQuerySuccessPlot (res) {
908
Eugenia Gabrielovae11965b2013-10-29 19:07:42 -0700909 // First, we check if any results came back in.
910 // If they didn't, return.
911 if (!res.hasOwnProperty("results")) {
912 reportUserMessage("Oops, no data matches this query.", false, "report-message");
913 return;
914 }
915
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700916 // Parse out tweet Ids, texts, and locations
917 var tweets = [];
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700918 var al = 1;
919
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700920 $.each(res.results, function(i, data) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700921
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700922 // First, clean up the data
923 //{ "tweetId": "100293", "tweetText": " like at&t the touch-screen is amazing", "tweetLoc": point("31.59,-84.23") }
924 // We need to turn the point object at the end into a string
925 var json = $.parseJSON(data
926 .replace(': point(',': ')
927 .replace(') }', ' }'));
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700928
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700929 // Now, we construct a tweet object
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700930 var tweetData = {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700931 "tweetEntryId" : parseInt(json.tweetId),
932 "tweetText" : json.tweetText,
933 "tweetLat" : json.tweetLoc.split(",")[0],
934 "tweetLng" : json.tweetLoc.split(",")[1]
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700935 };
936
937 // If we are parsing out tweetbook data with comments, we need to check
938 // for those here as well.
939 if (json.hasOwnProperty("tweetCom")) {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700940 tweetData["tweetComment"] = json.tweetCom;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700941 }
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700942
943 tweets.push(tweetData)
944 });
945
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700946 // Create a marker for each tweet
947 $.each(tweets, function(i, t) {
948 // Create a phone marker at tweet's position
949 var map_tweet_m = new google.maps.Marker({
950 position: new google.maps.LatLng(tweets[i]["tweetLat"], tweets[i]["tweetLng"]),
951 map: map,
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700952 icon: APIqueryTracker["marker_path"],
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700953 clickable: true,
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700954 });
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700955 map_tweet_m["test"] = t;
956
957 // Open Tweet exploration window on click
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700958 google.maps.event.addListener(map_tweet_m, 'click', function (event) {
959 onClickTweetbookMapMarker(map_tweet_markers[i]["test"]);
960 });
961
962 // Add marker to index of tweets
963 map_tweet_markers.push(map_tweet_m);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700964 });
965}
966
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700967/**
968* Checks if a tweetbook exists
969* @param tweetbook, a String
970*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700971function existsTweetbook(tweetbook) {
972 if (parseInt($.inArray(tweetbook, review_mode_tweetbooks)) == -1) {
973 return false;
974 } else {
975 return true;
976 }
977}
978
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700979/**
980* When a marker is clicked on in the tweetbook, it will launch a modal
981* view to examine or edit the appropriate tweet
982*/
983function onClickTweetbookMapMarker(t) {
984 onDrillDownAtLocation(t)
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700985 $('#drilldown_modal').modal();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700986}
987
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700988/**
989* Explore mode: Initial map creation and screen alignment
990*/
991function onOpenExploreMap () {
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700992 var explore_column_height = $('#explore-well').height();
993 var right_column_width = $('#right-col').width();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700994 $('#map_canvas').height(explore_column_height + "px");
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700995 $('#map_canvas').width(right_column_width + "px");
996
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700997 $('#review-well').height(explore_column_height + "px");
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700998 $('#review-well').css('max-height', explore_column_height + "px");
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700999 $('#right-col').height(explore_column_height + "px");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001000}
1001
1002/**
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001003* initializes demo - adds some extra events when review/explore
1004* mode are clicked, initializes tabs, aligns map box, moves
1005* active tab to about tab
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001006*/
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001007function initDemoPrepareTabs() {
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -07001008
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001009 // Tab behavior for About, Explore, and Demo
1010 $('#mode-tabs a').click(function (e) {
1011 e.preventDefault()
1012 $(this).tab('show')
1013 })
1014
1015 // Explore mode should show explore-mode query-builder UI
1016 $('#explore-mode').click(function(e) {
1017 $('#review-well').hide();
1018 $('#explore-well').show();
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -07001019 rectangleManager.setMap(map);
1020 rectangleManager.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001021 mapWidgetResetMap();
1022 });
1023
1024 // Review mode should show review well and hide explore well
1025 $('#review-mode').click(function(e) {
1026 $('#explore-well').hide();
1027 $('#review-well').show();
1028 mapWidgetResetMap();
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -07001029 rectangleManager.setMap(null);
Eugenia Gabrielovae11965b2013-10-29 19:07:42 -07001030 rectangleManager.setDrawingMode(null);
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001031 });
1032
1033 // Does some alignment necessary for the map canvas
1034 onOpenExploreMap();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001035}
1036
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001037/**
1038* Creates a delete icon button using default trash icon
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001039* @param {String} id, id for this element
1040* @param {String} attachTo, id string of an element to which I can attach this button.
1041* @param {Function} onClick, a function to fire when this icon is clicked
1042*/
1043function addDeleteButton(iconId, attachTo, onClick) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001044
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001045 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 -07001046 $('#' + attachTo).append(trashIcon);
1047
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001048 // When this trash button is clicked, the function is called.
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001049 $('#' + iconId).on('click', onClick);
1050}
1051
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001052/**
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001053* Creates a message and attaches it to data management area.
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001054* @param {String} message, a message to post
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001055* @param {Boolean} isPositiveMessage, whether or not this is a positive message.
1056* @param {String} target, the target div to attach this message.
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001057*/
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001058function reportUserMessage(message, isPositiveMessage, target) {
1059 // Clear out any existing messages
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001060 $('#' + target).html('');
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001061
1062 // Select appropriate alert-type
1063 var alertType = "alert-success";
1064 if (!isPositiveMessage) {
1065 alertType = "alert-danger";
1066 }
1067
1068 // Append the appropriate message
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001069 $('<div/>')
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001070 .attr("class", "alert " + alertType)
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001071 .html('<button type="button" class="close" data-dismiss="alert">&times;</button>' + message)
1072 .appendTo('#' + target);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001073}
1074
1075/**
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001076* mapWidgetResetMap
1077*
1078* [No Parameters]
1079*
1080* Clears ALL map elements - plotted items, overlays, then resets position
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001081*/
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001082function mapWidgetResetMap() {
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);
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -07001089
1090 // Selection button
1091 $("#selection-button").trigger("click");
1092 rectangleManager.setMap(map);
1093 rectangleManager.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001094}
1095
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001096/**
1097* mapWidgetClearMap
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001098* Removes data/markers
1099*/
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001100function mapWidgetClearMap() {
1101
1102 // Remove previously plotted data/markers
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001103 for (c in map_cells) {
1104 map_cells[c].setMap(null);
1105 }
1106 map_cells = [];
genia.likes.science@gmail.com65e04182013-10-04 04:31:41 -07001107
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001108 $.each(map_info_windows, function(i) {
1109 map_info_windows[i].close();
1110 });
1111 map_info_windows = {};
1112
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001113 for (m in map_tweet_markers) {
1114 map_tweet_markers[m].setMap(null);
1115 }
1116 map_tweet_markers = [];
Eugenia Gabrielova12de0302013-10-18 02:25:39 -07001117
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -07001118 // Hide legend
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -07001119 $("#rainbow-legend-container").hide();
Eugenia Gabrielovaf29a55f2013-10-28 03:18:18 -07001120
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -07001121 // Reenable submit button
Eugenia Gabrielova12de0302013-10-18 02:25:39 -07001122 $("#submit-button").attr("disabled", false);
Eugenia Gabrielovaea8f9482013-10-28 04:49:18 -07001123
1124 // Hide selection rectangle
1125 if (selectionRectangle) {
1126 selectionRectangle.setMap(null);
1127 selectionRectangle = null;
1128 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001129}
1130
1131/**
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001132* buildLegend
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001133*
1134* Generates gradient, button action for legend bar
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001135*/
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001136function buildLegend() {
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -07001137
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001138 // Fill in legend area with colors
1139 var gradientColor;
1140
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -07001141 for (i = 0; i<100; i++) {
1142 //$("#rainbow-legend-container").append("" + rainbow.colourAt(i));
1143 $("#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 -07001144 }
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001145
1146 // Window clear button closes all info count windows
1147 $("#windows-off-btn").on("click", function(e) {
1148 $.each(map_info_windows, function(i) {
1149 map_info_windows[i].close();
1150 });
1151 });
1152}
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001153
1154/**
1155* Computes radius for a given data point from a spatial cell
1156* @param {Object} keys => ["latSW" "lngSW" "latNE" "lngNE" "weight"]
1157* @returns {number} radius between 2 points in metres
1158*/
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001159function mapWidgetComputeCircleRadius(spatialCell, wLimit) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001160
1161 // Define Boundary Points
1162 var point_center = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
1163 var point_left = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, spatialCell.lngSW);
1164 var point_top = new google.maps.LatLng(spatialCell.latNE, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
1165
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001166 // Circle scale modifier =
1167 var scale = 500 + 500*(spatialCell.weight / wLimit);
1168
1169 // Return proportionate value so that circles mostly line up.
Eugenia Gabrielovaf29a55f2013-10-28 03:18:18 -07001170 return scale * Math.min(distanceBetweenPoints(point_center, point_left), distanceBetweenPoints(point_center, point_top));
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001171}
1172
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001173/**
Eugenia Gabrielovaf29a55f2013-10-28 03:18:18 -07001174* Calculates the distance between two latlng locations in km, using Google Geometry API.
1175* @param p1, a LatLng
1176* @param p2, a LatLng
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001177*/
Eugenia Gabrielovaf29a55f2013-10-28 03:18:18 -07001178function distanceBetweenPoints (p1, p2) {
1179 return 0.001 * google.maps.geometry.spherical.computeDistanceBetween(p1, p2);
Eugenia Gabrielova3d7bfe52013-10-28 02:36:44 -07001180};