Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
4618 lines (4086 loc) Β· 188 KB
/
Copy pathscript.js
File metadata and controls
4618 lines (4086 loc) Β· 188 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
console.log('SCRIPT LOADED: script.js');
if (typeof AndroidBridge !== 'undefined') {
document.documentElement.classList.add('is-android-app');
document.addEventListener('DOMContentLoaded', () => {
if (document.body) document.body.classList.add('is-android-app');
});
}
// Android SMB client bridge wrapper
window.AndroidSMB = {
callbacks: {},
callbackCounter: 0,
isAndroid: function () {
return typeof AndroidBridge !== 'undefined';
},
testConnection: function (server, share, path, username, password, domain) {
return new Promise((resolve, reject) => {
const callbackId = 'cb_' + (this.callbackCounter++);
this.callbacks[callbackId] = { resolve, reject };
AndroidBridge.testConnection(server, share, path, username, password, domain, callbackId);
});
},
pushFile: function (server, share, path, filename, content, username, password, domain) {
return new Promise((resolve, reject) => {
const callbackId = 'cb_' + (this.callbackCounter++);
this.callbacks[callbackId] = { resolve, reject };
AndroidBridge.pushFile(server, share, path, filename, content, username, password, domain, callbackId);
});
},
pullFile: function (server, share, path, filename, username, password, domain) {
return new Promise((resolve, reject) => {
const callbackId = 'cb_' + (this.callbackCounter++);
this.callbacks[callbackId] = { resolve, reject };
AndroidBridge.pullFile(server, share, path, filename, username, password, domain, callbackId);
});
},
getFileModifiedTime: function (server, share, path, filename, username, password, domain) {
return new Promise((resolve, reject) => {
const callbackId = 'cb_' + (this.callbackCounter++);
this.callbacks[callbackId] = { resolve, reject };
AndroidBridge.getFileModifiedTime(server, share, path, filename, username, password, domain, callbackId);
});
},
onResult: function (callbackId, success, resultOrError) {
const callback = this.callbacks[callbackId];
if (!callback) return;
delete this.callbacks[callbackId];
if (success) {
callback.resolve(resultOrError);
} else {
callback.reject(new Error(resultOrError));
}
}
};
// IndexedDB Card Image Cache Database Manager
const DB_NAME = 'travel_planner_images_db';
const DB_VERSION = 1;
const STORE_NAME = 'cached_images';
let dbInstance = null;
function getImageDB() {
return new Promise((resolve, reject) => {
if (dbInstance) return resolve(dbInstance);
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = function (e) {
const db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
};
request.onsuccess = function (e) {
dbInstance = e.target.result;
resolve(dbInstance);
};
request.onerror = function (e) {
reject(e.target.error);
};
});
}
function getCachedImage(url) {
return getImageDB().then(db => {
return new Promise((resolve) => {
const tx = db.transaction(STORE_NAME, 'readonly');
const store = tx.objectStore(STORE_NAME);
const req = store.get(url);
req.onsuccess = function () {
resolve(req.result || null);
};
req.onerror = function () {
resolve(null);
};
});
});
}
function setCachedImage(url, dataUrl) {
return getImageDB().then(db => {
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readwrite');
const store = tx.objectStore(STORE_NAME);
const req = store.put(dataUrl, url);
req.onsuccess = () => resolve();
req.onerror = () => reject(req.error);
});
});
}
function applyCardImage(url, cardElement, locationId) {
if (!url || !url.startsWith('http')) return;
getCachedImage(url).then(cached => {
if (cached) {
const imgDiv = (cardElement && cardElement.querySelector) ? cardElement.querySelector('.card-image') : document.getElementById(`card-image-${locationId}`);
if (imgDiv) imgDiv.style.backgroundImage = `url('${cached}')`;
} else {
// Silently attempt background caching to IndexedDB if environment allows
fetch(url)
.then(res => {
if (!res.ok) throw new Error('Fetch failed');
return res.blob();
})
.then(blob => {
const reader = new FileReader();
reader.onloadend = function () {
const dataUrl = reader.result;
setCachedImage(url, dataUrl).then(() => {
const curEl = (cardElement && cardElement.querySelector) ? cardElement.querySelector('.card-image') : document.getElementById(`card-image-${locationId}`);
if (curEl) curEl.style.backgroundImage = `url('${dataUrl}')`;
}).catch(() => { });
};
reader.readAsDataURL(blob);
})
.catch(() => {
// Suppress CORS fetch errors when running locally via file://
});
}
}).catch(() => { });
}
// State Management
let locations = JSON.parse(localStorage.getItem('travel_planner_locations')) || [];
let showRestaurants = localStorage.getItem('travel_planner_show_restaurants') !== 'false'; // Default true
let showSupermarkets = false; // Default false (heavy load)
let map;
let mapTileLayer;
let markers = [];
let restaurantMarkers = [];
let supermarketMarkers = [];
let travelTimeMarkers = [];
let polyline;
let tempClickCoords = null;
let currentTheme = localStorage.getItem('travel_planner_theme') || 'dark';
let globeView = localStorage.getItem('travel_planner_globe_view') === 'true';
let globeInstance = null;
let isGlobeActive = false;
let groupingEnabled = localStorage.getItem('travel_planner_grouping_enabled') === 'true';
let collapsedGroups = JSON.parse(localStorage.getItem('travel_planner_collapsed_groups')) || [];
let isTransitioning = false;
let restaurants = JSON.parse(localStorage.getItem('travel_planner_restaurants')) || [];
// Linked File State (Retired)
let autoSync = false;
// Network Sync State (Retired)
let syncEnabled = false;
let syncUrl = localStorage.getItem('travel_planner_sync_url') || '';
let kmlFileName = localStorage.getItem('travel_planner_kml_filename') || 'travel_planner_itinerary.kml';
let csvFileName = localStorage.getItem('travel_planner_csv_filename') || 'restaurants.csv';
let syncUsername = localStorage.getItem('travel_planner_sync_username') || '';
let syncPassword = localStorage.getItem('travel_planner_sync_password') || '';
let lastSyncTime = localStorage.getItem('travel_planner_last_sync_time') || 'Never';
// SMB Sync State
let smbEnabled = localStorage.getItem('travel_planner_smb_enabled') === 'true';
let smbAutoSync = localStorage.getItem('travel_planner_smb_autosync') !== 'false';
let smbServer = localStorage.getItem('travel_planner_smb_server') || '';
let smbShare = localStorage.getItem('travel_planner_smb_share') || '';
let smbPath = localStorage.getItem('travel_planner_smb_path') || '';
let smbUsername = localStorage.getItem('travel_planner_smb_username') || '';
let smbPassword = localStorage.getItem('travel_planner_smb_password') || '';
let smbDomain = localStorage.getItem('travel_planner_smb_domain') || '';
let smbLastModifiedKml = localStorage.getItem('travel_planner_smb_last_modified_kml') || '0';
let smbLastModifiedCsv = localStorage.getItem('travel_planner_smb_last_modified_csv') || '0';
let lastSmbSyncTime = localStorage.getItem('travel_planner_last_smb_sync_time') || 'Never';
// Currency conversion & exchange rates
let settingsCurrency = localStorage.getItem('travel_planner_settings_currency') || 'NZD';
let exchangeRates = JSON.parse(localStorage.getItem('travel_planner_exchange_rates')) || {
"USD": 1,
"EUR": 0.92,
"NZD": 1.63,
"AUD": 1.51,
"GBP": 0.78,
"CAD": 1.36,
"JPY": 159.20,
"CHF": 0.89,
"ZAR": 18.25
};
async function fetchExchangeRates() {
const lastFetch = parseInt(localStorage.getItem('travel_planner_exchange_rates_fetched_time')) || 0;
const oneDay = 24 * 60 * 60 * 1000;
if (Date.now() - lastFetch < oneDay && Object.keys(exchangeRates).length > 5) {
console.log('Exchange rates are up to date (fetched within 24h).');
return;
}
try {
console.log('Fetching fresh exchange rates...');
const response = await fetch('https://open.er-api.com/v6/latest/USD');
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
if (data && data.rates) {
exchangeRates = data.rates;
localStorage.setItem('travel_planner_exchange_rates', JSON.stringify(exchangeRates));
localStorage.setItem('travel_planner_exchange_rates_fetched_time', Date.now().toString());
console.log('Exchange rates updated successfully:', exchangeRates);
}
} catch (err) {
console.warn('Failed to fetch exchange rates, using cached/fallback rates:', err);
}
}
// DOM Elements (Initialized in DOMContentLoaded)
let locationModal;
let locationForm;
let locationSearch;
let itineraryList;
let locationCount;
let exportBtn;
let resetBtn;
let fullscreenBtn;
let themeToggleBtn;
let importRestaurantsBtn;
let importRestaurantsFile;
// Initialize App
document.addEventListener('DOMContentLoaded', () => {
console.log('App Initializing...');
fetchExchangeRates();
// Initialize DOM Elements
locationModal = document.getElementById('locationModal');
locationForm = document.getElementById('locationForm');
locationSearch = document.getElementById('locationSearch');
itineraryList = document.getElementById('itineraryList');
locationCount = document.getElementById('locationCount');
exportBtn = document.getElementById('exportBtn');
resetBtn = document.getElementById('resetBtn'); // Keep for safety or remove if unused in header
fullscreenBtn = document.getElementById('fullscreenBtn');
themeToggleBtn = document.getElementById('themeToggle');
// New Settings Elements
importRestaurantsFile = document.getElementById('importRestaurantsFile');
importFile = document.getElementById('importFile');
initMap();
renderApp();
setupEventListeners();
initMapResizer();
setupDragAndDrop();
// Load persisted restaurants
if (restaurants.length > 0) {
console.log(`Loading ${restaurants.length} persisted restaurants...`);
restaurants.forEach(r => addRestaurantMarker(r));
}
// Try to restore linked files from IndexedDB
restoreLinkedFiles();
// Apply persisted states
if (globeView) toggleGlobeView(true);
const groupingToggle = document.getElementById('toggleGrouping');
if (groupingToggle) {
groupingToggle.checked = groupingEnabled;
groupingToggle.addEventListener('change', (e) => {
groupingEnabled = e.target.checked;
localStorage.setItem('travel_planner_grouping_enabled', groupingEnabled);
updateSortableState();
renderApp();
});
}
// Show SMB Sync options if running on Android
if (window.AndroidSMB.isAndroid()) {
const smbGroup = document.getElementById('smbSettingsGroup');
if (smbGroup) smbGroup.style.display = 'block';
// Initial pull if enabled
if (smbEnabled) {
setTimeout(() => {
smbPullAll();
}, 1000);
}
// Periodic auto-update check
setInterval(smbCheckForUpdates, 15000); // Check every 15s
// Also check on window focus/visibilitychange
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') {
smbCheckForUpdates();
}
});
}
});
// Map Initialization
function initMap() {
// Default view (Europe)
map = L.map('map', {
dragging: true,
tap: true,
touchZoom: true,
zoomSnap: 0.1,
zoomDelta: 0.5,
wheelPxPerZoomLevel: 120,
attributionControl: false
}).setView([48.8566, 2.3522], 5);
// Initialize with current theme
setMapTheme(currentTheme);
updateThemeIcon();
// Map Click Handler
map.on('click', (e) => {
tempClickCoords = e.latlng;
openModal();
});
// Auto-switch to globe when user zooms out to world scale on flat map
map.on('zoomend', () => {
if (globeView && !isGlobeActive && !isTransitioning && map.getZoom() < 4) {
const center = map.getCenter().wrap(); // Ensure lng stays in [-180, 180]
const targetAlt = zoomToAltitude(map.getZoom());
executeViewSwap(true, { lat: center.lat, lng: center.lng, altitude: targetAlt });
}
});
}
// Set Map Theme
function setMapTheme(theme) {
// Remove existing tile layer if it exists
if (mapTileLayer) {
map.removeLayer(mapTileLayer);
}
if (theme === 'dark') {
// Dark mode - CartoDB Dark Matter
mapTileLayer = L.tileLayer('https://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}{r}.png', {
attribution: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>',
subdomains: 'abcd',
maxZoom: 20
}).addTo(map);
} else {
// Light mode - ArcGIS NatGeo World Map
mapTileLayer = L.tileLayer('http://services.arcgisonline.com/arcgis/rest/services/NatGeo_World_Map/MapServer/tile/{z}/{y}/{x}', {
attribution: '© <a href="https://www.esri.com">Esri</a>, NatGeo',
maxZoom: 20
}).addTo(map);
}
document.body.classList.toggle('dark-map-theme', theme === 'dark');
}
// Toggle Theme
function toggleTheme() {
currentTheme = currentTheme === 'dark' ? 'light' : 'dark';
localStorage.setItem('travel_planner_theme', currentTheme);
setMapTheme(currentTheme);
updateThemeIcon();
renderMapElements(); // Re-render to update polyline color
}
// Update Theme Icon
function updateThemeIcon() {
const icon = themeToggleBtn.querySelector('i');
if (currentTheme === 'dark') {
icon.className = 'fa-solid fa-moon';
} else {
icon.className = 'fa-solid fa-sun';
}
}
// Render App (Map Markers + Itinerary Cards)
function renderApp() {
renderMapElements();
renderItineraryList();
updateStats();
updateGlobeData(); // Keep 3D globe in sync if active
updateTagSuggestions();
}
// Calculate distance between two points (Haversine formula)
function calculateDistance(lat1, lng1, lat2, lng2) {
const R = 6371; // Earth's radius in km
const dLat = (lat2 - lat1) * Math.PI / 180;
const dLng = (lng2 - lng1) * Math.PI / 180;
const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
Math.sin(dLng / 2) * Math.sin(dLng / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c; // Distance in km
}
// Estimate travel time based on mode and distance
function estimateTravelTime(distance, mode) {
// Average speeds in km/h
const speeds = {
'walking': 5,
'biking': 15,
'car': 40, // Reduced from 60 to add ~50% more time for realistic estimates
'train': 80,
'boat': 30,
'plane': 500
};
const speed = speeds[mode] || 50; // Default 50 km/h if no mode
const hours = distance / speed;
if (hours < 1) {
const minutes = Math.round(hours * 60);
return `~${minutes}min`;
} else if (hours < 24) {
const h = Math.floor(hours);
const m = Math.round((hours - h) * 60);
return m > 0 ? `~${h}h ${m}min` : `~${h}h`;
} else {
const days = Math.round(hours / 24 * 10) / 10;
return `~${days} days`;
}
}
// Day Trip Helper Functions
function toggleDayTripLines(locId, showLines) {
const loc = locations.find(l => l.id === locId);
if (loc) {
loc.hideDayTripLines = !showLines;
renderMapElements();
saveData();
}
}
function toggleNextLine(locId, showLine) {
const loc = locations.find(l => l.id === locId);
if (loc) {
loc.hideNextLine = !showLine;
renderMapElements();
saveData();
}
}
function addDayTrip(parentId, editTripId = null) {
const loc = locations.find(l => l.id === parentId);
if (!loc) return;
// Find the form container within the card
const card = document.querySelector(`[data-id="${parentId}"]`);
if (!card) return;
const section = card.querySelector('.day-trips-section');
if (!section) return;
// Remove existing form if any
const existingForm = section.querySelector('.day-trip-form');
if (existingForm) {
existingForm.remove();
// If we clicked the same Add/Edit button, just toggle off
if (existingForm.dataset.mode === (editTripId ? 'edit' : 'add')) return;
}
let editTrip = null;
if (editTripId && loc.dayTrips) {
editTrip = loc.dayTrips.find(t => t.id === editTripId);
}
const form = document.createElement('div');
form.className = 'day-trip-form';
form.dataset.mode = editTrip ? 'edit' : 'add';
form.innerHTML = `
<div style="position: relative;">
<input type="text" class="dt-search" placeholder="Search location...">
<i class="fa-solid fa-magnifying-glass" style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); color: #64748b; font-size: 0.75rem;"></i>
</div>
<input type="text" class="dt-name" placeholder="Name (e.g., Mostar)">
<div class="form-row">
<input type="number" class="dt-lat" step="any" placeholder="Latitude">
<input type="number" class="dt-lng" step="any" placeholder="Longitude">
</div>
<textarea class="dt-notes" rows="2" placeholder="Notes (optional)"></textarea>
<div class="day-trip-form-actions">
<button type="button" class="cancel-trip-btn">Cancel</button>
<button type="button" class="save-trip-btn"><i class="fa-solid fa-plus"></i> Add</button>
</div>
`;
section.appendChild(form);
// Stop click propagation on entire form
form.addEventListener('click', e => e.stopPropagation());
// Search handler
const searchInput = form.querySelector('.dt-search');
const nameInput = form.querySelector('.dt-name');
const latInput = form.querySelector('.dt-lat');
const lngInput = form.querySelector('.dt-lng');
const searchIcon = form.querySelector('.fa-magnifying-glass');
searchInput.addEventListener('input', debounce(async (e) => {
const query = e.target.value.trim();
if (query.length < 3) return;
if (searchIcon) searchIcon.className = 'fa-solid fa-spinner fa-spin';
try {
const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}`);
const data = await response.json();
if (searchIcon) searchIcon.className = 'fa-solid fa-magnifying-glass';
if (data && data.length > 0) {
const result = data[0];
latInput.value = parseFloat(result.lat).toFixed(4);
lngInput.value = parseFloat(result.lon).toFixed(4);
if (!nameInput.value) {
nameInput.value = result.name || query;
}
}
} catch (err) {
if (searchIcon) searchIcon.className = 'fa-solid fa-triangle-exclamation';
}
}, 1200));
if (editTrip) {
nameInput.value = editTrip.name;
latInput.value = editTrip.lat;
lngInput.value = editTrip.lng;
form.querySelector('.dt-notes').value = editTrip.notes || '';
form.querySelector('.save-trip-btn').innerHTML = '<i class="fa-solid fa-save"></i> Save';
}
// Cancel
form.querySelector('.cancel-trip-btn').addEventListener('click', (e) => {
e.stopPropagation();
form.remove();
});
// Save
form.querySelector('.save-trip-btn').addEventListener('click', (e) => {
e.stopPropagation();
const name = nameInput.value.trim();
const lat = parseFloat(latInput.value);
const lng = parseFloat(lngInput.value);
const notes = form.querySelector('.dt-notes').value.trim();
if (!name || isNaN(lat) || isNaN(lng)) {
alert('Please provide a name and valid coordinates (use search to auto-fill).');
return;
}
if (editTrip) {
editTrip.name = name;
editTrip.lat = lat;
editTrip.lng = lng;
editTrip.notes = notes;
} else {
if (!loc.dayTrips) loc.dayTrips = [];
loc.dayTrips.push({
id: 'dt_' + Date.now().toString(),
name: name,
lat: lat,
lng: lng,
notes: notes
});
}
renderApp();
saveData();
});
// Focus search input
setTimeout(() => searchInput.focus(), 50);
}
function removeDayTrip(parentId, tripId) {
const loc = locations.find(l => l.id === parentId);
if (!loc || !loc.dayTrips) return;
loc.dayTrips = loc.dayTrips.filter(t => t.id !== tripId);
renderApp();
saveData();
}
function moveDayTrip(parentId, tripId, direction) {
const loc = locations.find(l => l.id === parentId);
if (!loc || !loc.dayTrips) return;
const idx = loc.dayTrips.findIndex(t => t.id === tripId);
if (idx === -1) return;
const targetIdx = direction === 'up' ? idx - 1 : idx + 1;
if (targetIdx < 0 || targetIdx >= loc.dayTrips.length) return;
const temp = loc.dayTrips[idx];
loc.dayTrips[idx] = loc.dayTrips[targetIdx];
loc.dayTrips[targetIdx] = temp;
renderApp();
saveData();
}
// Modal Day Trip State & Functions
let modalDayTrips = [];
function renderModalDayTrips() {
const list = document.getElementById('modalDayTripsList');
if (!list) return;
list.innerHTML = '';
modalDayTrips.forEach((trip, ti) => {
const subNum = String(ti + 1).padStart(2, '0');
const item = document.createElement('div');
item.className = 'day-trip-item';
item.innerHTML = `
<div class="day-trip-number">${subNum}</div>
<div class="day-trip-info">
<div class="day-trip-name">${trip.name}</div>
${trip.notes ? `<div class="day-trip-notes">${trip.notes}</div>` : ''}
</div>
<div class="day-trip-actions" style="opacity:1;">
<button type="button" class="day-trip-action-btn edit" title="Edit"><i class="fa-solid fa-pen"></i></button>
<button type="button" class="day-trip-action-btn" title="Move Up"><i class="fa-solid fa-chevron-up"></i></button>
<button type="button" class="day-trip-action-btn" title="Move Down"><i class="fa-solid fa-chevron-down"></i></button>
<button type="button" class="day-trip-action-btn delete" title="Remove"><i class="fa-solid fa-xmark"></i></button>
</div>
`;
const btns = item.querySelectorAll('.day-trip-action-btn');
btns[0].addEventListener('click', (e) => { e.stopPropagation(); showModalDayTripForm(ti); });
btns[1].addEventListener('click', (e) => { e.stopPropagation(); modalMoveDayTrip(ti, 'up'); });
btns[2].addEventListener('click', (e) => { e.stopPropagation(); modalMoveDayTrip(ti, 'down'); });
btns[3].addEventListener('click', (e) => { e.stopPropagation(); modalRemoveDayTrip(ti); });
list.appendChild(item);
});
}
function modalRemoveDayTrip(index) {
modalDayTrips.splice(index, 1);
renderModalDayTrips();
}
function modalMoveDayTrip(index, direction) {
const targetIdx = direction === 'up' ? index - 1 : index + 1;
if (targetIdx < 0 || targetIdx >= modalDayTrips.length) return;
const temp = modalDayTrips[index];
modalDayTrips[index] = modalDayTrips[targetIdx];
modalDayTrips[targetIdx] = temp;
renderModalDayTrips();
}
function showModalDayTripForm(editIndex = null) {
const container = document.getElementById('modalDayTripForm');
if (!container) return;
// Toggle off if already visible and clicking same action
if (container.style.display !== 'none') {
const currentMode = container.dataset.mode;
const newMode = editIndex !== null ? 'edit' : 'add';
if (currentMode === newMode) {
container.style.display = 'none';
container.innerHTML = '';
return;
}
}
let editTrip = null;
if (editIndex !== null && editIndex >= 0 && editIndex < modalDayTrips.length) {
editTrip = modalDayTrips[editIndex];
}
container.dataset.mode = editTrip ? 'edit' : 'add';
container.style.display = 'block';
container.innerHTML = `
<div class="day-trip-form">
<div style="position: relative;">
<input type="text" class="dt-search" placeholder="Search location...">
<i class="fa-solid fa-magnifying-glass" style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); color: #64748b; font-size: 0.75rem;"></i>
</div>
<input type="text" class="dt-name" placeholder="Name (e.g., Mostar)">
<div class="form-row">
<input type="number" class="dt-lat" step="any" placeholder="Latitude">
<input type="number" class="dt-lng" step="any" placeholder="Longitude">
</div>
<textarea class="dt-notes" rows="2" placeholder="Notes (optional)"></textarea>
<div class="day-trip-form-actions">
<button type="button" class="cancel-trip-btn">Cancel</button>
<button type="button" class="save-trip-btn"><i class="fa-solid fa-plus"></i> Add</button>
</div>
</div>
`;
const form = container.querySelector('.day-trip-form');
const searchInput = form.querySelector('.dt-search');
const nameInput = form.querySelector('.dt-name');
const latInput = form.querySelector('.dt-lat');
const lngInput = form.querySelector('.dt-lng');
const searchIcon = form.querySelector('.fa-magnifying-glass');
searchInput.addEventListener('input', debounce(async (e) => {
const query = e.target.value.trim();
if (query.length < 3) return;
if (searchIcon) searchIcon.className = 'fa-solid fa-spinner fa-spin';
try {
const response = await fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}`);
const data = await response.json();
if (searchIcon) searchIcon.className = 'fa-solid fa-magnifying-glass';
if (data && data.length > 0) {
const result = data[0];
latInput.value = parseFloat(result.lat).toFixed(4);
lngInput.value = parseFloat(result.lon).toFixed(4);
if (!nameInput.value) {
nameInput.value = result.name || query;
}
}
} catch (err) {
if (searchIcon) searchIcon.className = 'fa-solid fa-triangle-exclamation';
}
}, 1200));
if (editTrip) {
nameInput.value = editTrip.name;
latInput.value = editTrip.lat;
lngInput.value = editTrip.lng;
form.querySelector('.dt-notes').value = editTrip.notes || '';
form.querySelector('.save-trip-btn').innerHTML = '<i class="fa-solid fa-save"></i> Save';
}
form.querySelector('.cancel-trip-btn').addEventListener('click', () => {
container.style.display = 'none';
container.innerHTML = '';
});
form.querySelector('.save-trip-btn').addEventListener('click', () => {
const name = nameInput.value.trim();
const lat = parseFloat(latInput.value);
const lng = parseFloat(lngInput.value);
const notes = form.querySelector('.dt-notes').value.trim();
if (!name || isNaN(lat) || isNaN(lng)) {
alert('Please provide a name and valid coordinates (use search to auto-fill).');
return;
}
if (editTrip) {
editTrip.name = name;
editTrip.lat = lat;
editTrip.lng = lng;
editTrip.notes = notes;
} else {
modalDayTrips.push({
id: 'dt_' + Date.now().toString(),
name: name,
lat: lat,
lng: lng,
notes: notes
});
}
renderModalDayTrips();
container.style.display = 'none';
container.innerHTML = '';
});
setTimeout(() => searchInput.focus(), 50);
}
// Render Map Elements (Markers & Polyline)
function renderMapElements(overrideTheme) {
const theme = overrideTheme || currentTheme;
// Clear existing
markers.forEach(marker => map.removeLayer(marker));
markers = [];
travelTimeMarkers.forEach(marker => map.removeLayer(marker));
travelTimeMarkers = [];
if (polyline) map.removeLayer(polyline);
let activeCount = 0;
const activeLocations = locations.filter(l => !l.disabled);
// Add Markers
locations.forEach((loc, index) => {
let markerContent = '';
let markerColor = '#00d2ff'; // Default Cyan
let markerBorder = '#0f172a';
let zIndex = 1000;
if (loc.disabled) {
markerColor = '#64748b'; // Grey for disabled
markerContent = '<i class="fa-solid fa-eye-slash" style="font-size: 12px;"></i>';
zIndex = 500;
} else {
activeCount++;
markerContent = activeCount;
}
const customIcon = L.divIcon({
className: 'custom-map-marker',
html: `<div style="
background-color: ${markerColor};
width: 30px;
height: 30px;
border-radius: 50%;
border: 3px solid ${markerBorder};
display: flex;
align-items: center;
justify-content: center;
color: ${markerBorder};
font-weight: bold;
font-family: 'Outfit', sans-serif;
box-shadow: 0 4px 10px rgba(0,0,0,0.5);
opacity: ${loc.disabled ? 0.7 : 1};
">${markerContent}</div>`,
iconSize: [30, 30],
iconAnchor: [15, 15]
});
// Build activities HTML
let activitiesHTML = '';
if (loc.activities.allDay) {
activitiesHTML += `<p style="margin: 5px 0;"><strong>π All Day:</strong> ${loc.activities.allDay}</p>`;
}
if (loc.activities.morning) {
activitiesHTML += `<p style="margin: 5px 0;"><strong>π
Morning:</strong> ${loc.activities.morning}</p>`;
}
if (loc.activities.afternoon) {
activitiesHTML += `<p style="margin: 5px 0;"><strong>π Afternoon:</strong> ${loc.activities.afternoon}</p>`;
}
// Build day trips HTML for popup
let dayTripsPopupHTML = '';
if (loc.dayTrips && loc.dayTrips.length > 0) {
dayTripsPopupHTML = `<p style="margin: 8px 0 4px 0; font-weight: bold; border-top: 1px solid #ddd; padding-top: 6px;">π Activities:</p>`;
loc.dayTrips.forEach((trip, ti) => {
const subNum = `${activeCount}-${String(ti + 1).padStart(2, '0')}`;
dayTripsPopupHTML += `<p style="margin: 3px 0; font-size: 0.9em;"><strong>${subNum}</strong> ${trip.name}${trip.notes ? ` β ${trip.notes}` : ''}</p>`;
});
}
if (!activitiesHTML && !dayTripsPopupHTML) {
activitiesHTML = '<p style="margin: 5px 0; color: #888;">No activities set</p>';
}
const marker = L.marker([loc.lat, loc.lng], {
icon: customIcon,
zIndexOffset: zIndex
})
.addTo(map)
.bindPopup(`
<div style="font-family: 'Outfit', sans-serif; color: #0f172a; min-width: 200px;">
<h3 style="margin: 0 0 10px 0; color: ${markerColor}; text-align: center;">${loc.name} ${loc.disabled ? '(Disabled)' : ''}</h3>
${activitiesHTML}
${dayTripsPopupHTML}
</div>
`);
markers.push(marker);
// Add bed marker for accommodation if coordinates exist
if (loc.stayLat && loc.stayLng && !loc.disabled) {
const bedIcon = L.divIcon({
className: 'custom-map-marker',
html: `<div style="
background-color: #9b59b6;
width: 26px;
height: 26px;
border-radius: 50%;
border: 2px solid white;
display: flex;
align-items: center;
justify-content: center;
color: white;
box-shadow: 0 3px 8px rgba(0,0,0,0.4);
"><i class="fa-solid fa-bed" style="font-size: 12px;"></i></div>`,
iconSize: [26, 26],
iconAnchor: [13, 13]
});
const bedMarker = L.marker([loc.stayLat, loc.stayLng], {
icon: bedIcon,
zIndexOffset: 800
})
.addTo(map)
.bindPopup(`
<div style="font-family: 'Outfit', sans-serif; color: #0f172a; min-width: 180px;">
<h3 style="margin: 0 0 5px 0; color: #9b59b6; text-align: center;"><i class="fa-solid fa-bed"></i> Stay</h3>
<p style="margin: 5px 0; text-align: center;"><strong>${loc.placeToStay || 'Accommodation'}</strong></p>
${loc.stayAddress ? `<p style="margin: 5px 0; font-size: 0.9em; color: #666; text-align: center;">${loc.stayAddress}</p>` : ''}
${loc.stayDateFrom && loc.stayDateTo ? `<p style="margin: 8px 0 0 0; padding-top: 8px; border-top: 1px solid #ddd; text-align: center; font-size: 0.85em;">
<i class="fa-solid fa-moon" style="color: #9b59b6;"></i>
<strong>${Math.round((new Date(loc.stayDateTo) - new Date(loc.stayDateFrom)) / (1000 * 60 * 60 * 24))} nights</strong>
${loc.checkoutTime ? `<br><i class="fa-solid fa-clock" style="color: #888;"></i> Check-out: ${loc.checkoutTime}` : ''}
</p>` : ''}
</div>
`);
markers.push(bedMarker);
}
// Add day trip sub-markers
if (loc.dayTrips && loc.dayTrips.length > 0 && !loc.disabled) {
loc.dayTrips.forEach((trip, tripIndex) => {
const subNum = String(tripIndex + 1).padStart(2, '0');
const fullSubNum = `${activeCount}-${subNum}`;
const dtIcon = L.divIcon({
className: 'custom-map-marker',
html: `<div style="
background-color: #f59e0b;
width: 30px;
height: 30px;
border-radius: 50%;
border: 3px solid #0f172a;
display: flex;
align-items: center;
justify-content: center;
color: #0f172a;
font-weight: bold;
font-family: 'Outfit', sans-serif;
font-size: 11px;
box-shadow: 0 4px 10px rgba(0,0,0,0.5);
">${subNum}</div>`,
iconSize: [30, 30],
iconAnchor: [15, 15]
});
const dtMarker = L.marker([trip.lat, trip.lng], {
icon: dtIcon,
zIndexOffset: 900
})
.addTo(map)
.bindPopup(`
<div style="font-family: 'Outfit', sans-serif; color: #0f172a; min-width: 180px;">
<h3 style="margin: 0 0 5px 0; color: #f59e0b; text-align: center;">
<span style="font-size: 0.8em; opacity: 0.7;">${fullSubNum}</span> ${trip.name}
</h3>
<p style="margin: 3px 0; font-size: 0.85em; color: #666; text-align: center;">Activity from ${loc.name}</p>
${trip.notes ? `<p style="margin: 5px 0; font-size: 0.9em;">${trip.notes}</p>` : ''}
</div>
`);
markers.push(dtMarker);
// Draw dashed connector line from parent to day trip
if (!loc.hideDayTripLines) {
const dtLineColor = theme === 'light' ? '#d97706' : '#f59e0b';
const dtLine = L.polyline([[loc.lat, loc.lng], [trip.lat, trip.lng]], {
color: dtLineColor,
weight: 3,
opacity: 0.7,
dashArray: '10, 10',
lineCap: 'round'
}).addTo(map);
travelTimeMarkers.push(dtLine); // Reuse array for cleanup
}
});
}
});
// Draw Polyline (Only for active locations)
if (activeLocations.length > 1) {
const lineColor = theme === 'light' ? '#000000' : '#00d2ff';
// Add travel time labels at midpoints and draw line segments
for (let i = 0; i < activeLocations.length - 1; i++) {
const currentLoc = activeLocations[i];
const nextLoc = activeLocations[i + 1];
// Draw line to next if not hidden
if (!currentLoc.hideNextLine) {
const segment = L.polyline([[currentLoc.lat, currentLoc.lng], [nextLoc.lat, nextLoc.lng]], {
color: lineColor,
weight: 3,
opacity: 0.7,
dashArray: '10, 10',
lineCap: 'round'
}).addTo(map);
travelTimeMarkers.push(segment); // Reuse array for cleanup
}
// Determine travel time to display
let displayTime = nextLoc.travelTime && nextLoc.travelTime.trim() !== ''
? nextLoc.travelTime
: '';
// If no manual time and we have a mode, estimate it
if (!displayTime && nextLoc.travelMode) {
const distance = calculateDistance(
currentLoc.lat, currentLoc.lng,
nextLoc.lat, nextLoc.lng
);
displayTime = estimateTravelTime(distance, nextLoc.travelMode);
}