$(document).ready(function() {
  const $passwordInput = $('#password');
  const $showPasswordCheckbox = $('#showPasswordCheckbox');

 // Add event listener to toggle password visibility
  $showPasswordCheckbox.on('change', function() {
    if (this.checked) {
      // Show the password
      $passwordInput.attr('type', 'text');
    } else {
      // Hide the password
      $passwordInput.attr('type', 'password');
    }
  });
  $('#want_to_sponsor').change(function() {
    if ($(this).is(':checked')) {
      $('#sponsorshipLevels').show();
      // Reset to default sponsorship level (Silver)
      $('#silver_sponsor').prop('checked', true);
      $('#registrationFee').text('Sponsorship Fee: ₹200000');
      $('#selected_sponsorship_level').val('silver');
    } else {
      $('#sponsorshipLevels').hide();
      $('#registrationFee').text('Registration Fee: ₹80000');
      $('#selected_sponsorship_level').val(''); // Clear selected sponsorship level
    }
  });
  
  
  // Modal Functionality
      $('.info-icon').on('click', function() {
        const modalId = $(this).data('modal');
        $('#' + modalId).show();
      });

      $('.close').on('click', function() {
        const modalId = $(this).data('modal');
        $('#' + modalId).hide();
      });

      $(window).on('click', function(event) {
        if ($(event.target).hasClass('modal')) {
          $('.modal').hide();
        }
      });
  $('#registrationForm').submit(function(e) {
    // Check if the checkbox is checked
    if ($('#accepted_terms').is(':checked')) {
      // If checked, set the value to 1
      $('#accepted_terms').val('1');
    } else {
      // If not checked, set the value to 0
      $('#accepted_terms').val('0');
    }
    if ($('#want_to_sponsor').is(':checked')) {
    // If checked, set the value to 1
       $('#want_to_sponsor').val('1');
       $('#selected_sponsorship_level').val($('input[name="sponsorship_level"]:checked').val());
    } else {
    // If not checked, set the value to 0
      $('#want_to_sponsor').val('0');
      $('#selected_sponsorship_level').val('');
    }
  });
});
document.addEventListener('DOMContentLoaded', function() {
  const primaryCountryCodeDropdown = document.getElementById('primary_country_code');
  const secondaryCountryCodeDropdown = document.getElementById('secondary_country_code');

  // Populate primary and secondary country code dropdowns
  countryData.forEach(country => {
    const callingCode = country.countryCallingCode;
    const countryName = country.countryNameEn;

    // Create option elements for primary and secondary dropdowns
    const primaryOption = document.createElement('option');
    const secondaryOption = document.createElement('option');

    // Set option values and text
    primaryOption.value = callingCode;
    primaryOption.text = `${countryName} (+${callingCode})`;

    secondaryOption.value = callingCode;
    secondaryOption.text = `${countryName} (+${callingCode})`;

    // Append options to respective dropdowns
    primaryCountryCodeDropdown.appendChild(primaryOption);
    secondaryCountryCodeDropdown.appendChild(secondaryOption);
  });
// Password field blur event listener
 // Real-time Password Match Validation
 const $passwordInput = $('#password');
 const $confirmPasswordInput = $('#confirm_password');
 const $passwordError = $('#password_error');
 $passwordInput.on('input', validatePassword);
 $confirmPasswordInput.on('input', validatePassword);

function validatePassword() {
  const password = $passwordInput.val();
  const confirmPassword = $confirmPasswordInput.val();

  if (password !== confirmPassword) {
    $passwordError.text('Passwords do not match');
  } else if (!isStrongPassword(password)) {
    $passwordError.text('Password should be at least 8 characters long and contain at least one uppercase letter, one lowercase letter, one number, and one special character');
  } else {
    $passwordError.text('');
  }
}

function isStrongPassword(password) {
  const regex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[a-zA-Z]).{8,}$/;
  return regex.test(password);
}

  // Handle form submission
  document.getElementById('registrationForm').addEventListener('submit', function(event) {
    let isValid = true;
    if ($passwordError.text() !== '') {
      e.preventDefault();
      return false;
    }
    // Primary Contact Number validation
    const primaryContactNumber = document.getElementById('primary_contact_number').value;
    if (!/^\d+$/.test(primaryContactNumber)) {
      showError('primary_contact_number', 'Please enter a valid primary contact number.');
      isValid = false;
    } else {
      clearError('primary_contact_number');
    }

    // Secondary Contact Number validation
    const secondaryContactNumber = document.getElementById('secondary_contact_number').value;
    if (secondaryContactNumber && !/^\d+$/.test(secondaryContactNumber)) {
      showError('secondary_contact_number', 'Please enter a valid secondary contact number.');
      isValid = false;
    } else {
      clearError('secondary_contact_number');
    }

    // Email validation
    const email = document.getElementById('email').value;
    if (!/^\S+@\S+\.\S+$/.test(email)) {
      showError('email', 'Please enter a valid email address.');
      isValid = false;
    } else {
      clearError('email');
    }

    // Website URL validation
    const websiteUrl = document.getElementById('website_url').value;
    if (websiteUrl && !isValidUrl(websiteUrl)) {
      showError('website_url', 'Please enter a valid website URL (e.g., http://example.com).');
      isValid = false;
    } else {
      clearError('website_url');
    }
    // Terms and Conditions validation
    const acceptTerms = document.getElementById('accept_terms').checked;
    if (!acceptTerms) {
      showError('accept_terms', 'You must accept the terms and conditions.');
      isValid = false;
    } else {
      clearError('accept_terms');
    }

    // Prevent form submission if validation failed
    if (!isValid) {
      event.preventDefault();
    }

    return isValid;
  });
});

function showError(fieldId, errorMessage) {
  const field = document.getElementById(fieldId);
  let errorField = document.getElementById(fieldId + '_error');
  if (!errorField) {
    errorField = document.createElement('span');
    errorField.id = fieldId + '_error';
    errorField.textContent = errorMessage;
    errorField.className = 'error-message';
    field.parentNode.insertBefore(errorField, field.nextSibling);
  } else {
    errorField.textContent = errorMessage;
  }
  field.classList.add('error');
}

function clearError(fieldId) {
  const field = document.getElementById(fieldId);
  field.classList.remove('error');
  const errorField = document.getElementById(fieldId + '_error');
  if (errorField) {
    errorField.parentNode.removeChild(errorField);
  }
}


function isValidUrl(url) {
  const urlPattern = /^(https?:\/\/)?([\w\d.-]+\.[\w]{2,})(\/\S*)?$/;
  return urlPattern.test(url);
}
