-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
511 lines (435 loc) · 17.9 KB
/
main.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
//#region constants and global vars
var baseurl = "https://ballerup.mapcentia.com/api/v2/sql/";
var db = "collector";
var api_key;
var user_name;
//Status variables
bilregOK = false;
bilregIsSearch = false;
//#endregion
//Function for making web requests asynchronously
function HttpGetAsync(query, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(JSON.parse(xmlHttp.responseText));
}
var url = baseurl + user_name + "@" + db + "?key=" + api_key + "&q=" + query;
xmlHttp.open("GET", encodeURI(url), true);
xmlHttp.send(null);
}
function validateBilreg() {
var field = document.getElementById('bilReg');
//Is the field empty?
if (field.value == "") {
document.getElementById("bilRegNotKnown").style.display = 'none';
document.getElementById("bilRegError").style.display = 'none';
document.getElementById("bilAlrKnown").style.display = 'none';
return;
}
var exists = false;
HttpGetAsync("select distinct bilreg from lora_flaadestyring.bil_bilreg_euid",
function(json) {
//There's no way to break out of a foreach in js.
//Fix by changing to a regular for loop
json['features'].forEach(element => {
var bilreg = element.properties.bilreg
if (String(bilreg).toLowerCase() == String(field.value).toLowerCase()){
exists = true;
}
});
//Find out if we are updating an old car.
//If we are we need to validate the plate against existing records.
if (document.getElementById('nyBil').checked == false)
{
if (exists) {
bilregOK = true;
document.getElementById("bilRegNotKnown").style.display = 'none';
document.getElementById("bilRegError").style.display = 'none';
document.getElementById("bilAlrKnown").style.display = 'none';
showCarData(field.value)
} else {
bilregOK = false;
document.getElementById("bilRegNotKnown").style.display = 'block';
document.getElementById("bilRegError").style.display = 'none';
document.getElementById("bilAlrKnown").style.display = 'none';
}
}
else
{
//Check here if the car is already in the system.
if (exists) {
bilregOK = false;
document.getElementById("bilAlrKnown").style.display = 'block';
document.getElementById("bilRegNotKnown").style.display = 'none';
document.getElementById("bilRegError").style.display = 'none';
return;
}
//Verify format with regex
var re = /[A-Za-z]{2}\d{4,5}/;
if (re.test(String(field.value).toLowerCase())) {
//Test passed
bilregOK = true;
document.getElementById("bilRegError").style.display = 'none';
document.getElementById("bilRegNotKnown").style.display = 'none';
document.getElementById("bilAlrKnown").style.display = 'none';
} else {
//Test not passed
bilregOK = false;
document.getElementById("bilRegError").style.display = 'block';
document.getElementById("bilRegNotKnown").style.display = 'none';
document.getElementById("bilAlrKnown").style.display = 'none';
}
}
});
}
//Submit function
const DoSubmit = async () => {
var B = document.getElementById("bilReg").value;
var G = document.getElementById("gpsID").value;
var P = document.getElementById("parkering").value;
var A = document.getElementById("center").value;
if (B == "" || G == "" || P == "" || A == "" ) return false;
var query1;
var query2;
var query3;
if (document.getElementById('nyBil').checked == true) {
query1 = "INSERT INTO lora_flaadestyring.bil_bilreg_euid (eui, bilreg) VALUES ('"+G+"','"+B+"')";
query2 = "INSERT INTO lora_flaadestyring.bil_parkering_hjemme (bilreg, pnavn) VALUES ('"+B+"','"+P+"')";
query3 = "INSERT INTO lora_flaadestyring.bil_center (bilreg, center) VALUES ('"+B+"','"+A+"')";
HttpGetAsync(query1, function(json) { console.log('DONE: ' + query1) });
HttpGetAsync(query2, function(json) { console.log('DONE: ' + query2) });
HttpGetAsync(query3, function(json) { console.log('DONE: ' + query3) });
} else {
HttpGetAsync("SELECT COUNT(*) FROM lora_flaadestyring.bil_bilreg_euid WHERE bilreg = '"+B+"'", function(json){
if (json['features'][0]['properties']['count'] >= 1)
query1 = "UPDATE lora_flaadestyring.bil_bilreg_euid SET eui = '"+G+"' WHERE bilreg = '"+B+"'";
else
query1 = "INSERT INTO lora_flaadestyring.bil_bilreg_euid (eui, bilreg) VALUES ('"+G+"','"+B+"')";
HttpGetAsync("SELECT COUNT(*) FROM lora_flaadestyring.bil_parkering_hjemme WHERE bilreg = '"+B+"'", function(json) {
if (json['features'][0]['properties']['count'] >= 1)
query2 = "UPDATE lora_flaadestyring.bil_parkering_hjemme SET pnavn = '"+P+"' WHERE bilreg = '"+B+"'";
else
query2 = "INSERT INTO lora_flaadestyring.bil_parkering_hjemme (bilreg, pnavn) VALUES ('"+B+"','"+P+"')";
HttpGetAsync("SELECT COUNT(*) FROM lora_flaadestyring.bil_center WHERE bilreg = '"+B+"'", function(json) {
if (json['features'][0]['properties']['count'] >= 1)
query3 = "UPDATE lora_flaadestyring.bil_center SET center = '"+A+"' WHERE bilreg = '"+B+"'";
else
query3 = "INSERT INTO lora_flaadestyring.bil_center (bilreg, center) VALUES ('"+B+"','"+A+"')";
HttpGetAsync(query1, function(json) { console.log('DONE: ' + query1) });
HttpGetAsync(query2, function(json) { console.log('DONE: ' + query2) });
HttpGetAsync(query3, function(json) { console.log('DONE: ' + query3) });
});
});
});
}
return true;
}
// Delete record.
const DoDelete = async () => {
var B = document.getElementById("bilReg").value;
var G = document.getElementById("gpsID").value;
var P = document.getElementById("parkering").value;
var A = document.getElementById("center").value;
if (B == "" || G == "" || P == "" || A == "" ) return false;
var query_id = "UPDATE lora_flaadestyring.bil_bilreg_euid SET bilreg = '*mangler*' WHERE bilreg = '" + B + "'";
var query_park = "DELETE FROM lora_flaadestyring.bil_parkering_hjemme WHERE bilreg = '" + B + "'";
var query_center = "DELETE FROM lora_flaadestyring.bil_center WHERE bilreg = '" + B + "'";
// Check if car exists
HttpGetAsync("SELECT COUNT(*) FROM lora_flaadestyring.bil_bilreg_euid WHERE bilreg = '" + B + "'", function(json) {
if (json['features'][0]['properties']['count'] >= 1) {
HttpGetAsync(query_id, function(json) { console.log('DONE: ' + query_id) });
HttpGetAsync(query_park, function(json) { console.log('DONE: ' + query_park) });
HttpGetAsync(query_center, function(json) { console.log('DONE: ' + query_center) });
}
});
return true;
}
function nyBilChange() {
console.log("TestLog");
var ny = document.getElementById("nyBil").checked;
if (ny) {
disableBilregSearch();
} else {
enableBilregSearch();
}
}
function enableBilregSearch() {
var bilreg = document.getElementById("bilReg");
var arr = [];
var i = 0;
HttpGetAsync("select distinct bilreg from lora_flaadestyring.bil_bilreg_euid", function(json) {
json['features'].forEach(element => {
arr[i] = element.properties.bilreg;
i++;
})
autocomplete(bilreg, arr);
bilregIsSearch = true;
});
}
function disableBilregSearch() {
var bilreg = document.getElementById("bilReg");
removeautocomplete(bilreg);
}
//Make GPS a search field
function GPSSearch() {
var arr = [];
var i = 0;
let query = "select distinct eui from lora_flaadestyring.bil_bilreg_euid";
var ctrl = document.getElementById("gpsID");
HttpGetAsync(query, function(json) {
json['features'].forEach(element => {
arr[i] = element.properties.eui;
i++;
});
autocomplete(ctrl, arr);
});
}
// List parking places in dropdown
function populateParkingDropdown() {
var query = "SELECT distinct pnavn FROM lora_flaadestyring.p_pladser ORDER BY pnavn";
HttpGetAsync(query, function(json) {
json['features'].forEach(element => {
var node = document.createElement("option");
var textnode = document.createTextNode(element.properties.pnavn);
node.appendChild(textnode);
document.getElementById("parkering").appendChild(node);
});
});
}
function populateCenterDropdown() {
var query = "SELECT DISTINCT center FROM lora_flaadestyring.centre ORDER BY center";
HttpGetAsync(query, function(json) {
json['features'].forEach(element => {
var node = document.createElement("option");
node.appendChild(document.createTextNode(element.properties.center));
document.getElementById("center").appendChild(node);
});
});
}
// Table on listModal
function populateTable() {
$('#listModal').on('show.bs.modal', function (e) {
$("#allCars tr").remove();
var query = `SELECT DISTINCT bilreg, eui
FROM lora_flaadestyring.bil_bilreg_euid
WHERE bilreg != '*mangler*'`
HttpGetAsync(query, function(json) {
var $table = $('#allCars');
json['features'].forEach(element => {
var $tr = $('<tr><td><div>' + element.properties.bilreg + '</div></td><td><div>' + element.properties.eui + '</div></td></tr>').appendTo($table);
});
});
})
}
// Export list to Excel
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; } ) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
// Auto-fill form with car data
function showCarData(bilreg) {
var query =
`SELECT distinct a.bilreg, a.eui, b.pnavn, c.center
FROM lora_flaadestyring.bil_bilreg_euid a
LEFT JOIN lora_flaadestyring.bil_parkering_hjemme b
ON a.bilreg = b.bilreg
LEFT JOIN lora_flaadestyring.bil_center c
ON a.bilreg = c.bilreg
WHERE a.bilreg = '` + bilreg + "'"
HttpGetAsync(query, function(json) {
json['features'].forEach(element => {
$('#gpsID').val(element.properties.eui);
$('#parkering').val(element.properties.pnavn);
$('#center').val(element.properties.center);
});
});
}
// Start GC2 session and get API key.
function login() {
user = String($( "#user" ).val())
password = String($( "#pw" ).val())
url = "https://ballerup.mapcentia.com/api/v1/session/start"
$.post( url, { u: user, p: password }, function( data ) {
//Storing API key in globale variable
api_key = data.api_key;
user_name = user;
prepareForm();
}).fail(function() {
alert( "Forkert GC2 bruger eller password" );
$("#myModal").modal({backdrop: 'static', keyboard: false});
});
}
$(function() {
$('.modal-content').keypress(function(e) {
if (e.which == 13) $('#gc2login').click();
})
})
function stateDeleteBtn() {
// Delete button toggle active
var checker = document.getElementById('nyBil');
var btn = document.getElementById('del');
checker.onchange = function() {
btn.disabled = !!this.checked;
};
}
// Handling events etc.
$( document ).ready(function() {
$("#IE").hide();
$( "#gc2login" ).click(function() {
login();
});
stateDeleteBtn();
$( "#delete" ).click(function() {
$('#confirm').modal('hide')
DoDelete().then((result) => {
if (result) {
$("#DeleteSuccess").show();
hideAlertsWithDelay();
} else {
$("#InsertError").show();
hideAlertsWithDelay();
}
});
// Reset form
var form = document.getElementById("mainForm");
form.reset()
// Prepare form after reset
setTimeout(function() {
GPSSearch();
//activate btn after submit
$("#del").prop("disabled",false);
nyBilChange()
}, 1);
});
$("#myModal").modal({backdrop: 'static', keyboard: false});
});
function prepareForm() {
populateParkingDropdown();
populateCenterDropdown();
GPSSearch();
enableBilregSearch();
populateTable();
document.getElementById("loginButton").style.display = 'none';
document.getElementById("loginName").style.display = 'block';
document.getElementById("loginName").innerHTML = user_name;
var form = document.getElementById("mainForm");
function onSubmit(event) {
if (event) {event.preventDefault();}
if (!api_key) {$("#myModal").modal(); return;}
validateBilreg();
if (!bilregOK) return;
//Do submission of data async, if succesful reload page
DoSubmit().then((result) => {
if (result) {
$("#InsertSuccess").show();
hideAlertsWithDelay();
form.reset();
// executes after the form has been reset
setTimeout(function() {
GPSSearch();
//activate btn after submit
$("#del").prop("disabled",false);
nyBilChange()
}, 1);
} else {
$("#InsertError").show();
hideAlertsWithDelay(8000);
}
});
}
form.addEventListener('submit', onSubmit, false);
}
function hideAlertsWithDelay(delay = 6000) {
window.setTimeout(function(){
$(".alert").fadeTo(500,0).slideUp(500, function(){
$(this).hide();
});
}, delay);
}
//Autocomplete functionality
//Remove autocomplete to control
function removeautocomplete(inp) {
let clone = inp.cloneNode();
while (inp.firstChild) {
clone.appendChild(inp.lastChild);
}
inp.parentNode.replaceChild(clone, inp);
clone.focus();
}
//Add autocomplete to control
function autocomplete(inp, arr) {
var currentFocus;
function input_listener(e) {
var a, b, i, val = this.value;
closeAllLists();
if (!val) {return false;}
currentFocus = -1;
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
this.parentNode.appendChild(a);
for (i = 0; i < arr.length; i++) {
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
b = document.createElement("DIV");
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
b.innerHTML += "<input type='hidden' value = '" + arr[i] + "'>";
b.addEventListener("click", function(e) {
inp.value = this.getElementsByTagName("input")[0].value;
closeAllLists();
}, false);
a.appendChild(b);
}
}
}
inp.addEventListener("input", input_listener, false);
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
e.preventDefault();
currentFocus++;
addActive(x);
} else if (e.keyCode == 38) {
e.preventDefault();
currentFocus--;
addActive(x);
} else if (e.keyCode == 13) {
e.preventDefault();
if (currentFocus > -1) {
if (x) x[currentFocus].click();
}
}
}, false);
function addActive(x) {
if (!x) return false;
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
document.addEventListener("click", function(e) {
closeAllLists(e.target);
}, false);
}