-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
721 lines (632 loc) · 26.1 KB
/
Copy pathscript.js
File metadata and controls
721 lines (632 loc) · 26.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
// STATE MANAGEMENT
const APP_STATE = {
currentUser: null,
currentLanguage: 'en',
userLocation: null
};
// TRANSLATION DATA
const TRANSLATIONS = {
en: {
'Full Name': 'Full Name',
'Phone Number': 'Phone Number',
'Email': 'Email',
'Password': 'Password',
'Confirm Password': 'Confirm Password',
'Sign Up': 'Sign Up',
'Your location will only be shared during emergencies with police, safety teams, and trusted contacts.': 'Your location will only be shared during emergencies with police, safety teams, and trusted contacts.',
'Your Safety Shield': 'Your Safety Shield',
'Logout': 'Logout',
'EMERGENCY': 'EMERGENCY',
'Healthcare Info': 'Healthcare Info',
'Women Rights': 'Women Rights',
'Emergency Contacts': 'Emergency Contacts',
'Call 112': 'Call 112',
'Emergency': 'Emergency'
},
hi: {
'Full Name': 'पूरा नाम',
'Phone Number': 'फोन नंबर',
'Email': 'ईमेल',
'Password': 'पासवर्ड',
'Confirm Password': 'पासवर्ड की पुष्टि करें',
'Sign Up': 'साइन अप करें',
'Your location will only be shared during emergencies with police, safety teams, and trusted contacts.': 'आपका स्थान केवल आपातकाल के दौरान पुलिस, सुरक्षा टीमों और विश्वसनीय संपर्कों के साथ साझा किया जाएगा।',
'Your Safety Shield': 'आपकी सुरक्षा ढाल',
'Logout': 'लॉग आउट',
'EMERGENCY': 'आपातकाल',
'Healthcare Info': 'स्वास्थ्य जानकारी',
'Women Rights': 'महिला अधिकार',
'Emergency Contacts': 'आपातकालीन संपर्क',
'Call 112': '112 पर कॉल करें',
'Emergency': 'आपातकाल'
}
};
// DOM ELEMENTS
const signupPage = document.getElementById('signupPage');
const dashboardPage = document.getElementById('dashboardPage');
const signupForm = document.getElementById('signupForm');
const signupBtn = document.getElementById('signupBtn');
const locationStatus = document.getElementById('locationStatus');
const profileAvatar = document.getElementById('profileAvatar');
const profileDropdown = document.getElementById('profileDropdown');
const logoutBtn = document.getElementById('logoutBtn');
const languageSwitch = document.getElementById('languageSwitch');
const sosButton = document.getElementById('sosButton');
const modalOverlay = document.getElementById('modalOverlay');
const modalTitle = document.getElementById('modalTitle');
const modalContent = document.getElementById('modalContent');
const modalClose = document.getElementById('modalClose');
// MODAL CONTENT DATA
const MODAL_CONTENT = {
healthcare: {
title: 'Healthcare Information',
sections: [
{
icon: '🩸',
title: 'Menstrual Health',
description: 'Menstruation is a natural process. Understanding your cycle helps you stay healthy and recognize any irregularities.',
tips: [
'Change sanitary products every 4-6 hours to prevent infections',
'Use clean, good quality sanitary pads, tampons, or menstrual cups',
'Track your cycle to understand patterns and predict periods',
'Mild pain is normal, but severe cramps may need medical attention',
'Stay hydrated and maintain good hygiene during periods'
]
},
{
icon: '🤰',
title: 'Reproductive Health',
description: 'Taking care of your reproductive health is essential for overall wellbeing. Regular check-ups help detect issues early.',
tips: [
'Schedule annual gynecological check-ups',
'Discuss contraception options with a healthcare provider if needed',
'Be aware of signs like unusual discharge, pain, or irregular bleeding',
'Practice safe hygiene and wear breathable cotton underwear',
'Seek medical advice before planning pregnancy'
]
},
{
icon: '🧠',
title: 'Mental Health',
description: 'Mental health is just as important as physical health. It\'s okay to seek support when you need it.',
tips: [
'Talk to someone you trust when feeling overwhelmed',
'Practice self-care through activities you enjoy',
'Maintain a regular sleep schedule and eat nutritious meals',
'Set boundaries and don\'t hesitate to say no when needed',
'Seek professional help if experiencing persistent sadness or anxiety'
]
},
{
icon: '🥗',
title: 'Nutrition',
description: 'Balanced nutrition supports your body\'s needs throughout different life stages.',
tips: [
'Include iron-rich foods like spinach, lentils, and lean meat',
'Consume calcium through dairy, nuts, and green leafy vegetables',
'Eat a variety of fruits and vegetables for essential vitamins',
'Stay hydrated by drinking 8-10 glasses of water daily',
'Limit processed foods and maintain regular meal times'
]
},
{
icon: '🧼',
title: 'General Hygiene',
description: 'Good hygiene practices prevent infections and promote overall health.',
tips: [
'Wash intimate areas with water only; avoid harsh soaps',
'Wipe front to back after using the toilet',
'Change undergarments daily and choose breathable fabrics',
'Keep nails trimmed and hands clean',
'Avoid sharing personal items like razors or towels'
]
},
{
icon: '💪',
title: 'Safety & Self-Care',
description: 'Prioritizing your safety and wellbeing empowers you to live confidently.',
tips: [
'Trust your instincts if something feels unsafe',
'Share your location with trusted contacts when traveling alone',
'Keep emergency numbers readily accessible',
'Schedule regular health screenings appropriate for your age',
'Take time for activities that bring you peace and joy'
]
}
]
},
rights: {
title: 'Women Rights in India',
sections: [
{
icon: '⚖️',
title: 'Right to Equality',
description: 'The Indian Constitution guarantees equality to all citizens. No discrimination is permitted on grounds of sex.',
tips: [
'Article 14: Equal treatment before law for all citizens',
'Article 15: Prohibition of discrimination based on sex',
'Article 16: Equal opportunity in public employment',
'Right to equal pay for equal work',
'Access to education and public spaces without discrimination'
]
},
{
icon: '🏠',
title: 'Protection from Domestic Violence',
description: 'The Protection of Women from Domestic Violence Act, 2005 protects women from abuse in domestic relationships.',
tips: [
'Covers physical, emotional, sexual, verbal, and economic abuse',
'Protection available to wives, live-in partners, sisters, mothers',
'Right to residence in shared household',
'Can file complaint at police station or magistrate court',
'Domestic Violence Helpline: 181 (available 24/7)'
]
},
{
icon: '💼',
title: 'Sexual Harassment at Workplace (POSH)',
description: 'The Sexual Harassment of Women at Workplace Act, 2013 ensures safe and dignified work environment.',
tips: [
'Every workplace must have an Internal Complaints Committee',
'Covers unwelcome physical contact, demands, or sexual remarks',
'Complaint can be filed within 3 months of incident',
'Confidential inquiry process to protect complainant',
'Employer responsible for creating harassment-free environment'
]
},
{
icon: '👶',
title: 'Maternity Benefits',
description: 'The Maternity Benefit Act provides paid leave and protection to working women during pregnancy.',
tips: [
'26 weeks paid maternity leave (was 12 weeks before 2017)',
'Cannot be dismissed during pregnancy or maternity leave',
'Right to work from home options post maternity leave',
'Crèche facilities in establishments with 50+ employees',
'Medical bonus for prenatal and postnatal care'
]
},
{
icon: '📋',
title: 'Right to File FIR',
description: 'Every woman has the right to file a First Information Report (FIR) at any police station.',
tips: [
'Police cannot refuse to register your FIR',
'FIR can be filed at any police station regardless of jurisdiction',
'You have the right to receive a copy of the FIR',
'FIR can be filed online through state police websites',
'For crimes against women, women police officers should be present'
]
},
{
icon: '📞',
title: 'Important Helpline Numbers',
description: 'These helplines provide immediate assistance and support in emergencies.',
tips: [
'Women Helpline: 1091 (24/7 support)',
'National Commission for Women: 011-26944880',
'Domestic Violence Helpline: 181',
'Police Emergency: 100 or 112',
'Child Helpline (for minors): 1098'
]
}
]
}
};
// INITIALIZATION
document.addEventListener('DOMContentLoaded', () => {
initializeApp();
setupEventListeners();
});
// APP INITIALIZATION
function initializeApp() {
// Check if user is already logged in
const savedUser = localStorage.getItem('kavachUser');
if (savedUser) {
APP_STATE.currentUser = JSON.parse(savedUser);
showDashboard();
} else {
showSignup();
}
// Load saved language preference
const savedLanguage = localStorage.getItem('kavachLanguage') || 'en';
APP_STATE.currentLanguage = savedLanguage;
languageSwitch.value = savedLanguage;
}
// EVENT LISTENERS
function setupEventListeners() {
// Signup form submission
signupForm.addEventListener('submit', handleSignup);
// Profile avatar click
profileAvatar.addEventListener('click', toggleProfileDropdown);
// Logout button
logoutBtn.addEventListener('click', handleLogout);
// Language switch
languageSwitch.addEventListener('change', handleLanguageChange);
// SOS button
sosButton.addEventListener('click', handleSOS);
// Modal close buttons
modalClose.addEventListener('click', closeModal);
modalOverlay.addEventListener('click', (e) => {
if (e.target === modalOverlay) closeModal();
});
// ESC key to close modal
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !modalOverlay.classList.contains('hidden')) {
closeModal();
}
});
// Quick action cards - open modals
document.getElementById('healthcareCard').addEventListener('click', () => {
openModal('healthcare');
});
document.getElementById('rightsCard').addEventListener('click', () => {
openModal('rights');
});
document.getElementById('contactsCard').addEventListener('click', () => {
openModal('contacts');
});
// Close dropdown when clicking outside
document.addEventListener('click', (e) => {
if (!profileAvatar.contains(e.target) && !profileDropdown.contains(e.target)) {
profileDropdown.classList.add('hidden');
}
});
}
// MODAL FUNCTIONS
function openModal(type) {
// Prevent body scroll when modal is open
document.body.style.overflow = 'hidden';
if (type === 'healthcare') {
const content = MODAL_CONTENT.healthcare;
modalTitle.textContent = content.title;
modalContent.innerHTML = generateHealthcareContent(content.sections);
} else if (type === 'rights') {
const content = MODAL_CONTENT.rights;
modalTitle.textContent = content.title;
modalContent.innerHTML = generateRightsContent(content.sections);
} else if (type === 'contacts') {
modalTitle.textContent = 'Emergency Contacts';
modalContent.innerHTML = generateContactsContent();
setupContactsHandlers();
}
modalOverlay.classList.remove('hidden');
}
function closeModal() {
modalOverlay.classList.add('hidden');
document.body.style.overflow = 'auto';
}
// GENERATE HEALTHCARE CONTENT
function generateHealthcareContent(sections) {
return sections.map(section => `
<div class="modal-section">
<h3 class="section-title">
<span class="section-icon">${section.icon}</span>
${section.title}
</h3>
<p class="section-description">${section.description}</p>
<div class="section-tips">
<h4>Important Points:</h4>
<ul>
${section.tips.map(tip => `<li>${tip}</li>`).join('')}
</ul>
</div>
</div>
`).join('');
}
// GENERATE WOMEN RIGHTS CONTENT
function generateRightsContent(sections) {
return sections.map(section => `
<div class="modal-section">
<h3 class="section-title">
<span class="section-icon">${section.icon}</span>
${section.title}
</h3>
<p class="section-description">${section.description}</p>
<div class="section-tips">
<h4>Key Points:</h4>
<ul>
${section.tips.map(tip => `<li>${tip}</li>`).join('')}
</ul>
</div>
</div>
`).join('');
}
// GENERATE EMERGENCY CONTACTS CONTENT
function generateContactsContent() {
return `
<div class="contacts-form">
<h3>Add Trusted Contact</h3>
<div class="form-row">
<input type="text" id="contactName" placeholder="Full Name" required>
<input type="tel" id="contactPhone" placeholder="Phone Number" pattern="[0-9]{10}" required>
<input type="text" id="contactRelation" placeholder="Relation" required>
<button type="button" id="addContactBtn" class="btn-add">Add</button>
</div>
</div>
<div class="privacy-notice">
<p><strong>Privacy Notice:</strong> These contacts may be shared with police, safety teams, and emergency responders during crisis situations to ensure your safety.</p>
</div>
<div class="contacts-list">
<h3>Saved Contacts</h3>
<div id="contactsList"></div>
</div>
`;
}
// SETUP CONTACTS HANDLERS
function setupContactsHandlers() {
const addBtn = document.getElementById('addContactBtn');
addBtn.addEventListener('click', addContact);
// Display existing contacts
displayContacts();
}
// ADD CONTACT
function addContact() {
const nameInput = document.getElementById('contactName');
const phoneInput = document.getElementById('contactPhone');
const relationInput = document.getElementById('contactRelation');
const name = nameInput.value.trim();
const phone = phoneInput.value.trim();
const relation = relationInput.value.trim();
if (!name || !phone || !relation) {
alert('Please fill all fields');
return;
}
// Validate phone number (basic check)
if (!/^[0-9]{10}$/.test(phone)) {
alert('Please enter a valid 10-digit phone number');
return;
}
// Get existing contacts from localStorage
const contacts = getEmergencyContacts();
// Add new contact
const newContact = {
id: Date.now(),
name,
phone,
relation,
addedAt: new Date().toISOString()
};
contacts.push(newContact);
// Save to localStorage
localStorage.setItem('kavachEmergencyContacts', JSON.stringify(contacts));
// Clear inputs
nameInput.value = '';
phoneInput.value = '';
relationInput.value = '';
// Refresh display
displayContacts();
}
// GET EMERGENCY CONTACTS
function getEmergencyContacts() {
const stored = localStorage.getItem('kavachEmergencyContacts');
return stored ? JSON.parse(stored) : [];
}
// DISPLAY CONTACTS
function displayContacts() {
const contactsList = document.getElementById('contactsList');
const contacts = getEmergencyContacts();
if (contacts.length === 0) {
contactsList.innerHTML = '<div class="empty-state">No emergency contacts saved yet. Add your first trusted contact above.</div>';
return;
}
contactsList.innerHTML = contacts.map(contact => `
<div class="contact-item">
<div class="contact-info">
<div class="contact-name">${contact.name}</div>
<div class="contact-details">${contact.phone} • ${contact.relation}</div>
</div>
<button class="btn-delete" onclick="deleteContact(${contact.id})">Delete</button>
</div>
`).join('');
}
// DELETE CONTACT
function deleteContact(id) {
if (!confirm('Are you sure you want to remove this contact?')) {
return;
}
let contacts = getEmergencyContacts();
contacts = contacts.filter(contact => contact.id !== id);
localStorage.setItem('kavachEmergencyContacts', JSON.stringify(contacts));
displayContacts();
}
// Make deleteContact available globally (called from onclick in HTML)
window.deleteContact = deleteContact;
// EVENT LISTENERS (OLD)
// SIGNUP HANDLER
async function handleSignup(e) {
e.preventDefault();
const fullName = document.getElementById('fullName').value.trim();
const phone = document.getElementById('phone').value.trim();
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirmPassword').value;
// Validate password match
if (password !== confirmPassword) {
showLocationStatus('Passwords do not match', 'error');
return;
}
// Request location permission
signupBtn.disabled = true;
signupBtn.textContent = 'Getting Location...';
try {
const location = await getUserLocation();
// Create user object
const user = {
fullName,
phone,
email,
location,
createdAt: new Date().toISOString()
};
// Save to localStorage (in real app, this would be API call)
localStorage.setItem('kavachUser', JSON.stringify(user));
APP_STATE.currentUser = user;
// Show success and redirect
showLocationStatus('Signup successful! Redirecting...', 'success');
setTimeout(() => {
showDashboard();
}, 1000);
} catch (error) {
showLocationStatus(error.message, 'error');
signupBtn.disabled = false;
signupBtn.textContent = 'Sign Up';
}
}
// GET USER LOCATION
function getUserLocation() {
return new Promise((resolve, reject) => {
if (!navigator.geolocation) {
reject(new Error('Geolocation is not supported by your browser'));
return;
}
showLocationStatus('Requesting location permission...', 'success');
navigator.geolocation.getCurrentPosition(
(position) => {
const location = {
latitude: position.coords.latitude,
longitude: position.coords.longitude,
timestamp: new Date().toISOString()
};
APP_STATE.userLocation = location;
showLocationStatus('✓ Location captured successfully', 'success');
resolve(location);
},
(error) => {
let errorMessage = 'Unable to get location. ';
switch(error.code) {
case error.PERMISSION_DENIED:
errorMessage += 'Location permission is required for signup. Please enable location access.';
break;
case error.POSITION_UNAVAILABLE:
errorMessage += 'Location information is unavailable.';
break;
case error.TIMEOUT:
errorMessage += 'Location request timed out.';
break;
default:
errorMessage += 'An unknown error occurred.';
}
reject(new Error(errorMessage));
},
{
enableHighAccuracy: true,
timeout: 10000,
maximumAge: 0
}
);
});
}
// SHOW LOCATION STATUS
function showLocationStatus(message, type) {
locationStatus.textContent = message;
locationStatus.className = `location-status ${type}`;
}
// SHOW SIGNUP PAGE
function showSignup() {
signupPage.classList.remove('hidden');
dashboardPage.classList.add('hidden');
}
// SHOW DASHBOARD
function showDashboard() {
signupPage.classList.add('hidden');
dashboardPage.classList.remove('hidden');
// Update profile information
updateProfileUI();
}
// UPDATE PROFILE UI
function updateProfileUI() {
if (!APP_STATE.currentUser) return;
const { fullName, phone } = APP_STATE.currentUser;
// Set avatar letter (first character of name)
const avatarLetter = fullName.charAt(0).toUpperCase();
document.getElementById('avatarLetter').textContent = avatarLetter;
// Set dropdown info
document.getElementById('dropdownName').textContent = fullName;
document.getElementById('dropdownPhone').textContent = phone;
}
// TOGGLE PROFILE DROPDOWN
function toggleProfileDropdown(e) {
e.stopPropagation();
profileDropdown.classList.toggle('hidden');
}
// LOGOUT HANDLER
function handleLogout() {
// Clear user session
localStorage.removeItem('kavachUser');
APP_STATE.currentUser = null;
APP_STATE.userLocation = null;
// Hide dropdown
profileDropdown.classList.add('hidden');
// Redirect to signup
showSignup();
// Reset form
signupForm.reset();
locationStatus.textContent = '';
locationStatus.className = 'location-status';
}
// LANGUAGE CHANGE HANDLER
function handleLanguageChange(e) {
const newLanguage = e.target.value;
APP_STATE.currentLanguage = newLanguage;
// Save preference
localStorage.setItem('kavachLanguage', newLanguage);
// Update all translatable elements
updateLanguage();
}
// UPDATE LANGUAGE
function updateLanguage() {
const lang = APP_STATE.currentLanguage;
// Update all elements with data-en and data-hi attributes
const translatableElements = document.querySelectorAll('[data-en][data-hi]');
translatableElements.forEach(element => {
if (lang === 'hi') {
element.textContent = element.getAttribute('data-hi');
} else {
element.textContent = element.getAttribute('data-en');
}
});
}
// SOS HANDLER
function handleSOS() {
// In production, this would:
// 1. Send location to emergency services
// 2. Alert trusted contacts
// 3. Start recording audio/video
// 4. Send notification to police
const user = APP_STATE.currentUser;
if (user && user.location) {
const confirmSOS = confirm(
'EMERGENCY SOS ACTIVATED\n\n' +
'This will:\n' +
'• Share your location with emergency services\n' +
'• Alert your trusted contacts\n' +
'• Contact local police\n\n' +
'Proceed?'
);
if (confirmSOS) {
alert(
'SOS SENT!\n\n' +
'Emergency services notified.\n' +
'Location: ' + user.location.latitude.toFixed(4) + ', ' + user.location.longitude.toFixed(4) + '\n\n' +
'Help is on the way. Stay safe.'
);
}
} else {
alert('Unable to send SOS. Location not available.');
}
}
// UTILITY: Check if element is in viewport (for future lazy loading)
function isInViewport(element) {
const rect = element.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
// Initialize language on load
window.addEventListener('load', () => {
updateLanguage();
});