map.jsp 45.1 KB
Newer Older
1
2
<!DOCTYPE html>

3
<%@ include file="/WEB-INF/jsp/init.jsp" %>
4
5
6

<html>
<head>
Alexander Basov's avatar
Alexander Basov committed
7
    <title><spring:message code="maps.accession-map"/></title>
8
    <script type="text/javascript" src="<c:url value="${cdnServers.next}/html/1/js/browse.js" />"></script>
Maxim's avatar
Maxim committed
9
    <script type="text/javascript" src="<c:url value="/explore/i18n.js"/>"></script>
10
</head>
Maxim's avatar
Maxim committed
11
<body class="map-page overview-page explore-page">
Alexander Basov's avatar
Alexander Basov committed
12
13
<cms:informative-h1 title="maps.accession-map" fancy="true" info="maps.accession-map.intro"/>

Maxim's avatar
Maxim committed
14
15
<div class="container-fluid">

Maxim's avatar
Maxim committed
16
17
18
19
20
21
22
23
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content"></div>
        </div>
    </div>
    <!--End modal-->

Maxim's avatar
Maxim committed
24
25
    <div class="">
        <filters:filter-list availableFilters="${availableFilters}" filters="${filters}"
Maxim's avatar
Maxim committed
26
                             additionalFilters="${additionalFilters}" appliedFilters="${appliedFilters}"
27
                             crops="${crops}" crop="${crop}" geoRegions="${geoRegions}"/>
Maxim's avatar
Maxim committed
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

        <div class="col-lg-10 col-md-9 col-sm-9 col-xs-12 main-col-header">
            <div class="nav-header clearfix">

                <div class="pull-right list-view-controls">

                    <div class="btn-group" id="shareLink">
                        <a type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown"
                           aria-haspopup="true" aria-expanded="false" id="menuShareLink">
                            <span class="glyphicon glyphicon-share"></span>
                            <span><spring:message code="share.link"/></span>
                            <span class="caret"></span>
                        </a>
                        <ul class="dropdown-menu">
                            <li class="padding10">
                                <p><spring:message code="share.link.text"/></p>
                                <input id="shortLink" type="text"
                                       placeholder="<spring:message code="share.link.placeholder" />" value=""/>
                            </li>
                        </ul>
                    </div>

                    <a class="btn btn-default" id="exploreLink"
                       href="<c:url value="/explore"><c:param name="filter" value="${jsonFilter}" /></c:url>">
                        <span class="glyphicon glyphicon-list"></span>
                        <span style="margin-left: 0.5em;"><spring:message code="view.accessions"/></span></a>
                    <a class="btn btn-default" id="overviewLink"
Maxim's avatar
Maxim committed
55
                       style=${(empty additionalFilters)? "'display: inline'": "'display: none'" }
Maxim's avatar
Maxim committed
56
57
58
59
60
                       href="<c:url value="/explore/overview"><c:param name="filter">${jsonFilter}</c:param></c:url>">
                        <span class="glyphicon glyphicon-eye-open"></span>
                        <span><spring:message code="data-overview.short"/></span>
                    </a>

Taisiya Glushko's avatar
Taisiya Glushko committed
61
                    <%--<a class="btn btn-default" href="<c:url value="/explore" />" id="selectArea">
Maxim's avatar
Maxim committed
62
63
                        <span class="glyphicon glyphicon-list"></span>
                        <span><spring:message code="view.accessions"/></span>
Taisiya Glushko's avatar
Taisiya Glushko committed
64
                    </a>--%>
Maxim's avatar
Maxim committed
65

66
                    <form style="display: inline-block" method="post" id="downloadKml" action="<c:url value="/explore/kml" />">
Maxim's avatar
Maxim committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
                        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
                        <input type="hidden" name="filter" value="<c:out value="${jsonFilter}" />"/>
                        <button class="btn btn-default" type="submit">
                            <span class="glyphicon glyphicon-save"></span>
                            <span><spring:message code="download.kml"/></span>
                        </button>
                    </form>
                </div>

                <div class="pull-left list-view-controls">
                    <a class="btn btn-default btn-back" href="">
                        <spring:message code="navigate.back"/></a>
                </div>

            </div>
Alexander Basov's avatar
Alexander Basov committed
82
83

        </div>
Maxim's avatar
Maxim committed
84
85
86
87
88


        <div class="col-lg-10 col-md-9 col-sm-9 col-xs-12" id="content-area">

            <!-- Modal -->
89
            <div class="modal fade" id="modal-dialog" tabindex="-1" role="dialog" aria-labelledby="modal-label">
Maxim's avatar
Maxim committed
90
91
92
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
93
94
95
96
                            <button type="button" class="close" data-dismiss="modal">
                                <span>&times;</span>
                                <span class="sr-only">Close</span>
                            </button>
Maxim's avatar
Maxim committed
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
                            <h4 class="modal-title" id="modal-label"><spring:message code="savedmaps.save"/></h4>
                        </div>
                        <div class="modal-body">
                            <input type="text" class="form-control"
                                   placeholder="<spring:message code="filter.enter.title"/>"
                                   id="filter-title">

                            <div id="color">
                                <select name="colorpicker">
                                    <option value="#7bd148">#7bd148</option>
                                    <option value="#5484ed">#5484ed</option>
                                    <option value="#a4bdfc">#a4bdfc</option>
                                    <option value="#46d6db">#46d6db</option>
                                    <option value="#7ae7bf">#7ae7bf</option>
                                    <option value="#51b749">#51b749</option>
                                    <option value="#fbd75b">#fbd75b</option>
                                    <option value="#ffb878">#ffb878</option>
                                    <option value="#ff887c">#ff887c</option>
                                    <option value="#dc2127">#dc2127</option>
                                    <option value="#dbadff">#dbadff</option>
                                    <option value="#e1e1e1">#e1e1e1</option>
                                </select>
                            </div>
                        </div>
                        <div class="modal-footer">
