blob: 52ddadf8ac1556cc2c29b84ccc66cfac124650e6 [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,
65 draggable : false
66 };
67 map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
68
69 var input = document.getElementById('location-text-box');
70 var autocomplete = new google.maps.places.Autocomplete(input);
71 autocomplete.bindTo('bounds', map);
72
73 google.maps.event.addListener(autocomplete, 'place_changed', function() {
74 var place = autocomplete.getPlace();
75 if (place.geometry.viewport) {
76 map.fitBounds(place.geometry.viewport);
77 } else {
78 map.setCenter(place.geometry.location);
79 map.setZoom(17); // Why 17? Because it looks good.
80 }
81 var address = '';
82 if (place.address_components) {
83 address = [(place.address_components[0] && place.address_components[0].short_name || ''),
84 (place.address_components[1] && place.address_components[1].short_name || ''),
85 (place.address_components[2] && place.address_components[2].short_name || '') ].join(' ');
86 }
87 });
88
89 // UI Elements - Selection Rectangle Drawing
90 shouldDraw = false;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070091 selectionRect = null;
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -070092 var startLatLng;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -070093 var selectionRadio = $("#selection-button");
94 var firstClick = true;
95
96 google.maps.event.addListener(map, 'mousedown', function (event) {
97 // only allow drawing if selection is selected
98 if (selectionRadio.hasClass("active")) {
99 startLatLng = event.latLng;
100 shouldDraw = true;
101 }
102 });
103
104 google.maps.event.addListener(map, 'mousemove', drawRect);
105 function drawRect (event) {
106 if (shouldDraw) {
107 if (!selectionRect) {
108 var selectionRectOpts = {
109 bounds: new google.maps.LatLngBounds(startLatLng, event.latLng),
110 map: map,
111 strokeWeight: 1,
112 strokeColor: "2b3f8c",
113 fillColor: "2b3f8c"
114 };
115 selectionRect = new google.maps.Rectangle(selectionRectOpts);
116 google.maps.event.addListener(selectionRect, 'mouseup', function () {
117 shouldDraw = false;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700118 });
119 } else {
genia.likes.science@gmail.com4ada78c2013-09-07 13:53:48 -0700120
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700121 if (startLatLng.lng() < event.latLng.lng()) {
122 selectionRect.setBounds(new google.maps.LatLngBounds(startLatLng, event.latLng));
123 } else {
124 selectionRect.setBounds(new google.maps.LatLngBounds(event.latLng, startLatLng));
125 }
126 }
127 }
128 };
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700129
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700130 // Open about tab to start user on a tutorial
131 //$('#mode-tabs a:first').tab('show') // Select first tab
132
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700133 // Initialize data structures
134 APIqueryTracker = {};
135 asyncQueryManager = {};
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700136 map_cells = [];
137 map_tweet_markers = [];
138 map_info_windows = {};
139 review_mode_tweetbooks = [];
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700140
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700141 getAllDataverseTweetbooks();
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700142 initDemoUIButtonControls();
143});
144
145function initDemoUIButtonControls() {
146
147 // Explore Mode - Update Sliders
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700148 var updateSliderDisplay = function(event, ui) {
149 if (event.target.id == "grid-lat-slider") {
150 $("#gridlat").text(""+ui.value);
151 } else {
152 $("#gridlng").text(""+ui.value);
153 }
154 };
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700155 sliderOptions = {
156 max: 10,
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700157 min: 2.0,
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700158 step: .1,
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700159 value: 3.0,
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700160 slidechange: updateSliderDisplay,
161 slide: updateSliderDisplay,
162 start: updateSliderDisplay,
163 stop: updateSliderDisplay
164 };
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700165 $("#gridlat").text(""+sliderOptions.value);
166 $("#gridlng").text(""+sliderOptions.value);
167 $(".grid-slider").slider(sliderOptions);
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700168
169 // Explore Mode - Query Builder Date Pickers
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700170 var dateOptions = {
171 dateFormat: "yy-mm-dd",
172 defaultDate: "2012-01-02",
173 navigationAsDateFormat: true,
174 constrainInput: true
175 };
176 var start_dp = $("#start-date").datepicker(dateOptions);
177 start_dp.val(dateOptions.defaultDate);
178 dateOptions['defaultDate'] = "2012-12-31";
179 var end_dp= $("#end-date").datepicker(dateOptions);
180 end_dp.val(dateOptions.defaultDate);
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700181
182 // Explore Mode: Toggle Selection/Location Search
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700183 $('#selection-button').on('click', function (e) {
184 $("#location-text-box").attr("disabled", "disabled");
185 if (selectionRect) {
186 selectionRect.setMap(map);
187 }
188 });
189 $('#location-button').on('click', function (e) {
190 $("#location-text-box").removeAttr("disabled");
191 if (selectionRect) {
192 selectionRect.setMap(null);
193 }
194 });
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700195 $("#selection-button").trigger("click");
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700196
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700197 // Review Mode: New Tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700198 $('#new-tweetbook-button').on('click', function (e) {
199 onCreateNewTweetBook($('#new-tweetbook-entry').val());
200
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700201 $('#new-tweetbook-entry').val("");
202 $('#new-tweetbook-entry').attr("placeholder", "Name a new tweetbook");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700203 });
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700204
205 // Explore Mode - Clear Button
206 $("#clear-button").click(mapWidgetResetMap);
207
208 // Explore Mode: Query Submission
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700209 $("#submit-button").on("click", function () {
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700210
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700211 $("#report-message").html('');
212 $("#submit-button").attr("disabled", true);
213
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700214 var kwterm = $("#keyword-textbox").val();
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700215 var startdp = $("#start-date").datepicker("getDate");
216 var enddp = $("#end-date").datepicker("getDate");
217 var startdt = $.datepicker.formatDate("yy-mm-dd", startdp)+"T00:00:00Z";
218 var enddt = $.datepicker.formatDate("yy-mm-dd", enddp)+"T23:59:59Z";
219
220 var formData = {
221 "keyword": kwterm,
222 "startdt": startdt,
223 "enddt": enddt,
224 "gridlat": $("#grid-lat-slider").slider("value"),
225 "gridlng": $("#grid-lng-slider").slider("value")
226 };
227
228 // Get Map Bounds
229 var bounds;
230 if ($('#selection-button').hasClass("active") && selectionRect) {
231 bounds = selectionRect.getBounds();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700232 } else {
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700233 bounds = map.getBounds();
234 }
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700235
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700236 var swLat = Math.abs(bounds.getSouthWest().lat());
237 var swLng = Math.abs(bounds.getSouthWest().lng());
238 var neLat = Math.abs(bounds.getNorthEast().lat());
239 var neLng = Math.abs(bounds.getNorthEast().lng());
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700240
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700241 formData["swLat"] = Math.min(swLat, neLat);
242 formData["swLng"] = Math.max(swLng, neLng);
243 formData["neLat"] = Math.max(swLat, neLat);
244 formData["neLng"] = Math.min(swLng, neLng);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700245
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700246 var build_cherry_mode = "synchronous";
247 if ($('#asbox').is(":checked")) {
248 build_cherry_mode = "asynchronous";
249 //$('#show-query-button').attr("disabled", false);
250 } else {
251 //$('#show-query-button').attr("disabled", true);
252 }
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700253
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700254 var f = buildAQLQueryFromForm(formData);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700255
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700256 APIqueryTracker = {
257 "query" : "use dataverse twitter;\n" + f.val(),
258 "data" : formData
259 };
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700260
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700261 // TODO Make dialog work correctly.
262 //$('#dialog').html(APIqueryTracker["query"]);
genia.likes.science@gmail.com233fe972013-09-07 13:57:46 -0700263
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700264 if (build_cherry_mode == "synchronous") {
265 A.query(f.val(), cherryQuerySyncCallback, build_cherry_mode);
266 } else {
267 A.query(f.val(), cherryQueryAsyncCallback, build_cherry_mode);
268 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700269
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700270 // Clears selection rectangle on query execution, rather than waiting for another clear call.
271 if (selectionRect) {
272 selectionRect.setMap(null);
273 selectionRect = null;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700274 }
275 });
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700276}
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700277
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700278/**
279* Builds AsterixDB REST Query from explore mode form.
280*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700281function buildAQLQueryFromForm(parameters) {
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700282
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700283 var bounds = {
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700284 "ne" : { "lat" : parameters["neLat"], "lng" : -1*parameters["neLng"]},
285 "sw" : { "lat" : parameters["swLat"], "lng" : -1*parameters["swLng"]}
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700286 };
287
288 var rectangle =
289 new FunctionExpression("create-rectangle",
290 new FunctionExpression("create-point", bounds["sw"]["lat"], bounds["sw"]["lng"]),
291 new FunctionExpression("create-point", bounds["ne"]["lat"], bounds["ne"]["lng"]));
292
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700293 // You can chain these all together, but let's take them one at a time.
294 // Let's start with a ForClause. Here we go through each tweet $t in the
295 // dataset TweetMessageShifted.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700296 var aql = new FLWOGRExpression()
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700297 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"));
298
299 // We know we have bounds for our region, so we can add that LetClause next.
300 aql = aql.LetClause("$region", rectangle);
301
302 // Now, let's change it up. The keyword term doesn't always show up, so it might be blank.
303 // We'll attach a new let clause for it, and then a WhereClause.
304 if (parameters["keyword"].length > 0) {
305 aql = aql
306 .LetClause("$keyword", new AExpression('"' + parameters["keyword"] + '"'))
307 .WhereClause().and(
308 new FunctionExpression("spatial-intersect", "$t.sender-location", "$region"),
309 new AExpression('$t.send-time > datetime("' + parameters["startdt"] + '")'),
310 new AExpression('$t.send-time < datetime("' + parameters["enddt"] + '")'),
311 new FunctionExpression("contains", "$t.message-text", "$keyword")
312 );
313 } else {
314 aql = aql
315 .WhereClause().and(
316 new FunctionExpression("spatial-intersect", "$t.sender-location", "$region"),
317 new AExpression('$t.send-time > datetime("' + parameters["startdt"] + '")'),
318 new AExpression('$t.send-time < datetime("' + parameters["enddt"] + '")')
319 );
320 }
321
322 // Finally, we'll group our results into spatial cells.
323 aql = aql.GroupClause(
324 "$c",
325 new FunctionExpression("spatial-cell", "$t.sender-location",
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700326 new FunctionExpression("create-point", "24.5", "-125.5"),
327 parameters["gridlat"].toFixed(1), parameters["gridlng"].toFixed(1)),
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700328 "with",
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700329 "$t"
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700330 );
331
332 // ...and return a resulting cell and a count of results in that cell.
333 aql = aql.ReturnClause({ "cell" : "$c", "count" : "count($t)" });
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700334
335 return aql;
336}
337
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700338/**
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700339* getAllDataverseTweetbooks
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700340*
341* Returns all datasets of type TweetbookEntry, populates review_mode_tweetbooks
342*/
343function getAllDataverseTweetbooks(fn_tweetbooks) {
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700344
345 // This creates a query to the Metadata for datasets of type
346 // TweetBookEntry. Note that if we throw in a WhereClause (commented out below)
347 // there is an odd error. This is being fixed and will be removed from this demo.
348 var getTweetbooksQuery = new FLWOGRExpression()
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700349 .ForClause("$ds", new AExpression("dataset Metadata.Dataset"))
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700350 //.WhereClause(new AExpression('$ds.DataTypeName = "TweetbookEntry"'))
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700351 .ReturnClause({
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700352 "DataTypeName" : "$ds.DataTypeName",
353 "DatasetName" : "$ds.DatasetName"
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700354 });
355
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700356 // Now create a function that will be called when tweetbooks succeed.
357 // In this case, we want to parse out the results object from the Asterix
358 // REST API response.
359 var tweetbooksSuccess = function(r) {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700360 // Parse tweetbook metadata results
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700361 $.each(r.results, function(i, data) {
362 if ($.parseJSON(data)["DataTypeName"] == "TweetbookEntry") {
363 review_mode_tweetbooks.push($.parseJSON(data)["DatasetName"]);
364 }
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700365 });
366
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700367 // Now, if any tweetbooks already exist, opulate review screen.
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700368 $('#review-tweetbook-titles').html('');
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700369 $.each(review_mode_tweetbooks, function(i, tweetbook) {
370 addTweetBookDropdownItem(tweetbook);
371 });
372 };
373
374 // Now, we are ready to run a query.
375 A.meta(getTweetbooksQuery.val(), tweetbooksSuccess);
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700376}
377
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700378/**
379* Checks through each asynchronous query to see if they are ready yet
380*/
381function asynchronousQueryIntervalUpdate() {
382 for (var handle_key in asyncQueryManager) {
383 if (!asyncQueryManager[handle_key].hasOwnProperty("ready")) {
384 asynchronousQueryGetAPIQueryStatus( asyncQueryManager[handle_key]["handle"], handle_key );
385 }
386 }
387}
388
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700389/**
390* Returns current time interval to check for asynchronous query readiness
391* @returns {number} milliseconds between asychronous query checks
392*/
393function asynchronousQueryGetInterval() {
394 var seconds = 10;
395 return seconds * 1000;
396}
397
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700398/**
399* Retrieves status of an asynchronous query, using an opaque result handle from API
400* @param {Object} handle, an object previously returned from an async call
401* @param {number} handle_id, the integer ID parsed from the handle object
402*/
403function asynchronousQueryGetAPIQueryStatus (handle, handle_id) {
404
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700405 A.query_status(
406 {
407 "handle" : JSON.stringify(handle)
408 },
409 function (res) {
410 if (res["status"] == "SUCCESS") {
411 // We don't need to check if this one is ready again, it's not going anywhere...
412 // Unless the life cycle of handles has changed drastically
413 asyncQueryManager[handle_id]["ready"] = true;
414
415 // Indicate success.
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700416 $('#handle_' + handle_id).removeClass("btn-disabled").prop('disabled', false).addClass("btn-success");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700417 }
418 }
419 );
420}
421
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700422/**
423* On-success callback after async API query
424* @param {object} res, a result object containing an opaque result handle to Asterix
425*/
426function cherryQueryAsyncCallback(res) {
427
428 // Parse handle, handle id and query from async call result
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700429 var handle_query = APIqueryTracker["query"];
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700430 var handle = res;
431 var handle_id = res["handle"].toString().split(',')[0];
432
433 // Add to stored map of existing handles
434 asyncQueryManager[handle_id] = {
435 "handle" : handle,
436 "query" : handle_query,
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700437 "data" : APIqueryTracker["data"]
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700438 };
439
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700440 // Create a container for this async query handle
441 $('<div/>')
442 .css("margin-left", "1em")
443 .css("margin-bottom", "1em")
444 .css("display", "block")
445 .attr({
446 "class" : "btn-group",
447 "id" : "async_container_" + handle_id
448 })
449 .appendTo("#async-handle-controls");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700450
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700451 // Adds the main button for this async handle
452 var handle_action_button = '<button class="btn btn-disabled" id="handle_' + handle_id + '">Handle ' + handle_id + '</button>';
453 $('#async_container_' + handle_id).append(handle_action_button);
454 $('#handle_' + handle_id).prop('disabled', true);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700455 $('#handle_' + handle_id).on('click', function (e) {
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700456
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700457 // make sure query is ready to be run
458 if (asyncQueryManager[handle_id]["ready"]) {
459
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700460 APIqueryTracker = {
461 "query" : asyncQueryManager[handle_id]["query"],
462 "data" : asyncQueryManager[handle_id]["data"]
463 };
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700464 // TODO
465 //$('#dialog').html(APIqueryTracker["query"]);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700466
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -0700467 if (!asyncQueryManager[handle_id].hasOwnProperty("result")) {
468 // Generate new Asterix Core API Query
469 A.query_result(
470 { "handle" : JSON.stringify(asyncQueryManager[handle_id]["handle"]) },
471 function(res) {
472 asyncQueryManager[handle_id]["result"] = res;
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700473
474 var resultTransform = {
475 "results" : res.results[0]
476 };
477
478 cherryQuerySyncCallback(resultTransform);
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -0700479 }
480 );
481 } else {
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700482
483 var resultTransform = {
484 "results" : asyncQueryManager[handle_id]["result"].results[0]
485 };
486
487 cherryQuerySyncCallback(resultTransform);
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -0700488 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700489 }
490 });
genia.likes.science@gmail.com4259a542013-08-18 20:06:58 -0700491
492 // Adds a removal button for this async handle
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700493 var asyncDeleteButton = addDeleteButton(
494 "trashhandle_" + handle_id,
495 "async_container_" + handle_id,
496 function (e) {
497 $('#async_container_' + handle_id).remove();
498 delete asyncQueryManager[handle_id];
499 }
500 );
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700501
502 $('#async_container_' + handle_id).append('<br/>');
503
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700504 $("#submit-button").attr("disabled", false);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700505}
506
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700507/**
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700508* A spatial data cleaning and mapping call
509* @param {Object} res, a result object from a cherry geospatial query
510*/
511function cherryQuerySyncCallback(res) {
genia.likes.science@gmail.comd42b4022013-08-09 05:05:23 -0700512
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700513 // Initialize coordinates and weights, to store
514 // coordinates of map cells and their weights
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700515 var coordinates = [];
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 Gabrielovaf9fcd712013-10-20 02:37:35 -0700518
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700519 // Parse resulting JSON objects. Here is an example record:
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700520 // { "cell": rectangle("21.5,-98.5 24.5,-95.5"), "count": 78i64 }
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700521 $.each(res.results, function(i, data) {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700522
523 // We need to clean the JSON a bit to parse it properly in javascript
524 var cleanRecord = $.parseJSON(data
525 .replace('rectangle(', '')
526 .replace(')', '')
527 .replace('i64', ''));
528
529 var recordCount = cleanRecord["count"];
530 var rectangle = cleanRecord["cell"]
531 .replace(' ', ',')
532 .split(',')
533 .map( parseFloat );
534
535 // Now, using the record count and coordinates, we can create a
536 // coordinate system for this spatial cell.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700537 var coordinate = {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700538 "latSW" : rectangle[0],
539 "lngSW" : rectangle[1],
540 "latNE" : rectangle[2],
541 "lngNE" : rectangle[3],
542 "weight" : recordCount
543 };
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700544
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700545 // We track the minimum and maximum weight to support our legend.
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700546 maxWeight = Math.max(coordinate["weight"], maxWeight);
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700547 minWeight = Math.min(coordinate["weight"], minWeight);
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700548
549 // Save completed coordinate and move to next one.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700550 coordinates.push(coordinate);
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700551 });
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700552
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700553 triggerUIUpdate(coordinates, maxWeight, minWeight);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700554}
555
556/**
557* Triggers a map update based on a set of spatial query result cells
558* @param [Array] mapPlotData, an array of coordinate and weight objects
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700559* @param [Array] plotWeights, a list of weights of the spatial cells - e.g., number of tweets
560*/
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700561function triggerUIUpdate(mapPlotData, maxWeight, minWeight) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700562 /** Clear anything currently on the map **/
563 mapWidgetClearMap();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700564
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700565 // Initialize info windows.
genia.likes.science@gmail.com65e04182013-10-04 04:31:41 -0700566 map_info_windows = {};
567
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700568 $.each(mapPlotData, function (m) {
569
570 var point_center = new google.maps.LatLng(
571 (mapPlotData[m].latSW + mapPlotData[m].latNE)/2.0,
572 (mapPlotData[m].lngSW + mapPlotData[m].lngNE)/2.0);
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700573
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700574 var map_circle_options = {
575 center: point_center,
576 anchorPoint: point_center,
577 radius: mapWidgetComputeCircleRadius(mapPlotData[m], maxWeight),
578 map: map,
579 fillOpacity: 0.85,
580 fillColor: rainbow.colourAt(Math.ceil(100 * (mapPlotData[m].weight / maxWeight))),
581 clickable: true
582 };
583 var map_circle = new google.maps.Circle(map_circle_options);
584 map_circle.val = mapPlotData[m];
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700585
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700586 map_info_windows[m] = new google.maps.InfoWindow({
587 content: mapPlotData[m].weight + " tweets",
588 position: point_center
589 });
590
591 // Clicking on a circle drills down map to that value, hovering over it displays a count
592 // of tweets at that location.
593 google.maps.event.addListener(map_circle, 'click', function (event) {
594 $.each(map_info_windows, function(i) {
595 map_info_windows[i].close();
genia.likes.science@gmail.comec46c772013-09-07 18:13:00 -0700596 });
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700597 onMapPointDrillDown(map_circle.val);
598 });
genia.likes.science@gmail.comec46c772013-09-07 18:13:00 -0700599
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700600 google.maps.event.addListener(map_circle, 'mouseover', function(event) {
601 if (!map_info_windows[m].getMap()) {
602 map_info_windows[m].setPosition(map_circle.center);
603 map_info_windows[m].open(map);
604 }
605 });
606
607 // Add this marker to global marker cells
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700608 map_cells.push(map_circle);
609
610 // Show legend
611 $("#legend-min").html(minWeight);
612 $("#legend-max").html(maxWeight);
613 $("#rainbow-legend-container").show();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700614 });
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700615}
616
617/**
618* prepares an Asterix API query to drill down in a rectangular spatial zone
619*
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700620* @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 -0700621*/
622function onMapPointDrillDown(marker_borders) {
623 var zoneData = APIqueryTracker["data"];
624
625 var zswBounds = new google.maps.LatLng(marker_borders.latSW, marker_borders.lngSW);
626 var zneBounds = new google.maps.LatLng(marker_borders.latNE, marker_borders.lngNE);
627
628 var zoneBounds = new google.maps.LatLngBounds(zswBounds, zneBounds);
629 zoneData["swLat"] = zoneBounds.getSouthWest().lat();
630 zoneData["swLng"] = zoneBounds.getSouthWest().lng();
631 zoneData["neLat"] = zoneBounds.getNorthEast().lat();
632 zoneData["neLng"] = zoneBounds.getNorthEast().lng();
633 var zB = {
634 "sw" : {
635 "lat" : zoneBounds.getSouthWest().lat(),
636 "lng" : zoneBounds.getSouthWest().lng()
637 },
638 "ne" : {
639 "lat" : zoneBounds.getNorthEast().lat(),
640 "lng" : zoneBounds.getNorthEast().lng()
641 }
642 };
643
644 mapWidgetClearMap();
645
646 var customBounds = new google.maps.LatLngBounds();
647 var zoomSWBounds = new google.maps.LatLng(zoneData["swLat"], zoneData["swLng"]);
648 var zoomNEBounds = new google.maps.LatLng(zoneData["neLat"], zoneData["neLng"]);
649 customBounds.extend(zoomSWBounds);
650 customBounds.extend(zoomNEBounds);
651 map.fitBounds(customBounds);
652
653 var df = getDrillDownQuery(zoneData, zB);
654
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700655 APIqueryTracker = {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700656 "query_string" : "use dataverse twitter;\n" + df.val(),
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700657 "marker_path" : "static/img/mobile2.png"
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700658 };
659
660 A.query(df.val(), onTweetbookQuerySuccessPlot);
661}
662
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700663/**
664* Generates an aql query for zooming on a spatial cell and obtaining tweets contained therein.
665* @param parameters, the original query parameters
666* @param bounds, the bounds of the zone to zoom in on.
667*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700668function getDrillDownQuery(parameters, bounds) {
669
670 var zoomRectangle = new FunctionExpression("create-rectangle",
671 new FunctionExpression("create-point", bounds["sw"]["lat"], bounds["sw"]["lng"]),
672 new FunctionExpression("create-point", bounds["ne"]["lat"], bounds["ne"]["lng"]));
673
674 var drillDown = new FLWOGRExpression()
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700675 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700676 .LetClause("$region", zoomRectangle);
677
678 if (parameters["keyword"].length == 0) {
679 drillDown = drillDown
680 .WhereClause().and(
681 new FunctionExpression('spatial-intersect', '$t.sender-location', '$region'),
682 new AExpression().set('$t.send-time > datetime("' + parameters["startdt"] + '")'),
683 new AExpression().set('$t.send-time < datetime("' + parameters["enddt"] + '")')
684 );
685 } else {
686 drillDown = drillDown
687 .LetClause("$keyword", new AExpression('"' + parameters["keyword"] + '"'))
688 .WhereClause().and(
689 new FunctionExpression('spatial-intersect', '$t.sender-location', '$region'),
690 new AExpression().set('$t.send-time > datetime("' + parameters["startdt"] + '")'),
691 new AExpression().set('$t.send-time < datetime("' + parameters["enddt"] + '")'),
692 new FunctionExpression('contains', '$t.message-text', '$keyword')
693 );
694 }
695
696 drillDown = drillDown
697 .ReturnClause({
698 "tweetId" : "$t.tweetid",
699 "tweetText" : "$t.message-text",
700 "tweetLoc" : "$t.sender-location"
701 });
702
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700703 return drillDown;
704}
705
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700706/**
707* Given a location where a tweet exists, opens a modal to examine or update a tweet's content.
708* @param t0, a tweetobject that has a location, text, id, and optionally a comment.
709*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700710function onDrillDownAtLocation(tO) {
711
712 var tweetId = tO["tweetEntryId"];
713 var tweetText = tO["tweetText"];
714
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700715 // First, set tweet in drilldown modal to be this tweet's text
716 $('#modal-body-tweet').html('Tweet #' + tweetId + ": " + tweetText);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700717
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700718 // Next, empty any leftover tweetbook comments or error/success messages
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700719 $("#modal-body-add-to").val('');
720 $("#modal-body-add-note").val('');
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700721 $("#modal-body-message-holder").html("");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700722
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700723 // Next, if there is an existing tweetcomment reported, show it.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700724 if (tO.hasOwnProperty("tweetComment")) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700725
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").show();
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700728 $("#modal-save-tweet-panel").hide();
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700729
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700730 // Fill in existing tweet comment
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700731 $("#modal-body-tweet-note").val(tO["tweetComment"]);
732
733 // Change Tweetbook Badge
734 $("#modal-current-tweetbook").val(APIqueryTracker["active_tweetbook"]);
735
736 // Add deletion functionality
737 $("#modal-body-trash-icon").on('click', function () {
738 // Send comment deletion to asterix
739 var deleteTweetCommentOnId = '"' + tweetId + '"';
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700740 var toDelete = new DeleteStatement(
741 "$mt",
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700742 APIqueryTracker["active_tweetbook"],
743 new AExpression("$mt.tweetid = " + deleteTweetCommentOnId.toString())
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700744 );
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700745 A.update(
746 toDelete.val()
747 );
748
749 // Hide comment from map
750 $('#drilldown_modal').modal('hide');
751
752 // Replot tweetbook
753 onPlotTweetbook(APIqueryTracker["active_tweetbook"]);
754 });
755
756 } else {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700757 // Show correct panel
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700758 $("#modal-existing-note").hide();
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700759 $("#modal-save-tweet-panel").show();
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700760
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700761 // Now, when adding a comment on an available tweet to a tweetbook
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700762 $('#save-comment-tweetbook-modal').unbind('click');
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700763 $("#save-comment-tweetbook-modal").on('click', function(e) {
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700764
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700765 // Stuff to save about new comment
766 var save_metacomment_target_tweetbook = $("#modal-body-add-to").val();
767 var save_metacomment_target_comment = '"' + $("#modal-body-add-note").val() + '"';
768 var save_metacomment_target_tweet = '"' + tweetId + '"';
769
770 // Make sure content is entered, and then save this comment.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700771 if ($("#modal-body-add-note").val() == "") {
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700772
773 reportUserMessage("Please enter a comment about the tweet", false, "report-message");
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700774
775 } else if ($("#modal-body-add-to").val() == "") {
776
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700777 reportUserMessage("Please enter a tweetbook.", false, "report-message");
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700778
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700779 } else {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700780
781 // Check if tweetbook exists. If not, create it.
782 if (!(existsTweetbook(save_metacomment_target_tweetbook))) {
783 onCreateNewTweetBook(save_metacomment_target_tweetbook);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700784 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700785
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700786 var toInsert = new InsertStatement(
787 save_metacomment_target_tweetbook,
788 {
789 "tweetid" : save_metacomment_target_tweet.toString(),
790 "comment-text" : save_metacomment_target_comment
791 }
792 );
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700793
794 A.update(toInsert.val(), function () {
795 var successMessage = "Saved comment on <b>Tweet #" + tweetId +
796 "</b> in dataset <b>" + save_metacomment_target_tweetbook + "</b>.";
797 reportUserMessage(successMessage, true, "report-message");
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700798
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700799 $("#modal-body-add-to").val('');
800 $("#modal-body-add-note").val('');
801 $('#save-comment-tweetbook-modal').unbind('click');
802
803 // Close modal
804 $('#drilldown_modal').modal('hide');
805 });
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700806 }
807 });
808 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700809}
810
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700811/**
812* Adds a new tweetbook entry to the menu and creates a dataset of type TweetbookEntry.
813*/
814function onCreateNewTweetBook(tweetbook_title) {
815
816 var tweetbook_title = tweetbook_title.split(' ').join('_');
817
818 A.ddl(
819 "create dataset " + tweetbook_title + "(TweetbookEntry) primary key tweetid;",
820 function () {}
821 );
822
823 if (!(existsTweetbook(tweetbook_title))) {
824 review_mode_tweetbooks.push(tweetbook_title);
825 addTweetBookDropdownItem(tweetbook_title);
826 }
827}
828
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700829/**
830* Removes a tweetbook from both demo and from
831* dataverse metadata.
832*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700833function onDropTweetBook(tweetbook_title) {
834
835 // AQL Call
836 A.ddl(
837 "drop dataset " + tweetbook_title + " if exists;",
838 function () {}
839 );
840
841 // Removes tweetbook from review_mode_tweetbooks
842 var remove_position = $.inArray(tweetbook_title, review_mode_tweetbooks);
843 if (remove_position >= 0) review_mode_tweetbooks.splice(remove_position, 1);
844
845 // Clear UI with review tweetbook titles
846 $('#review-tweetbook-titles').html('');
847 for (r in review_mode_tweetbooks) {
848 addTweetBookDropdownItem(review_mode_tweetbooks[r]);
849 }
850}
851
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700852/**
853* Adds a tweetbook action button to the dropdown box in review mode.
854* @param tweetbook, a string representing a tweetbook
855*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700856function addTweetBookDropdownItem(tweetbook) {
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700857 // Add placeholder for this tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700858 $('<div/>')
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700859 .attr({
860 "class" : "btn-group",
861 "id" : "rm_holder_" + tweetbook
862 }).appendTo("#review-tweetbook-titles");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700863
864 // Add plotting button for this tweetbook
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700865 var plot_button = '<button class="btn btn-default" id="rm_plotbook_' + tweetbook + '">' + tweetbook + '</button>';
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700866 $("#rm_holder_" + tweetbook).append(plot_button);
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700867 $("#rm_plotbook_" + tweetbook).width("200px");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700868 $("#rm_plotbook_" + tweetbook).on('click', function(e) {
869 onPlotTweetbook(tweetbook);
870 });
871
872 // Add trash button for this tweetbook
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700873 var onTrashTweetbookButton = addDeleteButton(
874 "rm_trashbook_" + tweetbook,
875 "rm_holder_" + tweetbook,
876 function(e) {
877 onDropTweetBook(tweetbook);
878 }
879 );
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700880}
881
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700882/**
883* Generates AsterixDB query to plot existing tweetbook commnets
884* @param tweetbook, a string representing a tweetbook
885*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700886function onPlotTweetbook(tweetbook) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700887
888 // Clear map for this one
889 mapWidgetResetMap();
890
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700891 var plotTweetQuery = new FLWOGRExpression()
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700892 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700893 .ForClause("$m", new AExpression("dataset " + tweetbook))
894 .WhereClause(new AExpression("$m.tweetid = $t.tweetid"))
895 .ReturnClause({
896 "tweetId" : "$m.tweetid",
897 "tweetText" : "$t.message-text",
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700898 "tweetCom" : "$m.comment-text",
899 "tweetLoc" : "$t.sender-location"
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700900 });
901
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700902 APIqueryTracker = {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700903 "query_string" : "use dataverse twitter;\n" + plotTweetQuery.val(),
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700904 "marker_path" : "static/img/mobile_green2.png",
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700905 "active_tweetbook" : tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700906 };
907
908 A.query(plotTweetQuery.val(), onTweetbookQuerySuccessPlot);
909}
910
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700911/**
912* Given an output response set of tweet data,
913* prepares markers on map to represent individual tweets.
914* @param res, a JSON Object
915*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700916function onTweetbookQuerySuccessPlot (res) {
917
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700918 // Parse out tweet Ids, texts, and locations
919 var tweets = [];
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700920 var al = 1;
921
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700922 $.each(res.results, function(i, data) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700923
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700924 // First, clean up the data
925 //{ "tweetId": "100293", "tweetText": " like at&t the touch-screen is amazing", "tweetLoc": point("31.59,-84.23") }
926 // We need to turn the point object at the end into a string
927 var json = $.parseJSON(data
928 .replace(': point(',': ')
929 .replace(') }', ' }'));
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700930
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700931 // Now, we construct a tweet object
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700932 var tweetData = {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700933 "tweetEntryId" : parseInt(json.tweetId),
934 "tweetText" : json.tweetText,
935 "tweetLat" : json.tweetLoc.split(",")[0],
936 "tweetLng" : json.tweetLoc.split(",")[1]
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700937 };
938
939 // If we are parsing out tweetbook data with comments, we need to check
940 // for those here as well.
941 if (json.hasOwnProperty("tweetCom")) {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700942 tweetData["tweetComment"] = json.tweetCom;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700943 }
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700944
945 tweets.push(tweetData)
946 });
947
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700948 // Create a marker for each tweet
949 $.each(tweets, function(i, t) {
950 // Create a phone marker at tweet's position
951 var map_tweet_m = new google.maps.Marker({
952 position: new google.maps.LatLng(tweets[i]["tweetLat"], tweets[i]["tweetLng"]),
953 map: map,
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700954 icon: APIqueryTracker["marker_path"],
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700955 clickable: true,
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700956 });
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700957 map_tweet_m["test"] = t;
958
959 // Open Tweet exploration window on click
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700960 google.maps.event.addListener(map_tweet_m, 'click', function (event) {
961 onClickTweetbookMapMarker(map_tweet_markers[i]["test"]);
962 });
963
964 // Add marker to index of tweets
965 map_tweet_markers.push(map_tweet_m);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700966 });
967}
968
Eugenia Gabrielovab2457982013-10-21 14:36:09 -0700969/**
970* Checks if a tweetbook exists
971* @param tweetbook, a String
972*/
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700973function existsTweetbook(tweetbook) {
974 if (parseInt($.inArray(tweetbook, review_mode_tweetbooks)) == -1) {
975 return false;
976 } else {
977 return true;
978 }
979}
980
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700981/**
982* When a marker is clicked on in the tweetbook, it will launch a modal
983* view to examine or edit the appropriate tweet
984*/
985function onClickTweetbookMapMarker(t) {
986 onDrillDownAtLocation(t)
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700987 $('#drilldown_modal').modal();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700988}
989
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700990/**
991* Explore mode: Initial map creation and screen alignment
992*/
993function onOpenExploreMap () {
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700994 var explore_column_height = $('#explore-well').height();
995 var right_column_width = $('#right-col').width();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700996 $('#map_canvas').height(explore_column_height + "px");
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700997 $('#map_canvas').width(right_column_width + "px");
998
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700999 $('#review-well').height(explore_column_height + "px");
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001000 $('#review-well').css('max-height', explore_column_height + "px");
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -07001001 $('#right-col').height(explore_column_height + "px");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001002}
1003
1004/**
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001005* initializes demo - adds some extra events when review/explore
1006* mode are clicked, initializes tabs, aligns map box, moves
1007* active tab to about tab
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001008*/
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001009function initDemoPrepareTabs() {
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -07001010
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001011 // Tab behavior for About, Explore, and Demo
1012 $('#mode-tabs a').click(function (e) {
1013 e.preventDefault()
1014 $(this).tab('show')
1015 })
1016
1017 // Explore mode should show explore-mode query-builder UI
1018 $('#explore-mode').click(function(e) {
1019 $('#review-well').hide();
1020 $('#explore-well').show();
1021 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();
1029 });
1030
1031 // Does some alignment necessary for the map canvas
1032 onOpenExploreMap();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001033}
1034
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001035/**
1036* Creates a delete icon button using default trash icon
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001037* @param {String} id, id for this element
1038* @param {String} attachTo, id string of an element to which I can attach this button.
1039* @param {Function} onClick, a function to fire when this icon is clicked
1040*/
1041function addDeleteButton(iconId, attachTo, onClick) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001042
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001043 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 -07001044 $('#' + attachTo).append(trashIcon);
1045
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001046 // When this trash button is clicked, the function is called.
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001047 $('#' + iconId).on('click', onClick);
1048}
1049
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001050/**
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001051* Creates a message and attaches it to data management area.
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001052* @param {String} message, a message to post
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001053* @param {Boolean} isPositiveMessage, whether or not this is a positive message.
1054* @param {String} target, the target div to attach this message.
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001055*/
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001056function reportUserMessage(message, isPositiveMessage, target) {
1057 // Clear out any existing messages
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001058 $('#' + target).html('');
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001059
1060 // Select appropriate alert-type
1061 var alertType = "alert-success";
1062 if (!isPositiveMessage) {
1063 alertType = "alert-danger";
1064 }
1065
1066 // Append the appropriate message
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001067 $('<div/>')
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001068 .attr("class", "alert " + alertType)
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001069 .html('<button type="button" class="close" data-dismiss="alert">&times;</button>' + message)
1070 .appendTo('#' + target);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001071}
1072
1073/**
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001074* mapWidgetResetMap
1075*
1076* [No Parameters]
1077*
1078* Clears ALL map elements - plotted items, overlays, then resets position
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001079*/
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001080function mapWidgetResetMap() {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001081
1082 if (selectionRect) {
1083 selectionRect.setMap(null);
1084 selectionRect = null;
1085 }
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001086
1087 mapWidgetClearMap();
1088
1089 // Reset map center and zoom
1090 map.setCenter(new google.maps.LatLng(38.89, -77.03));
1091 map.setZoom(4);
1092}
1093
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001094/**
1095* mapWidgetClearMap
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001096* Removes data/markers
1097*/
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001098function mapWidgetClearMap() {
1099
1100 // Remove previously plotted data/markers
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001101 for (c in map_cells) {
1102 map_cells[c].setMap(null);
1103 }
1104 map_cells = [];
genia.likes.science@gmail.com65e04182013-10-04 04:31:41 -07001105
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001106 $.each(map_info_windows, function(i) {
1107 map_info_windows[i].close();
1108 });
1109 map_info_windows = {};
1110
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001111 for (m in map_tweet_markers) {
1112 map_tweet_markers[m].setMap(null);
1113 }
1114 map_tweet_markers = [];
Eugenia Gabrielova12de0302013-10-18 02:25:39 -07001115
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -07001116 $("#rainbow-legend-container").hide();
1117
Eugenia Gabrielova12de0302013-10-18 02:25:39 -07001118 $("#submit-button").attr("disabled", false);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001119}
1120
1121/**
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001122* buildLegend
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001123*
1124* Generates gradient, button action for legend bar
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001125*/
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001126function buildLegend() {
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -07001127
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001128 // Fill in legend area with colors
1129 var gradientColor;
1130
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -07001131 for (i = 0; i<100; i++) {
1132 //$("#rainbow-legend-container").append("" + rainbow.colourAt(i));
1133 $("#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 -07001134 }
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001135
1136 // Window clear button closes all info count windows
1137 $("#windows-off-btn").on("click", function(e) {
1138 $.each(map_info_windows, function(i) {
1139 map_info_windows[i].close();
1140 });
1141 });
1142}
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001143
1144/**
1145* Computes radius for a given data point from a spatial cell
1146* @param {Object} keys => ["latSW" "lngSW" "latNE" "lngNE" "weight"]
1147* @returns {number} radius between 2 points in metres
1148*/
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001149function mapWidgetComputeCircleRadius(spatialCell, wLimit) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001150
1151 // Define Boundary Points
1152 var point_center = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
1153 var point_left = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, spatialCell.lngSW);
1154 var point_top = new google.maps.LatLng(spatialCell.latNE, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
1155
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001156 // Circle scale modifier =
1157 var scale = 500 + 500*(spatialCell.weight / wLimit);
1158
1159 // Return proportionate value so that circles mostly line up.
1160 return scale * Math.min(distanceBetweenPoints_(point_center, point_left), distanceBetweenPoints_(point_center, point_top));
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001161}
1162
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001163/**
1164 * Calculates the distance between two latlng locations in km.
1165 * @see http://www.movable-type.co.uk/scripts/latlong.html
1166 *
1167 * @param {google.maps.LatLng} p1 The first lat lng point.
1168 * @param {google.maps.LatLng} p2 The second lat lng point.
1169 * @return {number} The distance between the two points in km.
1170 * @private
1171*/
1172function distanceBetweenPoints_(p1, p2) {
1173 if (!p1 || !p2) {
1174 return 0;
1175 }
1176
1177 var R = 6371; // Radius of the Earth in km
1178 var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
1179 var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
1180 var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
1181 Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
1182 Math.sin(dLon / 2) * Math.sin(dLon / 2);
1183 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1184 var d = R * c;
1185 return d;
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001186};