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