This repository has been archived by the owner on May 11, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
script.js
571 lines (479 loc) · 17.5 KB
/
script.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
/* Author:
*/
/* enable javascript gettext-translations */
var gt = new Gettext( { "domain": "messages" } );
function _(msgid) { return gt.gettext(msgid); }
// variable to hold the facet filters in memory, hash params across page navigation/history
var facethash = {};
function ld_parse_url_hash() {
var hash = window.location.hash;
var data = {};
var params = [];
if (hash.indexOf("#") != -1) params = hash.slice(1).split("&");
if (params.length==0) return data;
for (var temp in params) {
var param = params[temp];
var args = param.split("=");
data[args[0]]=decodeURI(args[1]);
}
return data;
}
function ld_append_url_hash(param) {
// get current parameters
var curHash = window.location.hash;
// get new parameters
var newParams = param.split("=");
var newKey = newParams[0];
var newVal = newParams[1];
// decode current hash data into object
var newData = {};
if (curHash.indexOf("#") != -1) {
var params = curHash.slice(1).split("&");
for (var temp in params) {
var param = params[temp];
var args = param.split("=");
newData[args[0]]=decodeURI(args[1]);
}
}
// check for old key
if (newData[newKey] != undefined) {
if (newVal=='') delete newData[newKey];
else newData[newKey] = encodeURI(newVal);
}
// insert new key & val if value is nonempty
else if (newVal != '') newData[newKey] = encodeURI(newVal);
// put new data into array
var newHash = [];
for (var key in newData) {
newHash.push(key + "=" + newData[key]);
}
if (newHash.length>0) window.location.hash = newHash.join("&");
else window.location.hash = "";
}
function ld_mapcontrol_init_geoloc(data) {
if (data.length==0) {
$('#basicmap').hide();
return;
}
// hide hero-unit if map visible
$("#introtext").slideUp();
/* initialize map canvas and set location for given coordinates */
$(window).scrollTop(0);
$('#basicmap').empty();
$('#mapcontrol').empty();
$('#basicmap').show();
var mapOptions = {
controls: [
new OpenLayers.Control.Navigation({'zoomWheelEnabled': false}),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.Attribution() ],
theme: '/js/libs/openlayers/style.css'
};
/* convert wgs-84 coordinates into OSM spherical mercator projection */
var fromProjection = new OpenLayers.Projection("EPSG:4326");
var toProjection = new OpenLayers.Projection("EPSG:900913");
//var mapLocation = new OpenLayers.LonLat(lon, lat).transform(fromProjection,toProjection);
/* add map layers */
var osmLayer = new OpenLayers.Layer.OSM("OpenStreetMap");
var gmapLayer = new OpenLayers.Layer.Google("Google Streets", { numZoomLevels: 19 });
var map = new OpenLayers.Map("basicmap", mapOptions);
//map.addLayers([osmLayer]);
map.addLayers([osmLayer, gmapLayer]);
//map.setCenter(mapLocation, 12);
/* add marker layer with coordinate projection transform */
var vectorLayer = new OpenLayers.Layer.Vector("Overlay");
map.addLayer(vectorLayer);
// show user position, if available
if (ld_position) {
var lat = ld_position_coords.latitude;
var lon = ld_position_coords.longitude;
var marker = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(lon, lat).transform(fromProjection,toProjection),
{ html: _("My Location") },
{ externalGraphic: 'js/libs/openlayers/markers/blue_dot_circle.png', graphicHeight: 10, graphicWidth: 10, graphicYOffset: -5 }
);
vectorLayer.addFeatures(marker);
}
/* selector for marker popups */
var controls = { selector: new OpenLayers.Control.SelectFeature(vectorLayer, { onSelect: createPopup, onUnselect: destroyPopup, hover: true }) };
map.addControl(controls['selector']);
controls['selector'].activate();
// bounding box for marker data
var bounds = new OpenLayers.Bounds();
/* add all libraries from results */
for (var item in data) {
var rec = data[item];
if (rec.contact.coordinates != undefined && rec.contact.coordinates.length>2) {
var lat = rec.contact.coordinates.split(",")[0];
var lon = rec.contact.coordinates.split(",")[1];
// extend marker bounding box
bounds.extend(new OpenLayers.Geometry.Point(lon, lat).transform(fromProjection,toProjection));
var html = rec.map_popup_html;
var markersymbol = 'js/libs/openlayers/markers/marker-red-small.png';
if (rec.open_now==true) markersymbol = 'js/libs/openlayers/markers/marker-green-small.png';
var marker = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(lon, lat).transform(fromProjection,toProjection),
{ html: html },
{ externalGraphic: markersymbol, graphicHeight: 26, graphicWidth: 16, graphicYOffset: -26 }
);
vectorLayer.addFeatures(marker);
}
}
// center map on markers and set proper zoomlevel
map.zoomToExtent(bounds, false);
/* click on marker */
function createPopup(feature) {
feature.popup =
new OpenLayers.Popup.FramedCloud(
"pop", feature.geometry.getBounds().getCenterLonLat(), null,
'<div>'+feature.attributes.html+'</div>', null, true,
function() { controls['selector'].unselectAll(); });
map.addPopup(feature.popup);
}
/* click somewhere else */
function destroyPopup(feature) {
feature.popup.destroy();
feature.popup = null;
}
}
function ld_mapcontrol_init(coords, info) {
if (coords.length<2) {
alert("Error: coordinates are missing");
return true; }
var lat = coords.split(",")[0];
var lon = coords.split(",")[1];
/* initialize map canvas and set location for given coordinates */
$(window).scrollTop(0);
$('#basicmap').empty();
$('#mapcontrol').empty();
$('#basicmap').show();
var mapOptions = {
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.LayerSwitcher(),
new OpenLayers.Control.Attribution() ],
theme: '/js/libs/openlayers/style.css'
};
/* convert wgs-84 coordinates into OSM spherical mercator projection */
var fromProjection = new OpenLayers.Projection("EPSG:4326");
var toProjection = new OpenLayers.Projection("EPSG:900913");
var mapLocation = new OpenLayers.LonLat(lon, lat).transform(fromProjection,toProjection);
/* add map layers */
var osmLayer = new OpenLayers.Layer.OSM("OpenStreetMap");
var gmapLayer = new OpenLayers.Layer.Google("Google Streets", { numZoomLevels: 19 });
map = new OpenLayers.Map("basicmap", mapOptions);
//map.addLayers([osmLayer]);
map.addLayers([osmLayer, gmapLayer]);
map.setCenter(mapLocation, 15);
/* add marker layer with coordinate projection transform */
var vectorLayer = new OpenLayers.Layer.Vector("Overlay");
map.addLayer(vectorLayer);
var marker = new OpenLayers.Feature.Vector(
new OpenLayers.Geometry.Point(lon, lat).transform(fromProjection,toProjection),
{ html: info },
{ externalGraphic: 'js/libs/openlayers/markers/marker-black.png', graphicHeight: 41, graphicWidth: 25, graphicYOffset: -41 }
);
vectorLayer.addFeatures(marker);
/* add marker popup */
if (info != "") {
var popup =
new OpenLayers.Popup.FramedCloud(
"pop", marker.geometry.getBounds().getCenterLonLat(), null,
'<div>'+marker.attributes.html+'</div>', null, false);
map.addPopup(popup);
}
// I don't think we need this?
// $('#mapcontrol').append('<button class="btn btn-danger" onclick="ld_mapcontrol_close();">Hide map</button>');
}
function ld_mapcontrol_close() {
/* clear and hide the map elements */
$('#basicmap').slideToggle();
$('#basicmap').empty();
$('#mapcontrol').empty();
}
/* geolocation related variables, globals for now */
var ld_position = false;
var ld_position_coords = null;
/* calculate whether library is open at given time or not, helper functions */
function ld_open_now(timerange) {
start = String(timerange.start)
stop = String(timerange.end)
timestamp = new Date();
mins = timestamp.getMinutes();
hrs = timestamp.getHours();
current_time = hrs*60+mins;
start_time = ld_get_minutes(start);
end_time = ld_get_minutes(stop);
/* 15 minute buffer for closing-time */
if (current_time>=start_time && current_time<=end_time) return true;
else return false;
}
function ld_get_minutes(time) {
mins = Number(time.slice(-2));
hrs = Number(time.slice(0,-2));
return hrs*60+mins;
}
function ld_format_time(time) {
time = String(time);
mins = time.slice(-2);
hrs = time.slice(0,-2);
return hrs+":"+mins
}
function ld_widget_wizard() {
// url for widgets/data
var url = "http://localhost:8080/";
function load_widget_css(type) {
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: url + "css/json_widget" + type + ".css" });
css_link.appendTo('head');
}
// preload jsonp-widget css
load_widget_css(4);
load_widget_css(5);
$(".langselector").prop('disabled', true);
$(".typeselector").prop('disabled', true);
$("#widget_style").prop('disabled', true);
// construct the widget code
function build_widget() {
var id = $("#widget_library").val();
var consortium = $("#widget_consortium").val();
var city = $("#widget_city").val();
var filter = $("#widget_filter").val();
var type = $("#widget_type").val();
var uuid = get_uuid();
var code = "";
var widget_lang = $("#widget_lang").val();
var lang = "";
// apply default css for iframe-widget
if (type=="1" || type=="2" || type=="3") {
if ($("#widget_style").val() == "") $("#widget_style").val("width: 550px;\nheight: 550px;")
}
var style = $("#widget_style").val().replace(/\n+/g," ");
//if (widget_lang != "") lang = '?lang=' + widget_lang;
if (widget_lang != "") lang = widget_lang;
switch(type) {
// 1-3 iframe widgets
case "1":
if (lang != '') lang+="/";
var code = '<iframe src="' + url + lang + 'widget1';
if (filter == 'area' && consortium != '') code += '?area='+consortium+'"';
else if (filter == 'city') code += '?city='+city+'"';
else code += '"';
if (style != '') code += ' style="' + style + '"';
code += '></iframe>';
break;
case "2":
if (lang != '') lang+="/";
var code = '<iframe src="' + url + lang;
code += 'widget2?id=' + id + '"';
if (style != '') code += ' style="' + style + '"';
code += '></iframe>';
break;
case "3":
if (lang != '') lang+="/";
var code = '<iframe src="' + url + lang;
code += 'widget3?id=' + id + '"';
if (style != '') code += ' style="' + style + '"';
code += '></iframe>';
break;
// jsonp-widgets
default:
var code = '<script class="libdir_widget" ';
code += 'data-params="id=' + id + '" ';
code += 'data-type="' + type + '" ';
code += 'data-id="' + uuid + '" ';
code += 'data-lang="' + lang + '" ';
code += 'src="' + url + 'js/widget.js' + '" ';
code += 'type="text/javascript"></script>';
code += '<div class="libdir_widget_' + type + '" ';
if (style!="") code += 'style="' + style + '" ';
code += 'id="libdir_widget-' + uuid + '"' + '></div>';
break;
}
$("#widget_code").val(code);
// update preview for jsonp-widgets
if (type=="4" || type=="5") {
var code = "";
code += '<div class="libdir_widget_' + type + '" ';
if (style!="") code += 'style="' + style + '" ';
code += 'id="libdir_widget-' + uuid + '"' + '></div>';
$("#widget_preview").html(code);
var jsonp_url = "";
if (lang != "") jsonp_url = url + lang + "/loadwidget?id="+id+"&type="+type+"&callback=?";
else jsonp_url = url + "loadwidget?id="+id+"&type="+type+"&callback=?";
$.getJSON(jsonp_url, function(data) { $('#libdir_widget-' + uuid).html(data.html); });
}
// update preview for iframe-widgets
else {
$("#widget_preview").html(code);
}
}
// generate unique identifier for jsonp-widget to avoid namespace collisions
function get_uuid() {
// http://www.ietf.org/rfc/rfc4122.txt
var s = [];
var hexDigits = "0123456789abcdef";
for (var i = 0; i < 36; i++) {
s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
}
s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
s[8] = s[13] = s[18] = s[23] = "-";
var uuid = s.join("");
return uuid;
}
$(".langselector").bind('click', function(event) {
event.preventDefault();
$("#widget_lang").val($(this).attr('value'));
build_widget();
});
$(".typeselector").bind('click', function(event) {
event.preventDefault();
var value = $(this).attr('value');
$("#widget_type").val(value);
if (value==1) $(".filter").show();
else $(".filter").hide();
build_widget();
});
$(".filterselector").bind('click', function(event) {
event.preventDefault();
$("#widget_filter").val($(this).attr('value'));
build_widget();
});
// submit on each key press if interval>800 ms
$('#widget_style').keyup(function() {
typewatch(function () {
build_widget();
}, 800);
});
$(document).bind('search', function(event, data) {
var url = "http://localhost:8888/testink/organisation/_search";
var query2 =
{
"size": 10,
"sort": [ { "name_fi" : {} } ],
"query":
{ "query_string":
{
//"default_operator": "AND",
"fields": ["contact.street_address.street_*", "name_*"],
"query": "*"+data.terms+"*"
}
}
};
query = JSON.stringify(query2);
//console.log(query);
var showerror = function(msg) {
if (!msg){ msg = _("Error: unspecified"); }
$('.search_results').html('<div id="errormsg" class="alert alert-error"><i class="icon-warning-sign"></i> <strong>' + _("Error") + ':</strong> '+msg+'</div>');
}
var searchTimer = window.setTimeout(function() { showerror(_("Could not connect to database. Please try again later.")) }, 5000);
$.ajax({
url: url,
data: { source: query },
dataType: "jsonp",
success: function(data) {
window.clearTimeout(searchTimer);
results = new Object();
results["records"] = new Array();
var index=1;
for (var item in data.hits.hits) {
data.hits.hits[item]._source["id"] = data.hits.hits[item]._id;
data.hits.hits[item]._source["count"] = index;
results["records"].push(data.hits.hits[item]._source);
index++;
}
results.hits = data.hits.total;
var template =
'{{#records}}' +
'<div style="width: 35%;" class="alert alert-info searchresults" data-id="{{id}}" data-consortium="{{consortium}}" '+
'data-city="' + '{{contact.street_address.municipality_' + _("locale") + '}}' + '">' +
'<strong>' +
'{{#name_' + _("locale") + '}}' +
'{{name_' + _("locale") + '}}' +
'{{/name_' + _("locale") + '}}' +
'{{^name_' + _("locale") + '}}' +
'{{name_fi}}' +
'{{/name_' + _("locale") + '}}' +
'</strong>' +
'<br>' +
'{{#contact.street_address.street_' + _("locale") + '}}' +
'{{contact.street_address.street_' + _("locale") + '}}' +
'{{/contact.street_address.street_' + _("locale") + '}}' +
'{{^contact.street_address.street_' + _("locale") + '}}' +
'{{contact.street_address.street_fi}}' +
'{{/contact.street_address.street_' + _("locale") + '}}' +
', ' +
'{{#contact.street_address.municipality_' + _("locale") + '}}' +
'{{contact.street_address.municipality_' + _("locale") + '}}' +
'{{/contact.street_address.municipality_' + _("locale") + '}}' +
'{{^contact.street_address.municipality_' + _("locale") + '}}' +
'{{contact.street_address.municipality_fi}}' +
'{{/contact.street_address.municipality_' + _("locale") + '}}' +
'</div>' +
'{{/records}}';
$('.search_results').empty();
if (results.hits>0) {
if (results.hits>10) $('#hits').html(_("Too many search results, showing first 10"));
else $('#hits').html("");
$('.search_results').html(Mustache.render(template, results));
$('.searchresults').bind('click', function(event) {
event.preventDefault();
$(this).siblings().remove();
$(this).removeClass("alert-info");
$(this).addClass("alert-success");
$('#widget_library').val($(this).attr("data-id"));
$('#widget_consortium').val($(this).attr("data-consortium"));
$('#widget_city').val($(this).attr("data-city"));
$('.typeselector').first().button('toggle').trigger('click');
$('.langselector').first().button('toggle').trigger('click');
$('.filterselector').first().button('toggle').trigger('click');
$(".langselector").removeProp('disabled');
$(".typeselector").removeProp('disabled');
$("#widget_style").removeProp('disabled');
});
} else {
$('.search_results').html("");
$('#hits').html(_("No search results"));
}
}
})
});
// submit on each key press if interval>500 ms
$('#search_txt').keyup(function() {
typewatch(function () {
var lastSearchTerm = $('#search_txt').data('lastSearchTerm');
if (!lastSearchTerm) {
lastSearchTerm = '';
}
if (lastSearchTerm != $('#search_txt').val()) {
$(document).trigger('search', {terms:$('#search_txt').val()});
}
$('#search_txt').data('lastSearchTerm', $('#search_txt').val());
}, 500);
});
var typewatch = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
}
})();
}
/*
Fix IOS scaling bug
http://stackoverflow.com/questions/5434656/ipad-layout-scales-up-when-rotating-from-portrait-to-landcape
*/
if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPad/i)) {
var viewportmeta = document.querySelector('meta[name="viewport"]');
if (viewportmeta) {
viewportmeta.content = 'width=device-width, minimum-scale=1.0, maximum-scale=1.0, initial-scale=1.0';
document.body.addEventListener('gesturestart', function () {
viewportmeta.content = 'width=device-width, minimum-scale=0.25, maximum-scale=1.6';
}, false);
}
}