/** * Non-SEHA Referral System - Completely Independent JavaScript * This system has its own functions, separate from the main referral system */ (function($) { 'use strict'; // Non-SEHA Referral System Namespace window.NoneSehaReferral = { // Initialize the system init: function() { this.initForms(); this.initExport(); this.initStatus(); console.log('Non-SEHA Referral System initialized'); }, // Initialize all non-SEHA forms initForms: function() { // Patient referral form this.initPatientForm(); // Physician registration form this.initRegistrationForm(); // Status check form this.initStatusForm(); // Reset code form this.initResetCodeForm(); }, // Initialize patient referral form initPatientForm: function() { var $form = $('.aaa-none-seha-form'); console.log('Non-SEHA Patient Form - Found forms:', $form.length); if ($form.length === 0) return; $form.each(function() { var $thisForm = $(this); console.log('Non-SEHA Patient Form - Initializing form:', $thisForm); // Email verification button $thisForm.find('.btn-verify-email').on('click', function(e) { e.preventDefault(); console.log('Non-SEHA Patient Form - Email verification button clicked'); NoneSehaReferral.verifyEmailAndShowForm($thisForm); }); // Form submission $thisForm.on('submit', function(e) { e.preventDefault(); console.log('Non-SEHA Patient Form - Form submitted'); NoneSehaReferral.submitPatientForm($thisForm); }); // Email verification on blur $thisForm.find('input[name="none_seha_code"]').on('blur', function() { console.log('Non-SEHA Patient Form - Email verification triggered'); NoneSehaReferral.verifyEmail($(this).val(), $thisForm); }); // Real-time validation - clear errors when user starts typing $thisForm.find('input, select, textarea').on('input change', function() { var $field = $(this); var $fieldGroup = $field.closest('.aaa-form-group'); console.log('Field changed:', $field.attr('name'), 'Value:', $field.val()); // Clear error state when user starts typing if ($field.val().trim()) { $fieldGroup.removeClass('has-error'); $fieldGroup.find('.error-message').remove(); // Add success state for valid input if ($field.val().trim().length > 0) { $fieldGroup.addClass('has-success'); } } else { // Remove success state if field becomes empty $fieldGroup.removeClass('has-success'); } }); // Clear errors on focus $thisForm.find('input, select, textarea').on('focus', function() { var $field = $(this); var $fieldGroup = $field.closest('.aaa-form-group'); // Remove error styling on focus $fieldGroup.removeClass('has-error'); $fieldGroup.find('.error-message').remove(); }); // Real-time phone number formatting $thisForm.find('input[name*="phone"], input[name*="contact"], input[name*="number"], input[name*="emergency"], input[name="nursing_contact"]').on('input', function() { var $field = $(this); var value = $field.val(); var formattedValue = NoneSehaReferral.formatPhoneNumber(value); // Only update if the formatted value is different if (formattedValue !== value) { $field.val(formattedValue); } }); // Clear email error when user starts typing $thisForm.find('input[name="none_seha_code"]').on('input', function() { var $field = $(this); var $fieldGroup = $field.closest('.aaa-form-group'); var $errorMessage = $thisForm.find('#email-error-message'); $fieldGroup.removeClass('has-error has-success'); $errorMessage.removeClass('show').text(''); }); }); }, // Initialize registration form initRegistrationForm: function() { $('.aaa-none-seha-register-form').each(function() { var $form = $(this); $form.on('submit', function(e) { e.preventDefault(); NoneSehaReferral.submitRegistration($form); }); }); }, // Initialize status form initStatusForm: function() { $('.aaa-none-seha-status-form').each(function() { var $form = $(this); $form.on('submit', function(e) { e.preventDefault(); NoneSehaReferral.checkStatus($form); }); }); }, // Initialize reset code form initResetCodeForm: function() { $('.aaa-none-seha-resetcode-form').each(function() { var $form = $(this); $form.on('submit', function(e) { e.preventDefault(); NoneSehaReferral.requestResetCode($form); }); }); }, // Form validation for single-page form validateForm: function($form) { var isValid = true; var requiredFields = $form.find('[required]'); requiredFields.each(function() { var $field = $(this); var value = $field.val(); if (!value || value.trim() === '') { $field.addClass('error'); isValid = false; } else { $field.removeClass('error'); } }); return isValid; }, // Verify email for non-SEHA referrals verifyEmail: function(email, $form) { if (!email) return; $.ajax({ url: NoneSehaReferral.ajaxUrl, type: 'POST', data: { action: 'verify_none_seha_email', email: email, nonce: NoneSehaReferral.nonce }, success: function(response) { if (response.success) { $form.find('.aaa-email-verification').addClass('verified'); $form.find('input[name="none_seha_code"]').addClass('valid'); console.log('Email verified successfully'); } else { $form.find('.aaa-email-verification').removeClass('verified'); $form.find('input[name="none_seha_code"]').removeClass('valid'); console.log('Email verification failed:', response.data.message); } }, error: function() { $form.find('.aaa-email-verification').removeClass('verified'); $form.find('.aaa-email-verification').removeClass('verified'); $form.find('input[name="none_seha_code"]').removeClass('valid'); console.log('Email verification error'); } }); }, // Verify email and show the main form verifyEmailAndShowForm: function($form) { var email = $form.find('input[name="none_seha_code"]').val(); var $emailGroup = $form.find('input[name="none_seha_code"]').closest('.aaa-form-group'); var $errorMessage = $form.find('#email-error-message'); // Clear previous errors $emailGroup.removeClass('has-error has-success'); $errorMessage.removeClass('show').text(''); // Validate email if (!email) { this.showFieldError($emailGroup, 'Email address is required'); return; } if (!this.isValidEmail(email)) { this.showFieldError($emailGroup, 'Please enter a valid email address'); return; } console.log('Verifying email and showing form for:', email); // Show loading state $form.find('.btn-verify-email').prop('disabled', true).text('Verifying...'); $.ajax({ url: NoneSehaReferral.ajaxUrl, type: 'POST', data: { action: 'verify_none_seha_email', email: email, nonce: NoneSehaReferral.nonce }, success: function(response) { if (response.success) { console.log('Email verified, showing main form'); // Show success state $emailGroup.addClass('has-success'); // Set email verification flag $form.find('input[name="_email_verified"]').val('1'); // Hide step 1 and show step 2 - Same as main referral $form.find('.step-1').hide(); $form.find('.step-2').show().addClass('show'); // Update the current email display $form.find('#current-email-display').text(email); // Scroll to top of form $('html, body').animate({ scrollTop: $form.offset().top }, 300); } else { // Show error message $errorMessage.text(response.data.message || 'Email verification failed').addClass('show'); $emailGroup.addClass('has-error'); // Reset email verification flag on error $form.find('input[name="_email_verified"]').val('0'); console.log('Email verification failed:', response.data.message); } }, error: function() { // Show generic error $errorMessage.text('Email verification failed. Please try again.').addClass('show'); $emailGroup.addClass('has-error'); // Reset email verification flag on error $form.find('input[name="_email_verified"]').val('0'); console.log('Email verification error'); }, complete: function() { // Reset button state $form.find('.btn-verify-email').prop('disabled', false).text('Verify Email'); } }); }, // Show field error showFieldError: function($fieldGroup, message) { $fieldGroup.addClass('has-error'); // Remove existing error message $fieldGroup.find('.error-message').remove(); // Add error message $fieldGroup.append('
'); }, // Clear field error clearFieldError: function($fieldGroup) { $fieldGroup.removeClass('has-error has-success'); $fieldGroup.find('.error-message').remove(); }, // Reset email verification state resetEmailVerification: function($form) { $form.find('input[name="_email_verified"]').val('0'); $form.find('.step-1').show(); $form.find('.step-2').hide().removeClass('show'); $form.find('.aaa-form-group').removeClass('has-error has-success'); $form.find('.error-message').remove(); $form.find('#email-error-message').removeClass('show').text(''); }, // Change email address - go back to step 1 changeEmail: function() { var $form = $('.aaa-none-seha-form'); if ($form.length) { this.resetEmailVerification($form); // Clear the email input $form.find('input[name="none_seha_code"]').val(''); // Scroll to top $('html, body').animate({ scrollTop: $form.offset().top }, 300); console.log('Email change requested - returning to step 1'); } }, // Validate email format isValidEmail: function(email) { var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; return emailRegex.test(email); }, // Validate main form validateMainForm: function($form) { var isValid = true; var $firstErrorField = null; console.log('Starting form validation...'); // Clear all previous errors $form.find('.aaa-form-group').removeClass('has-error has-success'); $form.find('.error-message').remove(); // Check all required fields $form.find('input[required], select[required], textarea[required]').each(function() { var $field = $(this); var $fieldGroup = $field.closest('.aaa-form-group'); var value = $field.val().trim(); var fieldName = $field.attr('name') || $field.attr('placeholder') || 'This field'; console.log('Validating field:', fieldName, 'Value:', value); if (!value) { isValid = false; NoneSehaReferral.showFieldError($fieldGroup, fieldName + ' is required'); if (!$firstErrorField) { $firstErrorField = $field; } } else { // Clear error and show success $fieldGroup.removeClass('has-error').addClass('has-success'); } }); // Check specific field validations $form.find('input[type="email"]').each(function() { var $field = $(this); var $fieldGroup = $field.closest('.aaa-form-group'); var value = $field.val().trim(); if (value && !NoneSehaReferral.isValidEmail(value)) { isValid = false; NoneSehaReferral.showFieldError($fieldGroup, 'Please enter a valid email address'); if (!$firstErrorField) { $firstErrorField = $field; } } }); // Check phone number format - improved detection $form.find('input[name*="phone"], input[name*="contact"], input[name*="number"], input[name*="emergency"], input[name="nursing_contact"]').each(function() { var $field = $(this); var $fieldGroup = $field.closest('.aaa-form-group'); var value = $field.val().trim(); console.log('Validating phone field:', $field.attr('name'), 'Value:', value); if (value && !NoneSehaReferral.isValidPhone(value)) { isValid = false; NoneSehaReferral.showFieldError($fieldGroup, 'Please enter a valid UAE phone number. Accepted formats: 501111111 or +971501111111'); if (!$firstErrorField) { $firstErrorField = $field; } } }); // Check date fields $form.find('input[type="date"]').each(function() { var $field = $(this); var $fieldGroup = $field.closest('.aaa-form-group'); var value = $field.val(); if (value && !NoneSehaReferral.isValidDate(value)) { isValid = false; NoneSehaReferral.showFieldError($fieldGroup, 'Please enter a valid date'); if (!$firstErrorField) { $firstErrorField = $field; } } }); // Scroll to first error if any if ($firstErrorField) { console.log('First error field:', $firstErrorField.attr('name')); $('html, body').animate({ scrollTop: $firstErrorField.offset().top - 100 }, 300); } console.log('Form validation result:', isValid); return isValid; }, // Validate phone number - Support both UAE local and international formats isValidPhone: function(phone) { // Remove any spaces, dashes, or other characters var cleanPhone = phone.replace(/[\s\-\(\)]/g, ''); // Check if it's a UAE number with country code (+971) if (cleanPhone.startsWith('+971')) { var uaeNumber = cleanPhone.substring(4); // Remove +971 // UAE mobile numbers after +971 should be 9 digits starting with 5 var uaeRegex = /^5[0-9]{8}$/; return uaeRegex.test(uaeNumber); } // Check if it's a UAE number without country code (9 digits starting with 5) var uaeLocalRegex = /^5[0-9]{8}$/; if (uaeLocalRegex.test(cleanPhone)) { return true; } // Check if it's exactly 9 digits and doesn't start with 0 (fallback) var phoneRegex = /^[1-9][0-9]{8}$/; return phoneRegex.test(cleanPhone); }, // Validate date isValidDate: function(dateString) { var date = new Date(dateString); return date instanceof Date && !isNaN(date); }, // Get field display name for better error messages getFieldDisplayName: function($field) { var name = $field.attr('name') || ''; var placeholder = $field.attr('placeholder') || ''; var label = $field.closest('.aaa-form-group').find('label').text() || ''; // Clean up the name for display if (name) { name = name.replace(/_/g, ' ').replace(/([A-Z])/g, ' $1').toLowerCase(); name = name.charAt(0).toUpperCase() + name.slice(1); } return label || placeholder || name || 'This field'; }, // Format phone number input - handle UAE and international formats formatPhoneNumber: function(phone) { // Remove all non-digit characters except + var cleanPhone = phone.replace(/[^\d+]/g, ''); // If it starts with +971, keep it as international format if (cleanPhone.startsWith('+971')) { var uaeNumber = cleanPhone.substring(4); // Remove +971 // Remove leading 0 if present if (uaeNumber.startsWith('0')) { uaeNumber = uaeNumber.substring(1); } // Limit to 9 digits if (uaeNumber.length > 9) { uaeNumber = uaeNumber.substring(0, 9); } return '+971' + uaeNumber; } // For local numbers, remove leading 0 and limit to 9 digits if (cleanPhone.startsWith('0')) { cleanPhone = cleanPhone.substring(1); } if (cleanPhone.length > 9) { cleanPhone = cleanPhone.substring(0, 9); } return cleanPhone; }, // Submit patient form - Now uses same process as main referral system submitPatientForm: function($form) { console.log('Submitting patient form using PHP form submission'); // Validate form before submission if (!this.validateMainForm($form)) { console.log('Form validation failed'); return; } // Since we're using the same PHP form submission as main referral system, // we just need to submit the form normally - no AJAX needed console.log('Form validation passed, submitting via PHP form submission'); // Show loading state var $submitBtn = $form.find('button[type="submit"]'); var originalText = $submitBtn.text(); $submitBtn.prop('disabled', true).text('Submitting...'); // Submit the form normally - this will trigger the PHP form processing $form[0].submit(); }, // Submit registration submitRegistration: function($form) { var formData = new FormData($form[0]); formData.append('action', 'submit_none_seha_registration'); formData.append('nonce', NoneSehaReferral.nonce); $.ajax({ url: NoneSehaReferral.ajaxUrl, type: 'POST', data: formData, processData: false, contentType: false, success: function(response) { if (response.success) { $form.html(''); } else { $form.find('.form-errors').html('