blob: 0715ffea4b9210e7973af583b1a95bed09556264 [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.
235 var buildCherryQuery = new AsterixCoreAPI()
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700236 .aql_for({ "t" : "TweetMessages"})
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700237 .aql_let({
238 "keyword" : '"' + formData["keyword"] + '"',
239 "region" : new AsterixCoreAPI()
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700240 .rectangle({
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700241 "ne" : { "lat" : formData["neLat"], "lng" : formData["neLng"]},
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700242 "sw" : { "lat" : formData["swLat"], "lng" : formData["swLng"]}
243 }).parameters["statements"]
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700244 })
245 .aql_where([
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.coma362b4d2013-04-26 08:29:25 -0700250 ])
251 .aql_groupby({
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700252 "groupby" : "$c := spatial-cell($t.sender-location, create-point(24.5,-125.5), " + formData["gridlat"].toFixed(1) + ", " + formData["gridlng"].toFixed(1) + ")",
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700253 "with" : "$t"
254 })
255 .aql_return({ "cell" : "$c", "count" : "count($t)" });
256
genia.likes.science@gmail.com20928902013-05-10 10:39:27 -0700257 var l = new LegacyExpression();
258 l.extra({
259 "payload" : formData,
260 "query_string" : "use dataverse twitter;\n" + buildCherryQuery.parameters["statements"].join("\n")
261 });
262 l.set(buildCherryQuery.parameters["statements"].join("\n"));
263 l.success(cherryQuerySyncCallback, true);
264 l.success(cherryQueryAsyncCallback, false);
265
266 l.send("http://localhost:19101/query",
267 {
268 "query" : "use dataverse twitter;\n" + buildCherryQuery.parameters["statements"].join("\n"),
269 "mode" : build_cherry_mode,
270 });
271
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700272 APIqueryTracker = {
273 "query" : buildCherryQuery.parameters["statements"].join("\n"),
274 "data" : formData
275 };
276
277 $('#dialog').html(APIqueryTracker["query"]);//.replace("\n", '<br />'));
278
279 if (!$('#asbox').is(":checked")) {
280 $('#show-query-button').attr("disabled", false);
281 } else {
282 $('#show-query-button').attr("disabled", true);
283 }
284 });
285
286});
287
288/** Asynchronous Query Management - Handles & Such **/
289
290/**
291* Checks through each asynchronous query to see if they are ready yet
292*/
293function asynchronousQueryIntervalUpdate() {
294 for (var handle_key in asyncQueryManager) {
295 if (!asyncQueryManager[handle_key].hasOwnProperty("ready")) {
296 asynchronousQueryGetAPIQueryStatus( asyncQueryManager[handle_key]["handle"], handle_key );
297 }
298 }
299}
300
301/**
302* Returns current time interval to check for asynchronous query readiness
303* @returns {number} milliseconds between asychronous query checks
304*/
305function asynchronousQueryGetInterval() {
306 var seconds = 10;
307 return seconds * 1000;
308}
309
310/**
311* Updates UI when an API Query's status is marked ready
312* @param {Object} res, a result object from the Asterix API
313* @param {object} extra_info, containing the asynchronous handle's id
314*/
315function asynchronousQueryAPIStatusReceived (res, extra_info) {
316 var handle_outcome = $.parseJSON(res[0]);
317 var handle_id = extra_info["handle_id"];
318 if (handle_outcome["status"] == "SUCCESS") {
319
320 // We don't need to check if this one is ready again, it's not going anywhere...
321 // Unless the life cycle of handles has changed drastically
322 asyncQueryManager[handle_id]["ready"] = true;
323
324 // Make this handle's result look retrievable
325 $('#handle_' + handle_id).addClass("label-success");
326 }
327}
328
329/**
330* Retrieves status of an asynchronous query, using an opaque result handle from API
331* @param {Object} handle, an object previously returned from an async call
332* @param {number} handle_id, the integer ID parsed from the handle object
333*/
334function asynchronousQueryGetAPIQueryStatus (handle, handle_id) {
335 var apiQueryStatus = new AsterixCoreAPI()
336 .dataverse("twitter")
337 .handle(handle)
338 .success(asynchronousQueryAPIStatusReceived, true)
339 .add_extra("handle_id", handle_id)
340 .api_core_query_status();
341}
342
343/**
344* On-success callback after async API query
345* @param {object} res, a result object containing an opaque result handle to Asterix
346* @param {object} extra, a result object containing a query string and query parameters
347*/
348function cherryQueryAsyncCallback(res, extra) {
349
350 // Parse handle, handle id and query from async call result
351 var handle = res[0];
352 var handle_query = extra["query_string"];
353 var handle_id = $.parseJSON(handle)["handle"].toString().split(',')[0];
354
355 // Add to stored map of existing handles
356 asyncQueryManager[handle_id] = {
357 "handle" : handle,
358 "query" : handle_query,
359 "data" : extra["payload"]
360 };
361
362 $('#review-handles-dropdown').append('<a href="#" class="holdmenu"><span class="label" id="handle_' + handle_id + '">Handle ' + handle_id + '</span></a>');
363
364 $('#handle_' + handle_id).hover(
365 function(){
366 $('#query-preview-window').html('');
367 $('#query-preview-window').html('<br/><br/>' + asyncQueryManager[handle_id]["query"]);
368 },
369 function() {
370 $('#query-preview-window').html('');
371 }
372 );
373
374 $('#handle_' + handle_id).on('click', function (e) {
375
376 // make sure query is ready to be run
377 if (asyncQueryManager[handle_id]["ready"]) {
378
379 // Update API Query Tracker and view to reflect this query
380 $('#query-preview-window').html('<br/><br/>' + asyncQueryManager[handle_id]["query"]);
381 APIqueryTracker = {
382 "query" : asyncQueryManager[handle_id]["query"],
383 "data" : asyncQueryManager[handle_id]["data"]
384 };
385 $('#dialog').html(APIqueryTracker["query"]);
386
387 // Generate new Asterix Core API Query
388 var asyncResultQuery = new AsterixCoreAPI()
389 .dataverse("twitter")
390 .handle(asyncQueryManager[handle_id]["handle"])
391 .success(cherryQuerySyncCallback, true)
392 .add_extra("payload", asyncQueryManager[handle_id]["data"]) // Legacy
393 .add_extra("query_string", asyncQueryManager[handle_id]["query"]) // Legacy
394 .api_core_query_result();
395 }
396 });
397}
398
399
400/** Core Query Management and Drilldown
401
402/**
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700403* Utility Method for parsing a record of this form:
404* { "cell": rectangle("22.5,64.5 24.5,66.5"), "count": 5 }
405* returns a json object with keys: weight, latSW, lngSW, latNE, lngNE
406*/
407function getRecord(cell_count_record) {
408 var record_representation = {};
409
410 var rectangle = cell_count_record.split('")')[0].split('("')[1];
411 record_representation["latSW"] = parseFloat(rectangle.split(" ")[0].split(',')[0]);
412 record_representation["lngSW"] = parseFloat(rectangle.split(" ")[0].split(',')[1]);
413 record_representation["latNE"] = parseFloat(rectangle.split(" ")[1].split(',')[0]);
414 record_representation["lngNE"] = parseFloat(rectangle.split(" ")[1].split(',')[1]);
415 record_representation["weight"] = parseInt(cell_count_record.split('count": ')[1].split(" ")[0]);
416
417 return record_representation;
418}
419
420/**
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700421* A spatial data cleaning and mapping call
422* @param {Object} res, a result object from a cherry geospatial query
423* @param {Object} extra, extra data passed from the API call - legacy stuff
424*/
425function cherryQuerySyncCallback(res, extra) {
genia.likes.science@gmail.combdfa27a2013-05-08 10:44:34 -0700426 records = res["results"];
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700427
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700428 var coordinates = [];
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700429 var weights = [];
430
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700431 for (var subrecord in records) {
432 for (var record in records[subrecord]) {
433
434 var coordinate = getRecord(records[subrecord][record]);
435 weights.push(coordinate["weight"]);
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700436 coordinates.push(coordinate);
437 }
438 }
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700439 triggerUIUpdate(coordinates, extra["payload"], weights);
440}
441
442/**
443* Triggers a map update based on a set of spatial query result cells
444* @param [Array] mapPlotData, an array of coordinate and weight objects
445* @param [Array] params, an object containing original query parameters [LEGACY]
446* @param [Array] plotWeights, a list of weights of the spatial cells - e.g., number of tweets
447*/
448function triggerUIUpdate(mapPlotData, params, plotWeights) {
449 /** Clear anything currently on the map **/
450 mapWidgetClearMap();
451 param_placeholder = params;
452
453 // Compute data point spread
454 var dataBreakpoints = mapWidgetLegendComputeNaturalBreaks(plotWeights);
455
456 $.each(mapPlotData, function (m, val) {
457
458 // Only map points in data range of top 4 natural breaks
459 if (mapPlotData[m].weight > dataBreakpoints[0]) {
460
461 // Get color value of legend
462 var mapColor = mapWidgetLegendGetHeatValue(mapPlotData[m].weight, dataBreakpoints);
463 var markerRadius = mapWidgetComputeCircleRadius(mapPlotData[m], dataBreakpoints);
464 var point_opacity = 1.0; // TODO
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700465
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700466 var point_center = new google.maps.LatLng(
467 (mapPlotData[m].latSW + mapPlotData[m].latNE)/2.0,
468 (mapPlotData[m].lngSW + mapPlotData[m].lngNE)/2.0);
469
470 // Create and plot marker
471 var map_circle_options = {
472 center: point_center,
473 radius: markerRadius,
474 map: map,
475 fillOpacity: point_opacity,
476 fillColor: mapColor,
477 clickable: true
478 };
479 var map_circle = new google.maps.Circle(map_circle_options);
480 map_circle.val = mapPlotData[m];
481
482 // Clicking on a circle drills down map to that value
483 google.maps.event.addListener(map_circle, 'click', function (event) {
484 onMapPointDrillDown(map_circle.val);
485 });
486
487 // Add this marker to global marker cells
488 map_cells.push(map_circle);
489 }
490 });
491
492 // Add a legend to the map
493 mapControlWidgetAddLegend(dataBreakpoints);
494}
495
496/**
497* prepares an Asterix API query to drill down in a rectangular spatial zone
498*
499* @params {object} marker_borders [LEGACY] a set of bounds for a region from a previous api result
500*/
501function onMapPointDrillDown(marker_borders) {
502 var zoneData = APIqueryTracker["data"]; // TODO: Change how this is managed
503
504 var zswBounds = new google.maps.LatLng(marker_borders.latSW, marker_borders.lngNE);
505 var zneBounds = new google.maps.LatLng(marker_borders.latNE, marker_borders.lngSW);
506
507 var zoneBounds = new google.maps.LatLngBounds(zswBounds, zneBounds);
508 zoneData["swLat"] = zoneBounds.getSouthWest().lat();
509 zoneData["swLng"] = -1*zoneBounds.getSouthWest().lng();
510 zoneData["neLat"] = zoneBounds.getNorthEast().lat();
511 zoneData["neLng"] = -1*zoneBounds.getNorthEast().lng();
512
513 mapWidgetClearMap();
514
515 var customBounds = new google.maps.LatLngBounds();
516 var zoomSWBounds = new google.maps.LatLng(zoneData["swLat"], -1*zoneData["swLng"]);
517 var zoomNEBounds = new google.maps.LatLng(zoneData["neLat"], -1*zoneData["neLng"]);
518 customBounds.extend(zoomSWBounds);
519 customBounds.extend(zoomNEBounds);
520 map.fitBounds(customBounds);
521
522 var drilldown_string = ["use dataverse " + "twitter" + ";",
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700523 "for $t in dataset('" + "TweetMessages" + "')",
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700524 "let $keyword := \"" +zoneData["keyword"] + "\"",
525 "let $region := polygon(\"",
526 zoneData["neLat"] + "," + zoneData["swLng"] + " ",
527 zoneData["swLat"] + "," + zoneData["swLng"] + " ",
528 zoneData["swLat"] + "," + zoneData["neLng"] + " ",
529 zoneData["neLat"] + "," + zoneData["neLng"] + "\")",
genia.likes.science@gmail.com57d9dc22013-05-08 06:31:41 -0700530 "where spatial-intersect($t.sender-location, $region) and",
531 "$t.send-time > datetime(\"" + zoneData["startdt"] + "\") and $t.send-time < datetime(\"" + zoneData["enddt"] + "\") and",
532 "contains($t.message-text, $keyword)",
533 "return { \"tweetId\": $t.tweetid, \"tweetText\": $t.message-text, \"tweetLoc\": $t.sender-location}"];
genia.likes.science@gmail.coma362b4d2013-04-26 08:29:25 -0700534
535 var zQ = new AsterixCoreAPI()
536 .dataverse("twitter")
537 .statements(drilldown_string)
538 .add_extra("payload", zoneData) // Legacy
539 .mode("synchronous")
540 .success(onTweetbookQuerySuccessPlot, true)
541 .add_extra("query_string", drilldown_string.join(" "))
542 .add_extra("marker_path", "../img/mobile2.png")
543 .add_extra("on_click_marker", onClickTweetbookMapMarker)
544 .add_extra("on_clean_result", onCleanTweetbookDrilldown)
545 .api_core_query();
546}
547
548function triggerUIUpdateOnDropTweetBook(extra_info) {
549 // TODO Remove menu entry
550 // review-tweetbook-titles.html('')
551 // Append each in review_mode_tweetbooks if not same as extra_info["title"]
552 // $('#review-tweetbook-titles').append('<li><a href="#">' + extra_info["title"] + '</a></li>');
553}
554
555function onDrillDownAtLocation(tO) {
556
557 $('#drilldown_modal_body').append('<div id="drilltweetobj' + tO["tweetEntryId"] + '"></div>');
558
559 $('#drilltweetobj' + tO["tweetEntryId"]).append('<p>' + tO["tweetText"] + '</p>');
560
561 $('#drilltweetobj' + tO["tweetEntryId"]).append('<input class="textbox" type="text" id="metacomment' + tO["tweetEntryId"] + '">');
562
563 if (tO.hasOwnProperty("tweetbookComment")) {
564 $('#metacomment' + tO["tweetEntryId"]).val(tO["tweetbookComment"]);
565 }
566
567 $('#drilltweetobj' + tO["tweetEntryId"]).append('<button title="' + tO["tweetEntryId"] + '" id="meta' + tO["tweetEntryId"] + '">Add Comment to...</button>');
568
569 $('#drilltweetobj' + tO["tweetEntryId"]).append('<input class="textbox" type="text" id="tweetbooktarget' + tO["tweetEntryId"] + '">');
570
571 $('#meta' + tO["tweetEntryId"])
572 .button()
573 .click( function () {
574
575 var valid = $('#meta' + tO["tweetEntryId"]).attr('title');
576 var valcomment = $("#metacomment" + valid).val();
577 var valtext = drilldown_data_map_vals[valid.toString()]["tweetText"];
578 var tweetbookname = $("#tweetbooktarget" + valid).val();
579
580 //Try to add the tweetbook, if it does not already exist
581 onCreateNewTweetBook(tweetbookname);
582
583 var apiCall = new AsterixCoreAPI()
584 .dataverse("twitter")
585 .statements([
586 'delete $l from dataset ' + tweetbookname + ' where $l.id = "' + valid + '";',
587 'insert into dataset ' + tweetbookname + '({ "id" : "' + valid + '", "metacomment" : "' + valcomment + '"});'
588 ])
589 .api_core_update();
590 });
591
592}
593
594function onCreateNewTweetBook(tweetbook_title) {
595
596 var newTweetbookAPICall = new AsterixCoreAPI()
597 .dataverse("twitter")
598 .create_dataset({
599 "dataset" : tweetbook_title,
600 "type" : "MetaTweet",
601 "primary_key" : "id"
602 })
603 .add_extra("title", tweetbook_title)
604 .success(triggerUIUpdateOnNewTweetBook, true)
605 .api_core_update();
606 // Possible bug...ERROR 1: Invalid statement: Non-DDL statement DATASET_DECL to the DDL API.
607
608 /*var removeTest = new AsterixCoreAPI()
609 .dataverse("twitter")
610 .drop_dataset("blah")
611 .api_core_update(); */
612}
613
614function onDropTweetBook(tweetbook_title) {
615 var removeTest = new AsterixCoreAPI()
616 .dataverse("twitter")
617 .drop_dataset(tweetbook_title)
618 .success(triggerUIUpdateOnDropTweetBook, true)
619 .api_core_update();
620}
621
622function onTweetbookQuerySuccessPlot (res, extra) {
623 var response = $.parseJSON(res[0]);
624 var records = response["results"];
625 var coordinates = [];
626 map_tweet_markers = [];
627 map_tweet_overlays = [];
628 drilldown_data_map = {};
629 drilldown_data_map_vals = {};
630
631 var micon = extra["marker_path"];
632 var marker_click_function = extra["on_click_marker"];
633 var clean_result_function = extra["on_clean_result"];
634
635 coordinates = clean_result_function(records);
636
637 for (var dm in coordinates) {
638 var keyLat = coordinates[dm].tweetLat.toString();
639 var keyLng = coordinates[dm].tweetLng.toString();
640 if (!drilldown_data_map.hasOwnProperty(keyLat)) {
641 drilldown_data_map[keyLat] = {};
642 }
643 if (!drilldown_data_map[keyLat].hasOwnProperty(keyLng)) {
644 drilldown_data_map[keyLat][keyLng] = [];
645 }
646 drilldown_data_map[keyLat][keyLng].push(coordinates[dm]);
647 drilldown_data_map_vals[coordinates[dm].tweetEntryId.toString()] = coordinates[dm];
648 }
649
650 $.each(drilldown_data_map, function(drillKeyLat, valuesAtLat) {
651 $.each(drilldown_data_map[drillKeyLat], function (drillKeyLng, valueAtLng) {
652
653 // Get subset of drilldown position on map
654 var cposition = new google.maps.LatLng(parseFloat(drillKeyLat), parseFloat(drillKeyLng));
655
656 // Create a marker using the snazzy phone icon
657 var map_tweet_m = new google.maps.Marker({
658 position: cposition,
659 map: map,
660 icon: micon,
661 clickable: true,
662 });
663
664 // Open Tweet exploration window on click
665 google.maps.event.addListener(map_tweet_m, 'click', function (event) {
666 marker_click_function(drilldown_data_map[drillKeyLat][drillKeyLng]);
667 });
668
669 // Add marker to index of tweets
670 map_tweet_markers.push(map_tweet_m);
671
672 });
673 });
674}
675
676function triggerUIUpdateOnNewTweetBook(extra_info) {
677 // Add tweetbook to log
678 if (parseInt($.inArray(extra_info["title"], review_mode_tweetbooks)) == -1) {
679 review_mode_tweetbooks.push(extra_info["title"]);
680
681 // Add menu entry
682 $('#review-tweetbook-titles').append('<li><a href="#"><span id="tbook_' + extra_info["title"] + '">' + extra_info["title"] + '</span></a></li>');
683
684 // Add on-click behavior
685 $("#tbook_" + extra_info["title"]).on('click', function(e) {
686 var plotTweetbookQuery = new AsterixCoreAPI()
687 .dataverse("twitter")
688 .success(onTweetbookQuerySuccessPlot, true)
689 .aql_for({"mt": extra_info["title"]})
690 .aql_where(["int64($mt.id)%1500 = 0"])
691 .aql_return({ "id" : "$mt.id", "location" : "$mt.loc", "comment" : "$mt.metacomment", "tweet" : "$mt.tweet" })
692 .add_extra("tweetbook_title", extra_info["title"])
693 .add_extra("marker_path", "../img/mobile_green2.png")
694 .add_extra("on_click_marker", onClickTweetbookMapMarker)
695 .add_extra("on_clean_result", onCleanPlotTweetbook)
696 .api_core_query();
697
698 });
699 }
700}
701
702function onCleanPlotTweetbook(records) {
703 var toPlot = [];
704 for (var subrecords = 0; subrecords < records.length; subrecords++) {
705 for (var record in records[subrecords]) {
706 var tweetbook_element = {
707 "tweetEntryId" : parseInt(records[subrecords][record].split(",")[0].split(":")[1].split('"')[1]),
708 "tweetLat" : parseFloat(records[subrecords][record].split("location\": point(\"")[1].split(",")[0]),
709 "tweetLng" : -1*parseFloat(records[subrecords][record].split("location\": point(\"")[1].split(",")[1].split("\"")[0]),
710 "tweetText" : records[subrecords][record].split("tweet\": \"")[1].split("\"")[0],
711 "tweetbookComment" : records[subrecords][record].split("comment\": \"")[1].split("\", \"tweet\":")[0]
712 };
713 toPlot.push(tweetbook_element);
714 }
715 }
716 return toPlot;
717}
718
719function onCleanTweetbookDrilldown (rec) {
720 var drilldown_cleaned = [];
721 for (var subresult = 0; subresult < rec.length; subresult++) {
722 for (var entry in rec[subresult]) {
723
724 var drill_element = {
725 "tweetEntryId" : parseInt(rec[subresult][entry].split(",")[0].split(":")[1].split('"')[1]),
726 "tweetText" : rec[subresult][entry].split("tweetText\": \"")[1].split("\", \"tweetLoc\":")[0],
727 "tweetLat" : parseFloat(rec[subresult][entry].split("tweetLoc\": point(\"")[1].split(",")[0]),
728 "tweetLng" : -1*parseFloat(rec[subresult][entry].split("tweetLoc\": point(\"")[1].split(",")[1].split("\"")[0])
729 };
730 drilldown_cleaned.push(drill_element);
731
732 }
733 }
734 return drilldown_cleaned;
735}
736
737function onClickTweetbookMapMarker(tweet_arr) {
738 $('#drilldown_modal_body').html('');
739
740 // Clear existing display
741 $.each(tweet_arr, function (t, valueT) {
742 var tweet_obj = tweet_arr[t];
743 onDrillDownAtLocation(tweet_obj);
744 });
745
746 $('#drilldown_modal').modal('show');
747}
748
749/** Toggling Review and Explore Modes **/
750
751/**
752* Explore mode: Initial map creation and screen alignment
753*/
754function onOpenExploreMap () {
755 var explore_column_height = $('#explore-well').height();
756 $('#map_canvas').height(explore_column_height + "px");
757 $('#review-well').height(explore_column_height + "px");
758 $('#review-well').css('max-height', explore_column_height + "px");
759 var pad = $('#review-well').innerHeight() - $('#review-well').height();
760 var prev_window_target = $('#review-well').height() - 20 - $('#group-tweetbooks').innerHeight() - $('#group-background-query').innerHeight() - 2*pad;
761 $('#query-preview-window').height(prev_window_target +'px');
762}
763
764/**
765* Launching explore mode: clear windows/variables, show correct sidebar
766*/
767function onLaunchExploreMode() {
768 $('#review-active').removeClass('active');
769 $('#review-well').hide();
770
771 $('#explore-active').addClass('active');
772 $('#explore-well').show();
773
774 $("#clear-button").trigger("click");
775}
776
777/**
778* Launching review mode: clear windows/variables, show correct sidebar
779*/
780function onLaunchReviewMode() {
781 $('#explore-active').removeClass('active');
782 $('#explore-well').hide();
783 $('#review-active').addClass('active');
784 $('#review-well').show();
785
786 $("#clear-button").trigger("click");
787}
788
789/** Map Widget Utility Methods **/
790
791/**
792* Plots a legend onto the map, with values in progress bars
793* @param {number Array} breakpoints, an array of numbers representing natural breakpoints
794*/
795function mapControlWidgetAddLegend(breakpoints) {
796
797 // Retriever colors, lightest to darkest
798 var colors = mapWidgetGetColorPalette();
799
800 // Initial div structure
801 $("#map_canvas_legend").html('<div id="legend-holder"><div id="legend-progress-bar" class="progress"></div><span id="legend-label"></span></div>');
802
803 // Add color scale to legend
804 $('#legend-progress-bar').css("width", "200px").html('');
805
806 // Add a progress bar for each color
807 for (var color in colors) {
808
809 // Bar values
810 var upperBound = breakpoints[parseInt(color) + 1];
811
812 // Create Progress Bar
813 $('<div/>')
814 .attr("class", "bar")
815 .attr("id", "pbar" + color)
816 .css("width" , '25.0%')
817 .html("< " + upperBound)
818 .appendTo('#legend-progress-bar');
819
820 $('#pbar' + color).css({
821 "background-image" : 'none',
822 "background-color" : colors[parseInt(color)]
823 });
824
825 // Attach a message showing minimum bounds
826 $('#legend-label').html('Regions with at least ' + breakpoints[0] + ' tweets');
827 $('#legend-label').css({
828 "color" : "black"
829 });
830 }
831
832 // Add legend to map
833 map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('legend-holder'));
834 $('#map_canvas_legend').show();
835}
836
837/**
838* Clears map elements - legend, plotted items, overlays
839*/
840function mapWidgetClearMap() {
841
842 if (selectionRect) {
843 selectionRect.setMap(null);
844 selectionRect = null;
845 }
846 for (c in map_cells) {
847 map_cells[c].setMap(null);
848 }
849 map_cells = [];
850 for (m in map_tweet_markers) {
851 map_tweet_markers[m].setMap(null);
852 }
853 map_tweet_markers = [];
854
855 // Remove legend from map
856 map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].clear();
857}
858
859/**
860* Uses jenks algorithm in geostats library to find natural breaks in numeric data
861* @param {number Array} weights of points to plot
862* @returns {number Array} array of natural breakpoints, of which the top 4 subsets will be plotted
863*/
864function mapWidgetLegendComputeNaturalBreaks(weights) {
865 var plotDataWeights = new geostats(weights.sort());
866 return plotDataWeights.getJenks(6).slice(2, 7);
867}
868
869/**
870* Computes values for map legend given a value and an array of jenks breakpoints
871* @param {number} weight of point to plot on map
872* @param {number Array} breakpoints, an array of 5 points corresponding to bounds of 4 natural ranges
873* @returns {String} an RGB value corresponding to a subset of data
874*/
875function mapWidgetLegendGetHeatValue(weight, breakpoints) {
876
877 // Determine into which range the weight falls
878 var weightColor = 0;
879 if (weight >= breakpoints[3]) {
880 weightColor = 3;
881 } else if (weight >= breakpoints[2]) {
882 weightColor = 2;
883 } else if (weight >= breakpoints[1]) {
884 weightColor = 1;
885 }
886
887 // Get default map color palette
888 var colorValues = mapWidgetGetColorPalette();
889 return colorValues[weightColor];
890}
891
892/**
893* Returns an array containing a 4-color palette, lightest to darkest
894* External palette source: http://www.colourlovers.com/palette/2763366/s_i_l_e_n_c_e_r
895* @returns {Array} [colors]
896*/
897function mapWidgetGetColorPalette() {
898 return [
899 "rgb(115,189,158)",
900 "rgb(74,142,145)",
901 "rgb(19,93,96)",
902 "rgb(7,51,46)"
903 ];
904}
905
906/**
907* Computes radius for a given data point from a spatial cell
908* @param {Object} keys => ["latSW" "lngSW" "latNE" "lngNE" "weight"]
909* @returns {number} radius between 2 points in metres
910*/
911function mapWidgetComputeCircleRadius(spatialCell, breakpoints) {
912
913 var weight = spatialCell.weight;
914 // Compute weight color
915 var weightColor = 0.25;
916 if (weight >= breakpoints[3]) {
917 weightColor = 1.0;
918 } else if (weight >= breakpoints[2]) {
919 weightColor = 0.75;
920 } else if (weight >= breakpoints[1]) {
921 weightColor = 0.5;
922 }
923
924 // Define Boundary Points
925 var point_center = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
926 var point_left = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, spatialCell.lngSW);
927 var point_top = new google.maps.LatLng(spatialCell.latNE, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
928
929 // TODO not actually a weight color :)
930 return weightColor * 1000 * Math.min(distanceBetweenPoints_(point_center, point_left), distanceBetweenPoints_(point_center, point_top));
931}
932
933/** External Utility Methods **/
934
935/**
936 * Calculates the distance between two latlng locations in km.
937 * @see http://www.movable-type.co.uk/scripts/latlong.html
938 *
939 * @param {google.maps.LatLng} p1 The first lat lng point.
940 * @param {google.maps.LatLng} p2 The second lat lng point.
941 * @return {number} The distance between the two points in km.
942 * @private
943*/
944function distanceBetweenPoints_(p1, p2) {
945 if (!p1 || !p2) {
946 return 0;
947 }
948
949 var R = 6371; // Radius of the Earth in km
950 var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
951 var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
952 var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
953 Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) *
954 Math.sin(dLon / 2) * Math.sin(dLon / 2);
955 var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
956 var d = R * c;
957 return d;
958};