blob: 3eccda99a540b7edaadc618ebf6311b7b6c7acd7 [file] [log] [blame]
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -07001$(function() {
2
genia.likes.science@gmail.com20928902013-05-10 10:39:27 -07003 APIHandler = new AsterixSDK();
4
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -07005 APIqueryTracker = {};
6 drilldown_data_map = {};
7 drilldown_data_map_vals = {};
8 asyncQueryManager = {};
9
10 // Review Mode
11 review_mode_tweetbooks = [];
12 review_mode_handles = [];
13
14 $('#drilldown_modal').modal({ show: false});
15 $('#explore-mode').click( onLaunchExploreMode );
16 $('#review-mode').click( onLaunchReviewMode );
17
18 /** UI **/
19 map_cells = [];
20 map_tweet_markers = [];
21 param_placeholder = {};
22
23 $("#clear-button").button().click(function () {
24 mapWidgetClearMap();
25 param_placeholder = {};
26
27 map.setZoom(4);
28 map.setCenter(new google.maps.LatLng(38.89, -77.03));
29
30 $('#query-preview-window').html('');
31 $("#metatweetzone").html('');
32 });
33
34 $("#selection-button").button('toggle');
35
36 var dialog = $("#dialog").dialog({
37 width: "auto",
38 title: "AQL Query"
39 }).dialog("close");
40 $("#show-query-button")
41 .button()
42 .attr("disabled", true)
43 .click(function (event) {
44 $("#dialog").dialog("open");
45 });
46
47 // setup grid sliders
48 var updateSliderDisplay = function(event, ui) {
49 if (event.target.id == "grid-lat-slider") {
50 $("#gridlat").text(""+ui.value);
51 } else {
52 $("#gridlng").text(""+ui.value);
53 }
54 };
55
56 sliderOptions = {
57 max: 20,
58 min: .1,
59 step: .1,
60 value: 2.0,
61 slidechange: updateSliderDisplay,
62 slide: updateSliderDisplay,
63 start: updateSliderDisplay,
64 stop: updateSliderDisplay
65 };
66
67 $("#gridlat").text(""+sliderOptions.value);
68 $("#gridlng").text(""+sliderOptions.value);
69 $(".grid-slider").slider(sliderOptions);
70
71 // setup datepickers
72 var dateOptions = {
73 dateFormat: "yy-mm-dd",
74 defaultDate: "2012-01-02",
75 navigationAsDateFormat: true,
76 constrainInput: true
77 };
78 var start_dp = $("#start-date").datepicker(dateOptions);
79 start_dp.val(dateOptions.defaultDate);
80 dateOptions['defaultDate'] = "2012-12-31";
81 var end_dp= $("#end-date").datepicker(dateOptions);
82 end_dp.val(dateOptions.defaultDate);
83
84 // This little bit of code manages period checks of the asynchronous query manager,
85 // which holds onto handles asynchornously received. We can set the handle update
86 // frequency using seconds, and it will let us know when it is ready.
87 var intervalID = setInterval(
88 function() {
89 asynchronousQueryIntervalUpdate();
90 },
91 asynchronousQueryGetInterval()
92 );
93
94 // setup map
95 onOpenExploreMap();
96 var mapOptions = {
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -070097 center: new google.maps.LatLng(38.89, 77.03),
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -070098 zoom: 4,
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -070099 mapTypeId: google.maps.MapTypeId.ROADMAP, // SATELLITE
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700100 streetViewControl: false,
101 draggable : false
102 };
103 map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
104
105 // setup location autocomplete
106 var input = document.getElementById('location-text-box');
107 var autocomplete = new google.maps.places.Autocomplete(input);
108 autocomplete.bindTo('bounds', map);
109
110 google.maps.event.addListener(autocomplete, 'place_changed', function() {
111 var place = autocomplete.getPlace();
112 if (place.geometry.viewport) {
113 map.fitBounds(place.geometry.viewport);
114 } else {
115 map.setCenter(place.geometry.location);
116 map.setZoom(17); // Why 17? Because it looks good.
117 }
118 var address = '';
119 if (place.address_components) {
120 address = [(place.address_components[0] && place.address_components[0].short_name || ''),
121 (place.address_components[1] && place.address_components[1].short_name || ''),
122 (place.address_components[2] && place.address_components[2].short_name || '') ].join(' ');
123 }
124 });
125
126 // handle selection rectangle drawing
127 shouldDraw = false;
128 var startLatLng;
129 selectionRect = null;
130 var selectionRadio = $("#selection-button");
131 var firstClick = true;
132
133 google.maps.event.addListener(map, 'mousedown', function (event) {
134 // only allow drawing if selection is selected
135 if (selectionRadio.hasClass("active")) {
136 startLatLng = event.latLng;
137 shouldDraw = true;
138 }
139 });
140
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700141 //triggerUIUpdateOnNewTweetBook({"title" : "Party"});
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700142
143 google.maps.event.addListener(map, 'mousemove', drawRect);
144 function drawRect (event) {
145 if (shouldDraw) {
146 if (!selectionRect) {
147 var selectionRectOpts = {
148 bounds: new google.maps.LatLngBounds(startLatLng, event.latLng),
149 map: map,
150 strokeWeight: 1,
151 strokeColor: "2b3f8c",
152 fillColor: "2b3f8c"
153 };
154 selectionRect = new google.maps.Rectangle(selectionRectOpts);
155 google.maps.event.addListener(selectionRect, 'mouseup', function () {
156 shouldDraw = false;
157 //submitQuery();
158 });
159 } else {
160 if (startLatLng.lng() < event.latLng.lng()) {
161 selectionRect.setBounds(new google.maps.LatLngBounds(startLatLng, event.latLng));
162 } else {
163 selectionRect.setBounds(new google.maps.LatLngBounds(event.latLng, startLatLng));
164 }
165 }
166 }
167 };
168
169 // toggle location search style: by location or by map selection
170 $('#selection-button').on('click', function (e) {
171 $("#location-text-box").attr("disabled", "disabled");
172 if (selectionRect) {
173 selectionRect.setMap(map);
174 }
175 });
176 $('#location-button').on('click', function (e) {
177 $("#location-text-box").removeAttr("disabled");
178 if (selectionRect) {
179 selectionRect.setMap(null);
180 }
181 });
182
183 $('.dropdown-menu a.holdmenu').click(function(e) {
184 e.stopPropagation();
185 });
186
187 $('#new-tweetbook-button').on('click', function (e) {
188 onCreateNewTweetBook($('#new-tweetbook-entry').val());
189
190 $('#new-tweetbook-entry').val($('#new-tweetbook-entry').attr('placeholder'));
191 });
192
193 // handle ajax calls
194 $("#submit-button").button().click(function () {
195 // Clear current map on trigger
196 mapWidgetClearMap();
197
198 // gather all of the data from the inputs
199 var kwterm = $("#keyword-textbox").val();
200 var startdp = $("#start-date").datepicker("getDate");
201 var enddp = $("#end-date").datepicker("getDate");
202 var startdt = $.datepicker.formatDate("yy-mm-dd", startdp)+"T00:00:00Z";
203 var enddt = $.datepicker.formatDate("yy-mm-dd", enddp)+"T23:59:59Z";
204
205 var formData = {
206 "keyword": kwterm,
207 "startdt": startdt,
208 "enddt": enddt,
209 "gridlat": $("#grid-lat-slider").slider("value"),
210 "gridlng": $("#grid-lng-slider").slider("value")
211 };
212
213 // Get Map Bounds
214 var bounds;
215 if ($('#selection-button').hasClass("active") && selectionRect) {
216 bounds = selectionRect.getBounds();
217 } else {
218 bounds = map.getBounds();
219 }
220
221 formData["swLat"] = Math.abs(bounds.getSouthWest().lat());
222 formData["swLng"] = Math.abs(bounds.getSouthWest().lng());
223 formData["neLat"] = Math.abs(bounds.getNorthEast().lat());
224 formData["neLng"] = Math.abs(bounds.getNorthEast().lng());
225
226 var build_cherry_mode = "synchronous";
227 if ($('#asbox').is(":checked")) {
228 build_cherry_mode = "asynchronous";
229 }
230
231 // You don't need to run a query to use the API!
232 // It can also be used to generate queries, which can
233 // then be passed into another API call or stored
234 // for a different application purpose.
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700235 .rectangle({
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700236 "ne" : { "lat" : formData["neLat"], "lng" : formData["neLng"]},
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700237 "sw" : { "lat" : formData["swLat"], "lng" : formData["swLng"]}
genia.likes.science@gmail.comc8e540d2013-05-10 14:02:30 -0700238 })
239
240 var l = new LegacyExpression()
241 .dataverse("twitter")
242 .bind(new ForClause("t", new AsterixClause().set("TweetMessages")))
243 .bind(new LetClause("keyword", new AsterixClause().set('"' + formData["keyword"] + '"')))
244 .bind(new LetClause("region", new ????))// TODO
245 .bind(new WhereClause("where " + [ // TODO
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700246 'spatial-intersect($t.sender-location, $region)',
247 '$t.send-time > datetime("' + formData["startdt"] + '")',
248 '$t.send-time < datetime("' + formData["enddt"] + '")',
249 'contains($t.message-text, $keyword)'
genia.likes.science@gmail.comc8e540d2013-05-10 14:02:30 -0700250 ]).join(" "))
251 .bind(new GroupClause().set("group by $c := spatial-cell($t.sender-location, create-point(24.5,-125.5), " + formData["gridlat"].toFixed(1) + ", " + formData["gridlng"].toFixed(1) + ")")) // TODO
252 .return({ "cell" : "$c", "count" : "count($t)" })
253 .success(cherryQuerySyncCallback, true)
254 .success(cherryQueryAsyncCallback, false)
genia.likes.science@gmail.com7d42df02013-05-10 12:41:11 -0700255 .extra({
256 "payload" : formData,
genia.likes.science@gmail.comc8e540d2013-05-10 14:02:30 -0700257 "query_string" : "use dataverse twitter;\n" //LEGACY + buildCherryQuery.parameters["statements"].join("\n")
genia.likes.science@gmail.com7d42df02013-05-10 12:41:11 -0700258 })
genia.likes.science@gmail.com7d42df02013-05-10 12:41:11 -0700259 .send("http://localhost:19101/query",
genia.likes.science@gmail.com20928902013-05-10 10:39:27 -0700260 {
261 "query" : "use dataverse twitter;\n" + buildCherryQuery.parameters["statements"].join("\n"),
262 "mode" : build_cherry_mode,
263 });
264
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700265 APIqueryTracker = {
genia.likes.science@gmail.comc8e540d2013-05-10 14:02:30 -0700266 "query" : "use dataverse twitter;",// buildCherryQuery.parameters["statements"].join("\n"),
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700267 "data" : formData
268 };
269
270 $('#dialog').html(APIqueryTracker["query"]);//.replace("\n", '<br />'));
271
272 if (!$('#asbox').is(":checked")) {
273 $('#show-query-button').attr("disabled", false);
274 } else {
275 $('#show-query-button').attr("disabled", true);
276 }
277 });
278
279});
280
281/** Asynchronous Query Management - Handles & Such **/
282
283/**
284* Checks through each asynchronous query to see if they are ready yet
285*/
286function asynchronousQueryIntervalUpdate() {
287 for (var handle_key in asyncQueryManager) {
288 if (!asyncQueryManager[handle_key].hasOwnProperty("ready")) {
289 asynchronousQueryGetAPIQueryStatus( asyncQueryManager[handle_key]["handle"], handle_key );
290 }
291 }
292}
293
294/**
295* Returns current time interval to check for asynchronous query readiness
296* @returns {number} milliseconds between asychronous query checks
297*/
298function asynchronousQueryGetInterval() {
299 var seconds = 10;
300 return seconds * 1000;
301}
302
303/**
304* Updates UI when an API Query's status is marked ready
305* @param {Object} res, a result object from the Asterix API
306* @param {object} extra_info, containing the asynchronous handle's id
307*/
308function asynchronousQueryAPIStatusReceived (res, extra_info) {
309 var handle_outcome = $.parseJSON(res[0]);
310 var handle_id = extra_info["handle_id"];
311 if (handle_outcome["status"] == "SUCCESS") {
312
313 // We don't need to check if this one is ready again, it's not going anywhere...
314 // Unless the life cycle of handles has changed drastically
315 asyncQueryManager[handle_id]["ready"] = true;
316
317 // Make this handle's result look retrievable
318 $('#handle_' + handle_id).addClass("label-success");
319 }
320}
321
322/**
323* Retrieves status of an asynchronous query, using an opaque result handle from API
324* @param {Object} handle, an object previously returned from an async call
325* @param {number} handle_id, the integer ID parsed from the handle object
326*/
327function asynchronousQueryGetAPIQueryStatus (handle, handle_id) {
328 var apiQueryStatus = new AsterixCoreAPI()
329 .dataverse("twitter")
330 .handle(handle)
331 .success(asynchronousQueryAPIStatusReceived, true)
332 .add_extra("handle_id", handle_id)
333 .api_core_query_status();
334}
335
336/**
337* On-success callback after async API query
338* @param {object} res, a result object containing an opaque result handle to Asterix
339* @param {object} extra, a result object containing a query string and query parameters
340*/
341function cherryQueryAsyncCallback(res, extra) {
342
343 // Parse handle, handle id and query from async call result
344 var handle = res[0];
345 var handle_query = extra["query_string"];
346 var handle_id = $.parseJSON(handle)["handle"].toString().split(',')[0];
347
348 // Add to stored map of existing handles
349 asyncQueryManager[handle_id] = {
350 "handle" : handle,
351 "query" : handle_query,
352 "data" : extra["payload"]
353 };
354
355 $('#review-handles-dropdown').append('<a href="#" class="holdmenu"><span class="label" id="handle_' + handle_id + '">Handle ' + handle_id + '</span></a>');
356
357 $('#handle_' + handle_id).hover(
358 function(){
359 $('#query-preview-window').html('');
360 $('#query-preview-window').html('<br/><br/>' + asyncQueryManager[handle_id]["query"]);
361 },
362 function() {
363 $('#query-preview-window').html('');
364 }
365 );
366
367 $('#handle_' + handle_id).on('click', function (e) {
368
369 // make sure query is ready to be run
370 if (asyncQueryManager[handle_id]["ready"]) {
371
372 // Update API Query Tracker and view to reflect this query
373 $('#query-preview-window').html('<br/><br/>' + asyncQueryManager[handle_id]["query"]);
374 APIqueryTracker = {
375 "query" : asyncQueryManager[handle_id]["query"],
376 "data" : asyncQueryManager[handle_id]["data"]
377 };
378 $('#dialog').html(APIqueryTracker["query"]);
379
380 // Generate new Asterix Core API Query
381 var asyncResultQuery = new AsterixCoreAPI()
382 .dataverse("twitter")
383 .handle(asyncQueryManager[handle_id]["handle"])
384 .success(cherryQuerySyncCallback, true)
385 .add_extra("payload", asyncQueryManager[handle_id]["data"]) // Legacy
386 .add_extra("query_string", asyncQueryManager[handle_id]["query"]) // Legacy
387 .api_core_query_result();
388 }
389 });
390}
391
392
393/** Core Query Management and Drilldown
394
395/**
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700396* Utility Method for parsing a record of this form:
397* { "cell": rectangle("22.5,64.5 24.5,66.5"), "count": 5 }
398* returns a json object with keys: weight, latSW, lngSW, latNE, lngNE
399*/
400function getRecord(cell_count_record) {
401 var record_representation = {};
402
403 var rectangle = cell_count_record.split('")')[0].split('("')[1];
404 record_representation["latSW"] = parseFloat(rectangle.split(" ")[0].split(',')[0]);
405 record_representation["lngSW"] = parseFloat(rectangle.split(" ")[0].split(',')[1]);
406 record_representation["latNE"] = parseFloat(rectangle.split(" ")[1].split(',')[0]);
407 record_representation["lngNE"] = parseFloat(rectangle.split(" ")[1].split(',')[1]);
408 record_representation["weight"] = parseInt(cell_count_record.split('count": ')[1].split(" ")[0]);
409
410 return record_representation;
411}
412
413/**
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700414* A spatial data cleaning and mapping call
415* @param {Object} res, a result object from a cherry geospatial query
416* @param {Object} extra, extra data passed from the API call - legacy stuff
417*/
418function cherryQuerySyncCallback(res, extra) {
genia.likes.science@gmail.combdfa27a2013-05-08 10:44:34 -0700419 records = res["results"];
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700420
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700421 var coordinates = [];
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700422 var weights = [];
423
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700424 for (var subrecord in records) {
425 for (var record in records[subrecord]) {
426
427 var coordinate = getRecord(records[subrecord][record]);
428 weights.push(coordinate["weight"]);
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700429 coordinates.push(coordinate);
430 }
431 }
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700432 triggerUIUpdate(coordinates, extra["payload"], weights);
433}
434
435/**
436* Triggers a map update based on a set of spatial query result cells
437* @param [Array] mapPlotData, an array of coordinate and weight objects
438* @param [Array] params, an object containing original query parameters [LEGACY]
439* @param [Array] plotWeights, a list of weights of the spatial cells - e.g., number of tweets
440*/
441function triggerUIUpdate(mapPlotData, params, plotWeights) {
442 /** Clear anything currently on the map **/
443 mapWidgetClearMap();
444 param_placeholder = params;
445
446 // Compute data point spread
447 var dataBreakpoints = mapWidgetLegendComputeNaturalBreaks(plotWeights);
448
449 $.each(mapPlotData, function (m, val) {
450
451 // Only map points in data range of top 4 natural breaks
452 if (mapPlotData[m].weight > dataBreakpoints[0]) {
453
454 // Get color value of legend
455 var mapColor = mapWidgetLegendGetHeatValue(mapPlotData[m].weight, dataBreakpoints);
456 var markerRadius = mapWidgetComputeCircleRadius(mapPlotData[m], dataBreakpoints);
457 var point_opacity = 1.0; // TODO
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700458
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700459 var point_center = new google.maps.LatLng(
460 (mapPlotData[m].latSW + mapPlotData[m].latNE)/2.0,
461 (mapPlotData[m].lngSW + mapPlotData[m].lngNE)/2.0);
462
463 // Create and plot marker
464 var map_circle_options = {
465 center: point_center,
466 radius: markerRadius,
467 map: map,
468 fillOpacity: point_opacity,
469 fillColor: mapColor,
470 clickable: true
471 };
472 var map_circle = new google.maps.Circle(map_circle_options);
473 map_circle.val = mapPlotData[m];
474
475 // Clicking on a circle drills down map to that value
476 google.maps.event.addListener(map_circle, 'click', function (event) {
477 onMapPointDrillDown(map_circle.val);
478 });
479
480 // Add this marker to global marker cells
481 map_cells.push(map_circle);
482 }
483 });
484
485 // Add a legend to the map
486 mapControlWidgetAddLegend(dataBreakpoints);
487}
488
489/**
490* prepares an Asterix API query to drill down in a rectangular spatial zone
491*
492* @params {object} marker_borders [LEGACY] a set of bounds for a region from a previous api result
493*/
494function onMapPointDrillDown(marker_borders) {
495 var zoneData = APIqueryTracker["data"]; // TODO: Change how this is managed
496
497 var zswBounds = new google.maps.LatLng(marker_borders.latSW, marker_borders.lngNE);
498 var zneBounds = new google.maps.LatLng(marker_borders.latNE, marker_borders.lngSW);
499
500 var zoneBounds = new google.maps.LatLngBounds(zswBounds, zneBounds);
501 zoneData["swLat"] = zoneBounds.getSouthWest().lat();
502 zoneData["swLng"] = -1*zoneBounds.getSouthWest().lng();
503 zoneData["neLat"] = zoneBounds.getNorthEast().lat();
504 zoneData["neLng"] = -1*zoneBounds.getNorthEast().lng();
505
506 mapWidgetClearMap();
507
508 var customBounds = new google.maps.LatLngBounds();
509 var zoomSWBounds = new google.maps.LatLng(zoneData["swLat"], -1*zoneData["swLng"]);
510 var zoomNEBounds = new google.maps.LatLng(zoneData["neLat"], -1*zoneData["neLng"]);
511 customBounds.extend(zoomSWBounds);
512 customBounds.extend(zoomNEBounds);
513 map.fitBounds(customBounds);
514
515 var drilldown_string = ["use dataverse " + "twitter" + ";",
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700516 "for $t in dataset('" + "TweetMessages" + "')",
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700517 "let $keyword := \"" +zoneData["keyword"] + "\"",
518 "let $region := polygon(\"",
519 zoneData["neLat"] + "," + zoneData["swLng"] + " ",
520 zoneData["swLat"] + "," + zoneData["swLng"] + " ",
521 zoneData["swLat"] + "," + zoneData["neLng"] + " ",
522 zoneData["neLat"] + "," + zoneData["neLng"] + "\")",
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700523 "where spatial-intersect($t.sender-location, $region) and",
524 "$t.send-time > datetime(\"" + zoneData["startdt"] + "\") and $t.send-time < datetime(\"" + zoneData["enddt"] + "\") and",
525 "contains($t.message-text, $keyword)",
526 "return { \"tweetId\": $t.tweetid, \"tweetText\": $t.message-text, \"tweetLoc\": $t.sender-location}"];
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700527
528 var zQ = new AsterixCoreAPI()
529 .dataverse("twitter")
530 .statements(drilldown_string)
531 .add_extra("payload", zoneData) // Legacy
532 .mode("synchronous")
533 .success(onTweetbookQuerySuccessPlot, true)
534 .add_extra("query_string", drilldown_string.join(" "))
535 .add_extra("marker_path", "../img/mobile2.png")
536 .add_extra("on_click_marker", onClickTweetbookMapMarker)
537 .add_extra("on_clean_result", onCleanTweetbookDrilldown)
538 .api_core_query();
539}
540
541function triggerUIUpdateOnDropTweetBook(extra_info) {
542 // TODO Remove menu entry
543 // review-tweetbook-titles.html('')
544 // Append each in review_mode_tweetbooks if not same as extra_info["title"]
545 // $('#review-tweetbook-titles').append('<li><a href="#">' + extra_info["title"] + '</a></li>');
546}
547
548function onDrillDownAtLocation(tO) {
549
550 $('#drilldown_modal_body').append('<div id="drilltweetobj' + tO["tweetEntryId"] + '"></div>');
551
552 $('#drilltweetobj' + tO["tweetEntryId"]).append('<p>' + tO["tweetText"] + '</p>');
553
554 $('#drilltweetobj' + tO["tweetEntryId"]).append('<input class="textbox" type="text" id="metacomment' + tO["tweetEntryId"] + '">');
555
556 if (tO.hasOwnProperty("tweetbookComment")) {
557 $('#metacomment' + tO["tweetEntryId"]).val(tO["tweetbookComment"]);
558 }
559
560 $('#drilltweetobj' + tO["tweetEntryId"]).append('<button title="' + tO["tweetEntryId"] + '" id="meta' + tO["tweetEntryId"] + '">Add Comment to...</button>');
561
562 $('#drilltweetobj' + tO["tweetEntryId"]).append('<input class="textbox" type="text" id="tweetbooktarget' + tO["tweetEntryId"] + '">');
563
564 $('#meta' + tO["tweetEntryId"])
565 .button()
566 .click( function () {
567
568 var valid = $('#meta' + tO["tweetEntryId"]).attr('title');
569 var valcomment = $("#metacomment" + valid).val();
570 var valtext = drilldown_data_map_vals[valid.toString()]["tweetText"];
571 var tweetbookname = $("#tweetbooktarget" + valid).val();
572
573 //Try to add the tweetbook, if it does not already exist
574 onCreateNewTweetBook(tweetbookname);
575
576 var apiCall = new AsterixCoreAPI()
577 .dataverse("twitter")
578 .statements([
579 'delete $l from dataset ' + tweetbookname + ' where $l.id = "' + valid + '";',
580 'insert into dataset ' + tweetbookname + '({ "id" : "' + valid + '", "metacomment" : "' + valcomment + '"});'
581 ])
582 .api_core_update();
583 });
584
585}
586
587function onCreateNewTweetBook(tweetbook_title) {
588
589 var newTweetbookAPICall = new AsterixCoreAPI()
590 .dataverse("twitter")
591 .create_dataset({
592 "dataset" : tweetbook_title,
593 "type" : "MetaTweet",
594 "primary_key" : "id"
595 })
596 .add_extra("title", tweetbook_title)
597 .success(triggerUIUpdateOnNewTweetBook, true)
598 .api_core_update();
599 // Possible bug...ERROR 1: Invalid statement: Non-DDL statement DATASET_DECL to the DDL API.
600
601 /*var removeTest = new AsterixCoreAPI()
602 .dataverse("twitter")
603 .drop_dataset("blah")
604 .api_core_update(); */
605}
606
607function onDropTweetBook(tweetbook_title) {
608 var removeTest = new AsterixCoreAPI()
609 .dataverse("twitter")
610 .drop_dataset(tweetbook_title)
611 .success(triggerUIUpdateOnDropTweetBook, true)
612 .api_core_update();
613}
614
615function onTweetbookQuerySuccessPlot (res, extra) {
616 var response = $.parseJSON(res[0]);
617 var records = response["results"];
618 var coordinates = [];
619 map_tweet_markers = [];
620 map_tweet_overlays = [];
621 drilldown_data_map = {};
622 drilldown_data_map_vals = {};
623
624 var micon = extra["marker_path"];
625 var marker_click_function = extra["on_click_marker"];
626 var clean_result_function = extra["on_clean_result"];
627
628 coordinates = clean_result_function(records);
629
630 for (var dm in coordinates) {
631 var keyLat = coordinates[dm].tweetLat.toString();
632 var keyLng = coordinates[dm].tweetLng.toString();
633 if (!drilldown_data_map.hasOwnProperty(keyLat)) {
634 drilldown_data_map[keyLat] = {};
635 }
636 if (!drilldown_data_map[keyLat].hasOwnProperty(keyLng)) {
637 drilldown_data_map[keyLat][keyLng] = [];
638 }
639 drilldown_data_map[keyLat][keyLng].push(coordinates[dm]);
640 drilldown_data_map_vals[coordinates[dm].tweetEntryId.toString()] = coordinates[dm];
641 }
642
643 $.each(drilldown_data_map, function(drillKeyLat, valuesAtLat) {
644 $.each(drilldown_data_map[drillKeyLat], function (drillKeyLng, valueAtLng) {
645
646 // Get subset of drilldown position on map
647 var cposition = new google.maps.LatLng(parseFloat(drillKeyLat), parseFloat(drillKeyLng));
648
649 // Create a marker using the snazzy phone icon
650 var map_tweet_m = new google.maps.Marker({
651 position: cposition,
652 map: map,
653 icon: micon,
654 clickable: true,
655 });
656
657 // Open Tweet exploration window on click
658 google.maps.event.addListener(map_tweet_m, 'click', function (event) {
659 marker_click_function(drilldown_data_map[drillKeyLat][drillKeyLng]);
660 });
661
662 // Add marker to index of tweets
663 map_tweet_markers.push(map_tweet_m);
664
665 });
666 });
667}
668
669function triggerUIUpdateOnNewTweetBook(extra_info) {
670 // Add tweetbook to log
671 if (parseInt($.inArray(extra_info["title"], review_mode_tweetbooks)) == -1) {
672 review_mode_tweetbooks.push(extra_info["title"]);
673
674 // Add menu entry
675 $('#review-tweetbook-titles').append('<li><a href="#"><span id="tbook_' + extra_info["title"] + '">' + extra_info["title"] + '</span></a></li>');
676
677 // Add on-click behavior
678 $("#tbook_" + extra_info["title"]).on('click', function(e) {
679 var plotTweetbookQuery = new AsterixCoreAPI()
680 .dataverse("twitter")
681 .success(onTweetbookQuerySuccessPlot, true)
682 .aql_for({"mt": extra_info["title"]})
683 .aql_where(["int64($mt.id)%1500 = 0"])
684 .aql_return({ "id" : "$mt.id", "location" : "$mt.loc", "comment" : "$mt.metacomment", "tweet" : "$mt.tweet" })
685 .add_extra("tweetbook_title", extra_info["title"])
686 .add_extra("marker_path", "../img/mobile_green2.png")
687 .add_extra("on_click_marker", onClickTweetbookMapMarker)
688 .add_extra("on_clean_result", onCleanPlotTweetbook)
689 .api_core_query();
690
691 });
692 }
693}
694
695function onCleanPlotTweetbook(records) {
696 var toPlot = [];
697 for (var subrecords = 0; subrecords < records.length; subrecords++) {
698 for (var record in records[subrecords]) {
699 var tweetbook_element = {
700 "tweetEntryId" : parseInt(records[subrecords][record].split(",")[0].split(":")[1].split('"')[1]),
701 "tweetLat" : parseFloat(records[subrecords][record].split("location\": point(\"")[1].split(",")[0]),
702 "tweetLng" : -1*parseFloat(records[subrecords][record].split("location\": point(\"")[1].split(",")[1].split("\"")[0]),
703 "tweetText" : records[subrecords][record].split("tweet\": \"")[1].split("\"")[0],
704 "tweetbookComment" : records[subrecords][record].split("comment\": \"")[1].split("\", \"tweet\":")[0]
705 };
706 toPlot.push(tweetbook_element);
707 }
708 }
709 return toPlot;
710}
711
712function onCleanTweetbookDrilldown (rec) {
713 var drilldown_cleaned = [];
714 for (var subresult = 0; subresult < rec.length; subresult++) {
715 for (var entry in rec[subresult]) {
716
717 var drill_element = {
718 "tweetEntryId" : parseInt(rec[subresult][entry].split(",")[0].split(":")[1].split('"')[1]),
719 "tweetText" : rec[subresult][entry].split("tweetText\": \"")[1].split("\", \"tweetLoc\":")[0],
720 "tweetLat" : parseFloat(rec[subresult][entry].split("tweetLoc\": point(\"")[1].split(",")[0]),
721 "tweetLng" : -1*parseFloat(rec[subresult][entry].split("tweetLoc\": point(\"")[1].split(",")[1].split("\"")[0])
722 };
723 drilldown_cleaned.push(drill_element);
724
725 }
726 }
727 return drilldown_cleaned;
728}
729
730function onClickTweetbookMapMarker(tweet_arr) {
731 $('#drilldown_modal_body').html('');
732
733 // Clear existing display
734 $.each(tweet_arr, function (t, valueT) {
735 var tweet_obj = tweet_arr[t];
736 onDrillDownAtLocation(tweet_obj);
737 });
738
739 $('#drilldown_modal').modal('show');
740}
741
742/** Toggling Review and Explore Modes **/
743
744/**
745* Explore mode: Initial map creation and screen alignment
746*/
747function onOpenExploreMap () {
748 var explore_column_height = $('#explore-well').height();
749 $('#map_canvas').height(explore_column_height + "px");
750 $('#review-well').height(explore_column_height + "px");
751 $('#review-well').css('max-height', explore_column_height + "px");
752 var pad = $('#review-well').innerHeight() - $('#review-well').height();
753 var prev_window_target = $('#review-well').height() - 20 - $('#group-tweetbooks').innerHeight() - $('#group-background-query').innerHeight() - 2*pad;
754 $('#query-preview-window').height(prev_window_target +'px');
755}
756
757/**
758* Launching explore mode: clear windows/variables, show correct sidebar
759*/
760function onLaunchExploreMode() {
761 $('#review-active').removeClass('active');
762 $('#review-well').hide();
763
764 $('#explore-active').addClass('active');
765 $('#explore-well').show();
766
767 $("#clear-button").trigger("click");
768}
769
770/**
771* Launching review mode: clear windows/variables, show correct sidebar
772*/
773function onLaunchReviewMode() {
774 $('#explore-active').removeClass('active');
775 $('#explore-well').hide();
776 $('#review-active').addClass('active');
777 $('#review-well').show();
778
779 $("#clear-button").trigger("click");
780}
781
782/** Map Widget Utility Methods **/
783
784/**
785* Plots a legend onto the map, with values in progress bars
786* @param {number Array} breakpoints, an array of numbers representing natural breakpoints
787*/
788function mapControlWidgetAddLegend(breakpoints) {
789
790 // Retriever colors, lightest to darkest
791 var colors = mapWidgetGetColorPalette();
792
793 // Initial div structure
794 $("#map_canvas_legend").html('<div id="legend-holder"><div id="legend-progress-bar" class="progress"></div><span id="legend-label"></span></div>');
795
796 // Add color scale to legend
797 $('#legend-progress-bar').css("width", "200px").html('');
798
799 // Add a progress bar for each color
800 for (var color in colors) {
801
802 // Bar values
803 var upperBound = breakpoints[parseInt(color) + 1];
804
805 // Create Progress Bar
806 $('<div/>')
807 .attr("class", "bar")
808 .attr("id", "pbar" + color)
809 .css("width" , '25.0%')
810 .html("< " + upperBound)
811 .appendTo('#legend-progress-bar');
812
813 $('#pbar' + color).css({
814 "background-image" : 'none',
815 "background-color" : colors[parseInt(color)]
816 });
817
818 // Attach a message showing minimum bounds
819 $('#legend-label').html('Regions with at least ' + breakpoints[0] + ' tweets');
820 $('#legend-label').css({
821 "color" : "black"
822 });
823 }
824
825 // Add legend to map
826 map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('legend-holder'));
827 $('#map_canvas_legend').show();
828}
829
830/**
831* Clears map elements - legend, plotted items, overlays
832*/
833function mapWidgetClearMap() {
834
835 if (selectionRect) {
836 selectionRect.setMap(null);
837 selectionRect = null;
838 }
839 for (c in map_cells) {
840 map_cells[c].setMap(null);
841 }
842 map_cells = [];
843 for (m in map_tweet_markers) {
844 map_tweet_markers[m].setMap(null);
845 }
846 map_tweet_markers = [];
847
848 // Remove legend from map
849 map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].clear();
850}
851
852/**
853* Uses jenks algorithm in geostats library to find natural breaks in numeric data
854* @param {number Array} weights of points to plot
855* @returns {number Array} array of natural breakpoints, of which the top 4 subsets will be plotted
856*/
857function mapWidgetLegendComputeNaturalBreaks(weights) {
858 var plotDataWeights = new geostats(weights.sort());
859 return plotDataWeights.getJenks(6).slice(2, 7);
860}
861
862/**
863* Computes values for map legend given a value and an array of jenks breakpoints
864* @param {number} weight of point to plot on map
865* @param {number Array} breakpoints, an array of 5 points corresponding to bounds of 4 natural ranges
866* @returns {String} an RGB value corresponding to a subset of data
867*/
868function mapWidgetLegendGetHeatValue(weight, breakpoints) {
869
870 // Determine into which range the weight falls
871 var weightColor = 0;
872 if (weight >= breakpoints[3]) {
873 weightColor = 3;
874 } else if (weight >= breakpoints[2]) {
875 weightColor = 2;
876 } else if (weight >= breakpoints[1]) {
877 weightColor = 1;
878 }
879
880 // Get default map color palette
881 var colorValues = mapWidgetGetColorPalette();
882 return colorValues[weightColor];
883}
884
885/**
886* Returns an array containing a 4-color palette, lightest to darkest
887* External palette source: http://www.colourlovers.com/palette/2763366/s_i_l_e_n_c_e_r
888* @returns {Array} [colors]
889*/
890function mapWidgetGetColorPalette() {
891 return [
892 "rgb(115,189,158)",
893 "rgb(74,142,145)",
894 "rgb(19,93,96)",
895 "rgb(7,51,46)"
896 ];
897}
898
899/**
900* Computes radius for a given data point from a spatial cell
901* @param {Object} keys => ["latSW" "lngSW" "latNE" "lngNE" "weight"]
902* @returns {number} radius between 2 points in metres
903*/
904function mapWidgetComputeCircleRadius(spatialCell, breakpoints) {
905
906 var weight = spatialCell.weight;
907 // Compute weight color
908 var weightColor = 0.25;
909 if (weight >= breakpoints[3]) {
910 weightColor = 1.0;
911 } else if (weight >= breakpoints[2]) {
912 weightColor = 0.75;
913 } else if (weight >= breakpoints[1]) {
914 weightColor = 0.5;
915 }
916
917 // Define Boundary Points
918 var point_center = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
919 var point_left = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, spatialCell.lngSW);
920 var point_top = new google.maps.LatLng(spatialCell.latNE, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
921
922 // TODO not actually a weight color :)
923 return weightColor * 1000 * Math.min(distanceBetweenPoints_(point_center, point_left), distanceBetweenPoints_(point_center, point_top));
924}
925
926/** External Utility Methods **/
927
928/**
929 * Calculates the distance between two latlng locations in km.
930 * @see http://www.movable-type.co.uk/scripts/latlong.html
931 *
932 * @param {google.maps.LatLng} p1 The first lat lng point.
933 * @param {google.maps.LatLng} p2 The second lat lng point.
934 * @return {number} The distance between the two points in km.
935 * @private
936*/
937function distanceBetweenPoints_(p1, p2) {
938 if (!p1 || !p2) {
939 return 0;
940 }
941
942 var R = 6371; // Radius of the Earth in km
943 var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
944 var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
945 var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
946 Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
947 Math.sin(dLon / 2) * Math.sin(dLon / 2);
948 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
949 var d = R * c;
950 return d;
951};