122
123
124
125
126
127
128
                            <div class="alert alert-danger" id="existingTitleError" style="display: none">
                                <spring:message code="savedmaps.existing-title.error"/>
                            </div>
                            <div class="alert alert-danger" id="emptyTitleError" style="display: none">
                                <spring:message code="savedmaps.empty-title.error"/>
                            </div>
                            <button type="button" id="cancel-filter-save" class="btn btn-primary">
129
130
                                <spring:message code="cancel"/>
                            </button>
131
                            <button id="save-filter" type="button" class="btn btn-primary">
132
133
                                <spring:message code="save"/>
                            </button>
Maxim's avatar
Maxim committed
134
135
136
137
138
139
140
141
142
                        </div>
                    </div>
                </div>
            </div>
            <%--End modal--%>


            <div class="row map-wrapper">
                <div class="map-container">
Taisiya Glushko's avatar
Taisiya Glushko committed
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
                    <div class="applied-filters">
                        <ul class="nav nav-pills ">
                            <li style="margin-left: 5px" class="active dropdown form-horizontal pull-right">
                                <a class="dropdown-toggle btn-primary" data-toggle="dropdown" href="#">
                                    <spring:message code="maps.baselayer.list"/>
                                </a>
                                <ul class="dropdown-menu">
                                    <li>
                                        <%--<label class="label-map-provider">--%>
                                        <%--<input class="map-provider"--%>
                                        <%--value="mapQuest"--%>
                                        <%--name="provider"--%>
                                        <%--style='margin-right: 10px;margin-left: 5px' type='radio'>MapQuest</label>--%>
                                        <label class="label-map-provider">
                                            <input name="provider" value="openstreetmap" class="map-provider"
                                                   style='margin-right: 10px;margin-left: 5px'
                                                   type='radio'>Openstreetmap</label>
                                        <label class="label-map-provider">
                                            <input name="provider" value="esriGray" class="map-provider"
                                                   style='margin-right: 10px;margin-left: 5px'
                                                   type='radio'>ESRI Gray</label>
                                        <label class="label-map-provider">
                                            <input name="provider" value="esriTopo" class="map-provider"
                                                   style='margin-right: 10px;margin-left: 5px'
                                                   type='radio'>ESRI Topo</label>
                                    </li>
                                </ul>
                            </li>
                            <li class="active dropdown form-horizontal pull-right">
                                <a id="get-filters" class="btn-primary" href="#">
                                    <spring:message code="savedmaps.list"/>
                                </a>
                                <ul id="enabled-filters" class="dropdown-menu"></ul>
                            </li>
                            <li style="margin-right: 5px" class="active form-horizontal pull-right" data-toggle="modal"
                                data-target="#modal-dialog">
                                <a id="remember-map" class="btn-primary" href="#">
                                    <spring:message code="savedmaps.save"/>
                                </a>
                            </li>
                        </ul>
                    </div>
Maxim's avatar
Maxim committed
185
186
187
                    <div id="map" class="gis-map gis-map-square"></div>
                </div>
            </div>
Alexander Basov's avatar
Alexander Basov committed
188
189
190
        </div>
    </div>
</div>
191

Maxim's avatar
Maxim committed
192
<content tag="javascript">
Maxym Borodenko's avatar
Maxym Borodenko committed
193
194
195
196
197
198
199
    <script type="text/javascript">
        var jsonData = ${jsonFilter};
        localStorage.setItem("historyStep", 1);
        var mapProviders = getMapProviders();
        var cookieUtils = getCookieUtils();
        var map = null;
        var layer = null;
Taisiya Glushko's avatar
Taisiya Glushko committed
200

