blob: b187d383aff56de0f26cde6afb6b40944b3fc3ee [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/**
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700508* cleanJSON
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700509* @param json, a JSON string that is not correctly formatted.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700510* Quick and dirty little function to clean up an Asterix JSON quirk.
511*/
512function cleanJSON(json) {
513 return json
514 .replace("rectangle", '"rectangle"')
515 .replace("point:", '"point":')
516 .replace("point:", '"point":')
517 .replace("int64", '"int64"');
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700518}
519
520/**
521* A spatial data cleaning and mapping call
522* @param {Object} res, a result object from a cherry geospatial query
523*/
524function cherryQuerySyncCallback(res) {
genia.likes.science@gmail.comd42b4022013-08-09 05:05:23 -0700525
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700526 // Initialize coordinates and weights, to store
527 // coordinates of map cells and their weights
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700528 var coordinates = [];
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700529 var maxWeight = 0;
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700530 var minWeight = Number.MAX_VALUE;
Eugenia Gabrielovaf9fcd712013-10-20 02:37:35 -0700531
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700532 // Parse resulting JSON objects. Here is an example record:
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700533 // { "cell": rectangle("21.5,-98.5 24.5,-95.5"), "count": 78i64 }
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700534 $.each(res.results, function(i, data) {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700535
536 // We need to clean the JSON a bit to parse it properly in javascript
537 var cleanRecord = $.parseJSON(data
538 .replace('rectangle(', '')
539 .replace(')', '')
540 .replace('i64', ''));
541
542 var recordCount = cleanRecord["count"];
543 var rectangle = cleanRecord["cell"]
544 .replace(' ', ',')
545 .split(',')
546 .map( parseFloat );
547
548 // Now, using the record count and coordinates, we can create a
549 // coordinate system for this spatial cell.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700550 var coordinate = {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700551 "latSW" : rectangle[0],
552 "lngSW" : rectangle[1],
553 "latNE" : rectangle[2],
554 "lngNE" : rectangle[3],
555 "weight" : recordCount
556 };
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700557
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700558 // We track the minimum and maximum weight to support our legend.
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700559 maxWeight = Math.max(coordinate["weight"], maxWeight);
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700560 minWeight = Math.min(coordinate["weight"], minWeight);
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700561
562 // Save completed coordinate and move to next one.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700563 coordinates.push(coordinate);
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700564 });
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700565
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700566 triggerUIUpdate(coordinates, maxWeight, minWeight);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700567}
568
569/**
570* Triggers a map update based on a set of spatial query result cells
571* @param [Array] mapPlotData, an array of coordinate and weight objects
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700572* @param [Array] plotWeights, a list of weights of the spatial cells - e.g., number of tweets
573*/
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700574function triggerUIUpdate(mapPlotData, maxWeight, minWeight) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700575 /** Clear anything currently on the map **/
576 mapWidgetClearMap();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700577
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700578 // Initialize info windows.
genia.likes.science@gmail.com65e04182013-10-04 04:31:41 -0700579 map_info_windows = {};
580
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700581 $.each(mapPlotData, function (m) {
582
583 var point_center = new google.maps.LatLng(
584 (mapPlotData[m].latSW + mapPlotData[m].latNE)/2.0,
585 (mapPlotData[m].lngSW + mapPlotData[m].lngNE)/2.0);
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700586
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700587 var map_circle_options = {
588 center: point_center,
589 anchorPoint: point_center,
590 radius: mapWidgetComputeCircleRadius(mapPlotData[m], maxWeight),
591 map: map,
592 fillOpacity: 0.85,
593 fillColor: rainbow.colourAt(Math.ceil(100 * (mapPlotData[m].weight / maxWeight))),
594 clickable: true
595 };
596 var map_circle = new google.maps.Circle(map_circle_options);
597 map_circle.val = mapPlotData[m];
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700598
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700599 map_info_windows[m] = new google.maps.InfoWindow({
600 content: mapPlotData[m].weight + " tweets",
601 position: point_center
602 });
603
604 // Clicking on a circle drills down map to that value, hovering over it displays a count
605 // of tweets at that location.
606 google.maps.event.addListener(map_circle, 'click', function (event) {
607 $.each(map_info_windows, function(i) {
608 map_info_windows[i].close();
genia.likes.science@gmail.comec46c772013-09-07 18:13:00 -0700609 });
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700610 onMapPointDrillDown(map_circle.val);
611 });
genia.likes.science@gmail.comec46c772013-09-07 18:13:00 -0700612
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -0700613 google.maps.event.addListener(map_circle, 'mouseover', function(event) {
614 if (!map_info_windows[m].getMap()) {
615 map_info_windows[m].setPosition(map_circle.center);
616 map_info_windows[m].open(map);
617 }
618 });
619
620 // Add this marker to global marker cells
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -0700621 map_cells.push(map_circle);
622
623 // Show legend
624 $("#legend-min").html(minWeight);
625 $("#legend-max").html(maxWeight);
626 $("#rainbow-legend-container").show();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700627 });
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700628}
629
630/**
631* prepares an Asterix API query to drill down in a rectangular spatial zone
632*
633* @params {object} marker_borders [LEGACY] a set of bounds for a region from a previous api result
634*/
635function onMapPointDrillDown(marker_borders) {
636 var zoneData = APIqueryTracker["data"];
637
638 var zswBounds = new google.maps.LatLng(marker_borders.latSW, marker_borders.lngSW);
639 var zneBounds = new google.maps.LatLng(marker_borders.latNE, marker_borders.lngNE);
640
641 var zoneBounds = new google.maps.LatLngBounds(zswBounds, zneBounds);
642 zoneData["swLat"] = zoneBounds.getSouthWest().lat();
643 zoneData["swLng"] = zoneBounds.getSouthWest().lng();
644 zoneData["neLat"] = zoneBounds.getNorthEast().lat();
645 zoneData["neLng"] = zoneBounds.getNorthEast().lng();
646 var zB = {
647 "sw" : {
648 "lat" : zoneBounds.getSouthWest().lat(),
649 "lng" : zoneBounds.getSouthWest().lng()
650 },
651 "ne" : {
652 "lat" : zoneBounds.getNorthEast().lat(),
653 "lng" : zoneBounds.getNorthEast().lng()
654 }
655 };
656
657 mapWidgetClearMap();
658
659 var customBounds = new google.maps.LatLngBounds();
660 var zoomSWBounds = new google.maps.LatLng(zoneData["swLat"], zoneData["swLng"]);
661 var zoomNEBounds = new google.maps.LatLng(zoneData["neLat"], zoneData["neLng"]);
662 customBounds.extend(zoomSWBounds);
663 customBounds.extend(zoomNEBounds);
664 map.fitBounds(customBounds);
665
666 var df = getDrillDownQuery(zoneData, zB);
667
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700668 APIqueryTracker = {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700669 "query_string" : "use dataverse twitter;\n" + df.val(),
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700670 "marker_path" : "static/img/mobile2.png"
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700671 };
672
673 A.query(df.val(), onTweetbookQuerySuccessPlot);
674}
675
676function getDrillDownQuery(parameters, bounds) {
677
678 var zoomRectangle = new FunctionExpression("create-rectangle",
679 new FunctionExpression("create-point", bounds["sw"]["lat"], bounds["sw"]["lng"]),
680 new FunctionExpression("create-point", bounds["ne"]["lat"], bounds["ne"]["lng"]));
681
682 var drillDown = new FLWOGRExpression()
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700683 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700684 .LetClause("$region", zoomRectangle);
685
686 if (parameters["keyword"].length == 0) {
687 drillDown = drillDown
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 );
693 } else {
694 drillDown = drillDown
695 .LetClause("$keyword", new AExpression('"' + parameters["keyword"] + '"'))
696 .WhereClause().and(
697 new FunctionExpression('spatial-intersect', '$t.sender-location', '$region'),
698 new AExpression().set('$t.send-time > datetime("' + parameters["startdt"] + '")'),
699 new AExpression().set('$t.send-time < datetime("' + parameters["enddt"] + '")'),
700 new FunctionExpression('contains', '$t.message-text', '$keyword')
701 );
702 }
703
704 drillDown = drillDown
705 .ReturnClause({
706 "tweetId" : "$t.tweetid",
707 "tweetText" : "$t.message-text",
708 "tweetLoc" : "$t.sender-location"
709 });
710
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700711 return drillDown;
712}
713
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700714function onDrillDownAtLocation(tO) {
715
716 var tweetId = tO["tweetEntryId"];
717 var tweetText = tO["tweetText"];
718
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700719 // First, set tweet in drilldown modal to be this tweet's text
720 $('#modal-body-tweet').html('Tweet #' + tweetId + ": " + tweetText);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700721
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700722 // Next, empty any leftover tweetbook comments or error/success messages
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700723 $("#modal-body-add-to").val('');
724 $("#modal-body-add-note").val('');
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700725 $("#modal-body-message-holder").html("");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700726
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700727 // Next, if there is an existing tweetcomment reported, show it.
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700728 if (tO.hasOwnProperty("tweetComment")) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700729
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700730 // Show correct panel
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700731 $("#modal-existing-note").show();
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700732 $("#modal-save-tweet-panel").hide();
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700733
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700734 // Fill in existing tweet comment
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700735 $("#modal-body-tweet-note").val(tO["tweetComment"]);
736
737 // Change Tweetbook Badge
738 $("#modal-current-tweetbook").val(APIqueryTracker["active_tweetbook"]);
739
740 // Add deletion functionality
741 $("#modal-body-trash-icon").on('click', function () {
742 // Send comment deletion to asterix
743 var deleteTweetCommentOnId = '"' + tweetId + '"';
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700744 var toDelete = new DeleteStatement(
745 "$mt",
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700746 APIqueryTracker["active_tweetbook"],
747 new AExpression("$mt.tweetid = " + deleteTweetCommentOnId.toString())
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700748 );
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700749 A.update(
750 toDelete.val()
751 );
752
753 // Hide comment from map
754 $('#drilldown_modal').modal('hide');
755
756 // Replot tweetbook
757 onPlotTweetbook(APIqueryTracker["active_tweetbook"]);
758 });
759
760 } else {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700761 // Show correct panel
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700762 $("#modal-existing-note").hide();
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700763 $("#modal-save-tweet-panel").show();
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700764
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700765 // Now, when adding a comment on an available tweet to a tweetbook
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700766 $('#save-comment-tweetbook-modal').unbind('click');
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700767 $("#save-comment-tweetbook-modal").on('click', function(e) {
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700768
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700769 // Stuff to save about new comment
770 var save_metacomment_target_tweetbook = $("#modal-body-add-to").val();
771 var save_metacomment_target_comment = '"' + $("#modal-body-add-note").val() + '"';
772 var save_metacomment_target_tweet = '"' + tweetId + '"';
773
774 // Make sure content is entered, and then save this comment.
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700775 if ($("#modal-body-add-note").val() == "") {
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700776
777 reportUserMessage("Please enter a comment about the tweet", false, "report-message");
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700778
779 } else if ($("#modal-body-add-to").val() == "") {
780
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700781 reportUserMessage("Please enter a tweetbook.", false, "report-message");
Eugenia Gabrielova12de0302013-10-18 02:25:39 -0700782
genia.likes.science@gmail.com0f67d9e2013-10-04 17:08:50 -0700783 } else {
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700784
785 // Check if tweetbook exists. If not, create it.
786 if (!(existsTweetbook(save_metacomment_target_tweetbook))) {
787 onCreateNewTweetBook(save_metacomment_target_tweetbook);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700788 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700789
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700790 var toInsert = new InsertStatement(
791 save_metacomment_target_tweetbook,
792 {
793 "tweetid" : save_metacomment_target_tweet.toString(),
794 "comment-text" : save_metacomment_target_comment
795 }
796 );
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700797
798 A.update(toInsert.val(), function () {
799 var successMessage = "Saved comment on <b>Tweet #" + tweetId +
800 "</b> in dataset <b>" + save_metacomment_target_tweetbook + "</b>.";
801 reportUserMessage(successMessage, true, "report-message");
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700802
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -0700803 $("#modal-body-add-to").val('');
804 $("#modal-body-add-note").val('');
805 $('#save-comment-tweetbook-modal').unbind('click');
806
807 // Close modal
808 $('#drilldown_modal').modal('hide');
809 });
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -0700810 }
811 });
812 }
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700813}
814
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700815/**
816* Adds a new tweetbook entry to the menu and creates a dataset of type TweetbookEntry.
817*/
818function onCreateNewTweetBook(tweetbook_title) {
819
820 var tweetbook_title = tweetbook_title.split(' ').join('_');
821
822 A.ddl(
823 "create dataset " + tweetbook_title + "(TweetbookEntry) primary key tweetid;",
824 function () {}
825 );
826
827 if (!(existsTweetbook(tweetbook_title))) {
828 review_mode_tweetbooks.push(tweetbook_title);
829 addTweetBookDropdownItem(tweetbook_title);
830 }
831}
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
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700852function addTweetBookDropdownItem(tweetbook) {
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700853 // Add placeholder for this tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700854 $('<div/>')
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700855 .attr({
856 "class" : "btn-group",
857 "id" : "rm_holder_" + tweetbook
858 }).appendTo("#review-tweetbook-titles");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700859
860 // Add plotting button for this tweetbook
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700861 var plot_button = '<button class="btn btn-default" id="rm_plotbook_' + tweetbook + '">' + tweetbook + '</button>';
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700862 $("#rm_holder_" + tweetbook).append(plot_button);
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700863 $("#rm_plotbook_" + tweetbook).width("200px");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700864 $("#rm_plotbook_" + tweetbook).on('click', function(e) {
865 onPlotTweetbook(tweetbook);
866 });
867
868 // Add trash button for this tweetbook
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700869 var onTrashTweetbookButton = addDeleteButton(
870 "rm_trashbook_" + tweetbook,
871 "rm_holder_" + tweetbook,
872 function(e) {
873 onDropTweetBook(tweetbook);
874 }
875 );
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700876}
877
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700878function onPlotTweetbook(tweetbook) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700879
880 // Clear map for this one
881 mapWidgetResetMap();
882
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700883 var plotTweetQuery = new FLWOGRExpression()
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -0700884 .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700885 .ForClause("$m", new AExpression("dataset " + tweetbook))
886 .WhereClause(new AExpression("$m.tweetid = $t.tweetid"))
887 .ReturnClause({
888 "tweetId" : "$m.tweetid",
889 "tweetText" : "$t.message-text",
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700890 "tweetCom" : "$m.comment-text",
891 "tweetLoc" : "$t.sender-location"
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700892 });
893
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700894 APIqueryTracker = {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700895 "query_string" : "use dataverse twitter;\n" + plotTweetQuery.val(),
genia.likes.science@gmail.com4833b412013-08-09 06:20:58 -0700896 "marker_path" : "static/img/mobile_green2.png",
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -0700897 "active_tweetbook" : tweetbook
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700898 };
899
900 A.query(plotTweetQuery.val(), onTweetbookQuerySuccessPlot);
901}
902
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700903function onTweetbookQuerySuccessPlot (res) {
904
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700905 // Parse out tweet Ids, texts, and locations
906 var tweets = [];
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700907 var al = 1;
908
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700909 $.each(res.results, function(i, data) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700910
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700911 // First, clean up the data
912 //{ "tweetId": "100293", "tweetText": " like at&t the touch-screen is amazing", "tweetLoc": point("31.59,-84.23") }
913 // We need to turn the point object at the end into a string
914 var json = $.parseJSON(data
915 .replace(': point(',': ')
916 .replace(') }', ' }'));
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700917
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700918 // Now, we construct a tweet object
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700919 var tweetData = {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700920 "tweetEntryId" : parseInt(json.tweetId),
921 "tweetText" : json.tweetText,
922 "tweetLat" : json.tweetLoc.split(",")[0],
923 "tweetLng" : json.tweetLoc.split(",")[1]
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700924 };
925
926 // If we are parsing out tweetbook data with comments, we need to check
927 // for those here as well.
928 if (json.hasOwnProperty("tweetCom")) {
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700929 tweetData["tweetComment"] = json.tweetCom;
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700930 }
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700931
932 tweets.push(tweetData)
933 });
934
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700935 // Create a marker for each tweet
936 $.each(tweets, function(i, t) {
937 // Create a phone marker at tweet's position
938 var map_tweet_m = new google.maps.Marker({
939 position: new google.maps.LatLng(tweets[i]["tweetLat"], tweets[i]["tweetLng"]),
940 map: map,
Eugenia Gabrielovacacc9f82013-10-21 14:10:21 -0700941 icon: APIqueryTracker["marker_path"],
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700942 clickable: true,
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700943 });
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700944 map_tweet_m["test"] = t;
945
946 // Open Tweet exploration window on click
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700947 google.maps.event.addListener(map_tweet_m, 'click', function (event) {
948 onClickTweetbookMapMarker(map_tweet_markers[i]["test"]);
949 });
950
951 // Add marker to index of tweets
952 map_tweet_markers.push(map_tweet_m);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700953 });
954}
955
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700956function existsTweetbook(tweetbook) {
957 if (parseInt($.inArray(tweetbook, review_mode_tweetbooks)) == -1) {
958 return false;
959 } else {
960 return true;
961 }
962}
963
Eugenia Gabrielovafcd28682013-10-20 05:36:36 -0700964/**
965* When a marker is clicked on in the tweetbook, it will launch a modal
966* view to examine or edit the appropriate tweet
967*/
968function onClickTweetbookMapMarker(t) {
969 onDrillDownAtLocation(t)
genia.likes.science@gmail.com1400a752013-10-04 04:59:12 -0700970 $('#drilldown_modal').modal();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700971}
972
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700973/**
974* Explore mode: Initial map creation and screen alignment
975*/
976function onOpenExploreMap () {
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700977 var explore_column_height = $('#explore-well').height();
978 var right_column_width = $('#right-col').width();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700979 $('#map_canvas').height(explore_column_height + "px");
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700980 $('#map_canvas').width(right_column_width + "px");
981
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700982 $('#review-well').height(explore_column_height + "px");
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700983 $('#review-well').css('max-height', explore_column_height + "px");
genia.likes.science@gmail.com724476d2013-10-04 03:31:16 -0700984 $('#right-col').height(explore_column_height + "px");
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700985}
986
987/**
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700988* initializes demo - adds some extra events when review/explore
989* mode are clicked, initializes tabs, aligns map box, moves
990* active tab to about tab
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -0700991*/
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700992function initDemoPrepareTabs() {
genia.likes.science@gmail.com2de4c182013-10-04 11:39:11 -0700993
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -0700994 // Tab behavior for About, Explore, and Demo
995 $('#mode-tabs a').click(function (e) {
996 e.preventDefault()
997 $(this).tab('show')
998 })
999
1000 // Explore mode should show explore-mode query-builder UI
1001 $('#explore-mode').click(function(e) {
1002 $('#review-well').hide();
1003 $('#explore-well').show();
1004 mapWidgetResetMap();
1005 });
1006
1007 // Review mode should show review well and hide explore well
1008 $('#review-mode').click(function(e) {
1009 $('#explore-well').hide();
1010 $('#review-well').show();
1011 mapWidgetResetMap();
1012 });
1013
1014 // Does some alignment necessary for the map canvas
1015 onOpenExploreMap();
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001016}
1017
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001018/**
1019* Creates a delete icon button using default trash icon
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001020* @param {String} id, id for this element
1021* @param {String} attachTo, id string of an element to which I can attach this button.
1022* @param {Function} onClick, a function to fire when this icon is clicked
1023*/
1024function addDeleteButton(iconId, attachTo, onClick) {
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001025
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001026 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 -07001027 $('#' + attachTo).append(trashIcon);
1028
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001029 // When this trash button is clicked, the function is called.
genia.likes.science@gmail.com8125bd92013-08-21 18:04:27 -07001030 $('#' + iconId).on('click', onClick);
1031}
1032
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001033/**
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001034* Creates a message and attaches it to data management area.
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001035* @param {String} message, a message to post
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001036* @param {Boolean} isPositiveMessage, whether or not this is a positive message.
1037* @param {String} target, the target div to attach this message.
genia.likes.science@gmail.comdd669072013-08-21 22:53:34 -07001038*/
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001039function reportUserMessage(message, isPositiveMessage, target) {
1040 // Clear out any existing messages
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001041 $('#' + target).html('');
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001042
1043 // Select appropriate alert-type
1044 var alertType = "alert-success";
1045 if (!isPositiveMessage) {
1046 alertType = "alert-danger";
1047 }
1048
1049 // Append the appropriate message
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001050 $('<div/>')
Eugenia Gabrielovadbd50a42013-10-19 00:30:27 -07001051 .attr("class", "alert " + alertType)
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001052 .html('<button type="button" class="close" data-dismiss="alert">&times;</button>' + message)
1053 .appendTo('#' + target);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001054}
1055
1056/**
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001057* mapWidgetResetMap
1058*
1059* [No Parameters]
1060*
1061* Clears ALL map elements - plotted items, overlays, then resets position
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001062*/
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001063function mapWidgetResetMap() {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001064
1065 if (selectionRect) {
1066 selectionRect.setMap(null);
1067 selectionRect = null;
1068 }
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001069
1070 mapWidgetClearMap();
1071
1072 // Reset map center and zoom
1073 map.setCenter(new google.maps.LatLng(38.89, -77.03));
1074 map.setZoom(4);
1075}
1076
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001077/**
1078* mapWidgetClearMap
Eugenia Gabrielovad07556a2013-10-11 03:45:06 -07001079* Removes data/markers
1080*/
genia.likes.science@gmail.com1b30f3d2013-08-17 23:53:37 -07001081function mapWidgetClearMap() {
1082
1083 // Remove previously plotted data/markers
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001084 for (c in map_cells) {
1085 map_cells[c].setMap(null);
1086 }
1087 map_cells = [];
genia.likes.science@gmail.com65e04182013-10-04 04:31:41 -07001088
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001089 $.each(map_info_windows, function(i) {
1090 map_info_windows[i].close();
1091 });
1092 map_info_windows = {};
1093
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001094 for (m in map_tweet_markers) {
1095 map_tweet_markers[m].setMap(null);
1096 }
1097 map_tweet_markers = [];
Eugenia Gabrielova12de0302013-10-18 02:25:39 -07001098
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -07001099 $("#rainbow-legend-container").hide();
1100
Eugenia Gabrielova12de0302013-10-18 02:25:39 -07001101 $("#submit-button").attr("disabled", false);
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001102}
1103
1104/**
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001105* buildLegend
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001106*
1107* Generates gradient, button action for legend bar
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001108*/
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001109function buildLegend() {
genia.likes.science@gmail.com84711b82013-08-22 03:47:41 -07001110
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001111 // Fill in legend area with colors
1112 var gradientColor;
1113
Eugenia Gabrielovad6e88e02013-10-19 08:26:54 -07001114 for (i = 0; i<100; i++) {
1115 //$("#rainbow-legend-container").append("" + rainbow.colourAt(i));
1116 $("#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 -07001117 }
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001118
1119 // Window clear button closes all info count windows
1120 $("#windows-off-btn").on("click", function(e) {
1121 $.each(map_info_windows, function(i) {
1122 map_info_windows[i].close();
1123 });
1124 });
1125}
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001126
1127/**
1128* Computes radius for a given data point from a spatial cell
1129* @param {Object} keys => ["latSW" "lngSW" "latNE" "lngNE" "weight"]
1130* @returns {number} radius between 2 points in metres
1131*/
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001132function mapWidgetComputeCircleRadius(spatialCell, wLimit) {
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001133
1134 // Define Boundary Points
1135 var point_center = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
1136 var point_left = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, spatialCell.lngSW);
1137 var point_top = new google.maps.LatLng(spatialCell.latNE, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
1138
Eugenia Gabrielova8b34c652013-10-19 06:53:27 -07001139 // Circle scale modifier =
1140 var scale = 500 + 500*(spatialCell.weight / wLimit);
1141
1142 // Return proportionate value so that circles mostly line up.
1143 return scale * Math.min(distanceBetweenPoints_(point_center, point_left), distanceBetweenPoints_(point_center, point_top));
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001144}
1145
genia.likes.science@gmail.com6d6aa8e2013-07-23 01:23:21 -07001146/**
1147 * Calculates the distance between two latlng locations in km.
1148 * @see http://www.movable-type.co.uk/scripts/latlong.html
1149 *
1150 * @param {google.maps.LatLng} p1 The first lat lng point.
1151 * @param {google.maps.LatLng} p2 The second lat lng point.
1152 * @return {number} The distance between the two points in km.
1153 * @private
1154*/
1155function distanceBetweenPoints_(p1, p2) {
1156 if (!p1 || !p2) {
1157 return 0;
1158 }
1159
1160 var R = 6371; // Radius of the Earth in km
1161 var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
1162 var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
1163 var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
1164 Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
1165 Math.sin(dLon / 2) * Math.sin(dLon / 2);
1166 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
1167 var d = R * c;
1168 return d;
Eugenia Gabrielovaab1ae552013-10-20 01:12:19 -07001169};