-
Notifications
You must be signed in to change notification settings - Fork 59
/
Copy pathtreemap.js
executable file
·1084 lines (955 loc) · 41.8 KB
/
treemap.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
tm_icons = {
//base folder for shadow and other icon specific stuff
base_folder : tm_static + 'static/images/map_icons/v3/',
small_trees : tm_static + "static/images/map_icons/v3/UFM_Tree_Icon_zoom7b.png",
small_plots : tm_static + "static/images/map_icons/v3/UFM_Tree_Icon_zoom7_plot.png",
small_trees_complete : tm_static + "static/images/map_icons/v3/UFM_Tree_Icon_zoom7b.png",
focus_tree : tm_static + 'static/images/map_icons/v4/marker-selected.png',
pending_tree : tm_static + 'static/images/map_icons/v4/marker-pending.png',
marker : tm_static + 'static/openlayers/img/marker.png'
};
tm = {
speciesData: null,
map : null,
tree_markers : [],
geocoded_locations: {},
plot_detail_market : null,
current_tile_overlay : null,
current_select_tile_overlay : null,
selected_tile_query : null,
mgr : null,
cur_polygon : null,
geocoder : null,
maxExtent : null,
clckTimeOut : null,
locations: null,
start_zoom: null,
add_start_zoom: null,
add_zoom: null,
google_bounds: null,
panoAddressControl: true,
searchParams: {},
benefitUnitTransformer: function(k,v) { return v; },
//initializes the map where a user places a new tree
get_icon: function(type, size) {
var size = new OpenLayers.Size(size, size);
var offset = new OpenLayers.Pixel(-(size.w/2), -(size.h/2));
if (type == tm_icons.marker) {
size = new OpenLayers.Size(33, 32);
offset = new OpenLayers.Pixel(-(size.w/2), -(size.h));
}
var icon = new OpenLayers.Icon(type, size, offset);
return icon
},
get_tree_marker: function(lat, lng) {
var ll = new OpenLayers.LonLat(lng, lat).transform(new OpenLayers.Projection("EPSG:4326"), tm.map.getProjectionObject());
var marker = new OpenLayers.Marker(ll, tm.get_icon(tm_icons.focus_tree, 19));
return marker
},
add_location_marker: function (ll) {
var icon = tm.get_icon(tm_icons.marker,0);
tm.location_marker = new OpenLayers.Marker(ll, icon);
tm.misc_markers.addMarker(tm.location_marker);
tm.location_marker.events.register("mouseover", tm.location_marker, function(e){
var popupPixel = tm.map.getViewPortPxFromLonLat(this.lonlat);
popupPixel.y += this.icon.offset.y - 25;
tm.smallPopup = new OpenLayers.Popup("popup_address",
tm.map.getLonLatFromPixel(popupPixel),
null,
$("#location_search_input").val(),
false);
tm.smallPopup.minSize = new OpenLayers.Size(20,25);
tm.smallPopup.maxSize = new OpenLayers.Size(150,25);
tm.smallPopup.border = "1px solid Black";
tm.map.addPopup(tm.smallPopup);
tm.smallPopup.updateSize();
});
tm.location_marker.events.register("mouseout", tm.location_marker, function(e){
tm.map.removePopup(tm.smallPopup);
});
},
display_benefits : function(benefits){
$('#results_wrapper').show();
$("#no_results").hide();
$.each(benefits, function(k,v){
$('#benefits_' + k).html(tm.addCommas(parseInt(v)));
});
if (benefits['total'] == 0.0)
{
$("#no_results").show();
}
},
display_summaries : function(summaries){
$(".tree_count").html(tm.addCommas(parseInt(summaries.total_trees)));
$(".plot_count").html(tm.addCommas(parseInt(summaries.total_plots)));
if (summaries.total_trees == '0' && summaries.total_plots == '0')
{
$(".moretrees").html("");
$(".notrees").html("No results? Try changing the filters above.");
} else {
$(".moretrees").html("");
$(".notrees").html("");
}
$.each(summaries, function(k,v){
var span = $('#' + k);
if (span.length > 0){
span.html(tm.addCommas(
tm.benefitUnitTransformer(k,parseInt(v))));
}
});
},
display_search_results : function(results){
if (tm.vector_layer) {tm.vector_layer.destroyFeatures();}
$('#displayResults').hide();
if (results) {
tm.display_summaries(results.summaries);
tm.display_benefits(results.benefits);
tm.tree_layer.setVisibility(false);
if (results.initial_tree_count != results.full_tree_count && !(results.summaries.total_trees == 0 && results.summaries.total_plots == 0)) {
if (results.featureids) {
var cql = results.featureids;
delete tm.tree_layer.params.CQL_FILTER;
tm.tree_layer.mergeNewParams({'FEATUREID':cql});
tm.tree_layer.setVisibility(true);
}
else if (results.tile_query) {
var cql = results.tile_query;
delete tm.tree_layer.params.FEATUREID;
if (tm.set_style) {
var style = tm.set_style(results.tile_query);
tm.tree_layer.mergeNewParams({'CQL_FILTER':cql, 'styles':style});
}
else {
tm.tree_layer.mergeNewParams({'CQL_FILTER':cql, 'styles': tm_urls.geo_style});
}
tm.tree_layer.setVisibility(true);
}
}
if (results.geography) {
var geog = results.geography;
$('#summary_subset_val').html(geog.name);
tm.highlight_geography(geog, 'neighborhood');
} else {
$('#summary_subset_val').html('the region');
}
}
},
highlight_geography : function(geometry, geog_type){
if (tm.vector_layer){
tm.vector_layer.destroyFeatures();
}
if (geometry.coordinates.length == 1) {
var feature = tm.getFeatureFromCoords(geometry.coordinates[0]);
tm.vector_layer.addFeatures(feature);
}
for (var i=0; i<geometry.coordinates.length;i++) {
var feature = tm.getFeatureFromCoords(geometry.coordinates[i][0])
tm.vector_layer.addFeatures(feature);
}
},
enableEditTreeLocation : function(){
tm.trackEvent('Edit', 'Location', 'Start');
tm.drag_control.activate();
//TODO: bounce marker a bit, or change its icon or something
var save_html = '<a href="javascript:tm.saveTreeLocation()" class="buttonSmall"><img src="' + tm_static + 'static/images/loading-indicator-trans.gif" width="12" /> Stop Editing and Save</a>'
$('#edit_tree_location').html(save_html);
return false;
},
saveTreeLocation : function(){
tm.trackEvent('Edit', 'Location', 'Save');
tm.drag_control.activate();
var edit_html = '<a href="#" onclick="tm.enableEditTreeLocation(); return false;"class="buttonSmall">Start Editing Location</a>'
$('#edit_tree_location').html(edit_html);
tm.updateEditableLocation(tm.currentPlotId);
},
validate_point : function(point,address) {
if (!point) {
alert(address + " not found");
return false;
}
var lat_lon = new GLatLng(point.lat(),point.lng(),0);
if (tm.maxExtent && !tm.maxExtent.containsLatLng(lat_lon)){
alert("Sorry, '" + address + "' appears to be too far away from our supported area.");
return false;
}
return true;
},
setupEdit: function(field, model, id, options) {
var editableOptions = {
submit: 'Save',
cancel: 'Cancel',
cssclass: 'activeEdit',
indicator: '<img src="' + tm_static + 'static/images/loading-indicator.gif" alt="" />',
width: '80%',
objectId: id,
model: model,
fieldName: field
};
if (options) {
for (var key in options) {
if (key == "loadurl") {
editableOptions[key] = options[key];
} else {
editableOptions[key] = options[key];
}
}
}
if (model == "Plot") {
$('#edit_'+field).editable(tm.updatePlotServerCall, editableOptions);
} else if (model == "TreeStewardship"){
$('#edit_'+field).editable(tm.addTreeStewardship, editableOptions);
} else if (model == "PlotStewardship"){
$('#edit_'+field).editable(tm.addPlotStewardship, editableOptions);
} else {
$('#edit_'+field).editable(tm.updateEditableServerCall, editableOptions);
}
},
updatePlotServerCall: function(value, settings) {
var data = {};
var plotId = settings.objectId;
var field = settings.fieldName;
data[field] = tm.coerceFromString(value)
this.innerHTML = "Saving..."; //TODO- is this needed?
var jsonString = JSON.stringify(data);
settings.obj = this;
$.ajax({
url: tm_static + 'plots/' + plotId + '/update/',
type: 'POST',
data: jsonString,
complete: function(xhr, textStatus) {
var response = JSON.parse(xhr.responseText);
if (response['success'] != true) {
settings.obj.className = "errorResponse";
settings.obj.innerHTML = "An error occurred in saving: "
$.each(response['errors'], function(i,err){
settings.obj.innerHTML += err;
});
} else {
var value = response['update'][settings.fieldName];
if (settings.fieldName == "width" || settings.fieldName == "length") {
if (value == 99.0) {value = "15+"}
}
settings.obj.innerHTML = value
tm.trackEvent("Edit", settings.fieldName)
}
}});
return "Saving... " + '<img src="' + tm_static + 'static/images/loading-indicator.gif" />';
},
addTreeStewardship: function(value, date, settings) {
var data = {};
var treeId = settings.objectId;
data['activity'] = tm.coerceFromString(value)
data['performed_date'] = tm.coerceFromString(date)
var jsonString = JSON.stringify(data);
settings.obj = this;
$.ajax({
url: tm_static + 'trees/' + treeId + '/stewardship/',
type: 'POST',
data: jsonString,
complete: function(xhr, textStatus) {
var response = JSON.parse(xhr.responseText);
if (response['success'] != true) {
settings.obj.className = "errorResponse";
settings.obj.innerHTML = "An error occurred in saving: "
$.each(response['errors'], function(i,err){
settings.obj.innerHTML += err;
});
} else {
var value = response['update']['activity'];
settings.obj.innerHTML = value
tm.trackEvent("Edit", settings.fieldName)
tm.newTreeActivity();
}
}});
return "Saving... " + '<img src="' + tm_static + 'static/images/loading-indicator.gif" />';
},
addPlotStewardship: function(value, date, settings) {
var data = {};
var plotId = settings.objectId;
data['activity'] = tm.coerceFromString(value)
data['performed_date'] = tm.coerceFromString(date)
var jsonString = JSON.stringify(data);
settings.obj = this;
$.ajax({
url: tm_static + 'plots/' + plotId + '/stewardship/',
type: 'POST',
data: jsonString,
complete: function(xhr, textStatus) {
var response = JSON.parse(xhr.responseText);
if (response['success'] != true) {
settings.obj.className = "errorResponse";
settings.obj.innerHTML = "An error occurred in saving: "
$.each(response['errors'], function(i,err){
settings.obj.innerHTML += err;
});
} else {
var value = response['update']['activity'];
settings.obj.innerHTML = value
tm.trackEvent("Edit", settings.fieldName)
tm.newPlotActivity();
}
}});
return "Saving... " + '<img src="' + tm_static + 'static/images/loading-indicator.gif" />';
},
updateEditableServerCall: function(value, settings) {
var data = {
'model': settings.model,
'update': {
}
};
if (settings.objectId) {
data.id = settings.objectId;
}
value = tm.coerceFromString(value);
$(this).removeClass("error");
if (settings.fieldName == 'species_id') {
if (value == 0) {
$(this).addClass("error");
return "Please select a species from the provided list.";
}
data['update']['species_other1'] = $('#other_species1')[0].value;
data['update']['species_other2'] = $('#other_species2')[0].value;
}
//do some validation for height and canopy height
if ((settings.fieldName == 'height' || settings.fieldName == 'canopy_height') && value > 300) {
$(this).addClass("error");
return "Height is too large.";
}
if (settings.fieldName == 'height' && isNaN(value)) {
$(this).addClass("error");
return "Height must be a number.";
}
if ($.inArray(settings.model, ["TreeAlert","TreeAction","TreeFlags"]) >=0) {
data['update']['value'] = value;
data['update']['key'] = settings.fieldName;
} else {
data['update'][settings.fieldName] = value;
}
if (settings.extraData) {
for (key in settings.extraData) {
data[key] = settings.extraData[key];
}
}
this.innerHTML = "Saving..."; //TODO: Is this needed?
var jsonString = JSON.stringify(data);
settings.obj = this;
$.ajax({
url: tm_static + 'update/',
type: 'POST',
data: jsonString,
complete: function(xhr, textStatus) {
var response = JSON.parse(xhr.responseText);
if (response['success'] != true) {
settings.obj.className = "errorResponse";
settings.obj.innerHTML = "An error occurred in saving: "
$.each(response['errors'], function(i,err){
settings.obj.innerHTML += err;
});
} else {
var value = response['update'][settings.fieldName];
if (!value) {
value = response['update']['value'];
}
if (settings.fieldName == "species_id") {
for (var i = 0; i < tm.speciesData.length; i++) {
if (tm.speciesData[i].id == value) {
value = tm.formatSpeciesName(tm.speciesData[i]);
$("#edit_species").html(tm.speciesData[i].cname);
}
}
var other1 = response['update']['species_other1'];
var other2 = response['update']['species_other2'];
if ($('#edit_species_other').length > 0) {
$('#edit_species_other')[0].innerHTML = other1 + " " + other2;
} else {
$("#edit_species").append('<br>' + other1 + " " + other2);
}
}
if (settings.fieldName == "plot_width" || settings.fieldName == "plot_length") {
if (value == 99.0) {value = "15+"}
}
settings.obj.innerHTML = value;
tm.trackEvent("Edit", settings.fieldName)
}
}});
return "Saving... " + '<img src="' + tm_static + 'static/images/loading-indicator.gif" />';
},
updateEditableLocation: function(currentPlotId) {
$("#edit_map_errors")[0].innerHTML = "Saving..."
var wkt = $('#id_geometry').val();
var geoaddy = $("#id_geocode_address").val();
var data = {
'model': 'Plot',
'id': currentPlotId,
'update': {
geometry: wkt,
geocoded_address: geoaddy
}
};
if (tm.update_address_on_location_update) {
data['update']['address_street'] = geoaddy;
};
var jsonString = JSON.stringify(data);
$.ajax({
url: tm_static + 'update/',
type: 'POST',
data: jsonString,
complete: function(xhr, textStatus) {
var response = JSON.parse(xhr.responseText);
$("#edit_map_errors")[0].innerHTML = ""
$("#edit_map_errors")[0].className = "";
if (response['success'] != true) {
$("#edit_map_errors")[0].className = "errorResponse";
$("#edit_map_errors")[0].innerHTML = "An error occurred in saving: ";
var newError = ""
$.each(response['errors'], function(i,err){
newError += err;
});
if (newError.indexOf("exclusion zone") >= 0 &&
newError.indexOf("Geometry") >= 0) {
$("#edit_map_errors")[0].innerHTML = "An error occurred in saving the location. Trees may not be placed within the white areas.";
} else {
$("#edit_map_errors")[0].innerHTML = newError;
}
} else {
$("#edit_map_errors")[0].innerHTML = "New location saved."
if (tm.update_address_on_location_update) {
$("#edit_address_street")[0].innerHTML = geoaddy;
};
}
}});
},
formatTreeName: function(item) {
var cultivar_portion = item.cultivar ? " '" + item.cultivar + "'" : " ";
return item.cname + " [ " + item.sname + " " + cultivar_portion +
" " + item.other_part + "]";
},
formatSpeciesName: function(item) {
var cultivar_portion = item.cultivar ? " '" + item.cultivar + "'" : " ";
return item.sname + cultivar_portion + item.family +
" " + item.other_part;
},
setupAutoComplete: function(field) {
return field.autocomplete({
source: function(request, response) {
response($.map(tm.speciesData, function(item) {
var lcTerm = request.term.toLowerCase(),
itemIContainsSearchTerm =
(item.cname.toLowerCase().indexOf(lcTerm) !== -1 ||
item.sname.toLowerCase().indexOf(lcTerm) !== -1);
if (itemIContainsSearchTerm) {
return {
label: tm.formatTreeName(item),
value: item.id
};
} else {
return null;
}
}));
},
minLength: 1,
select: function(event, ui) {
field.val(ui.item.label);
$("#species_search_id").val(ui.item.value).change();
if ($("#id_species_id").length > 0) {
$("#id_species_id").val(ui.item.value).change();
}
return false;
}
});
},
newTreeActivity: function() {
return tm.createAttributeDateRow("treeActivityTypeSelection", tm.choices['tree_stewardship'], "treeActivityTable",
tm.handleNewTreeStewardship("treeActivityTypeSelection",
"TreeStewardship",
"treeActivityTable",
"treeActivityCount"));
},
newPlotActivity: function() {
return tm.createAttributeDateRow("plotActivityTypeSelection", tm.choices['plot_stewardship'], "plotActivityTable",
tm.handleNewPlotStewardship("plotActivityTypeSelection",
"PlotStewardship",
"plotActivityTable",
"plotActivityCount"));
},
newAction: function() {
return tm.createAttributeRow("actionTypeSelection", tm.choices['actions'], "actionTable",
tm.handleNewAttribute("actionTypeSelection",
"TreeAction",
"actionTable",
"actionCount", tm.choices['actions']));
},
newLocal: function() {
return tm.createAttributeRow("localTypeSelection", tm.choices['projects'], "localTable",
tm.handleNewAttribute("localTypeSelection",
"TreeFlags",
"localTable",
"localCount", tm.choices['projects']));
},
newHazard: function() {
return tm.createAttributeRow("hazardTypeSelection", tm.choices['alerts'], "hazardTable",
tm.handleNewAttribute("hazardTypeSelection",
"TreeAlert",
"hazardTable",
"hazardCount", tm.choices['alerts']));
},
createAttributeRow: function(selectId, typesArray, tableName, submitEvent) {
var select = $("<select id='" + selectId + "' />");
for (var i=0; i < typesArray.length;i++) {
select.append($("<option value='"+typesArray[i][0]+"'>"+ typesArray[i][1]+"</option>"));
}
var row = $("<tr />");
row.append($(""), $("<td colspan='2' />").append(select)).append(
$("<td />").append(
$("<input type='submit' value='Submit' class='buttonSmall' />").click(submitEvent),
$("<input type='submit' value='Cancel' class='buttonSmall' />").click(function() {
row.remove();
})
)
);
$("#" + tableName).append(row);
},
createAttributeDateRow: function(selectId, typesArray, tableName, submitEvent) {
var select = $("<select id='" + selectId + "' />");
for (var i=0; i < typesArray.length;i++) {
select.append($("<option value='"+typesArray[i][0]+"'>"+ typesArray[i][1]+"</option>"));
}
var row = $("<tr id='data-row' />");
row.append(
$(""),
$("<td />").append(select),
$("<td />").append($("<input id='" + selectId + "-datepicker' type='text'>").datepicker({ maxDate: "+0d" })),
$("<td />").append(
$("<input type='submit' value='Submit' class='buttonSmall' />").click(submitEvent),
$("<input type='submit' value='Cancel' class='buttonSmall' />").click(function() {
row.remove();
})
)
);
$("#" + tableName).append(row);
},
handleNewTreeStewardship: function(select, model, table, count) {
return function() {
var data = $("#" + select)[0].value;
var data_date = $("#" + select + "-datepicker")[0].value;
if (data == "" || data_date == "") {
alert("You must enter a date for the tree activity.");
return;
}
settings = {
model: model,
objectId: tm.currentTreeId,
activity: data,
submit: 'Save',
cancel: 'Cancel'
};
$(this.parentNode.parentNode).remove();
tm.addTreeStewardship(data, data_date, settings);
var choices = tm.choices['tree_stewardship'];
for (var i=0;i<choices.length; i++) {
if (choices[i][0] == data) {
$("#" + table).append(
$("<tr><td>"+choices[i][1]+"</td><td>"+data_date+"</td><td></td></tr>"));
$("#" + count).html(parseInt($("#" + count)[0].innerHTML) + 1);
break;
}
}
};
},
handleNewPlotStewardship: function(select, model, table, count) {
return function() {
var data = $("#" + select)[0].value;
var data_date = $("#" + select + "-datepicker")[0].value;
if (data == "" || data_date == "") {
alert("You must enter a date for the planting site activity.");
return;
}
settings = {
model: model,
objectId: tm.currentPlotId,
activity: data,
performed_date: data_date,
submit: 'Save',
cancel: 'Cancel'
};
$(this.parentNode.parentNode).remove();
tm.addPlotStewardship(data, data_date, settings);
var choices = tm.choices['plot_stewardship'];
for (var i=0;i<choices.length; i++) {
if (choices[i][0] == data) {
$("#" + table).append(
$("<tr><td>"+choices[i][1]+"</td><td>"+data_date+"</td><td></td></tr>"));
$("#" + count).html(parseInt($("#" + count)[0].innerHTML) + 1);
break;
}
}
};
},
handleNewAttribute: function(select, model, table, count, data_array) {
return function() {
var data = $("#" + select)[0].value;
settings = {
'extraData': {
'parent': {
'model': 'Tree',
'id': tm.currentTreeId
}
},
model: model,
fieldName: data,
submit: 'Save',
cancel: 'Cancel'
};
$(this.parentNode.parentNode).remove();
var d = new Date();
var dateStr = (d.getYear()+1900)+"-"+(d.getMonth()+1)+"-"+d.getDate();
tm.updateEditableServerCall(dateStr, settings)
for (var i=0;i<data_array.length; i++) {
if (data_array[i][0] == data) {
$("#" + table).append(
$("<tr><td>"+data_array[i][1]+"</td><td>"+dateStr+"</td><td></td></tr>"));
$("#" + count).html(parseInt($("#" + count)[0].innerHTML) + 1);
break;
}
}
};
},
//TODO: These don't delete from the database
deleteAction: function(key, value, elem) {
$(elem.parentNode.parentNode).remove();
},
deleteHazard: function(key, value, elem) {
$(elem.parentNode.parentNode).remove();
},
deleteLocal: function(key, value, elem) {
$(elem.parentNode.parentNode).remove();
},
deleteTreeActivity: function(id, elem) {
$.ajax({
url: tm_static + 'trees/' + tm.currentTreeId + "/stewardship/" + id + "/delete/",
complete: function(xhr, textStatus) {
$(elem.parentNode.parentNode).remove();
$("#treeActivityCount").html(parseInt($("#treeActivityCount")[0].innerHTML) - 1);
}
});
},
deletePlotActivity: function(id, elem) {
$.ajax({
url: tm_static + 'plots/' + tm.currentPlotId + "/stewardship/" + id + "/delete/",
complete: function(xhr, textStatus) {
$(elem.parentNode.parentNode).remove();
$("#plotActivityCount").html(parseInt($("#plotActivityCount")[0].innerHTML) - 1);
}
});
},
pageLoadSearch: function () {
tm.loadingSearch = true;
tm.searchParams = {};
var params = $.address.parameterNames();
if (params.length) {
for (var i = 0; i < params.length; i++) {
var key = params[i];
var val = $.address.parameter(key);
tm.searchParams[key] = val;
if (val == "true") {
$("#"+key).attr('checked', true);
}
if (key == "diameter_range") {
var dvals = $.address.parameter(key).split("-");
$("#diameter_slider").slider('values', 0, dvals[0]);
$("#diameter_slider").slider('values', 1, dvals[1]);
}
if (key == "planted_range") {
var pvals = $.address.parameter(key).split("-");
$("#planted_slider").slider('values', 0, pvals[0]);
$("#planted_slider").slider('values', 1, pvals[1]);
}
if (key == "updated_range") {
var uvals = $.address.parameter(key).split("-");
$("#updated_slider").slider('values', 0, uvals[0]);
$("#updated_slider").slider('values', 1, uvals[1]);
}
if (key == "height_range") {
var hvals = $.address.parameter(key).split("-");
$("#height_slider").slider('values', 0, hvals[0]);
$("#height_slider").slider('values', 1, hvals[1]);
}
if (key == "plot_range") {
var plvals = $.address.parameter(key).split("-");
$("#plot_slider").slider('values', 0, plvals[0]);
$("#plot_slider").slider('values', 1, plvals[1]);
}
if (key == "species") {
tm.updateSpeciesFields('species_search',$.address.parameter(key), '');
}
if (key == "location") {
tm.updateLocationFields($.address.parameter(key).replace(/\+/g, " "));
}
if (key == "tree_stewardship") {
$("#steward-tree").click();
var actions = val.split(',');
for (j=0;j<actions.length;j++) {
$(".steward-action[value=" + actions[j] + "]").click();
}
}
if (key == "plot_stewardship") {
$("#steward-plot").click();
var actions = val.split(',');
for (k=0;k<actions.length;k++) {
$(".steward-action[value=" + actions[k] + "]").click();
}
}
if (key == "stewardship_reverse") {
$(".steward-reverse[value=" + val + "]").click();
}
if (key == "stewardship_range") {
var svals = $.address.parameter(key).split("-");
var date1 = new Date(parseInt(svals[0] * 1000));
var date2 = new Date(parseInt(svals[1] * 1000));
$("#steward-date-1").datepicker("setDate", date1).change();
$("#steward-date-2").datepicker("setDate", date2).change();
}
}
}
tm.loadingSearch = false;
tm.updateSearch();
},
serializeSearchParams: function() {
var q = $.query.empty();
for (var key in tm.searchParams) {
if (!tm.searchParams[key]){
continue;
}
var val = tm.searchParams[key];
q = q.set(key, val);
}
if (tm.handleStewardship) {
q = tm.handleStewardship(q);
}
var qstr = decodeURIComponent(q.toString()).replace(/\+/g, "%20")
if (qstr != '?'+$.query.toString()) {
if (!tm.loadingSearch) {
$.query.load(qstr);
}
}
return qstr;
},
updateSearch: function() {
if (tm.loadingSearch) { return; }
var qs = tm.serializeSearchParams();
$("#kml_link").attr('href', tm_static + "search/kml/"+qs);
$("#csv_link").attr('href', tm_static + "search/csv/"+qs);
$("#shp_link").attr('href', tm_static + "search/shp/"+qs);
if (qs === false) { return; }
tm.trackPageview('/search/' + qs);
$('#displayResults').show();
$.ajax({
url: tm_static + 'search/'+qs,
dataType: 'json',
success: tm.display_search_results,
error: function(err) {
$('#displayResults').hide();
alert("There was an error while executing your search");
}
});
},
updateLocationFields: function(loc){
if (loc){
$("#location_search_input").val(loc);
tm.handleSearchLocation(loc);
}
},
updateSpeciesFields: function(field_prefix, spec){
if (!tm.speciesData) {
return;
}
if (spec) {
$("#" + field_prefix + "_id").val(spec);
for (var i = 0; i < tm.speciesData.length; i++) {
if (tm.speciesData[i].id == spec) {
$("#" + field_prefix + "_input").val(tm.speciesData[i].cname + " [ " + tm.speciesData[i].sname + " ]");
break;
}
}
}
},
add_favorite_handlers : function(base_create, base_delete) {
$('.favorite.fave').live('click', function(e) {
var pk = $(this).attr('id').replace('favorite_', '');
var url = base_create + pk + '/';
$.getJSON(tm_static + url, function(data, textStatus) {
$('#favorite_' + pk).removeClass('fave').addClass('unfave');
$('#favorite_' + pk).html('Remove as favorite');
});
tm.trackEvent('Favorite', 'Add Favorite', 'Tree', pk);
return false;
});
$('.favorite.unfave').live('click', function(e) {
var pk = $(this).attr('id').replace('favorite_', '');
var url = base_delete + pk + '/';
$.getJSON(tm_static + url, function(data, textStatus) {
$('#favorite_' + pk).removeClass('unfave').addClass('fave');
$('#favorite_' + pk).html('Add as favorite');
});
tm.trackEvent('Favorite', 'Remove Favorite', 'Tree', pk);
return false;
});
},
/**
* Determine if "search" is a zipcode, neighborhood, or address
* and then <do more search stuff>
*/
handleSearchLocation: function(search) {
if (tm.misc_markers) {tm.misc_markers.clearMarkers();}
if (tm.vector_layer) {tm.vector_layer.destroyFeatures();}
tm.geocode_address = search;
// clean up any previous location search params
delete tm.searchParams.location;
delete tm.searchParams.geoName;
delete tm.searchParams.lat;
delete tm.searchParams.lon;
function continueSearchWithFeature(nbhoods) {
var bbox = OpenLayers.Bounds.fromArray(nbhoods.bbox).transform(new OpenLayers.Projection("EPSG:4326"), tm.map.getProjectionObject());
tm.map.zoomToExtent(bbox, true);
tm.add_location_marker(bbox.getCenterLonLat());
var featureName = nbhoods.features[0].properties.name;
if (featureName) {
tm.searchParams['geoName'] = featureName;
}
else {
featureName = nbhoods.features[0].properties.zip;
tm.searchParams['location'] = featureName;
tm.geocoded_locations[search] = featureName;
}
tm.updateSearch();
}
// Search order:
// -> If the string is a number, assume it is a zipcode and search by zipcode
// -> Otherwise:
// -> Check the string aginst the neighborhoods table
// -> Otherwise assume it's an address
if (tm.isNumber(search)) {
$.getJSON(tm_static + 'zipcodes/', {format:'json', name: search}, function(zips){
if (tm.location_marker) {tm.misc_markers.removeMarker(tm.location_marker)}
if (zips.features.length > 0) {
continueSearchWithFeature(zips);
}
});
}
else
{
$.getJSON(tm_static + 'neighborhoods/', {format:'json', name: search}, function(nbhoods){
if (tm.location_marker) {tm.misc_markers.removeMarker(tm.location_marker)}
if (nbhoods.features.length > 0) {
continueSearchWithFeature(nbhoods);
} else {
tm.geocode(search, function(lat, lng, place) {
var olPoint = new OpenLayers.LonLat(lng, lat);
var llpoint = new OpenLayers.LonLat(lng, lat).transform(new OpenLayers.Projection("EPSG:4326"), tm.map.getProjectionObject());
tm.map.setCenter(llpoint, tm.add_zoom);
tm.add_location_marker(llpoint);
tm.geocoded_locations[search] = [olPoint.lon, olPoint.lat];
tm.searchParams['lat'] = olPoint.lat;
tm.searchParams['lon'] = olPoint.lon;
tm.updateSearch();
});
}
});
}
},
editDiameter: function(field, diams) {
// no value: show box
// one value: show box w/ value
// many values: show boxes w/ split values
if (!$.isArray(diams)) {diams=[0];}
//diams is either [0] or an array of what's there by this point
diams = tm.currentTreeDiams || diams;
var html = '';
tm.currentDiameter = $(field).html();
if ($.isArray(diams)){
for (var i = 0; i < Math.max(diams.length, 1); i++) {
var val = '';
if (diams[i]) { val = parseFloat(diams[i].toFixed(3)); }
html += "<input type='text' size='7' id='dbh"+i+"' name='dbh"+i+"' value='"+val+"' />";
if (i == 0) {
html += "<br /><input type='radio' id='diam' checked name='circum' /><label for='diam'><small>Diameter</small></label><input type='radio' id='circum' name='circum' /><label for='circum'><small>Circumference</small></label>"
}
html += "<br />";
}
} else {
html += "<input type='text' size='7' id='dbh0' name='dbh0' value='"+ parseFloat(diams).toFixed(3) + "' />";