Maxym Borodenko's avatar
Maxym Borodenko committed
201
        $(document).ready(function () {
202
203
            $('#explore-li').find("a").addClass('active active-group');
            $('#explore-li').addClass('active');
Taisiya Glushko's avatar
Taisiya Glushko committed
204
205

            setHeight();
Maxym Borodenko's avatar
Maxym Borodenko committed
206
            map = L.map('map').setView([30, 0], 3);
Taisiya Glushko's avatar
Taisiya Glushko committed
207
208
209
210
211
212
213
214
215

            $(window).resize(function() {
                setHeight();
            });
            $(document).on('click', 'a[href*=#collapseFilters]', function() {
                $(this).toggleClass('closed');
                setHeight($(this).hasClass('closed'));
            });

Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
216
            BrowseUtil.applySuggestions(jsonData, messages);
Maxim's avatar
Maxim committed
217
218
219
220
221
222
223
224
225
226
227
            $("#panel_additional_id").hide();

            if (jsonData.crops != null && jsonData.crops.length > 0) {
                $("#panel_additional_id").show();
            }

            $.each(jsonData, function(key) {
                if(key.startsWith('gm:')) {
                    $("#panel_additional_id").show();
                }
            });
igoshin's avatar
igoshin committed
228

Maxim's avatar
Maxim committed
229
230
231
232
233
            $(document.getElementsByClassName("btn btn-default btn-back")).on('click', function (event) {
                event.preventDefault();
                var stepValue = localStorage.getItem("historyStep");
                window.history.go(-stepValue);
            });
igoshin's avatar
igoshin committed
234

Maxim's avatar
Maxim committed
235
236
237
238
239
240
            $('#collapseFilters').on('hidden.bs.collapse', function () {
                $("#content-area").addClass('fullwidth');
                map._onResize();
            }).children().on('hidden.bs.collapse', function () {
                return false;
            });
igoshin's avatar
igoshin committed
241

242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
            if(JSON.stringify(jsonData) == "{}") {
                useDefoultBoundingBox();
            }
            else {
                var notEmptyFilters = false;
                <c:forEach items="${appliedFilters}" var="appliedFilter">
                    <c:set var="normalizedAppliedFilter" value="${appliedFilter.key.replace(':', '_')}"/>
                    var collapseDiv = $(this).find($("div[id*='${normalizedAppliedFilter}']"));
                    if (collapseDiv[0] !== undefined) {
                        notEmptyFilters = true;
                    }
                </c:forEach>

                if(notEmptyFilters == false) {
                    useDefoultBoundingBox();
                }
            }

Maxim's avatar
Maxim committed
260
261
            $.each($('#collapseFilters').find("div.panel-collapse"), function () {
                <c:forEach items="${appliedFilters}" var="appliedFilter">
Maxym Borodenko's avatar
Maxym Borodenko committed
262
263
264
265
                    <c:set var="normalizedAppliedFilter" value="${appliedFilter.key.replace(':', '_')}"/>
                    var collapseDiv = $(this).find($("div[id*='${normalizedAppliedFilter}']"));
                    if (collapseDiv[0] !== undefined) {
                        $(this).collapse("show");
266
267
268
                        if(!$(this).is('#panel_additional_collapse')) {
                            $(this).children().children().find('.applyBtn').removeClass('disabled');
                        }
Maxym Borodenko's avatar
Maxym Borodenko committed
269
                    }
Maxim's avatar
Maxim committed
270
271
                </c:forEach>
            });
igoshin's avatar
igoshin committed
272

273
            $('body').on('input', '.panel-group .input-group .form-control', function () {
274
                BrowseUtil.validateInput($(this));
275
276
            });

Maxim's avatar
Maxim committed
277
            GenesysFilterUtil.registerAutocomplete(".filters", jsonData);
igoshin's avatar
igoshin committed
278

Maxim's avatar
Maxim committed
279
280
281
282
283
            $("body").on("keypress", ".string-type", function (e) {
                if (e.keyCode == 13) {
                    var btn = $(this).parent().find("button");
                    var selectedValue = $(this).parent().parent().find(".like-switcher option:selected").val();
                    if (selectedValue == "like") {
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
284
                        GenesysFilter.filterLike(btn, jsonData, BrowseUtil.i18nFilterMessage);
Maxim's avatar
Maxim committed
285
286
287
288
289
                    } else {
                        GenesysFilter.filterAutocomplete(btn, jsonData);
                    }
                }
            });
igoshin's avatar
igoshin committed
290

Maxim's avatar
Maxim committed
291
            $("body").on("click", ".filter-auto", function () {
292
293
294
295
296
                var filterVal = $(this).parent().parent().find('.string-type').val();
                if($.trim(filterVal) !== '') {
                    $(this).parent().parent().parent().find('.applyBtn').removeClass('disabled');
                }

Maxim's avatar
Maxim committed
297
                if (jsonData[$(this).attr("i-key")] === undefined) {
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
298
                    BrowseUtil.enableFilter(this, jsonData);
Maxim's avatar
Maxim committed
299
                }
igoshin's avatar
igoshin committed
300

Maxim's avatar
Maxim committed
301
                var selectedValue = $(this).parent().parent().parent().find(".like-switcher option:selected").val();
302
                if (selectedValue === 'like') {
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
303
                    GenesysFilter.filterLike($(this), jsonData, BrowseUtil.i18nFilterMessage);
Maxim's avatar
Maxim committed
304
305
306
307
                } else {
                    GenesysFilter.filterAutocomplete($(this), jsonData);
                }
            });
Alexander Basov's avatar
Alexander Basov committed
308

309
            $("body").on("change", ".geo-switcher", function () {
310
                $(this).parent().parent().parent().find('.applyBtn').removeClass('disabled');
311
312
313
314
315
316
                if (jsonData[$(this).attr("i-key")] === undefined) {
                    BrowseUtil.enableFilter(this, jsonData);
                }
                GenesysFilter.filterSelectList($(this), jsonData);
            });

Maxim's avatar
Maxim committed
317
            $("body").on("click", ".filter-list", function () {
318
319
                var parentEl = $(this).parent().parent().parent();
                $(this).parent().parent().parent().find('.applyBtn').removeClass('disabled');
Maxim's avatar
Maxim committed
320
                if (jsonData[$(this).attr("i-key")] === undefined) {
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
321
                    BrowseUtil.enableFilter(this, jsonData);
Maxim's avatar
Maxim committed
322
323
324
325
                }
                var text = $(this).parent().text();
                text = text.substring(0, text.indexOf('('));
                GenesysFilter.filterList($(this), jsonData, text);
326
327
328
329
330
331
332
333
334
335

                if(!$(this).is(':checked')) {
                    var needToApply = true;
                    $.each($(parentEl).find('.filtval'), function () {
                        needToApply = false;
                    });
                    if(needToApply) {
                        applyFilters();
                    }
                }
Maxim's avatar
Maxim committed
336
            });
igoshin's avatar
igoshin committed
337

Maxim's avatar
Maxim committed
338
339
            $("body").on("click", ".filter-range", function () {
                if (jsonData[$(this).attr("i-key")] === undefined) {
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
340
                    BrowseUtil.enableFilter(this, jsonData);
Maxim's avatar
Maxim committed
341
                }
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
342
                GenesysFilter.filterRange($(this), jsonData, BrowseUtil.i18nFilterMessage);
Maxim's avatar
Maxim committed
343
            });
344

Maxim's avatar
Maxim committed
345
            $("body").on("click", ".filter-bool", function () {
346
347
                var parentEl = $(this).parent().parent().parent();
                $(this).parent().parent().parent().find('.applyBtn').removeClass('disabled');
Maxim's avatar
Maxim committed
348
                if (jsonData[$(this).attr("i-key")] === undefined) {
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
349
                    BrowseUtil.enableFilter(this, jsonData);
Maxim's avatar
Maxim committed
350
                }
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
351
                GenesysFilter.filterBoolean($(this), jsonData, BrowseUtil.i18nFilterMessage);
352
353
354
355
356
357
358
359
360
361

                if(!$(this).is(':checked')) {
                    var needToApply = true;
                    $.each($(parentEl).find('.filtval'), function () {
                        needToApply = false;
                    });
                    if(needToApply) {
                        applyFilters();
                    }
                }
Maxim's avatar
Maxim committed
362
            });
363

Maxim's avatar
Maxim committed
364
            $('body').on('click', '.filter-crop', function () {
365
                $(this).parent().parent().find('.applyBtn').removeClass('disabled');
Maxim's avatar
Maxim committed
366
367
                GenesysFilter.filterCrop($(this), jsonData);
            });
Alexander Basov's avatar
Alexander Basov committed
368

Maxim's avatar
Maxim committed
369
370
371
372
373
            $("body").on("click", ".filtval", function (event) {
                event.preventDefault();
                var key = $(this).attr("i-key");
                var normKey = GenesysFilter.normKey(key);
                var value = $(this).attr("x-key").replace(normKey, "");
Alexander Basov's avatar
Alexander Basov committed
374

375
                if (value === 'null') value = null;
Maxim's avatar
Maxim committed
376
377
                GenesysFilterUtil.removeValue(value, key, jsonData);
                applyFilters();
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
378
                BrowseUtil.applySuggestions(jsonData, messages);
Alexander Basov's avatar
Alexander Basov committed
379

380
381
382
383
384
385
386
387
388
389
                var needToDisableBtn = true;
                $.each($(this).parent().find('.filtval'), function (index) {
                    if(index > 0) {
                        needToDisableBtn = false;
                    }
                });

                if (needToDisableBtn === true) {
                    $(this).parent().find('.applyBtn').addClass('disabled');
                }
Maxim's avatar
Maxim committed
390
                $(this).remove();
391
                $('input[i-key="' + key + '"][value="' + value + '"]').prop('checked', false);
Maxim's avatar
Maxim committed
392

393
                if (jsonData["crops"] !== undefined && jsonData["crops"].length === 0) {
Maxim's avatar
Maxim committed
394
395
396
                    delete jsonData["crops"];
                    $("#panel_additional_id").hide();
                }
Maxim's avatar
Maxim committed
397
            });
Alexander Basov's avatar
Alexander Basov committed
398

Maxym Borodenko's avatar
Maxym Borodenko committed
399
400
401
402
403
404
405
406
            $("body").on("input paste", ".date-input", function (e) {
                e.preventDefault();
                var key = e.keyCode || e.charCode;
                var val = $(this).val();
                var len = $(this).val().length;
                var lastChar = val.substring(len, len-1);
                var isDigit = lastChar.match(/^[0-9]+$/) != null;
                var date = this.value;
407
                if (key === 8 || key === 46 && lastChar === '-')
Maxym Borodenko's avatar
Maxym Borodenko committed
408
409
410
411
412
413
414
415
416
417
418
419
420
                    return;
                if (this.value.length > 10) {
                    this.value = date.substring(0, 10);
                } else {
                    if (isDigit) {
                        if (date.match(/^\d{4}$/) !== null) {
                            this.value = date + '-';
                        } else if (date.match(/^\d{4}\-\d{2}$/) !== null) {
                            this.value = date + '-';
                        }
                    }
                    else {
                        this.value = val.substring(0, len-1);
421
                        BrowseUtil.validateInput($(this));
Maxym Borodenko's avatar
Maxym Borodenko committed
422
423
424
425
                    }
                }
            });

Maxim's avatar
Maxim committed
426
427
428
429
430
431
432
433
434
435
            $("body").on("change", "#more-filters", function () {
                var key = $(this).val();
                var normKey = GenesysFilterUtil.normKey(key);
                var input = $(this).parent().find("input[type='text']");
                input.attr('id', normKey + "_input");
                if (key == "institute.country.iso3") {
                    input.attr('x-source', "/explore/ac/orgCty.iso3");
                } else {
                    input.attr('x-source', "/explore/ac/" + key);
                }
Alexander Basov's avatar
Alexander Basov committed
436

Maxim's avatar
Maxim committed
437
438
439
440
441
                var btn = $(this).parent().find("button.filter-auto");
                btn.attr("norm-key", normKey);
                btn.attr("i-key", key);
                jsonData[key] = [];
            });
Alexander Basov's avatar
Alexander Basov committed
442

Maxim's avatar
Maxim committed
443
            $('#remember-map').on('click', function(e) {
444
445
446
447
              e.preventDefault();
              $("#filter-title").val('');
              $('#existingTitleError').hide();
              $('#emptyTitleError').hide();
Maxim's avatar
Maxim committed
448
            });
Maxim's avatar
Maxim committed
449

Maxim's avatar
Maxim committed
450
451
452
453
454
455
456
            $("body").on("click", ".addFiltersBtn", function () {
                $.ajax("<c:url value="/modal" />", {
                    type: 'GET',
                    data: "shortName=" + jsonData.crops,
                    success: function (data) {
                        $(".modal-content").empty();
                        $(".modal-content").append(data);
Maxim's avatar
Maxim committed
457

Maxim's avatar
Maxim committed
458
459
460
461
462
463
464
465
                        for (var additionalFilterName in jsonData) {
                            $(".modal-body .filter-block label > input[value='" + additionalFilterName + "']").prop("checked", true);
                        }
                    },
                    error: function (error) {
                        console.log(error);
                    }
                });
Maxim's avatar
Maxim committed
466
467
            });

Maxim's avatar
Maxim committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
            $("body").on("click", ".additional", function () {
                var id = $(this).attr("id");
                var filterId = "#panel_" + id.replace("_id", "");
                var filter = id.replace("gm_", "gm:").replace("_id", "");

                if ($(this).is(":checked")) {
                    GenesysFilterUtil.appendFilter(filter, filterId, jsonData);
                    $("#overviewLink").hide();
                }
                else {
                    delete jsonData[filter];
                    $(filterId).remove();
                    $("#overviewLink").show();
                }
            });

            $("body").on("click", ".removeFilterBtn", function () {
                var className = $(this).parent().parent().attr("class");
Maxim's avatar
Maxim committed
486
487
                var filterId = "#panel_" + className.replace(" col-xs-12", "");
                var filter = className.replace("gm_", "gm:").replace("_id", "").replace(" col-xs-12", "");
Maxim's avatar
Maxim committed
488
489
490
491
492
493
494
495
496
497
498
499
500
501

                delete jsonData[filter];
                $(filterId).remove();

                if (!isExistAdditionalFilters()) {
                    $("#overviewLink").show();

                    if (jsonData.crops == null || jsonData.crops.length == 0) {
                        $("#panel_additional_id").hide();
                    }
                }

                applyFilters();
                BrowseUtil.applySuggestions(jsonData, messages);
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
502
503
            });

Maxim's avatar
Maxim committed
504
505
506
507
508
509
510
511
512
513
514
515
            $("#menuShareLink").on("click", function () {
                if ($('#shortLink').val() === '') {
                    $.ajax({
                        type: 'POST',
                        url: '/explore/shorten-url',
                        data: {
                            'browser': "map", 'filter': JSON.stringify(jsonData)
                        },
                        success: function (response) {
                            var inp = $("#shortLink");
                            inp.val(response.shortUrl);
                            inp.select();
Alexander Basov's avatar
Alexander Basov committed
516
                        }
Maxim's avatar
Maxim committed
517
518
519
520
521
                    });
                } else {
                    console.log('No repeat.');
                }
            });
Alexander Basov's avatar
Alexander Basov committed
522

Maxim's avatar
Maxim committed
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
            $(window).on("popstate", function (e) {
                if (e.originalEvent.state !== null) {
                    jsonData = JSON.parse(decodeURIComponent((new RegExp('[?|&]filter=' + '([^&;]+?)(&|#|;|$)').exec(location.search)
                            || [null, ''])[1].replace(/\+/g, '%20'))) || [];
                    page = decodeURIComponent((new RegExp('[?|&]page=' + '([^&;]+?)(&|#|;|$)').exec(location.search)
                            || [null, ''])[1].replace(/\+/g, '%20')) || 1;
                    results = decodeURIComponent((new RegExp('[?|&]results=' + '([^&;]+?)(&|#|;|$)').exec(location.search)
                            || [null, ''])[1].replace(/\+/g, '%20')) || 50;
                    var filter = JSON.stringify(jsonData);
                    var requestUrl = '//' + location.host + location.pathname +
                            "?filter=" + encodeURIComponent(filter);
                    $.ajax({
                        url: requestUrl,
                        method: 'get',
                        success: function (response) {
                            refreshData();
                        }
                    });
Aleksandr Sharaban's avatar
Aleksandr Sharaban committed
541
                    BrowseUtil.applySuggestions(jsonData, messages);
Maxim's avatar
Maxim committed
542
543
                } else {
                    location.reload();
Alexander Basov's avatar
Alexander Basov committed
544
                }
Maxim's avatar
Maxim committed
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
            });

            var topPane = map._createPane('leaflet-top-pane', map.getPanes().mapPane);

            var selectedBaseMap = cookieUtils.getCookie('mapProviders') || 'esriGray';
            if (mapProviders[selectedBaseMap] === undefined) {
                selectedBaseMap = 'esriGray';
            }
            [].forEach.call($('.label-map-provider input:radio'), function (radio) {
                $(radio).prop('checked', $(radio).val() === selectedBaseMap);
            });

            mapProviders[selectedBaseMap].addTo(map);
            topPane.appendChild(mapProviders[selectedBaseMap].getContainer());
            mapProviders[selectedBaseMap].setZIndex(0);

            loadTiles(map);

            $("body").on("click", ".applyBtn", function () {
564
565
566
567
568
                if( !$(this).hasClass('disabled') ) {
                    $(this).parent().parent().find("button.filter-auto, button.filter-range").trigger("click");
                    applyFilters();
                    BrowseUtil.applySuggestions(jsonData, messages);
                }
Maxim's avatar
Maxim committed
569
570
571
            });


Alexander Basov's avatar
Alexander Basov committed
572
573
            $(document).on('cookieUpdate', function () {
                for (var key in mapProviders) {
Alexander Basov's avatar
Alexander Basov committed
574
575
                    map.removeLayer(mapProviders[key]);
                }
Alexander Basov's avatar
Alexander Basov committed
576
                if (cookieUtils.getCookie('mapProviders')) {
Maxim's avatar
Maxim committed
577

Alexander Basov's avatar
Alexander Basov committed
578
                    mapProviders[cookieUtils.getCookie('mapProviders')].addTo(map);
Alexander Basov's avatar
Alexander Basov committed
579
580
                    topPane.appendChild(mapProviders[cookieUtils.getCookie('mapProviders')].getContainer());
                    mapProviders[cookieUtils.getCookie('mapProviders')].setZIndex(0);
Alexander Basov's avatar
Alexander Basov committed
581
                } else {
Maxim's avatar
Maxim committed
582

583
                    mapProviders.esriGray.addTo(map);
Alexander Basov's avatar
Alexander Basov committed
584
                    topPane.appendChild(mapProviders[cookieUtils.getCookie('mapProviders')].getContainer());
585
                    mapProviders.esriGray.setZIndex(0);
Alexander Basov's avatar
Alexander Basov committed
586
587
                }
            });
Matija Obreza's avatar
Matija Obreza committed
588
589
590

            $('.map-provider').click(function (e) {
                var providerName = $(this).val();
Alexander Basov's avatar
Alexander Basov committed
591
592
                if ($(this).is(":checked")) {
                    cookieUtils.setCookie('mapProviders', providerName, 0);
Alexander Basov's avatar
Alexander Basov committed
593
594
                    $(document).trigger('cookieUpdate');
                } else {
Alexander Basov's avatar
Alexander Basov committed
595
596
                    providerName = '';
                    cookieUtils.setCookie('mapProviders', providerName, 0);
Alexander Basov's avatar
Alexander Basov committed
597
598
599
                    $(document).trigger('cookieUpdate');
                }
            });
Maxim's avatar
Maxim committed
600

Alexander Basov's avatar
Alexander Basov committed
601
            $('#color select').simplecolorpicker();
igoshin's avatar
igoshin committed
602

603
604
605
606
            $("#cancel-filter-save").on("click", function (event) {
              event.preventDefault();
              $('.modal').modal('hide');
            });
Maxim's avatar
Maxim committed
607

Alexander Basov's avatar
Alexander Basov committed
608
            $("#save-filter").on("click", function (event) {
igoshin's avatar
igoshin committed
609
610
611
                event.preventDefault();

                var title = $("#filter-title").val();
Maxim's avatar
Maxim committed
612
                var filter = jsonData;
igoshin's avatar
igoshin committed
613
614

                $.ajax({
615
616
617
618
619
620
621
622
623
624
625
                  url: "/savedmaps/get",
                  type: "get",
                  dataType: "json",
                  contentType: 'application/json; charset=utf-8'
                }).done(function(res) {
                  var needToSave = true;
                  res.forEach(function(item) {
                    if(item.title === $.trim(title)) {
                      needToSave = false;
                      $('#existingTitleError').show();
                      $('#emptyTitleError').hide();
igoshin's avatar
igoshin committed
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
                  });
                  if($.trim(title) === '') {
                    needToSave = false;
                    $('#emptyTitleError').show();
                    $('#existingTitleError').hide();
                  }

                  if(needToSave) {
                    $.ajax({
                      url: "/savedmaps/save",
                      type: "post",
                      dataType: "json",
                      contentType: 'application/json; charset=utf-8',
                      data: JSON.stringify({
                      title: $.trim(title),
                      filter: JSON.stringify(filter),
                      color: $('#color select').val()
                      }),
                      error: function (error) {
                        console.log(error)
                      }
                    }).done(function() {
                      $('.modal').modal('hide');
                    });
                  }
igoshin's avatar
igoshin committed
652
653
654
                });
            });

Alexander Basov's avatar
Alexander Basov committed
655
            $("#get-filters").on("click", function (event) {
igoshin's avatar
igoshin committed
656
657
                event.preventDefault();

658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
                if ($("#enabled-filters").is(":visible")) {
                    $("#enabled-filters").hide();
                    $("#enabled-filters").empty();
                } else {
                    $.ajax({
                        url: "/savedmaps/get",
                        type: "get",
                        dataType: "json",
                        contentType: 'application/json; charset=utf-8',
                        success: function (data) {
                            if (data.length !== 0) {
                                $.each(data, function (idx, filter) {
                                    var li = $("<li/>")
                                        .append($("<label>").addClass("saved-filter").attr("x-fil", filter.filter).attr("x-color", filter.color)
                                            .append($("<input type='checkbox' style='margin-right: 10px;margin-left: 5px' />"))
                                            .append(filter.title)
                                            .append("</label>"));

                                    $("#enabled-filters").append(li);
                               });
                                $("#enabled-filters").show();
igoshin's avatar
igoshin committed
679
                            }
680
681
682
683
684
685
                        },
                        error: function (error) {
                            console.log(error)
                        }
                    });
                }
igoshin's avatar
igoshin committed
686
687
            });

Alexander Basov's avatar
Alexander Basov committed
688
            $("#selectArea").hide();
igoshin's avatar
igoshin committed
689
            var filterJson =${jsonFilter};
igoshin's avatar
igoshin committed
690
691
692
693
694
            var filterJsonObj = {};
            if (typeof filterJson !== 'undefined') {
                filterJsonObj = JSON.parse(JSON.stringify(filterJson));
            }

Alexander Basov's avatar
Alexander Basov committed
695
            var layers = {};
696
            $("body").on("click", ".saved-filter", function (e) {
igoshin's avatar
igoshin committed
697
                var title = $(this).text();
698
699
                var filter = $(this).attr("x-fil");
                var tilesColor = $(this).attr("x-color").substring(1);
igoshin's avatar
igoshin committed
700
701

                if ($(this).find("input:checkbox").is(":checked")) {
Alexander Basov's avatar
Alexander Basov committed
702
703
                    if (layers[title] == null) {
                        layers[title] = L.tileLayer("{s}/explore/tile/{z}/{x}/{y}?filter=" + filter + "&color=" + tilesColor, {
704
                            attribution: "<a href='<c:url value="${baseUrl}" />'>Genesys</a>",
Alexander Basov's avatar
Alexander Basov committed
705
                            styleId: 22677,
706
                            subdomains: ${cdnServers.serverList}
Alexander Basov's avatar
Alexander Basov committed
707
708
                        }).addTo(map);
                    }
igoshin's avatar
igoshin committed
709
                } else {
Alexander Basov's avatar
Alexander Basov committed
710
711
712
713
                    if (layers[title] != null) {
                        map.removeLayer(layers[title]);
                        layers[title] = null;
                    }
igoshin's avatar
igoshin committed
714
                }
igoshin's avatar
igoshin committed
715
716
            });

Alexander Basov's avatar
Alexander Basov committed
717
718
719
720
721
722
723
724
            var locationFilter = new L.LocationFilter({
                adjustButton: false,
                bounds: map.getBounds().pad(-0.1)
            }).addTo(map);
            locationFilter.on("change", function (e) {
                // Do something when the bounds change.
                // Bounds are available in `e.bounds`.
                var bounds = locationFilter.getBounds();
725
726
                filterJson['geo.latitude'] = [{range: [niceDec(nicebounds.getSouth()), niceDec(bounds.getNorth())]}];
                filterJson['geo.longitude'] = [{range: [niceDec(bounds.getWest()), niceDec(bounds.getEast())]}];
Alexander Basov's avatar
Alexander Basov committed
727
728
729
730
731
732
733
734
735
736
737
            });

            map.on("viewreset", function () {
                if (locationFilter.isEnabled())
                    return;
                var mapBounds = map.getBounds().pad(-0.1);
                locationFilter.setBounds(mapBounds);
            });
            locationFilter.on("enabled", function () {
                // Do something when enabled.
                var bounds = locationFilter.getBounds();
738
739
                filterJson['geo.latitude'] = [{range: [niceDec(bounds.getSouth()), niceDec(bounds.getNorth())]}];
                filterJson['geo.longitude'] = [{range: [niceDec(bounds.getWest()), niceDec(bounds.getEast())]}];
Alexander Basov's avatar
Alexander Basov committed
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
                $("#selectArea").show();
            });

            locationFilter.on("disabled", function () {
                // Do something when disabled.
                $("#selectArea").hide();
            });

            $("#selectArea").on("click", function (e) {
                this.href = this.href + '?filter=' + JSON.stringify(filterJson);
            });

            var loadDetailsTimeout = null;
            var clickMarker = null;
            map.on("click", function (e) {
                if (clickMarker != null) {
                    map.removeLayer(clickMarker);
                    clickMarker = null;
                }
                if (map.getZoom() > 4) {
                    if (loadDetailsTimeout != null) {
                        clearTimeout(loadDetailsTimeout);
                    }

                    var point = this.latLngToLayerPoint(e.latlng);
                    point.x -= 5;
                    point.y += 5;
                    var sw = this.layerPointToLatLng(point);
                    point.x += 10;
                    point.y -= 10;
                    var ne = this.layerPointToLatLng(point);
                    loadDetailsTimeout = setTimeout(function () {

                        var filterBounds = filterJsonObj;
                        filterBounds['geo.latitude'] = [{range: [sw.lat, ne.lat]}];
                        filterBounds['geo.longitude'] = [{range: [sw.lng, ne.lng]}];
                        $.ajax("<c:url value="/explore/geoJson"><c:param name="limit" value="11" /></c:url>&filter=" + JSON.stringify(filterBounds), {
                            type: "GET",
                            dataType: 'json',
                            success: function (respObject) {
Maxym Borodenko's avatar
Maxym Borodenko committed
780
781
                                var parsedRespObject = jQuery.parseJSON(respObject);
                                if (parsedRespObject.features === null || parsedRespObject.features.length === 0)
Alexander Basov's avatar
Alexander Basov committed
782
783
784
                                    return;

                                var c = "";
Maxym Borodenko's avatar
Maxym Borodenko committed
785
                                parsedRespObject.features.forEach(function (a, b) {
Alexander Basov's avatar
Alexander Basov committed
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
                                    if (b < 10)
                                        c += "<a href='<c:url value="/acn/id/" />" + a.id + "'>" + a.properties.acceNumb + " " + a.properties.instCode + "</a><br />";
                                    else
                                        c += "...";
                                });
                                clickMarker = L.rectangle([sw, ne], {stroke: false, fill: true}).addTo(map);
                                clickMarker.bindPopup(c).openPopup();
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                console.log(textStatus);
                                console.log(errorThrown);
                            }
                        });

                    }, 200);
                }
            });
            map.on("dblclick", function (e) {
                if (loadDetailsTimeout != null) {
                    //console.log("cleared" + loadDetailsTimeout);
                    clearTimeout(loadDetailsTimeout);
                    loadDetailsTimeout = null;
                }
            });
        });
Maxim's avatar
Maxim committed
811

Maxym Borodenko's avatar
Maxym Borodenko committed
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
        function setHeight(isClosed) {
            if ($(window).innerWidth() > 960) {
                $('.filters').css('height', 'auto');

                var windowHeight = $(window).innerHeight();
                var offsetMap = $('#map').offset().top;
                var offsetFilters = $('.filters').offset().top;

                $('#map').css('height', windowHeight - offsetMap, +'px');

                if(typeof isClosed == 'undefined'){
                    isClosed = !$('#collapseFilters').hasClass('in')
                }

                if($('#collapseFilters').hasClass('in') || !isClosed) {
                    $('.filters').css('height', windowHeight - offsetFilters, +'px');
                }
            }
            else {
                $(".filters").css('height', 'auto');
                $('#map').css('height', 600, +'px');
            }
        }

Maxim's avatar
Maxim committed
836
837
838
839
840
841
842
843
844
        function isExistAdditionalFilters() {
            for(var filter in jsonData) {
                if(filter.toString().startsWith("gm:")) {
                    return true;
                }
            }
            return false;
        }

Maxim's avatar
Maxim committed
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
        function getMapProviders() {
            return {
                openstreetmap: L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                    attribution: '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
                }),
                /*  OpenMapSurfer_Grayscale: L.tileLayer('http://openmapsurfer.uni-hd.de/tiles/roadsg/x={x}&y={y}&z={z}', {
                 maxZoom: 19,
                 attribution: 'Imagery from <a target="_blank" href="http://giscience.uni-hd.de/">GIScience Research Group, University of Heidelberg</a>, Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>'
                 }),*/
                esriGray: L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/Canvas/World_Light_Gray_Base/MapServer/tile/{z}/{y}/{x}', {
                    attribution: 'Tiles &copy; Esri &mdash; Esri, DeLorme, NAVTEQ',
                    maxZoom: 16
                }),
                esriTopo: L.tileLayer('https://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}', {
                    attribution: 'Tiles &copy; Esri &mdash; Esri, DeLorme, NAVTEQ, TomTom, Intermap, iPC, USGS, FAO, NPS, NRCAN, GeoBase, Kadaster NL, Ordnance Survey, Esri Japan, METI, Esri China (Hong Kong), and the GIS User Community'
                })
            }
        }

        function getCookieUtils() {
            return {
                getCookie: function (name) {
                    var matches = document.cookie.match(new RegExp(
                            "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
                    ));
                    return matches ? decodeURIComponent(matches[1]) : undefined;
                },
                setCookie: function (name, value, options) {
                    options = options || {};

                    var expires = options.expires;

                    if (typeof expires == "number" && expires) {
                        var d = new Date();
                        d.setTime(d.getTime() + expires * 1000);
                        expires = options.expires = d;
                    }
                    if (expires && expires.toUTCString) {
                        options.expires = expires.toUTCString();
                    }

                    value = encodeURIComponent(value);

                    var updatedCookie = name + "=" + value;

                    for (var propName in options) {
                        updatedCookie += "; " + propName;
                        var propValue = options[propName];
                        if (propValue !== true) {
                            updatedCookie += "=" + propValue;
                        }
                    }
                    document.cookie = updatedCookie;
                },
                deleteCookie: function (name) {
                    this.setCookie(name, "", {
                        expires: -1
                    })
                }
            }
        }

        function niceDec(d, b) {
            if (b == null) b = 5;
            var x = Math.pow(10, b);
            return d === null ? null : Math.round(d * x) / x;
        }

        function loadTiles() {
            layer = L.tileLayer("{s}/explore/tile/{z}/{x}/{y}?filter=" + JSON.stringify(jsonData), {
915
                attribution: "Accession localities from <a href='<c:url value="${baseUrl}" />'>Genesys PGR</a>",
Maxim's avatar
Maxim committed
916
                styleId: 22677,
917
                subdomains: ${cdnServers.serverList}
Maxim's avatar
Maxim committed
918
919
            });
            layer.addTo(map);
920
921
922
            if(shouldGetBoundingBox()) {
                centerMap();
            }
Maxim's avatar
Maxim committed
923
924
925
926
927
928
        }

        function reloadTiles() {
            if (layer !== null) {
                map.removeLayer(layer);
                layer = L.tileLayer("{s}/explore/tile/{z}/{x}/{y}?filter=" + JSON.stringify(jsonData), {
929
                    attribution: "Accession localities from <a href='<c:url value="${baseUrl}" />'>Genesys PGR</a>",
Maxim's avatar
Maxim committed
930
                    styleId: 22677,
931
                    subdomains: ${cdnServers.serverList}
Maxim's avatar
Maxim committed
932
933
                });
                layer.addTo(map);
934
935
936
                if(shouldGetBoundingBox()) {
                    centerMap();
                }
Maxim's avatar
Maxim committed
937
938
939
940
941
942
            }
            else {
                console.log("tileLayer is null");
            }
        }

