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