// Main JavaScript functions for Kayal Aqua Management System
document.addEventListener('DOMContentLoaded', function() {
// Initialize the app
initializeApp();
// Auto-hide alerts after 5 seconds
setTimeout(hideAlerts, 5000);
// Add loading states to forms
setupFormLoading();
// Setup mobile menu if exists
setupMobileMenu();
}
// Global error handler
window.addEventListener('error', function(e) {
console.error('JavaScript error:', e.error);
// Could implement error reporting here
});
// Global unhandled promise rejection handler
window.addEventListener('unhandledrejection', function(e) {
console.error('Unhandled promise rejection:', e.reason);
// Could implement error reporting here
e.preventDefault();
}););
// Initialize application
function initializeApp() {
// Set active navigation item
setActiveNavigation();
// Setup form validations
setupFormValidations();
// Setup confirmation dialogs
setupConfirmations();
// Handle anchor scrolling for edit forms
handleEditFormScrolling();
}
// Set active navigation item based on current page
function setActiveNavigation() {
const currentPage = window.location.pathname.split('/').pop() || 'index.php';
const navItems = document.querySelectorAll('.nav-item');
navItems.forEach(item => {
const href = item.getAttribute('href');
if (href === currentPage || (currentPage === '' && href === 'index.php')) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
}
// Auto-hide alert messages
function hideAlerts() {
const alerts = document.querySelectorAll('.alert');
alerts.forEach(alert => {
alert.style.transition = 'opacity 0.5s ease-out';
alert.style.opacity = '0';
setTimeout(() => {
if (alert.parentNode) {
alert.parentNode.removeChild(alert);
}
}, 500);
});
}
// Show alert message
function showAlert(message, type = 'success') {
const alertDiv = document.createElement('div');
alertDiv.className = `alert alert-${type}`;
alertDiv.textContent = message;
const mainContent = document.querySelector('.main-content');
if (mainContent) {
mainContent.insertBefore(alertDiv, mainContent.firstChild);
}
// Auto-hide after 5 seconds
setTimeout(() => {
hideAlert(alertDiv);
}, 5000);
}
// Hide specific alert
function hideAlert(alertElement) {
alertElement.style.transition = 'opacity 0.5s ease-out';
alertElement.style.opacity = '0';
setTimeout(() => {
if (alertElement.parentNode) {
alertElement.parentNode.removeChild(alertElement);
}
}, 500);
}
// Setup form loading states
function setupFormLoading() {
const forms = document.querySelectorAll('form');
forms.forEach(form => {
form.addEventListener('submit', function(e) {
const submitBtn = form.querySelector('button[type="submit"], input[type="submit"]');
if (submitBtn) {
const originalText = submitBtn.textContent || submitBtn.value;
submitBtn.disabled = true;
if (submitBtn.tagName === 'BUTTON') {
submitBtn.innerHTML = ' ' + originalText;
} else {
submitBtn.value = 'Processing...';
}
// Re-enable after 10 seconds as fallback
setTimeout(() => {
submitBtn.disabled = false;
if (submitBtn.tagName === 'BUTTON') {
submitBtn.textContent = originalText;
} else {
submitBtn.value = originalText;
}
}, 10000);
}
});
});
}
// Setup form validations
function setupFormValidations() {
// Phone number validation
const phoneInputs = document.querySelectorAll('input[name="phone"]');
phoneInputs.forEach(input => {
input.addEventListener('input', function() {
this.value = this.value.replace(/[^0-9+\-\s]/g, '');
});
input.addEventListener('blur', function() {
if (this.value && !isValidPhone(this.value)) {
showAlert('Please enter a valid phone number', 'error');
this.focus();
}
});
});
// Username validation
const usernameInputs = document.querySelectorAll('input[name="username"]');
usernameInputs.forEach(input => {
input.addEventListener('input', function() {
this.value = this.value.replace(/[^a-zA-Z0-9_]/g, '').toLowerCase();
});
});
// Password strength indicator
const passwordInputs = document.querySelectorAll('input[name="password"]');
passwordInputs.forEach(input => {
input.addEventListener('input', function() {
checkPasswordStrength(this);
});
});
}
// Validate phone number
function isValidPhone(phone) {
const phoneRegex = /^[\+]?[0-9\-\s]{10,15}$/;
return phoneRegex.test(phone.replace(/\s/g, ''));
}
// Check password strength
function checkPasswordStrength(passwordInput) {
const password = passwordInput.value;
const strengthIndicator = document.getElementById('password-strength');
if (!strengthIndicator) return;
let strength = 0;
let message = '';
let color = '';
if (password.length >= 8) strength++;
if (/[a-z]/.test(password)) strength++;
if (/[A-Z]/.test(password)) strength++;
if (/[0-9]/.test(password)) strength++;
if (/[^A-Za-z0-9]/.test(password)) strength++;
switch (strength) {
case 0:
case 1:
message = 'Very Weak';
color = '#f44336';
break;
case 2:
message = 'Weak';
color = '#ff9800';
break;
case 3:
message = 'Fair';
color = '#ffeb3b';
break;
case 4:
message = 'Good';
color = '#4caf50';
break;
case 5:
message = 'Strong';
color = '#2e7d32';
break;
}
strengthIndicator.textContent = message;
strengthIndicator.style.color = color;
}
// Setup confirmation dialogs
function setupConfirmations() {
const deleteButtons = document.querySelectorAll('.btn-danger, [data-confirm]');
deleteButtons.forEach(button => {
button.addEventListener('click', function(e) {
const message = this.dataset.confirm || 'Are you sure you want to perform this action?';
if (!confirm(message)) {
e.preventDefault();
return false;
}
});
});
}
// Setup mobile menu (if needed for future mobile navigation)
function setupMobileMenu() {
const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
const navMenu = document.querySelector('.nav-menu');
if (mobileMenuToggle && navMenu) {
mobileMenuToggle.addEventListener('click', function() {
navMenu.classList.toggle('show');
});
}
}
// Utility function to format currency
function formatCurrency(amount) {
return '₹' + parseFloat(amount).toLocaleString('en-IN', {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
}
// Utility function to format date
function formatDate(dateString) {
const date = new Date(dateString);
return date.toLocaleDateString('en-IN', {
year: 'numeric',
month: 'short',
day: 'numeric'
});
}
// Utility function to validate email
function isValidEmail(email) {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
// Utility function to show loading state
function showLoading(element) {
element.disabled = true;
element.innerHTML = ' ' + element.textContent;
}
// Utility function to hide loading state
function hideLoading(element, originalText) {
element.disabled = false;
element.textContent = originalText;
}
// Function to handle AJAX requests
function makeRequest(url, method = 'GET', data = null) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
try {
const response = JSON.parse(xhr.responseText);
resolve(response);
} catch (e) {
resolve(xhr.responseText);
}
} else {
reject(new Error('Request failed: ' + xhr.status));
}
}
};
xhr.send(data);
});
}
// Global error handler
window.addEventListener('error', function(e) {
console.error('JavaScript error:', e.error);
// Could implement error reporting here
});
// Handle anchor scrolling for edit forms in settings page
function handleEditFormScrolling() {
// Check if we're on settings page and have edit parameters
const currentPage = window.location.pathname.split('/').pop();
const urlParams = new URLSearchParams(window.location.search);
if (currentPage === 'settings.php' || currentPage === '') {
let targetSection = null;
// Determine which section to scroll to based on URL parameters
if (urlParams.has('edit_unit')) {
targetSection = 'units-section';
} else if (urlParams.has('edit_category')) {
targetSection = 'categories-section';
} else if (urlParams.has('edit_subcategory')) {
targetSection = 'subcategories-section';
} else if (urlParams.has('edit_ps')) {
targetSection = 'products-section';
}
// Also check for hash in URL
if (window.location.hash) {
const hashSection = window.location.hash.substring(1);
if (document.getElementById(hashSection)) {
targetSection = hashSection;
}
}
// Scroll to the target section if found
if (targetSection) {
setTimeout(() => {
const element = document.getElementById(targetSection);
if (element) {
element.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
// Add a subtle highlight effect
element.style.transition = 'background-color 0.3s ease';
element.style.backgroundColor = 'rgba(255, 215, 0, 0.1)';
setTimeout(() => {
element.style.backgroundColor = '';
}, 2000);
}
}, 100);
}
}
}