-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1069 lines (882 loc) · 37.1 KB
/
script.js
File metadata and controls
1069 lines (882 loc) · 37.1 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
window.addEventListener('load', () => {
/*-----------------LOG IN-----------------*/
const currentPage = window.location.pathname.split('/').pop();
console.log('currentPage: ', currentPage)
if(currentPage === 'index.html' || currentPage === '') {
const signUpLink = document.getElementById('sign-up-link');
const signUpSubmit = document.getElementById('sign-up-submit');
const signUpModal = document.querySelector('.sign-up-modal');
if (signUpLink && signUpModal) {
signUpLink.addEventListener('click', () => {
signUpModal.removeAttribute('hidden');
});
}
const users = JSON.parse(localStorage.getItem('user')) || [];
if(signUpSubmit) {
signUpSubmit.addEventListener('click', () => {
const firstName = document.getElementById('first_name').value;
const lastName = document.getElementById('last_name').value;
const dob = document.getElementById('dob').value;
const email = document.getElementById('email').value;
const password = document.getElementById('sign-up-password').value;
const confirmPassword = document.getElementById('confirm-password').value;
if (!firstName || !lastName || !dob || !email || !password || !confirmPassword) {
alert('Please fill out all fields');
return;
} else if (password !== confirmPassword) {
alert('Passwords do not match');
return;
} else if (users.find(user => user.email === email)) {
alert('Email already exists');
return;
} else {
users.push({
firstName,
lastName,
dob,
email,
password
});
localStorage.setItem('user', JSON.stringify(users));
signUpModal.setAttribute('hidden', true);
}
});
}
const logInSubmit = document.getElementById('log-in-btn');
if (logInSubmit) {
logInSubmit.addEventListener('click', (e) => {
e.preventDefault();
const email = document.getElementById('log-in-email').value;
const password = document.getElementById('log-in-password').value;
const updatedUsers = JSON.parse(localStorage.getItem('user')) || []; // Fetch the updated users array from localStorage
if (!email || !password) {
alert('Please fill out all fields');
return;
} else if (!updatedUsers.find(user => user.email === email)) {
alert('Email does not exist');
return;
} else if (updatedUsers.find(user => user.email === email && user.password !== password)) {
alert('Incorrect password');
return;
} else {
localStorage.setItem('currentUser', email);
console.log('About to Redirect');
// debugger;
setTimeout(() => {document.location.href = "pages/home.html"},100);
// window.location.href = 'https://www.google.com';
// window.history.pushState({}, '', 'https://www.google.com');
console.log("successfully redirected")
}
});
};
} else if ( currentPage === 'home.html') {
console.log('currentPage: ', currentPage)
/*-----------------HOME-----------------*/
console.log('currentPage: ', currentPage)
const currentUserEmail = localStorage.getItem('currentUser');
/*------CALENDAR----------*/
let nav = 0; // How we keep track of what month we're on
let clicked = null;
let events = localStorage.getItem('events') ? JSON.parse(localStorage.getItem('events')) : [];
const calendar = document.getElementById('calendar');
const newEventModal = document.getElementById('newEventModal');
const dayEventModal = document.getElementById('dayEventModal');
const backDrop = document.getElementById('modalBackDrop');
const eventInput= document.getElementById('eventInput');
const dayTitle = document.querySelector('.eventTitle');
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const exerciseData = Object.values(localStorage).filter(data => {
try {
const jsonData = JSON.parse(data);
return jsonData && jsonData.exercise;
} catch (error) {
return false;
}
}).map(data => JSON.parse(data));
console.log(exerciseData);
function openModal(date) {
const day = document.createElement('h2');
day.id = 'dayTitle';
day.innerText = date;
dayEventModal.appendChild(day);
clicked = date;
dayTitle.innerText = date;
console.log(dayTitle.innerText);
console.log(events);
const closeButton = document.createElement('button');
closeButton.id = 'closeButton';
closeButton.innerText = 'Close';
closeButton.addEventListener('click', function() {
closeModal();
});
dayEventModal.appendChild(closeButton);
const exerciseForDay = exerciseData.filter(e => {
const formattedDate = new Date(e.date).toLocaleDateString('en-US', {
month:'numeric',
day: 'numeric',
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short'
});
const clickedDate = new Date(clicked).toLocaleString('en-US', {
month:'numeric',
day: 'numeric',
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZoneName: 'short'
});
console.log(dayTitle.innerText)
return formattedDate === clickedDate;
});
console.log(exerciseForDay);
if(clicked) {
dayEventModal.style.display = 'block';
} else {
newEventModal.style.display = 'block';
backDrop.style.display = 'block';
}
console.log(exerciseForDay);
console.log(exerciseForDay[0].exercise)
if (exerciseForDay) {
for (const [index, value] of exerciseForDay.entries()) {
const exerciseOfDay = document.createElement('p');
exerciseOfDay.id = 'workoutText';
exerciseOfDay.contentEditable = false;
exerciseOfDay.innerText = exerciseForDay[index].exercise;
const setsHeading = document.createElement('h3');
setsHeading.innerText = "Sets:";
const sets = document.createElement('input');
sets.id = "sets_for_day";
sets.readOnly = true;
exerciseOfDay.appendChild(setsHeading);
setsHeading.id = "setsHeading";
setsHeading.appendChild(sets);
sets.value = ` ${exerciseForDay[index].sets}`;
for(const key in exerciseForDay[index]) {
if (key.startsWith('rep_')) {
const repKey = exerciseForDay[index][key];
const repsHeading = document.createElement('h3');
repsHeading.innerText = `Rep ${key.slice(4)}:`;
const reps = document.createElement('input');
reps.id = "reps_for_day";
reps.readOnly = true;
exerciseOfDay.appendChild(repsHeading);
repsHeading.id = "repsHeading";
repsHeading.appendChild(reps);
reps.value = repKey;
}
if (key.startsWith('weight_')) {
const weightKey = exerciseForDay[index][key];
const weightHeading = document.createElement('h3');
weightHeading.innerText = 'Weight:';
const weight = document.createElement('input');
weight.id = "weight_for_day";
weight.readOnly = true;
exerciseOfDay.appendChild(weightHeading);
weightHeading.id = "weightHeading";
weightHeading.appendChild(weight);
weight.value = weightKey;
}
};
dayEventModal.appendChild(exerciseOfDay);
const editButton = document.createElement('button');
editButton.id = "editButton";
editButton.innerText = "Edit";
exerciseOfDay.insertAdjacentElement("afterend", editButton);
let isEditable = false;
editButton.addEventListener('click', function() {
const setsInput = exerciseOfDay.querySelector('#sets_for_day');
const repsInputs = exerciseOfDay.querySelectorAll('[id^=reps_for_day]');
const weightInputs = exerciseOfDay.querySelectorAll('[id^=weight_for_day]');
const workoutText = document.querySelectorAll('[id^=workoutText]');
if (!isEditable) {
setsInput.readOnly = false;
for (let i = 0; i < repsInputs.length; i++) {
repsInputs[i].readOnly = false;
repsInputs[i].style.borderColor = "red";
}
for (let i = 0; i < weightInputs.length; i++) {
weightInputs[i].readOnly = false;
weightInputs[i].style.borderColor = "red";
}
editButton.innerText = "Save";
} else {
setsInput.readOnly = true;
for (let i = 0; i < repsInputs.length; i++) {
repsInputs[i].readOnly = true;
repsInputs[i].style.borderColor = "var(--darkest)";
}
for (let i = 0; i < weightInputs.length; i++) {
weightInputs[i].readOnly = true;
weightInputs[i].style.borderColor = "var(--darkest)";
}
editButton.innerText = "Edit";
workoutText[i].contentEditable = false;
workoutText[i].style.borderColor = "var(--darkest)";
}
isEditable = !isEditable;
});
const deleteButton = document.createElement('button');
deleteButton.id = "deleteButton";
deleteButton.innerText = "Delete";
editButton.insertAdjacentElement("afterend", deleteButton);
deleteButton.addEventListener('click', function() {
const confirmDelete = confirm('Are you sure you want to delete this workout?');
if (confirmDelete) {
const workout = deleteButton.previousElementSibling.previousElementSibling;
const exerciseText = workout.childNodes[0].textContent.trim();
if(exerciseText === exerciseForDay[index].exercise) {
workout.remove();
deleteButton.remove();
editButton.remove();
localStorage.removeItem(exerciseText);
}
}
location.reload();
});
}
}
};
const form = document.querySelector("#task-form");
const input = document.querySelector(".to-do");
const list_el = document.querySelector(".tasks");
let task_el;
function load() {
const dt = new Date();
if (nav !== 0) {
dt.setMonth(new Date().getMonth() + nav)
}
console.log(nav)
const day = dt.getDate();
const month = dt.getMonth();
const year = dt.getFullYear();
const firstDayOfMonth = new Date(year, month, 1);
const daysInMonth = new Date(year, month + 1, 0).getDate();
const dateString = firstDayOfMonth.toLocaleDateString('en-us', {
weekday: 'long',
year:"numeric",
month:"numeric",
day:"numeric",
});
const paddingDays = weekdays.indexOf(dateString.split(', ')[0]);
console.log(paddingDays);
document.getElementById("monthDisplay").innerText = `${dt.toLocaleDateString('en-us', {
month: "long"
})} ${year}`;
calendar.innerHTML = ''
for(let i = 1; i <= paddingDays + daysInMonth; i++) {
const daySquare = document.createElement('div');
daySquare.classList.add(`day`);
console.log(daySquare)
const dayString = `${month + 1}/${i - paddingDays}/${year}`;
if(i > paddingDays) {
daySquare.innerText = i - paddingDays;
const eventForDay = events.find(e => e.date === dayString);
if (i - paddingDays === day && nav === 0) {
daySquare.id = 'currentDay'
}
exerciseData.forEach(exercise => {
const exerciseDate = new Date(exercise.date);
if (exerciseDate.getFullYear() === year && exerciseDate.getMonth() === month && exerciseDate.getDate() === i - paddingDays) {
const workout = document.createElement('div');
workout.classList.add('workout_event');
workout.innerText = exercise.exercise;
daySquare.appendChild(workout);
}
});
if (eventForDay) {
const eventDiv = document.createElement('div');
eventDiv.classList.add('event');
eventDiv.innerText = eventForDay.title;
daySquare.appendChild(eventDiv);
}
daySquare.addEventListener('click', () => openModal(dayString));
} else {
daySquare.classList.add('padding');
}
calendar.appendChild(daySquare);
}
};
function closeModal(){
eventInput.classList.add('error');
newEventModal.style.display = 'none';
dayEventModal.style.display = 'none';
backDrop.style.display = 'none';
eventInput.value = '';
dayEventModal.innerHTML = '';
clicked = null;
load();
};
function saveEvent() {
if (eventInput.value) {
eventInput.classList.remove('error');
events.push({
date:clicked,
title: eventInput.value,
});
localStorage.setItem('events', JSON.stringify(events));
closeModal();
} else {
eventInput.classList.add('error');
}
};
function deleteEvent(index) {
exerciseData.splice(index, 1);
localStorage.setItem('exercise', JSON.stringify(exerciseData));
closeModal();
}
function editEvent(index) {
const exerciseText = document.getElementById('workoutText');
const updateExercise = prompt('Enter the updated exercise:');
exerciseData[index].exercise = updateExercise;
// exerciseText.innerText = updatedExercise;
localStorage.setItem('exercise', JSON.stringify(exerciseData));
}
function initButtons() {
document.getElementById('nextButton').addEventListener('click', () => {
nav++;
load();
});
document.getElementById('backButton').addEventListener('click', () => {
nav--;
load();
});
document.getElementById('saveButton').addEventListener('click', saveEvent);
document.getElementById('cancelButton').addEventListener('click', closeModal);
// document.getElementById('deleteButton').addEventListener('click', deleteEvent);
// document.getElementById('closeButton').addEventListener('click', closeModal);
}
// const currentPage = window.location.pathname.split('/').pop();
// if (location.pathname === '/pages/home.html') {
if (currentPage === 'home.html') {
console.log('home loaded')
initButtons();
load();
form.addEventListener('submit', (e) =>{
e.preventDefault();
const task = input.value;
if (!task) {
alert("Please fill out the task");
return;
}
task_el = document.createElement("div");
task_el.classList.add("task");
const task_content_el = document.createElement("div");
task_content_el.classList.add("content");
// task_content_el.innerText = task;
task_el.appendChild(task_content_el);
const date_input_el = document.querySelector('.date');
const date_el = document.createElement('h4');
date_el.setAttribute('id','date-input')
// Retrive the date value from the input element
const date_value = date_input_el.value;
if(!date_value) {
alert("Please select date")
return;
};
// Parse the date value inot a Date object
const date_obj = new Date(date_value);
// Get the user's preferred lanuage and country
const user_locale = navigator.language || 'en-US';
// Format the date using the user's locale
const formatted_date = date_obj.toLocaleDateString( user_locale, {
month: 'short',
day: 'numeric',
year: 'numeric',
})
// Set content of the h4 element to the formatted date
date_el.textContent = formatted_date;
task_content_el.appendChild(date_el);
if(task && date_value) {
const task_h = document.querySelector("h3");
task_h.removeAttribute("hidden")
}
const task_p_el = document.createElement("p");
task_p_el.classList.add("text");
task_p_el.contentEditable = false;
task_p_el.type = "text";
task_p_el.innerText = task;
task_p_el.setAttribute("readonly", "readonly");
task_content_el.appendChild(task_p_el);
const task_actions_el = document.createElement("div");
task_actions_el.classList.add("actions");
const edit_task = document.createElement("button");
edit_task.classList.add("edit");
edit_task.innerText = "edit"
const delete_task = document.createElement("button");
delete_task.classList.add("delete");
delete_task.innerText = "delete"
task_actions_el.appendChild(edit_task);
task_actions_el.appendChild(delete_task);
task_el.appendChild(task_actions_el);
list_el.appendChild(task_el);
input.value = "";
});
list_el.addEventListener('click', (e) => {
if (e.target.classList.contains('edit')) {
const todo = e.target.closest(".task");
const paragraph = todo.querySelector(".text");
if (paragraph.tagName === "P") {
if (paragraph.contentEditable === "false") {
paragraph.contentEditable = true;
e.target.textContent = "Save";
if (document.activeElement !== paragraph) {
paragraph.focus();
}
const range = document.createRange();
range.selectNodeContents(paragraph);
range.collapse(false);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
} else {
paragraph.contentEditable = false;
e.target.textContent = "Edit";
}
}
console.log(paragraph.contentEditable)
}
if(e.target.classList.contains('delete')) {
const del_task = e.target.closest(".task");
list_el.removeChild(del_task);
}
});
const dropdown = document.getElementById("workoutsDropdown");
const workoutFreq = document.querySelector('.workout-frequency')
const workoutContainer = document.querySelector('.workout-container')
const drpdwnBtn = document.querySelector(".dropbtn");
const workoutData = document.querySelector(".workout-data")
const exerciseInput = document.querySelector(".exercise-input")
let optionSelected = false;
let setsCreated = false;
let cardioInputsCreated = false;
let roundsCreated = false;
let time_el, distance_el, reps_el, weight_el;
const exerciseSubmit = document.querySelector(".exercise-submit");
const workoutDate = document.querySelector(".workout_date");
const workoutDate_el = document.createElement('div');
workoutDate_el.setAttribute('id','workout-date-input');
const addExercise = document.querySelector(".exercise-submit")
const exercise_el = document.querySelector(".add-exercise")
exerciseSubmit.setAttribute("hidden", "");
workoutDate.setAttribute("hidden", "");
dropdown.addEventListener('click', (e) => {
e.preventDefault();
drpdwnBtn.innerText = e.target.textContent;
workoutDate.removeAttribute("hidden");
if(e.target.textContent == "Weight Training 🏋️" || e.target.textContent == "Calisthenics 💪") {
// hide other exercise inputs
if (cardioInputsCreated) {
exercise_el.removeChild(time_el);
exercise_el.removeChild(distance_el);
cardioInputsCreated = false;
}
if (roundsCreated) {
exercise_el.removeChild(rounds_el);
roundsCreated = false;
}
console.log(drpdwnBtn)
// create sets input
if (!setsCreated) {
const sets_el = document.createElement("input");
sets_el.type = "number";
sets_el.name = "sets";
sets_el.classList.add("sets_input");
sets_el.placeholder = "Sets";
sets_el.min = 0;
exercise_el.appendChild(sets_el);
setsCreated = true;
}
optionSelected = true;
} else if(e.target.textContent == "Cardio 🏃") {
// hide sets input
if(setsCreated) {
const setsEl = document.querySelector(".sets_input");
exercise_el.removeChild(setsEl);
setsCreated = false;
}
if(roundsCreated) {
exercise_el.removeChild(rounds_el);
boxingInputsCreated = false;
}
// create cardio inputs
if(!cardioInputsCreated) {
time_el = document.createElement("input");
time_el.type = "number";
time_el.name = "time";
time_el.classList.add("time_input");
time_el.placeholder = "Time (min)";
time_el.min = 0;
exercise_el.appendChild(time_el);
distance_el = document.createElement("input");
distance_el.type = "text";
distance_el.name = "distance";
distance_el.classList.add("distance_input");
distance_el.placeholder = "Distance (mi)";
exercise_el.appendChild(distance_el);
exercise_el.appendChild(exerciseSubmit);
cardioInputsCreated = true;
}
optionSelected = true;
} else if(e.target.textContent == "Boxing 🥊") {
// hide other exercise inputs
if (cardioInputsCreated) {
exercise_el.removeChild(time_el);
exercise_el.removeChild(distance_el);
cardioInputsCreated = false;
}
if(setsCreated) {
const setsEl = document.querySelector(".sets_input");
exercise_el.removeChild(setsEl);
setsCreated = false;
}
if(!roundsCreated) {
rounds_el = document.createElement("input");
rounds_el.type = "number";
rounds_el.name = "rounds";
rounds_el.classList.add("rounds_input");
rounds_el.placeholder = "Rounds";
rounds_el.min = 0;
exercise_el.appendChild(rounds_el);
roundsCreated = true;
}
optionSelected = true;
} else {
optionSelected = false;
};
if (optionSelected) {
exerciseSubmit.removeAttribute("hidden");
} else {
exerciseSubmit.setAttribute("hidden", "");
}
});
const addRepsBtn = document.querySelector('.reps_weight_btn');
addRepsBtn.setAttribute("hidden", "");
const addRoundsBtn = document.querySelector('.rounds_btn');
addRoundsBtn.setAttribute("hidden", "");
const addCardioBtn = document.querySelector('.time_distance_btn');
addRepsBtn.setAttribute("hidden", "");
let exerciseObject = {};
let storageKeys = Object.keys(localStorage);
console.log(storageKeys);
const exerciseDataContainer = document.createElement('h3');
function updateExerciseObject(storageKeys, exerciseObject) {
const formattedExercise = exerciseObject.exercise.split(' ').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ');
const regex = new RegExp(`^${formattedExercise}(\\s+\\d+)?|${formattedExercise}$`, 'i');
const matchingKeys = storageKeys.filter(key => regex.test(key.toLowerCase()));
let nextNumber = 1;
console.log(matchingKeys);
if (matchingKeys.length === 1) {
const match = matchingKeys[0].match(/\d+$/);
console.log(match);
if (match) {
nextNumber = parseInt(match[0]) + 1;
console.log(match)
} else {
nextNumber = 2;
console.log(match);
}
exerciseObject.exercise = `${formattedExercise} ${nextNumber}`;
} else if (matchingKeys.length > 1) {
const matchingNumbers = matchingKeys.map(key => {
const match = key.match(/\d+$/);
return match ? parseInt(match[0]) : 0;
});
nextNumber = Math.max(...matchingNumbers) + 1;
exerciseObject.exercise = `${formattedExercise} ${nextNumber}`;
} else {
exerciseObject.exercise = `${formattedExercise}`;
}
};
addExercise.addEventListener('click', (e) => {
const sets = document.querySelector('.sets_input');
const rounds = document.querySelector('.rounds_input');
const time = document.querySelector('.time_input');
const distance = document.querySelector('distance_input');
exerciseDataContainer.classList.add('exercise_data');
const workoutName = document.createElement('div')
workoutName.classList.add('workout_name')
exerciseDataContainer.appendChild(workoutName);
workoutName.innerText = exerciseInput.value;
workoutContainer.appendChild(exerciseDataContainer);
const exercise_value = exerciseInput.value;
if(!exercise_value) {
alert("Please enter an exercise")
return;
};
const workoutDate_value = workoutDate.value;
if(!workoutDate_value) {
alert("Please select date")
return;
};
if(!exercise_value || !workoutDate_value) {
alert("Please enter exercise name and date")
return;
} else if(!exercise_value) {
alert("Please enter exercise name")
return;
} else if(!workoutDate_value) {
alert("Please enter date")
return;
} else {
// Parse the date value into a Date object
const workoutDate_obj = new Date(`${workoutDate_value}T00:00:00.000`);
workoutDate_obj.setMinutes(workoutDate_obj.getMinutes() + workoutDate_obj.getTimezoneOffset());
// Get the user's preferred lanuage and country
const user_locale = navigator.language || 'en-US';
// Format the date using the user's locale
const formatted_date = workoutDate_obj.toLocaleDateString( user_locale, {
month: 'long',
day: 'numeric',
year: 'numeric',
})
// Set content of the h4 element to the formatted date
workoutDate_el.textContent = formatted_date;
exerciseDataContainer.appendChild(workoutDate_el);
const date = workoutDate_obj.getDate();
console.log(date);
if(drpdwnBtn.innerText == "Weight Training 🏋️" || drpdwnBtn.innerText == "Calisthenics 💪") {
for(let i = 0; i < sets.value; i++) {
set_number = document.createElement('div');
set_number.classList.add('set_number');
set_number.innerText = `Set ${i + 1}`;
exerciseDataContainer.appendChild(set_number);
reps_el = document.createElement("input");
reps_el.type = "text"
reps_el.name = `rep_${i +1}`
reps_el.classList.add("reps_input");
reps_el.id = `rep_${i + 1}`
reps_el.placeholder = `Reps`;
exerciseDataContainer.appendChild(reps_el);
weight_el = document.createElement("input");
weight_el.type = "text"
weight_el.name = `weight_${i + 1}`
weight_el.classList.add("weight_input");
weight_el.id = `weight_${i + 1}`
weight_el.placeholder = "Weight (lbs)";
exerciseDataContainer.appendChild(weight_el);
exerciseDataContainer.appendChild(addRepsBtn)
addRepsBtn.removeAttribute("hidden");
if(exerciseDataContainer.children.length > 0) {
const lastElement = exerciseDataContainer.children[exerciseDataContainer.children.length - 2];
lastElement.style.marginBottom = "0px";
}
exerciseInput.value = " ";
exerciseObject.exercise = workoutName.innerText;
exerciseObject.date = formatted_date;
exerciseObject.sets = sets.value;
exerciseObject.type = drpdwnBtn.innerText;
console.log(exerciseObject.exercise);
updateExerciseObject(storageKeys, exerciseObject);
console.log(exerciseObject);
}
}else if(drpdwnBtn.innerText == "Boxing 🥊") {
for(let i = 0; i < rounds.value; i++) {
round_number = document.createElement('div');
round_number.classList.add('round_number');
round_number.innerText = `Round ${i + 1}`;
exerciseDataContainer.appendChild(round_number);
mins_el = document.createElement("input");
mins_el.type = "number"
mins_el.name = `mins_${i + 1}`
mins_el.classList.add("mins_input");
mins_el.id = `mins_${i + 1}`
mins_el.placeholder = "Minutes";
exerciseDataContainer.appendChild(mins_el);
exerciseDataContainer.appendChild(addRoundsBtn)
addRoundsBtn.removeAttribute("hidden");
if(exerciseDataContainer.children.length > 0) {
const lastElement = exerciseDataContainer.children[exerciseDataContainer.children.length - 2];
lastElement.style.marginBottom = "0px";
}
exerciseInput.value = " ";
exerciseObject.exercise = workoutName.innerText;
exerciseObject.date = formatted_date;
exerciseObject.rounds = rounds.value;
exerciseObject.type = drpdwnBtn.innerText;
console.log(exerciseObject.exercise);
updateExerciseObject(storageKeys, exerciseObject);
console.log(exerciseObject);
}
} else if (drpdwnBtn.innerText == "Cardio 🏃") {
if(!time_el.value || !distance_el.value) {
alert("Please enter time and distance")
return;
} else if(!time_el) {
alert("Please enter time")
return;
} else if(!distance_el) {
alert("Please enter distance")
return;
} else {
exerciseObject.time = time_el.value;
exerciseObject.distance = distance_el.value;
exerciseObject.date = formatted_date;
exerciseObject.exercise = workoutName.innerText;
exerciseObject.type = drpdwnBtn.innerText;
updateExerciseObject(storageKeys, exerciseObject);
let exerciseString = JSON.stringify(exerciseObject);
console.log(exerciseString)
localStorage.setItem(`exerciseData_${currentUserEmail}`, exerciseString);
let exerciseObj = JSON.parse(localStorage.getItem(exerciseObject.exercise))
console.log(exerciseObject);
console.log(exerciseObj);
if(exerciseObject) {
const dateObj = new Date(exerciseObject.date);
const month = dateObj.toLocaleDateString('default', {month: 'long'});
const year = dateObj.getFullYear();
const day = dateObj.getDate();
const monthDisplay = document.querySelector('#monthDisplay');
const day_els = document.querySelectorAll('#calendar .day:not([class*="padding"])');
const exerciseKey = workoutName.innerText;
day_els.forEach(day_el => {
if (monthDisplay.textContent.includes(month) && monthDisplay.textContent.includes(year)) {
if (day_el.innerText == day) {
console.log(day_el);
console.log(day);
const existingWorkout = day_el.querySelector('.workout_event');
console.log(existingWorkout);
if (existingWorkout) {
existingWorkout.innerText = exerciseKey;
} else {
const workout = document.createElement('div');
workout.classList.add('workout_event');
workout.innerText = exerciseKey;
day_el.appendChild(workout);
}
}
exerciseDataContainer.innerHTML = "";
}
});
load();
}
};
};
};
});
addRepsBtn.addEventListener('click', () => {
const exerciseKey = exerciseObject.exercise;
for(let i = 1; ; i++) {
const rep = document.getElementById(`rep_` + i);
const weight = document.getElementById(`weight_` + i);
if(!rep || !weight) {
break;
};
if (rep && weight) {
if (!rep.value && !weight.value) {
alert(`Please enter the amount of reps and weight for set ${i}.`);
return;
} else if (!rep.value) {
alert(`Please enter the amount of reps for set ${i}`);
return;
} else if (!weight.value) {
alert(`Please enter the amount of weight for set ${i}.`);
return;
}
exerciseObject[rep.id] = rep.value;
exerciseObject[weight.id] = weight.value;
const exerciseString = JSON.stringify(exerciseObject);
localStorage.setItem(`exerciseData_${currentUserEmail}`, exerciseString);
}
}
localStorage.setItem(`exerciseData_${currentUserEmail}`, JSON.stringify(exerciseObject));
let exerciseObj = JSON.parse(localStorage.getItem("exerciseObject"))
console.log(exerciseObj);
const exerciseLoggedData = JSON.parse(localStorage.getItem(exerciseKey));
console.log(exerciseLoggedData);
if(exerciseLoggedData) {
const dateObj = new Date(exerciseLoggedData.date);
const month = dateObj.toLocaleDateString('default', {month: 'long'});
const year = dateObj.getFullYear();
const day = dateObj.getDate();
console.log(month);
console.log(year);
console.log(day);
const monthDisplay = document.querySelector('#monthDisplay');
const day_els = document.querySelectorAll('#calendar .day:not([class*="padding"])');
day_els.forEach(day_el => {
if (monthDisplay.textContent.includes(month) && monthDisplay.textContent.includes(year)) {
if (day_el.innerText == day) {
console.log(day_el)
const existingWorkout = day_el.querySelector('.workout_event');
if (existingWorkout) {
existingWorkout.innerText = exerciseKey;
} else {
const workout = document.createElement('div');
workout.classList.add('workout_event');
workout.innerText = exerciseKey;
day_el.appendChild(workout);
}
}
}
});
}
exerciseDataContainer.innerHTML = '';
console.log(exerciseDataContainer);
setTimeout(() => {
load();
location.reload();
}, 0);