943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
        function shouldGetBoundingBox() {
            for(var filter in jsonData) {
                var filterName = filter.toString();
                if(filterName) {
                    if(filterName == 'regionOrigin') {
                        if(jsonData[filterName].length != 0) {
                            return true;
                        }
                    }
                    if(filterName == 'orgCty.iso3') {
                        if(jsonData[filterName].length != 0) {
                            return true;
                        }
                    }
                }
            }
            return false;
        }

Maxim's avatar
Maxim committed
962
        function refreshLinks() {
963
964
965
            $.each($("#downloadKml").find("input[name='filter']"), function () {
                $(this).val(JSON.stringify(jsonData));
            });
Maxim's avatar
Maxim committed
966
967
968
969
970
971
972
973
974
975
            var re = /filter=(.*)/;
            $("#exploreLink").attr("href", $("#exploreLink").attr("href").replace(re, "filter=" + encodeURIComponent(JSON.stringify(jsonData))));
            $("#overviewLink").attr("href", $("#overviewLink").attr("href").replace(re, "filter=" + encodeURIComponent(JSON.stringify(jsonData))));
        }

        function refreshData() {
            reloadTiles();
            refreshLinks();
        }

976
977
978
979
980
981
982
983
984
985
986
987
988
989
        function centerMap() {
            $.ajax("<c:url value="/explore/bounding-box"/>", {
                type: 'GET',
                data: "filter=" + JSON.stringify(jsonData),
                success: function (respObject) {
                    var west = respObject.west;
                    var south = respObject.south;
                    var east = respObject.east;
                    var north = respObject.north;

                    if (west == 0 && south == 0 && east == 0 && north == 0)
                        return;

                    var bounds = new GenesysMaps.BoundingBox();
Maxym Borodenko's avatar
Maxym Borodenko committed
990
991
992
                    bounds.add([south, west]);
                    bounds.add([north, east]);

993
994
995
996
997
998
999
1000
1001
1002
1003
                    map.fitBounds(bounds.getBounds());
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
        }

        function useDefoultBoundingBox() {
            var bounds = new GenesysMaps.BoundingBox();
Maxym Borodenko's avatar
Maxym Borodenko committed
1004
1005
            bounds.add([-60, -160]);
            bounds.add([60, 160]);
1006
1007
1008
            map.fitBounds(bounds.getBounds());
        }

Maxim's avatar
Maxim committed
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
        function applyFilters() {
            var stepValue = (parseInt(localStorage.getItem("historyStep")) + 1);
            localStorage.setItem("historyStep", stepValue);
            var filter = JSON.stringify(jsonData);
            var requestUrl = '//' + location.host + location.pathname +
                    "?filter=" + encodeURIComponent(filter);
            window.history.pushState(requestUrl, '', requestUrl);

            refreshData();
        }

Alexander Basov's avatar
Alexander Basov committed
1020
    </script>
1021
1022
1023
</content>
</body>
</html>