/**
 * HVAC Registration Form JavaScript - Safari Compatible Version
 * 
 * This version uses ES5 compatible JavaScript for maximum browser compatibility
 */
jQuery(document).ready(function($) {
    // Use var instead of const/let for Safari compatibility
    var $countrySelect = $('#user_country');
    var $stateSelect = $('#user_state');
    var $stateOtherInput = $('#user_state_other');
    var $registrationForm = $('#hvac-registration-form');
    
    // Headquarters fields
    var $hqCountrySelect = $('#org_headquarters_country');
    var $hqStateSelect = $('#org_headquarters_state');
    var $hqStateOtherInput = $('#org_headquarters_state_other');
    
    // Venue fields
    var $createVenue = $('input[name="create_venue"]');
    var $venueDetails = $('#venue-details');
    var $venueName = $('#venue_name');
    var $businessName = $('#business_name');
    var $userCity = $('#user_city');
    var $venuePhone = $('#venue_phone');
    var $venueWebsite = $('#venue_website');
    var $businessPhone = $('#business_phone');
    var $businessWebsite = $('#business_website');
    
    // Form validation helpers
    function showFieldError(fieldId, message) {
        var $field = $('#' + fieldId);
        var $existingError = $field.siblings('.error-message');
        
        if ($existingError.length) {
            $existingError.text(message);
        } else {
            $field.after('<p class="error-message" id="' + fieldId + '_error">' + message + '</p>');
        }
        
        $field.addClass('error');
    }
    
    function clearFieldError(fieldId) {
        var $field = $('#' + fieldId);
        $field.siblings('.error-message').remove();
        $field.removeClass('error');
    }
    
    // Real-time email validation
    $('#user_email').on('blur', function() {
        var email = $(this).val();
        if (email && !isValidEmail(email)) {
            showFieldError('user_email', 'Please enter a valid email address.');
        } else {
            clearFieldError('user_email');
        }
    });
    
    $('#business_email').on('blur', function() {
        var email = $(this).val();
        if (email && !isValidEmail(email)) {
            showFieldError('business_email', 'Please enter a valid business email address.');
        } else {
            clearFieldError('business_email');
        }
    });
    
    function isValidEmail(email) {
        var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }
    
    // Real-time password validation
    $('#user_pass').on('input blur', function() {
        var password = $(this).val();
        if (password) {
            var errors = [];
            if (password.length < 8) {
                errors.push('at least 8 characters');
            }
            if (!/[A-Z]/.test(password)) {
                errors.push('one uppercase letter');
            }
            if (!/[a-z]/.test(password)) {
                errors.push('one lowercase letter');
            }
            if (!/[0-9]/.test(password)) {
                errors.push('one number');
            }
            
            if (errors.length > 0) {
                showFieldError('user_pass', 'Password must contain ' + errors.join(', ') + '.');
            } else {
                clearFieldError('user_pass');
                // Check confirm password if it has a value
                var confirmPass = $('#confirm_password').val();
                if (confirmPass) {
                    $('#confirm_password').trigger('blur');
                }
            }
        }
    });
    
    // Confirm password validation
    $('#confirm_password').on('blur', function() {
        var password = $('#user_pass').val();
        var confirmPassword = $(this).val();
        
        if (confirmPassword && password !== confirmPassword) {
            showFieldError('confirm_password', 'Passwords do not match.');
        } else {
            clearFieldError('confirm_password');
        }
    });
    
    // URL validation for optional fields - Safari compatible
    function isValidURL(url) {
        // Use regex instead of URL constructor for Safari compatibility
        var urlRegex = /^https?:\/\/([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/;
        return urlRegex.test(url);
    }
    
    $('#user_url, #user_linkedin, #business_website, #venue_website').on('blur', function() {
        var url = $(this).val();
        var fieldId = $(this).attr('id');
        
        if (url && !isValidURL(url)) {
            var fieldName = fieldId === 'user_url' ? 'personal website' : 
                           fieldId === 'user_linkedin' ? 'LinkedIn profile' : 
                           fieldId === 'business_website' ? 'organization website' :
                           'venue website';
            showFieldError(fieldId, 'Please enter a valid URL for your ' + fieldName + '.');
        } else {
            clearFieldError(fieldId);
        }
    });
    
    // Auto-populate venue name function
    function updateVenueName() {
        if ($venueName.val() === '') {
            var businessName = $businessName.val();
            var city = $userCity.val();
            
            if (businessName && city) {
                $venueName.val(businessName + ' ' + city);
            } else if (businessName) {
                $venueName.val(businessName + ' Training Center');
            }
        }
    }
    
    // Handle venue creation toggle
    $createVenue.on('change', function() {
        if ($(this).val() === 'Yes') {
            $venueDetails.slideDown();
            // Auto-populate venue name if empty
            updateVenueName();
            // Auto-populate venue phone and website
            if (!$venuePhone.val() && $businessPhone.val()) {
                $venuePhone.val($businessPhone.val());
            }
            if (!$venueWebsite.val() && $businessWebsite.val()) {
                $venueWebsite.val($businessWebsite.val());
            }
        } else {
            $venueDetails.slideUp();
        }
    });
    
    // Update venue name when business name or city changes
    $businessName.on('blur', updateVenueName);
    $userCity.on('blur', updateVenueName);
    
    // Form submission with comprehensive validation
    $registrationForm.on('submit', function(e) {
        e.preventDefault();
        
        var hasErrors = false;
        var errors = [];
        
        // Define required fields - compatible with older browsers
        var requiredFields = [
            { id: 'user_email', name: 'Email' },
            { id: 'user_pass', name: 'Password' },
            { id: 'confirm_password', name: 'Confirm Password' },
            { id: 'first_name', name: 'First Name' },
            { id: 'last_name', name: 'Last Name' },
            { id: 'display_name', name: 'Display Name' },
            { id: 'user_bio', name: 'Biographical Info' },
            { id: 'application_details', name: 'Application Details' },
            { id: 'business_name', name: 'Organization Name' },
            { id: 'business_phone', name: 'Organization Phone' },
            { id: 'business_email', name: 'Organization Email' },
            { id: 'business_description', name: 'Organization Description' },
            { id: 'business_type', name: 'Business Type' },
            { id: 'org_headquarters_country', name: 'Headquarters Country' },
            { id: 'org_headquarters_city', name: 'Headquarters City' }
        ];
        
        // Check required fields - use traditional for loop for Safari compatibility
        for (var i = 0; i < requiredFields.length; i++) {
            var field = requiredFields[i];
            var $field = $('#' + field.id);
            var value = $field.val();
            
            if (!value || value.trim() === '') {
                showFieldError(field.id, field.name + ' is required.');
                errors.push(field.name + ' is required');
                hasErrors = true;
            } else {
                clearFieldError(field.id);
            }
        }
        
        // Check organization logo requirement
        var $orgLogo = $('#org_logo');
        if ($orgLogo.length && !$orgLogo.val() && !$orgLogo.data('existing')) {
            showFieldError('org_logo', 'Organization Logo is required.');
            errors.push('Organization Logo is required');
            hasErrors = true;
        }
        
        // Validate state fields for countries that require them
        if ($countrySelect.length) {
            var country = $('#user_country').val();
            if (country === 'United States' || country === 'Canada') {
                if ($stateSelect.is(':visible')) {
                    var state = $('#user_state').val();
                    if (!state || state === '') {
                        showFieldError('user_state', 'State/Province is required for ' + country + '.');
                        errors.push('State/Province is required');
                        hasErrors = true;
                    }
                } else if ($stateOtherInput.is(':visible')) {
                    var otherState = $('#user_state_other').val();
                    if (!otherState || otherState.trim() === '') {
                        showFieldError('user_state_other', 'State/Province is required for ' + country + '.');
                        errors.push('State/Province is required');
                        hasErrors = true;
                    }
                }
            }
        }
        
        // Similar validation for HQ fields
        if ($hqCountrySelect.length) {
            var hqCountry = $hqCountrySelect.val();
            if ((hqCountry === 'United States' || hqCountry === 'Canada') && $hqStateSelect.is(':visible')) {
                var hqState = $hqStateSelect.val();
                if (!hqState || hqState === '') {
                    showFieldError('org_headquarters_state', 'Headquarters State/Province is required for ' + hqCountry + '.');
                    errors.push('Headquarters State/Province is required');
                    hasErrors = true;
                }
            }
        }
        
        // Check business type
        var businessType = $('#business_type').val();
        if (!businessType || businessType === '') {
            showFieldError('business_type', 'Please select your business type.');
            errors.push('Business type is required');
            hasErrors = true;
        }
        
        // Check training audience - at least one must be selected
        var trainingAudienceChecked = $('input[name="training_audience[]"]:checked').length > 0;
        if (!trainingAudienceChecked) {
            $('.training-audience-group').addClass('error');
            errors.push('Please select at least one training audience');
            hasErrors = true;
        } else {
            $('.training-audience-group').removeClass('error');
        }
        
        // Display error summary if there are errors
        if (hasErrors) {
            var $errorSummary = $('.hvac-form-errors');
            if (!$errorSummary.length) {
                $errorSummary = $('<div class="hvac-form-errors"><h4>Please correct the following errors:</h4><ul></ul></div>');
                $registrationForm.prepend($errorSummary);
            }
            var $errorList = $errorSummary.find('ul');
            $errorList.empty();
            for (var j = 0; j < errors.length; j++) {
                $errorList.append('<li>' + errors[j] + '</li>');
            }
            $errorSummary.show();
            
            // Scroll to top of form
            $('html, body').animate({
                scrollTop: $registrationForm.offset().top - 50
            }, 500);
            
            return false;
        } else {
            $('.hvac-form-errors').hide();
        }
        
        // If no errors, submit the form normally
        this.submit();
    });
    
    // Country/State handling - Safari compatible
    function populateStates($stateSelect, countryCode) {
        var options = {};
        
        if (countryCode === 'US') {
            options = {
                'AL': 'Alabama', 'AK': 'Alaska', 'AZ': 'Arizona', 'AR': 'Arkansas', 'CA': 'California',
                'CO': 'Colorado', 'CT': 'Connecticut', 'DE': 'Delaware', 'FL': 'Florida', 'GA': 'Georgia',
                'HI': 'Hawaii', 'ID': 'Idaho', 'IL': 'Illinois', 'IN': 'Indiana', 'IA': 'Iowa',
                'KS': 'Kansas', 'KY': 'Kentucky', 'LA': 'Louisiana', 'ME': 'Maine', 'MD': 'Maryland',
                'MA': 'Massachusetts', 'MI': 'Michigan', 'MN': 'Minnesota', 'MS': 'Mississippi', 'MO': 'Missouri',
                'MT': 'Montana', 'NE': 'Nebraska', 'NV': 'Nevada', 'NH': 'New Hampshire', 'NJ': 'New Jersey',
                'NM': 'New Mexico', 'NY': 'New York', 'NC': 'North Carolina', 'ND': 'North Dakota', 'OH': 'Ohio',
                'OK': 'Oklahoma', 'OR': 'Oregon', 'PA': 'Pennsylvania', 'RI': 'Rhode Island', 'SC': 'South Carolina',
                'SD': 'South Dakota', 'TN': 'Tennessee', 'TX': 'Texas', 'UT': 'Utah', 'VT': 'Vermont',
                'VA': 'Virginia', 'WA': 'Washington', 'WV': 'West Virginia', 'WI': 'Wisconsin', 'WY': 'Wyoming'
            };
        } else if (countryCode === 'CA') {
            options = {
                'AB': 'Alberta', 'BC': 'British Columbia', 'MB': 'Manitoba', 'NB': 'New Brunswick',
                'NL': 'Newfoundland and Labrador', 'NS': 'Nova Scotia', 'NT': 'Northwest Territories',
                'NU': 'Nunavut', 'ON': 'Ontario', 'PE': 'Prince Edward Island', 'QC': 'Quebec',
                'SK': 'Saskatchewan', 'YT': 'Yukon'
            };
        }
        
        $stateSelect.find('option:not([value=""])').remove();
        
        if (Object.keys(options).length > 0) {
            // Use traditional for-in loop for Safari compatibility
            for (var value in options) {
                if (options.hasOwnProperty(value)) {
                    var label = options[value];
                    var $otherOption = $stateSelect.find('option[value="Other"]');
                    var $newOption = $('<option></option>').val(value).text(label);
                    
                    if ($otherOption.length) {
                        $otherOption.before($newOption);
                    } else {
                        $stateSelect.append($newOption);
                    }
                }
            }
        }
        
        $stateSelect.show();
    }
    
    // Handle country selection change
    $countrySelect.on('change', function() {
        var country = $(this).val();
        
        if (country === 'United States') {
            populateStates($stateSelect, 'US');
            $stateSelect.show();
            $stateOtherInput.hide();
        } else if (country === 'Canada') {
            populateStates($stateSelect, 'CA');
            $stateSelect.show();
            $stateOtherInput.hide();
        } else if (country) {
            $stateSelect.hide();
            $stateOtherInput.show();
        } else {
            $stateSelect.hide();
            $stateOtherInput.hide();
        }
    });
    
    // Handle HQ country selection change
    $hqCountrySelect.on('change', function() {
        var country = $(this).val();
        
        if (country === 'United States') {
            populateStates($hqStateSelect, 'US');
            $hqStateSelect.show();
            $hqStateOtherInput.hide();
        } else if (country === 'Canada') {
            populateStates($hqStateSelect, 'CA');
            $hqStateSelect.show();
            $hqStateOtherInput.hide();
        } else if (country) {
            $hqStateSelect.hide();
            $hqStateOtherInput.show();
        } else {
            $hqStateSelect.hide();
            $hqStateOtherInput.hide();
        }
    });
    
    // Initialize state fields on page load
    if ($countrySelect.val()) {
        $countrySelect.trigger('change');
    }
    
    if ($hqCountrySelect.val()) {
        $hqCountrySelect.trigger('change');
    }
    
    // Initialize venue creation state
    if ($createVenue.filter(':checked').val() === 'Yes') {
        $venueDetails.show();
    }
});