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