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