-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1466 lines (1261 loc) · 67.2 KB
/
script.js
File metadata and controls
1466 lines (1261 loc) · 67.2 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
$(document).ready(function() { // Theme Definitions with Icons
const themes = [
// Image Theme: Light Blue / Classic
{
name: "Light Blue Classic",
icon: "fas fa-water",
description: "Classic ocean-inspired theme",
"--body-bg": "#BBDDEE", "--container-bg": "#E0F2F7", "--text-color": "#333",
"--button-bg": "#03A9F4", "--button-hover-bg": "#0288D1", "--player-bg": "white",
"--player-text": "#333", "--border-color": "rgba(0, 0, 0, 0.1)"
},
// Original Theme: Classic Walnut
{
name: "Classic Walnut",
icon: "fas fa-tree",
description: "Warm vintage wood tones",
"--body-bg": "#FAF0E6", /* Linen-ish */ "--container-bg": "#F5DEB3", /* Moccasin */
"--text-color": "#4A230B", /* Dark Brown */ "--button-bg": "#A0522D", /* Sienna */
"--button-hover-bg": "#8B4513", /* SaddleBrown */ "--player-bg": "white",
"--player-text": "#4A230B", "--border-color": "rgba(139, 69, 19, 0.2)" /* Brownish border */
},
// Image Theme: Art Deco Green
{
name: "Art Deco Green",
icon: "fas fa-leaf",
description: "Fresh nature-inspired design",
"--body-bg": "#E8F5E9", /* Light Green */ "--container-bg": "#C8E6C9", /* Lighter Green */
"--text-color": "#1B5E20", /* Dark Green */ "--button-bg": "#388E3C", /* Medium Green */
"--button-hover-bg": "#2E7D32", /* Darker Green */ "--player-bg": "#F1F8E9",
"--player-text": "#1B5E20", "--border-color": "rgba(46, 125, 50, 0.2)"
},
// Image Theme: Bakelite Ivory
{
name: "Bakelite Ivory",
icon: "fas fa-sun",
description: "Bright retro sunshine theme",
"--body-bg": "#FFFDE7", /* Very Light Yellow */ "--container-bg": "#FFF8E1", /* Light Yellow */
"--text-color": "#212121", /* Black */ "--button-bg": "#FFCA28", /* Amber */
"--button-hover-bg": "#FFB300", /* Darker Amber */ "--player-bg": "white",
"--player-text": "#212121", "--border-color": "rgba(33, 33, 33, 0.2)"
},
// Image Theme: Mid-Century Teak
{
name: "Mid-Century Teak",
icon: "fas fa-home",
description: "Cozy mid-century modern",
"--body-bg": "#D7CCC8", /* Light Grey Brown */ "--container-bg": "#BCAAA4", /* Medium Grey Brown */
"--text-color": "#3E2723", /* Very Dark Brown */ "--button-bg": "#6D4C41", /* Brown */
"--button-hover-bg": "#5D4037", /* Dark Brown */ "--player-bg": "#EFEBE9",
"--player-text": "#3E2723", "--border-color": "rgba(62, 39, 35, 0.2)"
},
// Image Theme: Retro Transistor Blue
{
name: "Retro Transistor Blue",
icon: "fas fa-bolt",
description: "Electric retro vibes",
"--body-bg": "#E1F5FE", /* Lighter Blue */ "--container-bg": "#B3E5FC", /* Light Cyan */
"--text-color": "#01579B", /* Dark Blue */ "--button-bg": "#039BE5", /* Medium Blue */
"--button-hover-bg": "#0288D1", /* Darker Blue */ "--player-bg": "white",
"--player-text": "#01579B", "--border-color": "rgba(1, 87, 155, 0.2)"
},
// Image Theme: Steampunk Brass
{
name: "Steampunk Brass",
icon: "fas fa-cogs",
description: "Industrial steampunk style",
"--body-bg": "#A1887F", /* Brown Grey */ "--container-bg": "#D7BDA2", /* Brass/Bronze like */
"--text-color": "#3E2723", /* Dark Brown */ "--button-bg": "#8D6E63", /* Medium Brown */
"--button-hover-bg": "#795548", /* Darker Brown */ "--player-bg": "#EFEBE9",
"--player-text": "#3E2723", "--border-color": "rgba(62, 39, 35, 0.3)"
},
// More themes...
{
name: "Vintage Red",
icon: "fas fa-heart",
description: "Classic romantic red",
"--body-bg": "#FFEBEE", /* Lightest Red */ "--container-bg": "#FFCDD2", /* Lighter Red */
"--text-color": "#B71C1C", /* Dark Red */ "--button-bg": "#E53935", /* Medium Red */
"--button-hover-bg": "#C62828", /* Darker Red */ "--player-bg": "#FFFAFA",
"--player-text": "#B71C1C", "--border-color": "rgba(183, 28, 28, 0.2)"
},
{
name: "Dark Mode",
icon: "fas fa-moon",
description: "Easy on the eyes darkness",
"--body-bg": "#212121", "--container-bg": "#424242", "--text-color": "#E0E0E0",
"--button-bg": "#616161", "--button-hover-bg": "#757575", "--player-bg": "#303030",
"--player-text": "#E0E0E0", "--border-color": "rgba(224, 224, 224, 0.1)"
}
];
const root = document.documentElement; // Get the root HTML element for CSS variables
// Create modern theme selector with icons
function createModernThemeSelector() {
// Hide the original select element
$('#themeSelector').hide();
// Create the custom theme selector
const customSelector = $(`
<div class="modern-theme-selector">
<div class="theme-selector-trigger">
<div class="selected-theme-preview">
<i class="fas fa-water theme-icon"></i>
<div class="theme-info">
<span class="theme-name">Light Blue Classic</span>
<span class="theme-description">Classic ocean-inspired theme</span>
</div>
<i class="fas fa-chevron-down dropdown-arrow"></i>
</div>
</div>
<div class="theme-selector-dropdown">
<div class="theme-options-container">
${themes.map(theme => `
<div class="theme-option" data-theme="${theme.name}">
<div class="theme-preview-box" style="background: linear-gradient(135deg, ${theme['--container-bg']}, ${theme['--button-bg']});">
<i class="${theme.icon} theme-option-icon" style="color: ${theme['--text-color']};"></i>
</div>
<div class="theme-details">
<span class="theme-option-name">${theme.name}</span>
<span class="theme-option-description">${theme.description}</span>
</div>
<div class="theme-colors">
<div class="color-swatch" style="background-color: ${theme['--container-bg']};"></div>
<div class="color-swatch" style="background-color: ${theme['--button-bg']};"></div>
<div class="color-swatch" style="background-color: ${theme['--text-color']};"></div>
</div>
</div>
`).join('')}
</div>
</div>
</div>
`);
// Insert after the original theme selector
$('#themeSelector').after(customSelector);
// Handle dropdown toggle
$('.theme-selector-trigger').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
$('.theme-selector-dropdown').toggleClass('active');
$('.dropdown-arrow').toggleClass('rotated');
});
// Handle theme selection
$('.theme-option').on('click', function(e) {
e.preventDefault();
e.stopPropagation();
const themeName = $(this).data('theme');
const selectedTheme = themes.find(t => t.name === themeName);
if (selectedTheme) {
// Update the trigger display
$('.selected-theme-preview .theme-icon').attr('class', `${selectedTheme.icon} theme-icon`);
$('.selected-theme-preview .theme-name').text(selectedTheme.name);
$('.selected-theme-preview .theme-description').text(selectedTheme.description);
// Apply the theme
applyTheme(themeName);
// Close dropdown
$('.theme-selector-dropdown').removeClass('active');
$('.dropdown-arrow').removeClass('rotated');
// Update active state
$('.theme-option').removeClass('active');
$(this).addClass('active');
}
});
// Close dropdown when clicking outside
$(document).on('click', function(e) {
if (!$(e.target).closest('.modern-theme-selector').length) {
$('.theme-selector-dropdown').removeClass('active');
$('.dropdown-arrow').removeClass('rotated');
}
});
// Set initial active theme
const savedTheme = localStorage.getItem('selectedTheme') || themes[0].name;
$(`.theme-option[data-theme="${savedTheme}"]`).addClass('active');
}
// Initialize the modern theme selector
createModernThemeSelector(); // Function to apply a theme
function applyTheme(themeName) {
const theme = themes.find(t => t.name === themeName);
if (theme) {
for (const variable in theme) {
if (variable.startsWith('--')) {
root.style.setProperty(variable, theme[variable]);
}
}
// Set RGB variables for colors that need it
if (theme['--button-bg']) {
const rgbColor = hexToRGB(theme['--button-bg']);
if (rgbColor) {
root.style.setProperty('--button-bg-rgb', `${rgbColor.r}, ${rgbColor.g}, ${rgbColor.b}`);
}
}
// Save the selected theme to local storage
localStorage.setItem('selectedTheme', themeName);
// Update the modern selector display
const selectedTheme = themes.find(t => t.name === themeName);
if (selectedTheme) {
$('.selected-theme-preview .theme-icon').attr('class', `${selectedTheme.icon} theme-icon`);
$('.selected-theme-preview .theme-name').text(selectedTheme.name);
$('.selected-theme-preview .theme-description').text(selectedTheme.description);
}
}
}
// Apply saved theme on page load, or the first theme (Light Blue Classic)
const savedTheme = localStorage.getItem('selectedTheme');
const initialTheme = savedTheme || themes[0].name;
applyTheme(initialTheme);
// Static countries (Can keep these as quick access, though API gets all)
const staticCountries = [
{ name: "India", code: "IN" },
{ name: "United States", code: "US" },
{ name: "United Kingdom", code: "GB" },
{ name: "Germany", code: "DE" },
{ name: "France", code: "FR" },
{ name: "Canada", code: "CA" }
];
let allCountries = []; // Store the full list of countries
let displayedCountries = []; // Store currently displayed countries for search/filter
let stations = [];
// Fetch countries
$.getJSON('https://de1.api.radio-browser.info/json/countries', function(data) {
allCountries = data.map(country => ({
name: country.name,
code: country.iso_3166_1
}));
// Add static countries if they aren't already in the fetched list
staticCountries.forEach(staticCountry => {
if (!allCountries.some(country => country.code === staticCountry.code)) {
allCountries.push(staticCountry);
}
});
allCountries.sort((a, b) => a.name.localeCompare(b.name));
displayedCountries = allCountries; // Initially display all
displayCountries(displayedCountries);
}).fail(function() {
// Fallback to just static countries if API fails
console.error("Failed to fetch countries from API, using static list.");
allCountries = staticCountries;
allCountries.sort((a, b) => a.name.localeCompare(b.name));
displayedCountries = allCountries;
displayCountries(displayedCountries);
});
// Enhanced country and station display with metadata
let favorites = JSON.parse(localStorage.getItem('favoriteStations') || '[]');
let stationGenres = [];
let countryRegions = {
'africa': ['DZ', 'AO', 'BJ', 'BW', 'BF', 'BI', 'CV', 'CM', 'CF', 'TD', 'KM', 'CD', 'DJ', 'EG', 'GQ', 'ER', 'ET', 'GA', 'GM', 'GH', 'GN', 'GW', 'CI', 'KE', 'LS', 'LR', 'LY', 'MG', 'MW', 'ML', 'MR', 'MU', 'MA', 'MZ', 'NA', 'NE', 'NG', 'CG', 'RW', 'ST', 'SN', 'SC', 'SL', 'SO', 'ZA', 'SS', 'SD', 'SZ', 'TZ', 'TG', 'TN', 'UG', 'ZM', 'ZW'],
'americas': ['AR', 'BS', 'BB', 'BZ', 'BO', 'BR', 'CA', 'CL', 'CO', 'CR', 'CU', 'DM', 'DO', 'EC', 'SV', 'GD', 'GT', 'GY', 'HT', 'HN', 'JM', 'MX', 'NI', 'PA', 'PY', 'PE', 'LC', 'VC', 'SR', 'TT', 'US', 'UY', 'VE'],
'asia': ['AF', 'AM', 'AZ', 'BH', 'BD', 'BT', 'BN', 'KH', 'CN', 'CY', 'GE', 'IN', 'ID', 'IR', 'IQ', 'IL', 'JP', 'JO', 'KZ', 'KW', 'KG', 'LA', 'LB', 'MY', 'MV', 'MN', 'MM', 'NP', 'KP', 'OM', 'PK', 'PS', 'PH', 'QA', 'SA', 'SG', 'KR', 'LK', 'SY', 'TW', 'TJ', 'TH', 'TL', 'TR', 'TM', 'AE', 'UZ', 'VN', 'YE'],
'europe': ['AL', 'AD', 'AT', 'BY', 'BE', 'BA', 'BG', 'HR', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IS', 'IE', 'IT', 'LV', 'LI', 'LT', 'LU', 'MT', 'MD', 'MC', 'ME', 'NL', 'MK', 'NO', 'PL', 'PT', 'RO', 'RU', 'SM', 'RS', 'SK', 'SI', 'ES', 'SE', 'CH', 'UA', 'GB', 'VA'],
'oceania': ['AU', 'FJ', 'KI', 'MH', 'FM', 'NR', 'NZ', 'PW', 'PG', 'WS', 'SB', 'TO', 'TV', 'VU']
};
// Animation and micro-interactions
function initAnimations() {
// Add staggered animation to country and station items
function animateStaggeredItems(container, items, delay = 50) {
$(items).each(function(index) {
const $this = $(this);
$this.addClass('staggered-item');
setTimeout(() => {
$this.css({
'animation': 'fadeSlideIn 0.5s ease forwards',
'animation-delay': (index * delay) + 'ms'
});
}, 10);
});
}
// Set up observers for animations
if ('IntersectionObserver' in window) {
const options = {
root: null,
rootMargin: '0px',
threshold: 0.1
};
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('section-transition');
observer.unobserve(entry.target);
}
});
}, options);
// Observe sections
document.querySelectorAll('section').forEach(section => {
observer.observe(section);
});
} else {
// Fallback for browsers that don't support IntersectionObserver
$('section').addClass('section-transition');
}
// Apply staggered animations when content changes
const countryObserver = new MutationObserver(() => {
animateStaggeredItems('#countryList', '.country-item', 30);
});
const stationObserver = new MutationObserver(() => {
animateStaggeredItems('#stationListContainer', '.station-item', 30);
});
countryObserver.observe(document.getElementById('countryList'), { childList: true });
stationObserver.observe(document.getElementById('stationListContainer'), { childList: true });
}
// Call animation initialization
initAnimations();
// Add loading indicators
function showLoading(container) {
$(container).html(`
<div class="loader">
<div class="loader-spinner"></div>
</div>
`);
} function showNowPlaying(stationUrl) {
// Remove now-playing class from all stations
$('.station-card, .station-item').removeClass('now-playing');
// Add to the currently playing station (supports both old and new styles)
$(`.station-card[data-url="${stationUrl}"], .station-item[data-url="${stationUrl}"]`).addClass('now-playing');
// Update the play button to pause icon on the station card
$(`.station-card[data-url="${stationUrl}"] .play-station-btn i`).removeClass('fa-play').addClass('fa-pause');
}
// Updated display country function with enhanced UI
function displayCountries(countriesToDisplay) {
var countryList = $('#countryList');
countryList.empty();
if (countriesToDisplay.length === 0) {
countryList.append('<p class="text-center">No countries found matching your search.</p>');
} else {
countriesToDisplay.forEach(function(country) {
var flagUrl = `https://flagpedia.net/data/flags/w160/${country.code.toLowerCase()}.png`;
// Determine which region the country belongs to
let region = 'unknown';
for (const [key, countries] of Object.entries(countryRegions)) {
if (countries.includes(country.code)) {
region = key;
break;
}
}
var countryItem = $(`
<div class="country-item card" data-code="${country.code}" data-name="${country.name}" data-region="${region}">
<div class="country-flag-container">
<img src="${flagUrl}" class="flag" alt="${country.name} flag" onerror="this.src='images/default-flag.png';">
</div>
<span class="country-name">${country.name}</span>
<span class="country-count badge"></span>
</div>
`);
countryList.append(countryItem);
// Optional: Fetch station count for this country
$.getJSON(`https://de1.api.radio-browser.info/json/stations/bycountrycodeexact/${country.code}?limit=1&hidebroken=true`, function(data) {
countryItem.find('.country-count').text(`${data.length}+ stations`);
}).fail(function() {
countryItem.find('.country-count').remove();
});
});
}
}
// Updated station display with enhanced UI and metadata
function displayStations(stationsToDisplay) {
var stationListContainer = $('#stationListContainer');
stationListContainer.empty();
if (stationsToDisplay.length === 0) {
stationListContainer.append('<p class="text-center">No stations found for this country.</p>');
} else {
// Create a grid wrapper for the stations
const stationGrid = $('<div class="station-grid"></div>');
stationListContainer.append(stationGrid);
stationsToDisplay.forEach(function(station) {
if (station.url && station.url !== "") {
// Extract potential FM frequency from station name
const fmRegex = /\b(\d{2,3}(?:\.\d)?)\s*(?:FM|MHz)\b/i;
const fmMatch = station.name.match(fmRegex);
const frequency = fmMatch ? fmMatch[1] : null;
// Generate a color based on station name for stations without specific genre
const nameHash = station.name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
const hue = nameHash % 360;
const stationColor = `hsl(${hue}, 70%, 50%)`;
// Check for certain keywords to assign genre icons if genre not provided
let genreIcon = 'fa-broadcast-tower';
let genreName = '';
if (station.name.match(/news|noticias|info|actualidad/i)) {
genreIcon = 'fa-newspaper';
genreName = 'News';
} else if (station.name.match(/rock|metal|punk/i)) {
genreIcon = 'fa-guitar';
genreName = 'Rock';
} else if (station.name.match(/pop|hits|top/i)) {
genreIcon = 'fa-music';
genreName = 'Pop';
} else if (station.name.match(/jazz|blues/i)) {
genreIcon = 'fa-saxophone';
genreName = 'Jazz';
} else if (station.name.match(/classic|clasica|symphony/i)) {
genreIcon = 'fa-violin';
genreName = 'Classical';
} else if (station.name.match(/dance|electro|house|techno|dj/i)) {
genreIcon = 'fa-compact-disc';
genreName = 'Electronic';
}
// Create the station card with enhanced visual elements
var stationItem = $(`
<div class="station-card" data-url="${station.url}" data-name="${station.name}">
<div class="station-card-header" style="background: linear-gradient(to right, ${stationColor}, transparent);">
<div class="station-icon" style="background-color: ${stationColor}">
<i class="fas ${genreIcon}"></i>
</div>
<div class="station-title-area">
<h3 class="station-name">${station.name}</h3>
${frequency ? `<span class="station-frequency">${frequency} FM</span>` : ''}
</div>
</div>
<div class="station-card-body">
<div class="station-meta">
${genreName ? `<span class="station-genre"><i class="fas ${genreIcon}"></i> ${genreName}</span>` : ''}
${station.language ? `<span class="station-language"><i class="fas fa-language"></i> ${station.language}</span>` : ''}
</div>
<div class="station-action">
<button class="play-station-btn" aria-label="Play ${station.name}">
<i class="fas fa-play"></i>
</button>
</div>
</div>
</div>
`);
stationGrid.append(stationItem);
} else {
console.warn(`Station "${station.name}" has no resolved URL.`);
}
});
}
}
// Handle remove favorite button
$(document).on('click', '.remove-favorite-btn', function(e) {
e.stopPropagation(); // Prevent triggering card click
const stationUrl = $(this).data('url');
const index = favorites.findIndex(fav => fav.url === stationUrl);
if (index !== -1) {
favorites.splice(index, 1);
localStorage.setItem('favoriteStations', JSON.stringify(favorites));
// Update UI
$(this).closest('.favorite-station-card').fadeOut(300, function() {
$(this).remove();
displayFavorites();
// Also update main station list if visible
$('.favorite-btn[data-url="' + stationUrl + '"]').removeClass('active');
});
}
});
// Play from favorites
$(document).on('click', '.play-favorite-btn, .favorite-station-card', function(e) {
const card = $(this).hasClass('favorite-station-card') ? $(this) : $(this).closest('.favorite-station-card');
const url = card.data('url');
const name = card.data('name');
if (url) {
$('#nowPlaying').text(name);
$('#stationDisplayName').text(name);
player.pause();
player.src = url;
player.load();
// Initialize audio visualization if first time playing
setupAudioVisualization();
setTimeout(() => {
const playPromise = player.play();
if (playPromise !== undefined) {
playPromise.then(() => {
playPauseBtn.html('<i class="fas fa-pause"></i>');
}).catch(error => {
console.error("Playback failed:", error);
$('#nowPlaying').text(`Could not play: ${name}. Please try again.`);
$('#stationDisplayName').text("Playback error");
playPauseBtn.html('<i class="fas fa-play"></i>');
});
}
}, 100);
}
});
// Play station when clicking the play button
$(document).on('click', '.station-item .play-btn, .station-card .play-station-btn', function(e) {
e.stopPropagation(); // Prevent triggering the parent click
// Support both old and new UI elements
const parent = $(this).closest('.station-item, .station-card');
const url = parent.data('url');
const name = parent.data('name') || parent.find('.station-name').text().trim();
playStation(url, name);
});
// Centralized function to play a station
function playStation(url, name) {
if (!url) {
console.error("Attempted to play station with no URL.");
$('#nowPlaying').text(`Error: No stream found for ${name}`);
$('#stationDisplayName').text("No stream available");
return;
}
$('#nowPlaying').text(name);
$('#stationDisplayName').text(name);
// Update station UI to show which is playing
showNowPlaying(url);
// Pause current playback and reset src
player.pause();
player.src = url;
player.load();
// Initialize audio visualization if first time playing
setupAudioVisualization();
setTimeout(() => {
const playPromise = player.play();
if (playPromise !== undefined) {
playPromise.then(() => {
playPauseBtn.html('<i class="fas fa-pause"></i>');
// Store in recently played
addToRecentlyPlayed(url, name);
}).catch(error => {
console.error("Playback failed:", error);
$('#nowPlaying').text(`Could not play: ${name}. Please try again or check browser permissions.`);
$('#stationDisplayName').text("Playback error");
playPauseBtn.html('<i class="fas fa-play"></i>');
});
}
}, 100);
}
// Recently played stations
function addToRecentlyPlayed(url, name) {
let recentlyPlayed = JSON.parse(localStorage.getItem('recentlyPlayed') || '[]');
// Remove if already exists
recentlyPlayed = recentlyPlayed.filter(station => station.url !== url);
// Add to beginning
recentlyPlayed.unshift({ url, name, timestamp: Date.now() });
// Limit to 10 items
if (recentlyPlayed.length > 10) {
recentlyPlayed = recentlyPlayed.slice(0, 10);
}
localStorage.setItem('recentlyPlayed', JSON.stringify(recentlyPlayed));
}
// Handle region filter
$(document).on('click', '#regionFilterMenu .dropdown-item', function(e) {
e.preventDefault();
const region = $(this).data('region');
// Update button text
$('#regionFilterBtn').html(`<i class="fas fa-globe"></i> ${$(this).text()}`);
// Update active state
$('#regionFilterMenu .dropdown-item').removeClass('active');
$(this).addClass('active');
// Filter countries
if (region === 'all') {
displayedCountries = allCountries;
} else {
displayedCountries = allCountries.filter(country =>
countryRegions[region] && countryRegions[region].includes(country.code)
);
}
displayCountries(displayedCountries);
});
// Clear search buttons
$('#countrySearch').on('input', function() {
$('#clearCountrySearch').toggle($(this).val().length > 0);
});
$('#stationSearch').on('input', function() {
$('#clearStationSearch').toggle($(this).val().length > 0);
});
$('#clearCountrySearch').on('click', function() {
$('#countrySearch').val('');
$(this).hide();
displayedCountries = allCountries;
displayCountries(displayedCountries);
});
$('#clearStationSearch').on('click', function() {
$('#stationSearch').val('');
$(this).hide();
displayStations(stations);
});
// Refresh stations button
$('#refreshStations').on('click', function() {
const countryCode = $('#selectedCountry').data('code');
const countryName = $('#selectedCountry').text();
if (countryCode) {
$(this).find('i').addClass('fa-spin');
$.getJSON(`https://de1.api.radio-browser.info/json/stations/bycountrycodeexact/${countryCode}?limit=100&hidebroken=true`, function(data) {
stations = data.map(station => ({
name: station.name,
url: station.url_resolved,
language: station.language,
genres: station.tags ? station.tags.split(',').map(tag => tag.trim()) : [],
votes: station.votes
})).filter(s => s.url && s.url !== "");
$('#refreshStations').find('i').removeClass('fa-spin');
displayStations(stations);
}).fail(function() {
console.error("Failed to refresh stations");
$('#refreshStations').find('i').removeClass('fa-spin');
});
}
});
// Display countries
function displayCountries(countriesToDisplay) {
var countryList = $('#countryList');
countryList.empty();
if (countriesToDisplay.length === 0) {
countryList.append('<p class="text-center">No countries found matching your search.</p>');
} else {
countriesToDisplay.forEach(function(country) {
var flagUrl = `https://flagpedia.net/data/flags/w160/${country.code.toLowerCase()}.png`;
var countryItem = $(`
<div class="country-item card" data-code="${country.code}" data-name="${country.name}">
<img src="${flagUrl}" class="flag" alt="${country.name} flag" onerror="this.style.display='none';">
<span class="country-name">${country.name}</span>
</div>
`);
countryList.append(countryItem);
});
}
}
// Country search
$('#countrySearch').on('input', function() {
var searchTerm = $(this).val().toLowerCase();
displayedCountries = allCountries.filter(function(country) {
return country.name.toLowerCase().includes(searchTerm);
});
displayCountries(displayedCountries);
}); // Country selection
$(document).on('click', '.country-item', function() {
var countryCode = $(this).data('code');
var countryName = $(this).data('name');
$('#selectedCountry').text(countryName).data('code', countryCode);
// Smooth transition with fade
$('#country-selection').fadeOut(300, function() {
$('#station-list').fadeIn(300);
});
$('#stationSearch').val(''); // Clear station search input
stations = []; // Clear previous stations
// Show loading indicator
showLoading('#stationListContainer');
// Specific logic for India channels
if (countryName === "India") {
const desiredChannels = [
"Bollywood Gaane Purane", "Vivid Bharti", "Radio Mirchi Hindi",
"Radio Bollywood 90s", "Red FM 93.5", "Hindi Gold Radio",
"LataMangeshkarRadio", "Goldy Evergreen", "AIR FM Gold Delhi",
"Mirchi Top 20", "Hindi Retro", "Aaj Tak News Radio Live",
"Radio Aashiyana", "Bollywood 90s radio", "90sonceagainradio",
"Radio Hungama Bollywood Dil Se", "Radio Aashiyanaa", "Madhur Sangeet Radio",
"Rafi Hits Songs", "My Radio DJ", "Radio City Hindi", "Fever FM", "BIG FM"
];
// Use Promise.all to fetch all specific channels concurrently
Promise.all(desiredChannels.map(channel =>
$.getJSON(`https://de1.api.radio-browser.info/json/stations/bynameexact/${encodeURIComponent(channel)}?countrycode=IN&hidebroken=true`) // Use bynameexact, hidebroken
.then(data => data.length > 0 ? { name: data[0].name, url: data[0].url_resolved } : null)
.catch(() => null) // Catch errors for individual lookups
))
.then(results => {
// Filter out null results and use only the first match for each name
stations = results.filter(station => station !== null)
.filter((v,i,a)=>a.findIndex(t=>(t.name === v.name))===i); // Deduplicate by name
// Fallback: If specific channels not found or too few, fetch a general list for India
if (stations.length < 15) { // If fewer than X specific channels found
console.warn("Could not find enough specific Indian channels or API error, fetching a general list.");
$.getJSON(`https://de1.api.radio-browser.info/json/stations/bycountrycodeexact/IN?limit=100&hidebroken=true`, function(data) {
// Combine found specific stations with general ones, prioritizing specific
const generalStations = data.map(station => ({
name: station.name,
url: station.url_resolved
})).filter(gs => gs.url && gs.url !== "" && !stations.some(s => s.name === gs.name)); // Filter out specific ones already found and check URL
stations = stations.concat(generalStations);
displayStations(stations);
}).fail(() => {
console.error("Failed to fetch general Indian stations.");
displayStations(stations); // Display only specific ones found, or empty list
});
} else {
displayStations(stations); // Display specific channels found
}
})
.catch(error => {
console.error("Error fetching specific Indian stations:", error);
// Fallback to general fetch on overall error
$.getJSON(`https://de1.api.radio-browser.info/json/stations/bycountrycodeexact/IN?limit=100&hidebroken=true`, function(data) {
stations = data.map(station => ({
name: station.name,
url: station.url_resolved
})).filter(s => s.url && s.url !== ""); // Filter stations without URLs
displayStations(stations);
}).fail(() => {
console.error("Failed to fetch general Indian stations.");
displayStations([]); // Display empty list on total failure
});
});
} else {
// General fetch for other countries
$.getJSON(`https://de1.api.radio-browser.info/json/stations/bycountrycodeexact/${countryCode}?limit=100&hidebroken=true`, function(data) { // Increased limit, hidebroken
stations = data.map(station => ({
name: station.name,
url: station.url_resolved
})).filter(s => s.url && s.url !== ""); // Filter stations without URLs
displayStations(stations);
}).fail(function() {
console.error("Failed to fetch stations for country:", countryName);
stations = []; // Clear stations on error
displayStations([]); // Display empty list
});
}
}); // Back to countries
$('#backToCountries').click(function() {
// Smooth transition with fade
$('#station-list').fadeOut(300, function() {
$('#country-selection').fadeIn(300);
});
$('#countrySearch').val(''); // Clear country search input
displayedCountries = allCountries; // Reset displayed countries to full list
displayCountries(displayedCountries); // Redisplay the full country list
});
// Display stations
function displayStations(stationsToDisplay) {
var stationListContainer = $('#stationListContainer');
stationListContainer.empty();
if (stationsToDisplay.length === 0) {
stationListContainer.append('<p class="text-center">No stations found for this country.</p>');
} else {
// Create a grid wrapper for the stations
const stationGrid = $('<div class="station-grid"></div>');
stationListContainer.append(stationGrid);
stationsToDisplay.forEach(function(station) {
if (station.url && station.url !== "") {
// Extract potential FM frequency from station name
const fmRegex = /\b(\d{2,3}(?:\.\d)?)\s*(?:FM|MHz)\b/i;
const fmMatch = station.name.match(fmRegex);
const frequency = fmMatch ? fmMatch[1] : null;
// Generate a color based on station name for stations without specific genre
const nameHash = station.name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
const hue = nameHash % 360;
const stationColor = `hsl(${hue}, 70%, 50%)`;
// Check for certain keywords to assign genre icons if genre not provided
let genreIcon = 'fa-broadcast-tower';
let genreName = '';
if (station.name.match(/news|noticias|info|actualidad/i)) {
genreIcon = 'fa-newspaper';
genreName = 'News';
} else if (station.name.match(/rock|metal|punk/i)) {
genreIcon = 'fa-guitar';
genreName = 'Rock';
} else if (station.name.match(/pop|hits|top/i)) {
genreIcon = 'fa-music';
genreName = 'Pop';
} else if (station.name.match(/jazz|blues/i)) {
genreIcon = 'fa-saxophone';
genreName = 'Jazz';
} else if (station.name.match(/classic|clasica|symphony/i)) {
genreIcon = 'fa-violin';
genreName = 'Classical';
} else if (station.name.match(/dance|electro|house|techno|dj/i)) {
genreIcon = 'fa-compact-disc';
genreName = 'Electronic';
}
// Create the station card with enhanced visual elements
var stationItem = $(`
<div class="station-card" data-url="${station.url}" data-name="${station.name}">
<div class="station-card-header" style="background: linear-gradient(to right, ${stationColor}, transparent);">
<div class="station-icon" style="background-color: ${stationColor}">
<i class="fas ${genreIcon}"></i>
</div>
<div class="station-title-area">
<h3 class="station-name">${station.name}</h3>
${frequency ? `<span class="station-frequency">${frequency} FM</span>` : ''}
</div>
</div>
<div class="station-card-body">
<div class="station-meta">
${genreName ? `<span class="station-genre"><i class="fas ${genreIcon}"></i> ${genreName}</span>` : ''}
${station.language ? `<span class="station-language"><i class="fas fa-language"></i> ${station.language}</span>` : ''}
</div>
<div class="station-action">
<button class="play-station-btn" aria-label="Play ${station.name}">
<i class="fas fa-play"></i>
</button>
</div>
</div>
</div>
`);
stationGrid.append(stationItem);
} else {
console.warn(`Station "${station.name}" has no resolved URL.`);
}
});
}
}
// Station search
$('#stationSearch').on('input', function() {
var searchTerm = $(this).val().toLowerCase();
var filteredStations = stations.filter(function(station) {
return station.name.toLowerCase().includes(searchTerm);
});
displayStations(filteredStations);
});
// Custom Audio Player Logic
const player = $('#radioPlayer')[0];
const playPauseBtn = $('#playPauseBtn');
const muteBtn = $('#muteBtn');
const volumeSlider = $('#volumeSlider');
const stationDisplayName = $('#stationDisplayName');
const nowPlaying = $('#nowPlaying');
const canvas = $('#audioVisualization')[0];
let audioContext, analyser, dataArray, canvasCtx; // Initialize volume from localStorage or default
let volume = parseFloat(localStorage.getItem('playerVolume')) || 0.8;
player.volume = volume;
volumeSlider.val(volume * 100);
// Set the CSS variable for volume slider appearance
document.documentElement.style.setProperty('--volume-percent', `${volume * 100}%`);
// Set appropriate volume icon
if (volume === 0) {
muteBtn.html('<i class="fas fa-volume-mute"></i>');
} else if (volume < 0.5) {
muteBtn.html('<i class="fas fa-volume-down"></i>');
} else {
muteBtn.html('<i class="fas fa-volume-up"></i>');
}
console.log("Initial volume set to:", volume);// Play/Pause functionality
playPauseBtn.on('click', function() {
if (player.paused) {
if (player.src) {
// Make sure AudioContext is resumed if it was suspended
if (audioContext && audioContext.state === 'suspended') {
audioContext.resume().then(() => {
console.log('AudioContext resumed');
});
}
// Ensure we're not muted
player.muted = false;
const playPromise = player.play();
if (playPromise !== undefined) {
playPromise.then(() => {
playPauseBtn.html('<i class="fas fa-pause"></i>');
console.log("Playback started with current volume:", player.volume);
}).catch(error => {
console.error("Playback failed:", error);
});
}
}
} else {
player.pause();
playPauseBtn.html('<i class="fas fa-play"></i>');
}
}); // Mute functionality
muteBtn.on('click', function() {
player.muted = !player.muted;
if (player.muted) {
muteBtn.html('<i class="fas fa-volume-mute"></i>');
console.log("Audio muted");
} else {
// Use appropriate icon based on current volume
const currentVolume = player.volume;
if (currentVolume === 0) {
// If volume is 0, set it to a reasonable value
player.volume = 0.5;
volumeSlider.val(50);
muteBtn.html('<i class="fas fa-volume-up"></i>');
} else if (currentVolume < 0.5) {
muteBtn.html('<i class="fas fa-volume-down"></i>');
} else {
muteBtn.html('<i class="fas fa-volume-up"></i>');
}
console.log("Audio unmuted, volume:", player.volume);
}
}); // Volume control
volumeSlider.on('input', function() {
const newVolume = $(this).val() / 100;
player.volume = newVolume;
localStorage.setItem('playerVolume', newVolume);
// Update volume slider appearance
document.documentElement.style.setProperty('--volume-percent', `${newVolume * 100}%`);
// Update mute button icon based on volume
if (newVolume === 0) {
muteBtn.html('<i class="fas fa-volume-mute"></i>');
player.muted = true;
} else {
if (player.muted) player.muted = false;
if (newVolume < 0.5) {
muteBtn.html('<i class="fas fa-volume-down"></i>');
} else {
muteBtn.html('<i class="fas fa-volume-up"></i>');
}
}
});// Setup audio visualization with enhanced effects
function setupAudioVisualization() {
try {
if (!audioContext) {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
analyser = audioContext.createAnalyser();
// Create a new source every time to avoid issues with reconnecting
const source = audioContext.createMediaElementSource(player);
source.connect(analyser);
analyser.connect(audioContext.destination);
// Make sure we're not muted and volume is set correctly
player.muted = false;